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: resilience layer, avatar color picker, walk NPCs, and environment dialogue
nirholasca73cceedeee
diff --git a/.env.example b/.env.exampleindex f05728984..ad1f165cf 100644--- a/.env.example+++ b/.env.example@@ -28,6 +28,12 @@ UPSTASH_REDIS_REST_TOKEN=# Optional: Error monitoringSENTRY_DSN=+# Optional: Payment/business metrics → Axiom (success rate, p95 latency, per network).+# Unset = no-op (see api/_lib/axiom.js). Create an API token + dataset at axiom.co,+# then set both. AXIOM_URL overrides the host (e.g. https://api.eu.axiom.co for EU).+AXIOM_TOKEN=+AXIOM_DATASET=+# JWT signing — rotate by appending to key set, never remove the old one mid-rotation# Generate with: openssl rand -base64 64JWT_SECRET=diff --git a/.vercelignore b/.vercelignoreindex 530a5b45f..51e16e34b 100644--- a/.vercelignore+++ b/.vercelignore@@ -4,7 +4,22 @@.husky.vscode-tests+# Keep the full test suite's source out of the deploy upload, but PRESERVE the+# critical-path gate files (scripts/test-gate.mjs runs them during the Vercel+# build and FAILS the deploy if they are stripped). Mirror the examples/ idiom+# below: exclude contents, re-include the directory, then re-include the exact+# files. This list MUST stay in sync with GATE_TESTS in scripts/test-gate.mjs —+# the gate now fails loudly naming any file missing from the build context.+tests/*+!tests/api+tests/api/*+!tests/solana-confirm.test.js+!tests/http-cache-control.test.js+!tests/agent-custody-guards.test.js+!tests/agent-wallet-vanity.test.js+!tests/api/x402.test.js+!tests/api/three-token-leaderboard.test.js+!tests/api/healthz.test.jsspecsexamples/*!examples/skills@@ -35,7 +50,8 @@ dist-artifactpublic/screenshotspublic/skills.mp4-vitest.config.js+# vitest.config.js stays in the upload: scripts/test-gate.mjs needs its extended+# hookTimeouts + @grpc dedupe to run the gate tests' heavy cold imports on Vercel.vite.config.artifact.jsplaywright.config.*scripts/gitpretty.shdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4a20b53ca..0e399234b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -29,6 +29,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **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]`- **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]`- **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]`diff --git a/api/_lib/avatar-wallet.js b/api/_lib/avatar-wallet.jsindex 84ad1291c..8fec05995 100644--- a/api/_lib/avatar-wallet.js+++ b/api/_lib/avatar-wallet.js@@ -22,7 +22,7 @@ import {TransactionInstruction,} from '@solana/web3.js';import { solanaConnection } from './solana/connection.js';-import { confirmOrThrow } from './solana/confirm.js';+import { submitProtected } from './execution-engine.js';import bs58 from 'bs58';const bs58decode = bs58.default ? bs58.default.decode : bs58.decode;@@ -158,23 +158,15 @@ export async function getSolBalance(connection, pubkey) {* broadcasting — split out from sendSol so the exact tx the endpoint submits* can be verified offline (see scripts/verify-send-sol.mjs).*/-export function buildSignedSolTransfer({ fromKeypair, to, lamports, memo, blockhash }) {+function buildSolTransferInstructions({ fromKeypair, to, lamports, memo }) {const toPubkey = to instanceof PublicKey ? to : new PublicKey(to);const lamportsInt = Math.round(Number(lamports));if (!Number.isFinite(lamportsInt) || lamportsInt <= 0) {throw Object.assign(new Error('transfer amount must be a positive number of lamports'), { code: 'bad_amount' });}-- const tx = new Transaction();- tx.add(- SystemProgram.transfer({- fromPubkey: fromKeypair.publicKey,- toPubkey,- lamports: lamportsInt,- }),- );+ const ixs = [SystemProgram.transfer({ fromPubkey: fromKeypair.publicKey, toPubkey, lamports: lamportsInt })];if (memo) {- tx.add(+ ixs.push(new TransactionInstruction({programId: MEMO_PROGRAM_ID,keys: [],@@ -182,7 +174,11 @@ export function buildSignedSolTransfer({ fromKeypair, to, lamports, memo, blockh}),);}+ return ixs;+}+export function buildSignedSolTransfer({ fromKeypair, to, lamports, memo, blockhash }) {+ const tx = new Transaction().add(...buildSolTransferInstructions({ fromKeypair, to, lamports, memo }));tx.feePayer = fromKeypair.publicKey;tx.recentBlockhash = blockhash;tx.sign(fromKeypair);@@ -190,19 +186,16 @@ export function buildSignedSolTransfer({ fromKeypair, to, lamports, memo, blockh}/**- * Sign and submit a native SOL transfer, waiting for `confirmed` commitment.- * Returns the transaction signature. This is the single money-moving primitive- * shared by the /api/agent/send-sol endpoint and the verification script.+ * Sign and submit a native SOL transfer, returning the signature on confirmation.+ * The single money-moving primitive shared by /api/agent/send-sol, the chat+ * sendSol tool, the agent economy, and the verification script. Routes through+ * the protected sender: data-driven priority fee + CU, rebroadcast with blockhash+ * refresh, and a hard throw on an on-chain revert — so a send no longer drops+ * silently under congestion or reports a reverted transfer as success.*/-export async function sendSol({ connection, fromKeypair, to, lamports, memo }) {- const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash('confirmed');- const tx = buildSignedSolTransfer({ fromKeypair, to, lamports, memo, blockhash });-- const signature = await connection.sendRawTransaction(tx.serialize(), {- skipPreflight: false,- maxRetries: 3,- });- await confirmOrThrow(connection, { signature, blockhash, lastValidBlockHeight }, 'confirmed');+export async function sendSol({ connection, fromKeypair, to, lamports, memo, network = 'mainnet' }) {+ const instructions = buildSolTransferInstructions({ fromKeypair, to, lamports, memo });+ const { signature } = await submitProtected({ network, connection, payer: fromKeypair, instructions });return signature;}diff --git a/api/_lib/axiom.js b/api/_lib/axiom.jsnew file mode 100644index 000000000..10d99035d--- /dev/null+++ b/api/_lib/axiom.js@@ -0,0 +1,104 @@+// Axiom event ingest for Vercel serverless functions — payment/business metrics.+// Optional env: AXIOM_TOKEN (API token), AXIOM_DATASET (dataset name).+// AXIOM_URL (override host, e.g. https://api.eu.axiom.co for EU).+//+// Usage: import { recordPaymentMetric } from './_lib/axiom.js'+//+// WHY A RAW fetch AND NOT @axiomhq/js — same reasoning as sentry.js: this can be+// imported by many serverless functions, and we want zero SDK weight / no+// cold-start init. Axiom's ingest API is a single authenticated POST of a JSON+// event array, so we send it straight. Fire-and-forget with a hard timeout so a+// slow/blocked ingest never delays — or hangs — the money path it reports on.+//+// Fail-closed-to-noop: when AXIOM_TOKEN / AXIOM_DATASET are unset (local, CI, or+// before the Vercel↔Axiom account is connected) every export is a no-op. Wiring+// it in now means metrics start flowing the moment those env vars are set — no+// code change, exactly like the SENTRY_DSN gate in sentry.js.+//+// Ingest API: POST {host}/v1/datasets/{dataset}/ingest (Bearer token, JSON array)+// Docs: https://axiom.co/docs/restapi/ingest++const DEFAULT_HOST = 'https://api.axiom.co';++let _cfg;+function cfg() {+ if (_cfg === undefined) {+ const token = process.env.AXIOM_TOKEN;+ const dataset = process.env.AXIOM_DATASET;+ _cfg =+ token && dataset+ ? {+ url: `${(process.env.AXIOM_URL || DEFAULT_HOST).replace(/\/+$/, '')}/v1/datasets/${encodeURIComponent(dataset)}/ingest`,+ token,+ }+ : null;+ }+ return _cfg;+}++/** True when ingest is configured — lets callers skip building a payload entirely. */+export function axiomEnabled() {+ return cfg() !== null;+}++// Common envelope fields, mirroring sentry.js: Axiom keys on `_time`, and we tag+// every row with environment / release / region so dashboards can slice by deploy.+function envelope(fields) {+ return {+ _time: new Date().toISOString(),+ environment: process.env.VERCEL_ENV || process.env.NODE_ENV || 'development',+ release: process.env.VERCEL_GIT_COMMIT_SHA || undefined,+ region: process.env.VERCEL_REGION || undefined,+ ...fields,+ };+}++/**+ * Fire-and-forget ingest of one structured event. Never throws, never blocks.+ * @param {object} fields — flat JSON; avoid PII. `_time` is added automatically.+ */+export function ingestEvent(fields) {+ const c = cfg();+ if (!c) return;+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), 2500);+ fetch(c.url, {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ authorization: `Bearer ${c.token}`,+ },+ body: JSON.stringify([envelope(fields)]),+ signal: controller.signal,+ keepalive: true,+ })+ .catch(() => {})+ .finally(() => clearTimeout(timer));+}++/**+ * Record a payment/settlement metric — the data the audit found we couldn't yet+ * see (success rate + latency per network). One row per attempt; dashboard the+ * rest in Axiom (e.g. `status:'ok'` ÷ total, p95 of `latency_ms`).+ * @param {object} m+ * @param {string} m.kind — e.g. 'avatar_payout', 'plan_subscription', 'x402'+ * @param {'ok'|'failed'} m.status+ * @param {string} [m.network] — 'solana' | 'base' | …+ * @param {number} [m.amountUsd]+ * @param {number} [m.latencyMs]+ * @param {string} [m.reason] — failure reason / error code+ * @param {string} [m.signature] — on-chain tx signature, when settled+ */+export function recordPaymentMetric({ kind, status, network, amountUsd, latencyMs, reason, signature } = {}) {+ if (!cfg()) return;+ ingestEvent({+ type: 'payment',+ kind,+ status,+ network,+ amount_usd: amountUsd,+ latency_ms: latencyMs,+ reason,+ signature,+ });+}diff --git a/api/_lib/club/payouts.js b/api/_lib/club/payouts.jsindex 42a10f074..0ace52ffb 100644--- a/api/_lib/club/payouts.js+++ b/api/_lib/club/payouts.js@@ -17,11 +17,9 @@ import {Connection,Keypair,PublicKey,- Transaction,- ComputeBudgetProgram,} from '@solana/web3.js';import { solanaConnection } from '../solana/connection.js';-import { confirmOrThrow } from '../solana/confirm.js';+import { submitProtected } from '../execution-engine.js';import {getAssociatedTokenAddress,createAssociatedTokenAccountInstruction,@@ -41,7 +39,6 @@ import { env } from '../env.js';import { chainOf } from './chain.js';import { SOLANA_USDC_MINT, EVM_USDC } from '../../payments/_config.js';-const SOLANA_PRIORITY_MICRO_LAMPORTS = 50_000;const SEND_TIMEOUT_MS = 45_000;/**@@ -72,43 +69,17 @@ export async function sendClubUsdcSolana({ recipient, amount }) {const senderAta = await getAssociatedTokenAddress(mint, kp.publicKey);const recipientAta = await getAssociatedTokenAddress(mint, to);- const tx = new Transaction();- tx.add(ComputeBudgetProgram.setComputeUnitPrice({ microLamports: SOLANA_PRIORITY_MICRO_LAMPORTS }));-+ const instructions = [];const recipientInfo = await connection.getAccountInfo(recipientAta);if (!recipientInfo) {- tx.add(createAssociatedTokenAccountInstruction(kp.publicKey, recipientAta, to, mint));+ instructions.push(createAssociatedTokenAccountInstruction(kp.publicKey, recipientAta, to, mint));}- tx.add(createTransferInstruction(senderAta, recipientAta, kp.publicKey, amt));-- const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash('confirmed');- tx.feePayer = kp.publicKey;- tx.recentBlockhash = blockhash;- tx.sign(kp);-- const sig = await connection.sendRawTransaction(tx.serialize(), {- skipPreflight: false,- maxRetries: 5,- });- await confirmWithTimeout(connection, sig, { blockhash, lastValidBlockHeight });- return { signature: sig, network: 'solana', amount_atomics: amt.toString() };-}+ instructions.push(createTransferInstruction(senderAta, recipientAta, kp.publicKey, amt));-async function confirmWithTimeout(connection, signature, { blockhash, lastValidBlockHeight }) {- const start = Date.now();- try {- await confirmOrThrow(connection, { signature, blockhash, lastValidBlockHeight }, 'confirmed');- return;- } catch {- while (Date.now() - start < SEND_TIMEOUT_MS) {- const status = await connection.getSignatureStatus(signature, { searchTransactionHistory: true });- const val = status?.value;- if (val?.err) throw new Error('solana_tx_failed: ' + JSON.stringify(val.err));- if (val?.confirmationStatus === 'confirmed' || val?.confirmationStatus === 'finalized') return;- await new Promise((r) => setTimeout(r, 1500));- }- throw new Error('solana_confirm_timeout');- }+ // Protected send: priority fee + CU estimate, rebroadcast with blockhash+ // refresh, hard throw on revert. (submitProtected sets its own compute-budget.)+ const { signature } = await submitProtected({ network: 'mainnet', connection, payer: kp, instructions });+ return { signature, network: 'solana', amount_atomics: amt.toString() };}const ERC20_TRANSFER_ABI = parseAbi(['function transfer(address to, uint256 amount) returns (bool)']);diff --git a/api/_lib/coin/creator-fees.js b/api/_lib/coin/creator-fees.jsindex 6a5af89fc..ac5a603ac 100644--- a/api/_lib/coin/creator-fees.js+++ b/api/_lib/coin/creator-fees.js@@ -26,7 +26,7 @@ import {import { NATIVE_MINT, getAssociatedTokenAddressSync, createCloseAccountInstruction } from '@solana/spl-token';import { getConnection, getPumpSdk, solanaPubkey } from '../pump.js';-import { confirmOrThrow } from '../solana/confirm.js';+import { submitProtected } from '../execution-engine.js';const PRIORITY_MICRO_LAMPORTS = 100_000;@@ -79,25 +79,18 @@ export async function claimCreatorFees({ coin, coinCreator, treasury }) {creatorWsolAta = null;}- const tx = new Transaction();- tx.add(ComputeBudgetProgram.setComputeUnitPrice({ microLamports: PRIORITY_MICRO_LAMPORTS }));- for (const ix of ixs) tx.add(ix);- tx.feePayer = treasuryPk;- const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash('confirmed');- tx.recentBlockhash = blockhash;-- // Sign with both keys: treasury pays + signs as fee payer, creator signs- // the collectCreatorFee instruction. When they're the same keypair, this- // gracefully deduplicates inside @solana/web3.js.- const signers = [treasury];- if (creatorPk.toBase58() !== treasuryPk.toBase58()) signers.push(coinCreator);- tx.sign(...signers);-- const sig = await connection.sendRawTransaction(tx.serialize(), {- skipPreflight: false,- maxRetries: 5,+ // Protected send: treasury is fee-payer + signer; the coin creator co-signs the+ // collectCreatorFee instruction when it's a distinct key. submitProtected sets+ // its own compute-budget, rebroadcasts with a fresh blockhash, and throws on an+ // on-chain revert.+ const extraSigners = creatorPk.toBase58() !== treasuryPk.toBase58() ? [coinCreator] : [];+ const { signature: sig } = await submitProtected({+ network,+ connection,+ payer: treasury,+ instructions: ixs,+ opts: { extraSigners },});- await confirmOrThrow(connection, { signature: sig, blockhash, lastValidBlockHeight }, 'confirmed');// Attempt the unwrap as a follow-up tx (best-effort).if (creatorWsolAta) {diff --git a/api/_lib/coin/treasury.js b/api/_lib/coin/treasury.jsindex 0700329be..1f38f44e7 100644--- a/api/_lib/coin/treasury.js+++ b/api/_lib/coin/treasury.js@@ -18,9 +18,9 @@// then gets unwrapped and routed to the treasury inside the same// transaction.-import { Keypair, PublicKey, SystemProgram, Transaction, ComputeBudgetProgram } from '@solana/web3.js';+import { Keypair, PublicKey, SystemProgram } from '@solana/web3.js';import { getConnection } from '../pump.js';-import { confirmOrThrow } from '../solana/confirm.js';+import { submitProtected } from '../execution-engine.js';import { decryptSecret, isEncryptedSecret } from '../secret-box.js';const SOL_LAMPORTS = 1_000_000_000n;@@ -98,39 +98,6 @@ export function lamportsToSol(lamports) {return `${whole}.${frac.toString().padStart(9, '0')}`;}-/**- * Confirm a recent signature against the network with a bounded timeout.- * Vercel function executions are short-lived; we don't want to hang on- * confirmation if the cluster is slow.- */-async function confirmWithTimeout(connection, signature, { commitment = 'confirmed', timeoutMs = 30_000 } = {}) {- const start = Date.now();- // First try the explicit confirm API; if that errors transiently, fall back- // to polling getSignatureStatus.- try {- const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash(commitment);- await confirmOrThrow(- connection,- { signature, blockhash, lastValidBlockHeight },- commitment,- );- return true;- } catch {- while (Date.now() - start < timeoutMs) {- const status = await connection.getSignatureStatus(signature, {- searchTransactionHistory: true,- });- const val = status?.value;- if (val?.err) throw new Error('tx_failed: ' + JSON.stringify(val.err));- if (val?.confirmationStatus === 'confirmed' || val?.confirmationStatus === 'finalized') {- return true;- }- await new Promise((r) => setTimeout(r, 1_500));- }- throw new Error('confirm_timeout');- }-}-/*** Send a single SystemProgram.transfer of `lamports` SOL from `from` to `to`.* Returns the tx signature on confirmation. Used for the lottery winner payout.@@ -147,18 +114,16 @@ export async function sendSolTransfer({ from, to, lamports, network = 'mainnet'const amount = typeof lamports === 'bigint' ? lamports : BigInt(lamports);if (amount <= 0n) throw new Error('sendSolTransfer: amount must be > 0');- const tx = new Transaction();- tx.add(ComputeBudgetProgram.setComputeUnitPrice({ microLamports: PRIORITY_MICRO_LAMPORTS }));- tx.add(SystemProgram.transfer({ fromPubkey: from.publicKey, toPubkey: toPk, lamports: amount }));- tx.feePayer = from.publicKey;- const { blockhash } = await connection.getLatestBlockhash('confirmed');- tx.recentBlockhash = blockhash;- tx.sign(from);-- const raw = tx.serialize();- const sig = await connection.sendRawTransaction(raw, { skipPreflight: false, maxRetries: 5 });- await confirmWithTimeout(connection, sig);- return sig;+ // Protected send: data-driven priority fee + CU, rebroadcast with blockhash+ // refresh, and a hard throw on an on-chain revert. (submitProtected sets its+ // own compute-budget, so we no longer add one here.)+ const { signature } = await submitProtected({+ network,+ connection,+ payer: from,+ instructions: [SystemProgram.transfer({ fromPubkey: from.publicKey, toPubkey: toPk, lamports: amount })],+ });+ return signature;}/**@@ -167,28 +132,15 @@ export async function sendSolTransfer({ from, to, lamports, network = 'mainnet'*/async function sendChunk({ from, transfers, network }) {const connection = getConnection({ network });- const tx = new Transaction();- tx.add(ComputeBudgetProgram.setComputeUnitPrice({ microLamports: PRIORITY_MICRO_LAMPORTS }));- for (const t of transfers) {- tx.add(- SystemProgram.transfer({- fromPubkey: from.publicKey,- toPubkey: typeof t.to === 'string' ? new PublicKey(t.to) : t.to,- lamports: typeof t.lamports === 'bigint' ? t.lamports : BigInt(t.lamports),- }),- );- }- tx.feePayer = from.publicKey;- const { blockhash } = await connection.getLatestBlockhash('confirmed');- tx.recentBlockhash = blockhash;- tx.sign(from);-- const sig = await connection.sendRawTransaction(tx.serialize(), {- skipPreflight: false,- maxRetries: 5,- });- await confirmWithTimeout(connection, sig);- return sig;+ const instructions = transfers.map((t) =>+ SystemProgram.transfer({+ fromPubkey: from.publicKey,+ toPubkey: typeof t.to === 'string' ? new PublicKey(t.to) : t.to,+ lamports: typeof t.lamports === 'bigint' ? t.lamports : BigInt(t.lamports),+ }),+ );+ const { signature } = await submitProtected({ network, connection, payer: from, instructions });+ return signature;}/**diff --git a/api/_lib/execution-engine.js b/api/_lib/execution-engine.jsindex 2196b9705..cac1431bc 100644--- a/api/_lib/execution-engine.js+++ b/api/_lib/execution-engine.js@@ -349,6 +349,8 @@ async function sendProtected(signedTx, signature, connection, blockhashCtx, conf* @param {import('@solana/web3.js').TransactionInstruction[]} o.instructions the trade ixs* @param {object} [o.opts]* @param {'off'|'economy'|'turbo'} [o.opts.tipMode='off'] per-strategy Jito tip policy+ * @param {import('@solana/web3.js').Keypair[]} [o.opts.extraSigners=[]] co-signers+ * beyond the fee-payer (e.g. a new mint Keypair on a launch)* @param {number} [o.opts.confirmTimeoutMs=45000] protected-route confirm bound* @param {boolean} [o.opts.preSimulated=false] caller already simulated (firewall) — still estimates CU* @param {(tipLamports: bigint, route: string) => Promise<void>} [o.opts.onTip]@@ -361,13 +363,24 @@ async function sendProtected(signedTx, signature, connection, blockhashCtx, confexport async function submitProtected({ network, connection, payer, instructions, opts = {} }) {const tipMode = ['economy', 'turbo'].includes(opts.tipMode) ? opts.tipMode : 'off';const confirmTimeoutMs = Number.isFinite(opts.confirmTimeoutMs) ? opts.confirmTimeoutMs : 45_000;+ // Co-signers beyond the fee-payer — e.g. a freshly generated mint Keypair on a+ // token launch. The fee payer is always `payer`; these are added to the+ // signature set. (Sim uses sigVerify:false, so it needs only the account metas+ // the instructions already carry, not these keypairs.)+ const extraSigners = Array.isArray(opts.extraSigners) ? opts.extraSigners : [];+ // Strip any caller-supplied ComputeBudget instructions: this engine sets its own+ // data-driven CU limit + escalating priority fee, and a SECOND ComputeBudget+ // instruction of the same kind makes the runtime reject the whole transaction.+ // No-op for the trade path (passes none); lets migrated send paths hand us their+ // raw instructions untouched without each having to remember to drop their own.+ const userIxs = instructions.filter((ix) => !ix.programId.equals(ComputeBudgetProgram.programId));const t0 = Date.now();// 1. Data-driven compute budget. Estimate the priority fee and the CU limit in// parallel — both are real RPC reads (fee cached, CU is a fresh simulate).const [priorityFeeBase, cuLimit] = await Promise.all([estimatePriorityFeeMicroLamports(connection, network),- estimateComputeUnits(connection, payer, instructions),+ estimateComputeUnits(connection, payer, userIxs),]);const canJito = jitoEligible(network, tipMode);@@ -395,7 +408,7 @@ export async function submitProtected({ network, connection, payer, instructionsComputeBudgetProgram.setComputeUnitLimit({ units: cuLimit }),ComputeBudgetProgram.setComputeUnitPrice({ microLamports: priorityFeeMicroLamports }),];- const txIxs = [...budgetIxs, ...instructions];+ const txIxs = [...budgetIxs, ...userIxs];if (tryJito) {tipLamports = resolveTipLamports(tipMode, tipFloor, attempt);@@ -440,7 +453,7 @@ export async function submitProtected({ network, connection, payer, instructionsinstructions: txIxs,}).compileToV0Message();const tx = new VersionedTransaction(msg);- tx.sign([payer]);+ tx.sign([payer, ...extraSigners]);const signature = bs58Sig(tx);try {diff --git a/api/_lib/feed.js b/api/_lib/feed.jsindex 1ac9d9883..600c72d73 100644--- a/api/_lib/feed.js+++ b/api/_lib/feed.js@@ -58,6 +58,8 @@ export const USER_EVENT_TYPES = new Set(['embed', // someone embedded the creator's agent'remix', // someone remixed a creation'reply', // new reply to an agent interaction+ 'follow', // someone followed you; { actor, follower_username, link }+ 'agent_review', // someone reviewed your agent; { actor, agent_id, agent_name, rating, link }// types already produced by purchase-confirm / buy-asset confirm flows'skill_purchased','skill_purchase_confirmed',diff --git a/api/_lib/resilience.js b/api/_lib/resilience.jsnew file mode 100644index 000000000..5732808ed--- /dev/null+++ b/api/_lib/resilience.js@@ -0,0 +1,80 @@+// Shared resilience helpers — thin, reusable wrappers over `cockatiel` so every+// external call (pump.fun, Birdeye, Solana RPC, LLM proxies, …) can get a+// battle-tested circuit breaker + timeout without each endpoint hand-rolling its+// own cooldown flag. ADDITIVE: existing guards stay; this just gives new/raw call+// sites a one-liner to fail fast and degrade gracefully during an upstream outage.+//+// Serverless note: breaker + timeout state is PER-LAMBDA-INSTANCE (cockatiel+// holds it in memory), exactly like the hand-rolled cooldowns it replaces. That+// is the right model for "fail fast on a sick upstream" — it does not need to be+// distributed. Truly shared state (rate limits, holder snapshot lock) stays on+// Redis, untouched.++import {+ circuitBreaker,+ ConsecutiveBreaker,+ handleAll,+ BrokenCircuitError,+ TaskCancelledError,+} from 'cockatiel';++// One breaker per logical upstream name, memoized for the life of the instance so+// repeated failures to the same service accumulate toward the open threshold.+const _breakers = new Map();++function getBreaker(name, { threshold, halfOpenAfterMs }) {+ const key = `${name}:${threshold}:${halfOpenAfterMs}`;+ let b = _breakers.get(key);+ if (!b) {+ b = circuitBreaker(handleAll, {+ halfOpenAfter: halfOpenAfterMs,+ breaker: new ConsecutiveBreaker(threshold),+ });+ _breakers.set(key, b);+ }+ return b;+}++/**+ * Run `fn` behind a named circuit breaker. On success, returns its value. When+ * the breaker is OPEN (recent consecutive failures) the call is rejected+ * instantly without invoking `fn` — so an influx during an upstream outage stops+ * paying the per-request timeout. On an open circuit OR an `fn` failure, resolves+ * to `fallback` (a value, or a function of the error) instead of throwing, so+ * callers degrade gracefully exactly where they already expected a soft failure.+ *+ * @template T+ * @param {string} name logical upstream id, e.g. 'pumpfun:creator-fees'+ * @param {() => Promise<T>} fn the async operation (already timeout-bounded if it does I/O)+ * @param {object} [opts]+ * @param {T | ((err: unknown) => T)} [opts.fallback=null] value/factory returned on open-circuit or failure+ * @param {number} [opts.threshold=5] consecutive failures before the circuit opens+ * @param {number} [opts.halfOpenAfterMs=30000] cooldown before a single trial request is allowed through+ * @returns {Promise<T>}+ */+export async function withBreaker(name, fn, opts = {}) {+ const { fallback = null, threshold = 5, halfOpenAfterMs = 30_000 } = opts;+ const breaker = getBreaker(name, { threshold, halfOpenAfterMs });+ try {+ return await breaker.execute(fn);+ } catch (err) {+ // BrokenCircuitError (open), TaskCancelledError (timeout), or the operation's+ // own error — all degrade to the fallback so the caller never hard-fails on+ // a non-critical upstream.+ return typeof fallback === 'function' ? fallback(err) : fallback;+ }+}++/**+ * Whether an error came from the resilience layer short-circuiting (open circuit+ * or a cancelled/timed-out task) rather than the operation itself — useful when a+ * caller wants to log "skipped, upstream cooling down" distinctly from a real error.+ */+export function isCircuitError(err) {+ return err instanceof BrokenCircuitError || err instanceof TaskCancelledError;+}++// Test/ops hook — drop all memoized breakers so a fresh state can be asserted.+export function _resetBreakers() {+ _breakers.clear();+}diff --git a/api/_lib/solana-transfer.js b/api/_lib/solana-transfer.jsindex c23755bbd..ef70225a9 100644--- a/api/_lib/solana-transfer.js+++ b/api/_lib/solana-transfer.js@@ -1,6 +1,6 @@-import { PublicKey, Transaction, Keypair } from '@solana/web3.js';+import { PublicKey, Keypair } from '@solana/web3.js';import { solanaConnection } from './solana/connection.js';-import { confirmOrThrow } from './solana/confirm.js';+import { submitProtected } from './execution-engine.js';import {getAssociatedTokenAddress,createAssociatedTokenAccountInstruction,@@ -29,21 +29,21 @@ export async function transferSolanaUSDC({ fromWallet, toAddress, amount, mint }const senderATA = await getAssociatedTokenAddress(mintPubkey, kp.publicKey);const recipientATA = await getAssociatedTokenAddress(mintPubkey, recipientPubkey);- const tx = new Transaction();-+ const instructions = [];const recipientAccount = await connection.getAccountInfo(recipientATA);if (!recipientAccount) {- tx.add(createAssociatedTokenAccountInstruction(kp.publicKey, recipientATA, recipientPubkey, mintPubkey));+ instructions.push(createAssociatedTokenAccountInstruction(kp.publicKey, recipientATA, recipientPubkey, mintPubkey));}-- tx.add(createTransferInstruction(senderATA, recipientATA, kp.publicKey, BigInt(amount)));-- const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash();- tx.feePayer = kp.publicKey;- tx.recentBlockhash = blockhash;-- tx.sign(kp);- const sig = await connection.sendRawTransaction(tx.serialize(), { skipPreflight: false });- await confirmOrThrow(connection, { signature: sig, blockhash, lastValidBlockHeight }, 'confirmed');- return sig;+ instructions.push(createTransferInstruction(senderATA, recipientATA, kp.publicKey, BigInt(amount)));++ // Protected send: data-driven priority fee + CU, rebroadcast with blockhash+ // refresh until it lands, and a hard throw on an on-chain revert — replaces the+ // previous send-once-and-confirm, which dropped silently under congestion.+ const { signature } = await submitProtected({+ network: 'mainnet',+ connection,+ payer: kp,+ instructions,+ });+ return signature;}diff --git a/api/_lib/x402/bazaar-helpers.js b/api/_lib/x402/bazaar-helpers.jsindex e557f4974..4dd080a01 100644--- a/api/_lib/x402/bazaar-helpers.js+++ b/api/_lib/x402/bazaar-helpers.js@@ -196,7 +196,12 @@ export function declareMcpDiscovery({throw new Error(`declareMcpDiscovery: SDK rejected config: ${err.message}`);}const sdkInner = sdkBlock?.bazaar || Object.values(sdkBlock || {})[0];- return sdkInner;+ // Force the top-level `discoverable: true` flag. The SDK's inner block omits+ // it, but CDP Bazaar / agentic.market only catalog a resource whose bazaar+ // extension is explicitly discoverable — without this, every priced MCP tool+ // row is silently skipped by the discovery crawler. declareHttpDiscovery sets+ // the same flag for REST routes; this keeps MCP rows at parity.+ return { ...sdkInner, discoverable: true };}// Convenience: returns the full extensions block `{ bazaar: <inner> }` fordiff --git a/api/_mcpagent/tools.js b/api/_mcpagent/tools.jsindex 02816e4e9..5386c30a2 100644--- a/api/_mcpagent/tools.js+++ b/api/_mcpagent/tools.js@@ -457,7 +457,15 @@ export const toolDefs = [type: 'object',description: 'Optional JSON Schema for the request body.',},- network: { type: 'string', enum: ['solana', 'base'], default: 'solana' },+ // Base is the default monetization rail: it matches the handler's own+ // fallback (`args.network === 'solana' ? 'solana' : 'base'`) and+ // createPaidService's `network = 'base'`. The validator compiles with+ // Ajv `useDefaults: true`, so this default is written into `args.network`+ // before the handler runs — a `'solana'` default here silently forced+ // every default-network call onto the Solana payout path (reading the+ // usually-empty meta.solana_address) and rejected it as no_payout_wallet,+ // even for an agent with a Base EVM wallet.+ network: { type: 'string', enum: ['solana', 'base'], default: 'base' },},required: ['agent_id', 'name', 'description', 'price_usdc', 'target_url'],additionalProperties: false,diff --git a/api/agent/send-sol.js b/api/agent/send-sol.jsindex a0daad9cd..68d0e123d 100644--- a/api/agent/send-sol.js+++ b/api/agent/send-sol.js@@ -17,6 +17,7 @@ import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/import { parse } from '../_lib/validate.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { logAudit } from '../_lib/audit.js';+import { recordPaymentMetric } from '../_lib/axiom.js';import {avatarWalletConfig,loadAvatarKeypair,@@ -151,6 +152,7 @@ export default wrap(async (req, res) => {}let signature;+ const sendStartedAt = Date.now();try {signature = await sendSol({connection,@@ -160,8 +162,24 @@ export default wrap(async (req, res) => {memo: body.memo || `three.ws avatar · $${usd.toFixed(2)} SOL`,});} catch (err) {+ recordPaymentMetric({+ kind: 'avatar_payout',+ status: 'failed',+ network: cfg.network,+ amountUsd: usd,+ latencyMs: Date.now() - sendStartedAt,+ reason: err?.message || 'unknown',+ });return error(res, 502, 'send_failed', `on-chain transfer failed: ${err?.message || 'unknown error'}`);}+ recordPaymentMetric({+ kind: 'avatar_payout',+ status: 'ok',+ network: cfg.network,+ amountUsd: usd,+ latencyMs: Date.now() - sendStartedAt,+ signature,+ });// Immutable trail for the one custodial money-out path: who triggered a// payout (by IP/UA — this endpoint is session-less, gated by demo-token /diff --git a/api/agents/pumpfun/[action].js b/api/agents/pumpfun/[action].jsindex 4d17874fa..b57dc8a8c 100644--- a/api/agents/pumpfun/[action].js+++ b/api/agents/pumpfun/[action].js@@ -16,11 +16,11 @@ import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auimport { cors, json, method, readJson, wrap, error, rateLimited, serverError, respondError } from '../../_lib/http.js';import { limits, clientIp } from '../../_lib/rate-limit.js';import { loadAgentForSigning, solanaConnection } from '../../_lib/agent-pumpfun.js';-import { confirmOrThrow } from '../../_lib/solana/confirm.js';+import { submitProtected } from '../../_lib/execution-engine.js';import { reserveSpend, finalizeSpend, releaseSpend } from '../../_lib/agent-spend-policy.js';import { grindMintKeypair } from '../../_lib/pump-vanity.js';import { sql } from '../../_lib/db.js';-import { Keypair, PublicKey, Transaction } from '@solana/web3.js';+import { Keypair, PublicKey } from '@solana/web3.js';import { z } from 'zod';const NATIVE_SOL_MINT = 'So11111111111111111111111111111111111111112';@@ -262,16 +262,11 @@ async function handleBuy(req, res, id) {return error(res, reservation.status, reservation.code, reservation.msg);}- const tx = new Transaction().add(...instructions);- tx.feePayer = keypair.publicKey;- const { blockhash } = await conn.getLatestBlockhash();- tx.recentBlockhash = blockhash;- tx.sign(keypair);-let signature;try {- signature = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false });- await confirmOrThrow(conn, signature, 'confirmed');+ // Protected send: priority fee + CU estimate, rebroadcast with blockhash+ // refresh until it lands, hard throw on an on-chain revert.+ ({ signature } = await submitProtected({ network: body.network, connection: conn, payer: keypair, instructions }));} catch (err) {console.error('[pumpfun/buy] send failed', err);if (reservation) await releaseSpend(reservation.reservationId);@@ -485,16 +480,18 @@ async function handleLaunch(req, res, id) {});if (!reservation.ok) return error(res, reservation.status, reservation.code, reservation.msg);- const tx = new Transaction().add(...instructions);- tx.feePayer = keypair.publicKey;- const { blockhash } = await conn.getLatestBlockhash();- tx.recentBlockhash = blockhash;- tx.sign(keypair, mint);-let signature;try {- signature = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false });- await confirmOrThrow(conn, signature, 'confirmed');+ // Protected send: the agent keypair 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: keypair,+ instructions,+ opts: { extraSigners: [mint] },+ }));} catch (err) {console.error('[pumpfun/launch] send failed', err);await releaseSpend(reservation.reservationId);@@ -719,16 +716,11 @@ async function handlePay(req, res, id) {return error(res, 422, 'build_failed', err.message || 'could not build instruction');}- const tx = new Transaction().add(...instructions);- tx.feePayer = keypair.publicKey;- const { blockhash } = await conn.getLatestBlockhash();- tx.recentBlockhash = blockhash;- tx.sign(keypair);-let signature;try {- signature = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false });- await confirmOrThrow(conn, signature, 'confirmed');+ // Protected send: priority fee + CU estimate, rebroadcast with blockhash+ // refresh until it lands, hard throw on an on-chain revert.+ ({ signature } = await submitProtected({ network: body.network, connection: conn, payer: keypair, instructions }));} catch (err) {console.error(`[pumpfun/pay] ${body.action} send failed`, err);return serverError(res, 502, 'rpc_error', err);@@ -1117,16 +1109,11 @@ async function handleSell(req, res, id) {return respondError(res, err.status || 422, err.code || 'build_failed', err);}- const tx = new Transaction().add(...instructions);- tx.feePayer = keypair.publicKey;- const { blockhash } = await conn.getLatestBlockhash();- tx.recentBlockhash = blockhash;- tx.sign(keypair);-let signature;try {- signature = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false });- await confirmOrThrow(conn, signature, 'confirmed');+ // Protected send: priority fee + CU estimate, rebroadcast with blockhash+ // refresh until it lands, hard throw on an on-chain revert.+ ({ signature } = await submitProtected({ network: body.network, connection: conn, payer: keypair, instructions }));} catch (err) {console.error('[pumpfun/sell] send failed', err);return serverError(res, 502, 'rpc_error', err);@@ -1377,16 +1364,11 @@ async function handleSwap(req, res, id) {return error(res, reservation.status, reservation.code, reservation.msg);}- const tx = new Transaction().add(...instructions);- tx.feePayer = keypair.publicKey;- const { blockhash } = await conn.getLatestBlockhash();- tx.recentBlockhash = blockhash;- tx.sign(keypair);-let signature;try {- signature = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false });- await confirmOrThrow(conn, signature, 'confirmed');+ // Protected send: priority fee + CU estimate, rebroadcast with blockhash+ // refresh until it lands, hard throw on an on-chain revert.+ ({ signature } = await submitProtected({ network: body.network, connection: conn, payer: keypair, instructions }));} catch (err) {console.error('[pumpfun/swap] send failed', err);if (reservation) await releaseSpend(reservation.reservationId);diff --git a/api/marketplace/purchase-as-agent.js b/api/marketplace/purchase-as-agent.jsindex 6c8ce2e0c..75858f371 100644--- a/api/marketplace/purchase-as-agent.js+++ b/api/marketplace/purchase-as-agent.js@@ -17,9 +17,9 @@** Revenue + notifications are handled by confirmSkillPurchase (purchase-confirm.js).*/-import { Keypair, PublicKey, Transaction } from '@solana/web3.js';+import { Keypair, PublicKey } from '@solana/web3.js';import { solanaConnection } from '../_lib/solana/connection.js';-import { confirmOrThrow } from '../_lib/solana/confirm.js';+import { submitProtected } from '../_lib/execution-engine.js';import {getAssociatedTokenAddressSync,createTransferCheckedInstruction,@@ -262,18 +262,11 @@ export default wrap(async (req, res) => {transferIx.keys.push({ pubkey: referenceKey, isSigner: false, isWritable: false });ixs.push(transferIx);- const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash('confirmed');- const tx = new Transaction({ feePayer: buyerKeypair.publicKey, recentBlockhash: blockhash, lastValidBlockHeight });- for (const ix of ixs) tx.add(ix);- tx.sign(buyerKeypair);-let txSig;try {- txSig = await connection.sendRawTransaction(tx.serialize(), {- skipPreflight: false,- preflightCommitment: 'confirmed',- });- await confirmOrThrow(connection, { signature: txSig, blockhash, lastValidBlockHeight }, 'confirmed');+ // Protected send: priority fee + CU estimate, rebroadcast with blockhash+ // refresh until it lands, hard throw on an on-chain revert.+ ({ signature: txSig } = await submitProtected({ network: 'mainnet', connection, payer: buyerKeypair, instructions: ixs }));log('purchase_as_agent.tx_confirmed', { purchase_id: pur.id, tx_signature: txSig });} catch (e) {await sql`diff --git a/api/marketplace/reviews.js b/api/marketplace/reviews.jsindex 511f4a9cd..75c3c9f71 100644--- a/api/marketplace/reviews.js+++ b/api/marketplace/reviews.js@@ -20,6 +20,7 @@ import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/import { clientIp, limits } from '../_lib/rate-limit.js';import { requireCsrf } from '../_lib/csrf.js';import { isUuid } from '../_lib/validate.js';+import { publishUserEvent } from '../_lib/feed.js';const reviewSchema = z.object({rating: z.number().int().min(1).max(5),@@ -148,7 +149,7 @@ async function handleUpsert(req, res, agentId) {if (!rl.success) return rateLimited(res, rl);const [agent] = await sql`- SELECT id, user_id FROM agent_identities+ SELECT id, user_id, name FROM agent_identitiesWHERE id = ${agentId} AND deleted_at IS NULL AND is_published = true`;if (!agent) return error(res, 404, 'not_found', 'agent not found');@@ -178,6 +179,23 @@ async function handleUpsert(req, res, agentId) {FROM agent_reviews WHERE agent_id = ${agentId}`;+ // Notify the owner of a genuinely NEW review (not an edit). On a fresh insert+ // created_at === updated_at; an upsert-update bumps updated_at, so this gates+ // out edit spam. Fire-and-forget via the existing in-app notification system.+ if (+new Date(row.created_at) === +new Date(row.updated_at)) {+ const [reviewer] = await sql`+ SELECT display_name, username FROM users WHERE id = ${auth.userId} AND deleted_at IS NULL+ `;+ publishUserEvent(agent.user_id, {+ type: 'agent_review',+ actor: reviewer?.display_name || reviewer?.username || 'Someone',+ agent_id: agentId,+ agent_name: agent.name || null,+ rating: parsed.data.rating,+ link: `/agent/${agentId}`,+ });+ }+return json(res, 200, {data: {review: row,diff --git a/api/pump/launch-detail.js b/api/pump/launch-detail.jsindex d0ce774d6..50fcaeaca 100644--- a/api/pump/launch-detail.js+++ b/api/pump/launch-detail.js@@ -33,6 +33,7 @@ import { sql } from '../_lib/db.js';import { publicUrl as r2PublicUrl } from '../_lib/r2.js';import { normalizeGatewayURL } from '../../src/ipfs.js';import { getTraderStats } from '../_lib/trader-stats.js';+import { withBreaker } from '../_lib/resilience.js';const MINT_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;const lamportsToSol = (v) => (v == null ? null : Number(BigInt(v)) / 1e9);@@ -53,42 +54,45 @@ function safeR2Url(key) {// Creator fee-sharing earnings — what the coin's creator has actually earned// from pump.fun's creator-reward program. Two public pump.fun endpoints (the// same ones the pump.fun frontend calls): coin metadata → creator wallet, then-// the creator's fee-sharing totals filtered to this mint. Best-effort and-// timeout-bounded; degrades to null so it never blocks or slows the page.+// the creator's fee-sharing totals filtered to this mint.+//+// Each call is timeout-bounded, and the whole thing runs behind a circuit+// breaker at the call site (see buildDetail): an UNHEALTHY upstream (network+// error, timeout, non-2xx) throws so consecutive failures open the breaker and+// later requests skip pump.fun instantly instead of every launch-page load+// waiting out two 5s timeouts during an outage. A VALID-but-empty response (no+// creator, no earnings) returns null and counts as a success — it isn't an+// outage, so it must not trip the breaker.const PUMP_FRONTEND_V3 = 'https://frontend-api-v3.pump.fun';const PUMP_SWAP_API = 'https://swap-api.pump.fun';async function fetchCreatorFees(mint, network) {if (network !== 'mainnet') return null;- try {- const metaResp = await fetch(`${PUMP_FRONTEND_V3}/coins-v2/${mint}`, {- headers: { accept: 'application/json' },- signal: AbortSignal.timeout(5000),- });- if (!metaResp.ok) return null;- const meta = await metaResp.json();- const creator = meta?.creator || meta?.creator_address;- if (!creator || typeof creator !== 'string') return null;+ const metaResp = await fetch(`${PUMP_FRONTEND_V3}/coins-v2/${mint}`, {+ headers: { accept: 'application/json' },+ signal: AbortSignal.timeout(5000),+ });+ if (!metaResp.ok) throw new Error(`pump.fun coin meta ${metaResp.status}`);+ const meta = await metaResp.json();+ const creator = meta?.creator || meta?.creator_address;+ if (!creator || typeof creator !== 'string') return null; // valid: no creator on file- const totResp = await fetch(- `${PUMP_SWAP_API}/v1/fee-sharing/account/${creator}/totals?mint=${mint}`,- { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(5000) },- );- if (!totResp.ok) return null;- const t = await totResp.json();- const earnedSol = Number(t?.shareholderTotalEarned?.sol);- if (!Number.isFinite(earnedSol)) return null;- return {- creator,- earned_sol: earnedSol,- earned_usd: Number(t?.shareholderTotalEarned?.usd) || null,- claimed_sol: Number(t?.shareholderClaimed?.sol) || 0,- unclaimed_sol: Number(t?.shareholderUnclaimed?.sol) || 0,- mint_count: t?.mintCount != null ? Number(t.mintCount) : null,- };- } catch {- return null;- }+ const totResp = await fetch(+ `${PUMP_SWAP_API}/v1/fee-sharing/account/${creator}/totals?mint=${mint}`,+ { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(5000) },+ );+ if (!totResp.ok) throw new Error(`pump.fun fee-sharing ${totResp.status}`);+ const t = await totResp.json();+ const earnedSol = Number(t?.shareholderTotalEarned?.sol);+ if (!Number.isFinite(earnedSol)) return null; // valid: creator has no fee-sharing earnings+ return {+ creator,+ earned_sol: earnedSol,+ earned_usd: Number(t?.shareholderTotalEarned?.usd) || null,+ claimed_sol: Number(t?.shareholderClaimed?.sol) || 0,+ unclaimed_sol: Number(t?.shareholderUnclaimed?.sol) || 0,+ mint_count: t?.mintCount != null ? Number(t.mintCount) : null,+ };}// Short-lived per-instance cache — the page is read far more than coins are@@ -203,7 +207,15 @@ async function buildDetail(mint, network) {where mint_id=${reg.id} and status='confirmed'order by created_at desc limit 8`,- fetchCreatorFees(mint, network),+ // Behind a circuit breaker: a healthy pump.fun returns the fees (or a+ // valid null); a sick one trips the breaker after 3 failures so later+ // launch-page loads skip it instantly and degrade to null instead of+ // each waiting out two 5s timeouts during an outage.+ withBreaker('pumpfun:creator-fees', () => fetchCreatorFees(mint, network), {+ fallback: null,+ threshold: 3,+ halfOpenAfterMs: 30_000,+ }),]);economics = {confirmed_payments: stats?.confirmed_payments ?? 0,diff --git a/api/subscriptions/index.js b/api/subscriptions/index.jsindex 707b6ac34..fe7dc8e25 100644--- a/api/subscriptions/index.js+++ b/api/subscriptions/index.js@@ -50,7 +50,7 @@ async function handleMine(req, res) {cs.id, cs.plan_id, cs.status, cs.current_period_start, cs.current_period_end,cs.payment_method, cs.wallet_address, cs.created_at, cs.cancelled_at,sp.name AS plan_name, sp.price_usd, sp.interval,- u.display_name AS creator_name, u.id AS creator_id+ u.display_name AS creator_name, u.id AS creator_id, u.username AS creator_usernameFROM creator_subscriptions csJOIN subscription_plans sp ON sp.id = cs.plan_idJOIN users u ON u.id = sp.creator_iddiff --git a/api/users/[username]/follow.js b/api/users/[username]/follow.jsindex 26a64d10f..6ca1b62fd 100644--- a/api/users/[username]/follow.js+++ b/api/users/[username]/follow.js@@ -15,6 +15,7 @@ import { cors, json, method, wrap, error, rateLimited } from '../../_lib/http.jsimport { getSessionUser } from '../../_lib/auth.js';import { requireCsrf } from '../../_lib/csrf.js';import { limits, clientIp } from '../../_lib/rate-limit.js';+import { publishUserEvent } from '../../_lib/feed.js';async function counts(userId) {const [row] = await sql`@@ -79,11 +80,24 @@ export default wrap(async (req, res) => {}if (req.method === 'POST') {- await sql`+ // RETURNING yields a row only when a NEW edge was created — re-following an+ // account you already follow is a no-op and must not re-notify.+ const inserted = await sql`insert into user_follows (follower_id, following_id)values (${viewer.id}, ${target.id})on conflict do nothing+ returning follower_id`;+ if (inserted.length) {+ // Reuse the existing in-app notification system (nav bell) — fire-and-+ // forget, never blocks the response.+ publishUserEvent(target.id, {+ type: 'follow',+ actor: viewer.display_name || viewer.username || 'Someone',+ follower_username: viewer.username || null,+ link: viewer.username ? `/u/${viewer.username}` : '/feed',+ });+ }} else {await sql`delete from user_followsdiff --git a/api/wk.js b/api/wk.jsindex af5ddefd2..027038fb7 100644--- a/api/wk.js+++ b/api/wk.js@@ -649,7 +649,7 @@ async function handleX402Discovery(req, res) {tags: ['solana', 'vanity', 'keypair', 'wallet', 'address'],}),vanityVerifiable: withService({- serviceName: 'three.ws Provably-Fair Vanity Grinder',+ serviceName: 'three.ws Provable Vanity Grinder',tags: ['solana', 'vanity', 'keypair', 'wallet', 'verifiable', 'commit-reveal'],}),permit2Demo: withService({@@ -693,7 +693,7 @@ async function handleX402Discovery(req, res) {tags: ['3d', 'avatar', 'club', 'access', 'cover'],}),forge: withService({- serviceName: 'three.ws Forge — text/image → 3D',+ serviceName: 'three.ws Forge: text/image to 3D',tags: ['3d', 'generation', 'text-to-3d', 'image-to-3d', 'glb', 'mesh'],}),};diff --git a/api/x402/pay-by-name.js b/api/x402/pay-by-name.jsindex 042a6dd44..43d07c15d 100644--- a/api/x402/pay-by-name.js+++ b/api/x402/pay-by-name.js@@ -36,7 +36,7 @@ import {} from '@solana/spl-token';import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';-import { confirmOrThrow } from '../_lib/solana/confirm.js';+import { submitProtected } from '../_lib/execution-engine.js';import { sql } from '../_lib/db.js';import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';@@ -286,23 +286,11 @@ async function handleSend(req, res, auth, body) {recipient,amountAtoms,});- const { blockhash, lastValidBlockHeight } = await conn.getLatestBlockhash('confirmed');- const msg = new TransactionMessage({- payerKey: keypair.publicKey,- recentBlockhash: blockhash,- instructions: ixs,- }).compileToV0Message();- const tx = new VersionedTransaction(msg);- tx.sign([keypair]);-let signature;try {- signature = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false });- await confirmOrThrow(- conn,- { signature, blockhash, lastValidBlockHeight },- 'confirmed',- );+ // Protected send: priority fee + CU estimate, rebroadcast with blockhash+ // refresh until it lands, hard throw on an on-chain revert.+ ({ signature } = await submitProtected({ network: 'mainnet', connection: conn, payer: keypair, instructions: ixs }));} catch (err) {console.error('[pay-by-name] send_failed', err);return error(res, 502, 'upstream_error', err?.message || 'transfer failed');diff --git a/data/changelog.json b/data/changelog.jsonindex bcf9fdaa8..fc1d12c4a 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,15 @@{"$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": "Imported avatars now animate with correct arm and leg orientation",+ "summary": "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.",+ "tags": [+ "fix",+ "improvement"+ ]+ },{"date": "2026-06-21","title": "Walk picks up where you left off, plus click-to-walk",diff --git a/package-lock.json b/package-lock.jsonindex f966c2f60..39dead18c 100644--- a/package-lock.json+++ b/package-lock.json@@ -51,6 +51,7 @@"@gltf-transform/functions": "^4.4.0","@grpc/grpc-js": "^1.14.4","@grpc/proto-loader": "^0.8.1",+ "@jaames/iro": "^5.5.2","@jup-ag/api": "^6.0.48","@mediapipe/tasks-vision": "^0.10.35","@metaplex-foundation/js": "^0.20.1",@@ -116,6 +117,7 @@"borsher": "^4.0.0","bs58": "^6.0.0","cborg": "^4.5.8",+ "cockatiel": "^4.0.0","colyseus": "^0.17.10","colyseus.js": "0.16.22","dat.gui": "^0.7.9",@@ -9707,6 +9709,12 @@"node": ">=18.20.0"}},+ "node_modules/@irojs/iro-core": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/@irojs/iro-core/-/iro-core-1.2.1.tgz",+ "integrity": "sha512-p2OvsBSSmidsDsTSkID6jEyXDF7lcyxPrkh3qBzasBZFpjkYd6kZ3yMWai3MlAaQ3F7li/Et7rSJVV09Fpei+A==",+ "license": "MPL-2.0"+ },"node_modules/@irys/arweave": {"version": "0.0.2","resolved": "https://registry.npmjs.org/@irys/arweave/-/arweave-0.0.2.tgz",@@ -9873,6 +9881,16 @@"node": ">=8"}},+ "node_modules/@jaames/iro": {+ "version": "5.5.2",+ "resolved": "https://registry.npmjs.org/@jaames/iro/-/iro-5.5.2.tgz",+ "integrity": "sha512-Fbi5U4Vdkw6UsF+R3oMlPONqkvUDMkwzh+mX718gQsDFt3+1r1jvGsrfCbedmXAAy0WsjDHOrefK0BkDk99TQg==",+ "license": "MPL-2.0",+ "dependencies": {+ "@irojs/iro-core": "^1.2.1",+ "preact": "^10.0.0"+ }+ },"node_modules/@jest/console": {"version": "30.3.0","resolved": "https://registry.npmjs.org/@jest/console/-/console-30.3.0.tgz",@@ -30119,6 +30137,15 @@"node": ">= 0.12.0"}},+ "node_modules/cockatiel": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/cockatiel/-/cockatiel-4.0.0.tgz",+ "integrity": "sha512-XpUZJnogsd03BGB19T9sv7Xb8SwvD8JddZV2Tlp0LNspopZ6Idv24ZwCl8vAGJ6JwODZ0zLRYVj3NWvmRcUDqA==",+ "license": "MIT",+ "engines": {+ "node": ">=22"+ }+ },"node_modules/collect-v8-coverage": {"version": "1.0.3","resolved": "https://registry.npmjs.org/collect-v8-coverage/-/collect-v8-coverage-1.0.3.tgz",@@ -45281,7 +45308,6 @@"resolved": "https://registry.npmjs.org/preact/-/preact-10.24.2.tgz","integrity": "sha512-1cSoF0aCC8uaARATfrlz4VCBqE8LwZwRfLgkxJOQwAlQt6ayTmi0D9OF7nXid1POI5SZidFuG9CnlXbDfLqY/Q==","license": "MIT",- "optional": true,"funding": {"type": "opencollective","url": "https://opencollective.com/preact"diff --git a/package.json b/package.jsonindex dc7aaebbd..eee1ab890 100644--- a/package.json+++ b/package.json@@ -190,6 +190,7 @@"@gltf-transform/functions": "^4.4.0","@grpc/grpc-js": "^1.14.4","@grpc/proto-loader": "^0.8.1",+ "@jaames/iro": "^5.5.2","@jup-ag/api": "^6.0.48","@mediapipe/tasks-vision": "^0.10.35","@metaplex-foundation/js": "^0.20.1",@@ -255,6 +256,7 @@"borsher": "^4.0.0","bs58": "^6.0.0","cborg": "^4.5.8",+ "cockatiel": "^4.0.0","colyseus": "^0.17.10","colyseus.js": "0.16.22","dat.gui": "^0.7.9",diff --git a/pages/tour.html b/pages/tour.htmlindex a42a8ee53..3d9dac568 100644--- a/pages/tour.html+++ b/pages/tour.html@@ -526,7 +526,6 @@}document.getElementById('tour-resume-link').addEventListener('click', (e) => {e.preventDefault();- const param = inProgress ? '?tour=1' : '?tour=1';fetch('/tour/curriculum.json', { cache: 'force-cache' }).then((r) => r.json()).then((c) => {@@ -548,9 +547,9 @@);} catch (_) {}}- location.href = (stop ? stop.path : '/') + param;+ location.href = (stop ? stop.path : '/') + '?tour=1';})- .catch(() => (location.href = '/' + param));+ .catch(() => (location.href = '/?tour=1'));});})();diff --git a/public/changelog.json b/public/changelog.jsonindex 853044f2f..5efeef971 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-21T07:38:52.775Z",+ "generated_at": "2026-06-21T07:43:25.312Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -250,6 +250,17 @@"improvement"]},+ {+ "date": "2026-06-21",+ "type": "update",+ "title": "Imported avatars now animate with correct arm and leg orientation",+ "summary": "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.",+ "link": null,+ "tags": [+ "fix",+ "improvement"+ ]+ },{"date": "2026-06-21","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 383be0ad9..a1f6247a4 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -190,6 +190,14 @@<category>fix</category><description>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.</description></item>+ <item>+ <title>Imported avatars now animate with correct arm and leg orientation</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-21:Imported avatars now animate with correct arm and leg orientation</guid>+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>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.</description>+ </item><item><title>Live market feed stays up through provider blips</title><link>https://three.ws/changelog</link>diff --git a/public/environments/beach/dialogue.json b/public/environments/beach/dialogue.jsonnew file mode 100644index 000000000..c850f4e2e--- /dev/null+++ b/public/environments/beach/dialogue.json@@ -0,0 +1,25 @@+{+ "$schema": "NPC dialogue table for the walk scene (Task 19). Slots: greeter, guide-wait, guide-arrive ({landmark} token). landmarks steer the guide NPC.",+ "greeter": [+ "Welcome to the beach — mind the warm sand.",+ "Hey there. The water's perfect today.",+ "Glad you came down. Grab a parasol if the sun's too much.",+ "Welcome in. The tide's calm, the view's all yours."+ ],+ "guide-wait": [+ "Take your time — I'll wait by the shoreline.",+ "No rush, the waves keep good company.",+ "I'll hold here in the shade until you're ready."+ ],+ "guide-arrive": [+ "Here we are — {landmark}.",+ "This is {landmark}. Best seat on the coast.",+ "Welcome to {landmark}. Listen to that surf."+ ],+ "landmarks": [+ { "name": "the palm grove", "pos": [-4.314, 0, 5.217] },+ { "name": "the parasols", "pos": [4.33, 0, 1.355] },+ { "name": "the water's edge", "pos": [0, 0, 9] },+ { "name": "the far dune", "pos": [-4.779, 0, -7.944] }+ ]+}diff --git a/public/environments/cyberpunk/dialogue.json b/public/environments/cyberpunk/dialogue.jsonnew file mode 100644index 000000000..312ce8648--- /dev/null+++ b/public/environments/cyberpunk/dialogue.json@@ -0,0 +1,25 @@+{+ "$schema": "NPC dialogue table for the walk scene (Task 19). Slots: greeter, guide-wait, guide-arrive ({landmark} token). landmarks steer the guide NPC.",+ "greeter": [+ "Welcome to the strip — neon never sleeps here.",+ "Hey. Watch the puddles, the lights look better in them anyway.",+ "Glad you dropped in. The signs are louder than they look.",+ "Welcome in. Stick to the glow and you won't get lost."+ ],+ "guide-wait": [+ "Take your time — I'll wait under the sign.",+ "No rush. The city runs all night.",+ "I'll hold here by the lights until you catch up."+ ],+ "guide-arrive": [+ "Here we go — {landmark}.",+ "This is {landmark}. Best view of the towers.",+ "We made it to {landmark}. Soak in the neon."+ ],+ "landmarks": [+ { "name": "the holo signs", "pos": [5.975, 0, 5.769] },+ { "name": "the tower base", "pos": [-8.31, 0, 6.546] },+ { "name": "the rain-dark alley", "pos": [-1.604, 0, -9.815] },+ { "name": "the east overpass", "pos": [8.21, 0, -1.985] }+ ]+}diff --git a/public/environments/gallery/dialogue.json b/public/environments/gallery/dialogue.jsonnew file mode 100644index 000000000..058f15a20--- /dev/null+++ b/public/environments/gallery/dialogue.json@@ -0,0 +1,25 @@+{+ "$schema": "NPC dialogue table for the walk scene (Task 19). Slots: greeter, guide-wait, guide-arrive ({landmark} token). landmarks steer the guide NPC.",+ "greeter": [+ "Welcome to the gallery — every wall has something to say.",+ "Hello, and welcome in. Feel free to take it all in slowly.",+ "Glad you're here. The collection rotates, so look closely.",+ "Welcome. Quiet steps, open mind — enjoy the show."+ ],+ "guide-wait": [+ "Take your time with the pieces — I'll wait here.",+ "No rush. Good art rewards a slow walk.",+ "I'll pause by the pedestal until you're ready."+ ],+ "guide-arrive": [+ "This way — {landmark}.",+ "Here's {landmark}. One of my favourites in the space.",+ "We've reached {landmark}. Worth a long look."+ ],+ "landmarks": [+ { "name": "the central pedestals", "pos": [0, 0, 3.6] },+ { "name": "the east wall", "pos": [7.361, 0, 4.25] },+ { "name": "the north exhibit", "pos": [0, 0, 8.5] },+ { "name": "the west gallery", "pos": [-8.5, 0, 0] }+ ]+}diff --git a/public/environments/office/dialogue.json b/public/environments/office/dialogue.jsonnew file mode 100644index 000000000..92681ccee--- /dev/null+++ b/public/environments/office/dialogue.json@@ -0,0 +1,25 @@+{+ "$schema": "NPC dialogue table for the walk scene (Task 19). Slots: greeter, guide-wait, guide-arrive ({landmark} token). landmarks steer the guide NPC.",+ "greeter": [+ "Welcome to the three.ws office — make yourself at home.",+ "Hey, good to have you in. Desks are open, wander freely.",+ "Welcome aboard. The plants are real, the coffee's hot.",+ "Glad you stopped by. Take a lap, see the whole floor."+ ],+ "guide-wait": [+ "Take your time — I'll wait by the desks.",+ "No rush, the floor's quiet today.",+ "I'll hold here until you're ready to move on."+ ],+ "guide-arrive": [+ "And this is — {landmark}.",+ "Here's {landmark}. Heart of the place.",+ "We've reached {landmark}. Have a look around."+ ],+ "landmarks": [+ { "name": "the brand wall", "pos": [0, 0, 2.6] },+ { "name": "the east desks", "pos": [4.147, 0, 1.753] },+ { "name": "the plant corner", "pos": [-4.525, 0, 4.525] },+ { "name": "the south meeting space", "pos": [-0.573, 0, -4.615] }+ ]+}diff --git a/public/environments/park/dialogue.json b/public/environments/park/dialogue.jsonnew file mode 100644index 000000000..6eb92cea4--- /dev/null+++ b/public/environments/park/dialogue.json@@ -0,0 +1,25 @@+{+ "$schema": "NPC dialogue table for the walk scene (Task 19). Slots: greeter, guide-wait, guide-arrive ({landmark} token). landmarks steer the guide NPC.",+ "greeter": [+ "Welcome to the park — the grass is yours to wander.",+ "Hey, glad you made it. Plenty of shade if you want it.",+ "Good to see you out here. Take the long way around.",+ "Welcome in. The benches are a nice spot to pause."+ ],+ "guide-wait": [+ "Take your time — I'll wait by the path.",+ "No rush, the park isn't going anywhere.",+ "I'll hold up here until you catch up."+ ],+ "guide-arrive": [+ "And here we are — {landmark}.",+ "This is {landmark}. Lovely under the trees, isn't it?",+ "Welcome to {landmark}. Stay as long as you like."+ ],+ "landmarks": [+ { "name": "the old shade tree", "pos": [-4.15, 0, 4.167] },+ { "name": "the far benches", "pos": [2.6, 0, -1.6] },+ { "name": "the north lawn", "pos": [-0.271, 0, 9.848] },+ { "name": "the south clearing", "pos": [0.347, 0, -8.791] }+ ]+}diff --git a/public/environments/void/dialogue.json b/public/environments/void/dialogue.jsonnew file mode 100644index 000000000..d12734a71--- /dev/null+++ b/public/environments/void/dialogue.json@@ -0,0 +1,25 @@+{+ "$schema": "NPC dialogue table for the walk scene (Task 19). Slots: greeter, guide-wait, guide-arrive ({landmark} token). landmarks steer the guide NPC.",+ "greeter": [+ "Welcome to the void — nothing here but focus.",+ "Hey. Pure grid, pure quiet. Wander as far as you like.",+ "Glad you came. Sometimes empty space is the point.",+ "Welcome in. No distractions out here — just you."+ ],+ "guide-wait": [+ "Take your time — I'll wait on the grid.",+ "No rush. There's nowhere to be but here.",+ "I'll hold this spot until you catch up."+ ],+ "guide-arrive": [+ "Here — {landmark}.",+ "This is {landmark}, such as it is.",+ "We've reached {landmark}. Breathe it in."+ ],+ "landmarks": [+ { "name": "the grid's edge", "pos": [0, 0, -8] },+ { "name": "the far marker", "pos": [8, 0, 0] },+ { "name": "the quiet corner", "pos": [0, 0, 8] },+ { "name": "the open expanse", "pos": [-8, 0, 0] }+ ]+}diff --git a/public/features.json b/public/features.jsonindex 8b11091e7..4bb25c227 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-21T07:38:52.762Z",+ "generated_at": "2026-06-21T07:43:25.291Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/public/notifications.js b/public/notifications.jsindex 71d1bbc92..78b2fe786 100644--- a/public/notifications.js+++ b/public/notifications.js@@ -207,6 +207,20 @@return { icon: '↻', href: p.link || '/dashboard', parts: ['Someone remixed your creation'] };case 'reply':return { icon: '“', href: p.link || agentHref, parts: ['You have a new reply'] };+ case 'follow':+ return {+ icon: '+',+ href: p.link || (p.follower_username ? '/u/' + encodeURIComponent(p.follower_username) : '/feed'),+ parts: [bold(p.actor || 'Someone'), ' followed you'],+ };+ case 'agent_review': {+ var stars = p.rating ? ' ' + '★'.repeat(Math.max(1, Math.min(5, p.rating))) : '';+ return {+ icon: '★',+ href: p.link || agentHref,+ parts: [bold(p.actor || 'Someone'), ' reviewed ', bold(p.agent_name || 'your agent'), stars],+ };+ }default:return { icon: '•', href: p.link || '/dashboard', parts: [titleCase(n.type) || 'New notification'] };}diff --git a/public/tour/curriculum.json b/public/tour/curriculum.jsonindex fefbf99d0..dfcc11211 100644--- a/public/tour/curriculum.json+++ b/public/tour/curriculum.json@@ -1,6 +1,6 @@{"version": 2,- "generatedAt": "2026-06-21T07:29:15.186Z",+ "generatedAt": "2026-06-21T07:32:34.837Z","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/scripts/build-canonical-rest.mjs b/scripts/build-canonical-rest.mjsindex 2280312e8..fff5a03a3 100644--- a/scripts/build-canonical-rest.mjs+++ b/scripts/build-canonical-rest.mjs@@ -18,6 +18,7 @@import fs from 'node:fs';import path from 'node:path';import { fileURLToPath } from 'node:url';+import { Quaternion } from 'three';import { canonicalizeBoneName } from '../src/glb-canonicalize.js';const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');@@ -38,15 +39,43 @@ function readGlbJson(file) {const gltf = readGlbJson(REFERENCE_RIG);const nodes = gltf.nodes || [];+// Each glTF node's local rotation (identity [0,0,0,1] when omitted).+const localQuat = (i) => {+ const r = Array.isArray(nodes[i]?.rotation) ? nodes[i].rotation : [0, 0, 0, 1];+ return new Quaternion(r[0], r[1], r[2], r[3]);+};++// child index → parent index, so we can compose each bone's WORLD bind rotation.+const parentOf = new Array(nodes.length).fill(-1);+for (let i = 0; i < nodes.length; i++) {+ for (const c of nodes[i]?.children || []) parentOf[c] = i;+}++// World bind rotation of node i = parentWorld · local, composed up the scene+// graph. Mirrors src/animation-retarget.js's runtime world composition (pure+// quaternion product of ancestor rotations), so source and target are measured+// in the same frame. Rotation-only — uniform-scale humanoid rigs carry no shear.+const worldCache = new Map();+function worldQuat(i) {+ if (worldCache.has(i)) return worldCache.get(i);+ const q = localQuat(i);+ if (parentOf[i] !== -1) q.premultiply(worldQuat(parentOf[i]));+ worldCache.set(i, q);+ return q;+}+// First occurrence wins, matching canonicalRestMapFromObject's traversal order.const rest = new Map();-for (const node of nodes) {+const restWorld = new Map();+for (let i = 0; i < nodes.length; i++) {+ const node = nodes[i];if (!node?.name) continue;const canonical = canonicalizeBoneName(node.name);if (!canonical || rest.has(canonical)) continue;// glTF node rotation defaults to identity [0,0,0,1] when omitted.- const r = Array.isArray(node.rotation) ? node.rotation : [0, 0, 0, 1];- rest.set(canonical, r);+ rest.set(canonical, Array.isArray(node.rotation) ? node.rotation : [0, 0, 0, 1]);+ const w = worldQuat(i);+ restWorld.set(canonical, [w.x, w.y, w.z, w.w]);}if (rest.size === 0) throw new Error(`${REFERENCE_RIG}: no canonical bones found`);@@ -56,22 +85,33 @@ const sorted = [...rest.entries()].sort((a, b) => a[0].localeCompare(b[0]));const body = sorted.map(([bone, q]) => `\t${bone}: [${q.map((n) => +n).join(', ')}],`).join('\n');+const worldBody = sorted+ .map(([bone]) => `\t${bone}: [${restWorld.get(bone).map((n) => +n).join(', ')}],`)+ .join('\n');const out = `// GENERATED by scripts/build-canonical-rest.mjs from public/avatars/cz.glb.// Do not edit by hand — re-run the generator instead.//-// Each entry is a canonical bone's local rest (bind-pose) quaternion [x,y,z,w]-// on the Avaturn reference rig the clip library is authored against. Consumed by-// src/animation-retarget.js to replay clip motion in a target rig's own rest-// frame (Ta = Tr · Sr⁻¹ · Sa), so clips authored for cz's A-pose drive a-// Mixamo T-pose (or any rig) without breaking limb poses. Values are verbatim-// from cz.glb so retargeting onto cz is identity → byte-for-byte round-trip.+// CANONICAL_REST — each canonical bone's LOCAL rest (bind-pose) quaternion+// [x,y,z,w] on the Avaturn reference rig the clip library is authored against.+// CANONICAL_REST_WORLD — the same bones' WORLD (model-space) bind rotations,+// composed up cz's scene graph. Both feed src/animation-retarget.js's bind+// correction q' = L·q·R (L = Rt·WT⁻¹·WS·Rs⁻¹, R = WS⁻¹·WT), which replays a+// clip bone's motion as the SAME world-space delta on a target rig of any rest+// pose — fixing the ~30° limb skew a local-only premultiply produced on+// non-cz rigs (A-pose vs T-pose), while still correcting the Hips up-axis+// convention. Local values are verbatim from cz.glb so retargeting onto cz is+// identity (L=R=I within FP noise) → byte-for-byte round-trip.export const CANONICAL_REST = Object.freeze({${body}});++export const CANONICAL_REST_WORLD = Object.freeze({+${worldBody}+});`;fs.writeFileSync(OUT, out);-console.log(`wrote ${path.relative(ROOT, OUT)} — ${rest.size} canonical bones`);+console.log(`wrote ${path.relative(ROOT, OUT)} — ${rest.size} canonical bones (local + world)`);console.log('bones:', sorted.map(([b]) => b).join(', '));diff --git a/scripts/build-vercel.mjs b/scripts/build-vercel.mjsindex e574b3026..5a0cc7dde 100644--- a/scripts/build-vercel.mjs+++ b/scripts/build-vercel.mjs@@ -8,12 +8,31 @@* - Clear timing + error reporting*/import { execSync, spawn } from 'child_process';+import { createRequire } from 'module';import { existsSync } from 'fs';import { resolve, dirname } from 'path';import { fileURLToPath } from 'url';import { isCached, writeStamp } from './build-cache.mjs';const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');+const require = createRequire(import.meta.url);++// Resolve a dev tool's CLI entry through Node module resolution instead of the+// `.bin/<tool>` shim. Vercel restores a cached `node_modules` between builds+// but does NOT always recreate the `.bin/` symlinks — so the package dir is+// present while `.bin/<tool>` is missing, and `npx <tool>` dies with+// "<tool>: not found" in <1s, failing the deploy though nothing regressed.+// This exact stripped-bin hit the test gate (2026-06-21); the build's other+// tool invocations (tsc, vite) share the landmine, so route them all through+// the package's own bin file, which needs only the (intact) package directory.+// Returns a shell-quoted absolute path safe to splice into an `sh -c` command.+function binCli(pkg, binName = pkg) {+ const pkgJsonPath = require.resolve(`${pkg}/package.json`);+ const bin = require(pkgJsonPath).bin;+ const rel = typeof bin === 'string' ? bin : bin?.[binName];+ if (!rel) throw new Error(`[build:vercel] ${pkg} exposes no \`${binName}\` bin entry`);+ return JSON.stringify(resolve(dirname(pkgJsonPath), rel));+}const running = new Set();@@ -152,7 +171,7 @@ async function prebuild() {// deploy build is the only automated checkpoint, so a type error in a// ratcheted file (see jsconfig.json) fails the deploy instead of shipping.// Cheap (~5s) and has already caught a real prod bug (elevenlabs voice_id).- await run('typecheck', 'npx tsc -p jsconfig.json');+ await run('typecheck', `node ${binCli('typescript', 'tsc')} -p jsconfig.json`);await Promise.all([run('build:news', 'node scripts/build-news.mjs'),run('build:skill-metadata', 'node scripts/build-skill-metadata.mjs'),@@ -173,12 +192,12 @@ async function prebuild() {}async function buildLib() {- await run('build:lib', 'TARGET=lib npx vite build');+ await run('build:lib', `TARGET=lib node ${binCli('vite')} build`);await run('avatar-sdk', 'node avatar-sdk/build.mjs');}async function buildApp() {- await run('build:app', 'npx vite build && node scripts/strip-sw-from-embeds.mjs', {+ await run('build:app', `node ${binCli('vite')} build && node scripts/strip-sw-from-embeds.mjs`, {env: { NODE_OPTIONS: '--no-deprecation --max-old-space-size=6144' },});}diff --git a/scripts/copy-avatar-studio.mjs b/scripts/copy-avatar-studio.mjsindex fe42c4780..8516a6ca5 100644--- a/scripts/copy-avatar-studio.mjs+++ b/scripts/copy-avatar-studio.mjs@@ -12,9 +12,30 @@ const root = resolve(here, '..');const src = resolve(root, 'character-studio/build');const dest = resolve(root, 'dist/avatar-studio');-if (existsSync(src)) {- cpSync(src, dest, { recursive: true });- console.log('[copy-avatar-studio] dist/avatar-studio populated');-} else {- console.warn('[copy-avatar-studio] character-studio/build/ missing — avatar-studio not in dist');+// On Vercel the avatar studio is built (phase 3) before this copy (phase 5), so+// a missing source here means the studio SPA would be absent from dist and+// /avatar-studio/ — a live, nav-linked production route — would 404 silently.+// Fail the deploy loudly rather than ship a 404. Locally (no VERCEL env) the+// studio may legitimately be unbuilt, so stay a warning there.+const isVercel = Boolean(process.env.VERCEL);++if (!existsSync(src)) {+ const msg = '[copy-avatar-studio] character-studio/build/ missing — avatar-studio would 404 in production';+ if (isVercel) {+ console.error(`${msg}; failing the build (run \`npm run build --prefix character-studio\` first)`);+ process.exit(1);+ }+ console.warn(`${msg} (skipped: not a Vercel build)`);+ process.exit(0);+}++cpSync(src, dest, { recursive: true });++// A source that exists but copies to an empty/incomplete dest (e.g. the SPA+// build emitted no entry HTML) is just as broken as a missing one — verify the+// served entry point actually landed before declaring success.+if (!existsSync(resolve(dest, 'index.html'))) {+ console.error('[copy-avatar-studio] dist/avatar-studio/index.html missing after copy — incomplete studio build');+ if (isVercel) process.exit(1);}+console.log('[copy-avatar-studio] dist/avatar-studio populated');diff --git a/scripts/test-gate.mjs b/scripts/test-gate.mjsindex 05aa3a3ca..c9fad2dba 100644--- a/scripts/test-gate.mjs+++ b/scripts/test-gate.mjs@@ -18,6 +18,7 @@*/import { execFileSync } from 'child_process';import { createRequire } from 'module';+import { existsSync } from 'fs';import { resolve, dirname, join } from 'path';import { fileURLToPath } from 'url';@@ -53,6 +54,21 @@ const GATE_TESTS = [console.log(`[test-gate] running ${GATE_TESTS.length} critical-path test files…`);+// On Vercel the repo is cloned and then `.vercelignore` paths are STRIPPED before+// the build runs. `tests/` is ignored to keep the suite out of the deploy upload,+// so each gate file must be explicitly re-included in `.vercelignore`. If one is+// missing here, vitest would just print a cryptic "No test files found" and exit+// 1 — indistinguishable from a real regression. Detect it ourselves and fail with+// a message that names the file and points at the actual fix.+const missing = GATE_TESTS.filter((t) => !existsSync(resolve(ROOT, t)));+if (missing.length) {+ console.error(`[test-gate] ✗ ${missing.length} gate test file(s) absent from the build context:`);+ for (const m of missing) console.error(`[test-gate] ${m}`);+ console.error('[test-gate] These are stripped by .vercelignore (which excludes tests/). Re-include each');+ console.error('[test-gate] gate file there with a `!` negation — keep .vercelignore in sync with GATE_TESTS.');+ process.exit(1);+}+let vitestCli;try {vitestCli = resolveVitestCli();diff --git a/scripts/x402-register-discovery.mjs b/scripts/x402-register-discovery.mjsnew file mode 100644index 000000000..dc3f31941--- /dev/null+++ b/scripts/x402-register-discovery.mjs@@ -0,0 +1,139 @@+// Register three.ws's paid x402 endpoints with open discovery indexes so agents+// can find and pay them. Reads our OWN live discovery catalog+// (https://three.ws/.well-known/x402.json) as the single source of truth — no+// hardcoded endpoint list — and maps each resource onto the 402index.io /+// x402search register schema.+//+// The CDP Bazaar needs no submission (it auto-catalogs on first CDP-facilitator+// settlement); this script handles the open indexes that take a direct POST.+//+// Usage:+// node scripts/x402-register-discovery.mjs # DRY RUN — prints payloads, sends nothing+// node scripts/x402-register-discovery.mjs --live # actually submit+// node scripts/x402-register-discovery.mjs --live --limit 8 # respect 10/hr/IP rate cap+// node scripts/x402-register-discovery.mjs --only model-check,fact-check # filter by path/name+//+// 402index.io: POST /api/v1/register — no API key, rate-limited 10 registrations/hour/IP.++const CATALOG_URL = process.env.X402_CATALOG_URL || 'https://three.ws/.well-known/x402.json';+const REGISTER_URL = process.env.X402_REGISTER_URL || 'https://402index.io/api/v1/register';+const PROVIDER = 'three.ws';+const CONTACT_EMAIL = '[email protected]';++function parseArgs(argv) {+ const args = { live: false, limit: Infinity, only: null, skip: 0 };+ for (let i = 0; i < argv.length; i++) {+ const a = argv[i];+ if (a === '--live') args.live = true;+ else if (a === '--limit') args.limit = Math.max(1, Number(argv[++i]) || Infinity);+ else if (a === '--skip') args.skip = Math.max(0, Number(argv[++i]) || 0);+ else if (a === '--only') args.only = String(argv[++i] || '').split(',').map((s) => s.trim()).filter(Boolean);+ }+ return args;+}++function usdFromPrice(accept) {+ if (accept?.price && /\$[\d.]+/.test(accept.price)) return Number(accept.price.replace(/[^\d.]/g, ''));+ const decimals = Number(accept?.extra?.decimals ?? 6);+ if (accept?.amount != null) return Number(accept.amount) / 10 ** decimals;+ return undefined;+}++// Map one catalog resource → a 402index register payload. Prefer the Solana+// accept's network label when present (so the index shows our multi-chain+// support), else the first accept.+function toRegistration(resource) {+ const accepts = Array.isArray(resource.accepts) ? resource.accepts : [];+ const primary = accepts[0] || {};+ const networks = [...new Set(accepts.map((a) => a.network_label || a.network).filter(Boolean))];+ const reg = {+ url: resource.url,+ name: resource.serviceName || resource.path || resource.url,+ protocol: 'x402',+ http_method: (resource.method || 'GET').toUpperCase(),+ description: resource.description || undefined,+ price_usd: usdFromPrice(primary),+ payment_asset: primary.asset_symbol || 'USDC',+ payment_network: networks.join(', ') || undefined,+ category: (resource.tags && resource.tags[0]) || 'ai-agents',+ provider: PROVIDER,+ contact_email: CONTACT_EMAIL,+ };+ // POST endpoints that validate a body: hand the index a probe body so its+ // compliance check can reach the 402 instead of a 400.+ const input = resource.extensions?.bazaar?.info?.input;+ if (reg.http_method !== 'GET' && input && input.body) {+ reg.probe_body = typeof input.body === 'string' ? input.body : JSON.stringify(input.body);+ }+ // Drop undefined keys for a clean payload.+ return Object.fromEntries(Object.entries(reg).filter(([, v]) => v !== undefined));+}++async function main() {+ const args = parseArgs(process.argv.slice(2));+ process.stdout.write(`\nDiscovery registration → ${REGISTER_URL}\nCatalog: ${CATALOG_URL}\nMode: ${args.live ? 'LIVE (submitting)' : 'DRY RUN (nothing sent)'}\n\n`);++ const res = await fetch(CATALOG_URL);+ if (!res.ok) throw new Error(`could not fetch catalog: HTTP ${res.status}`);+ const catalog = await res.json();+ let resources = Array.isArray(catalog.resources) ? catalog.resources : [];+ if (args.only) {+ resources = resources.filter((r) =>+ args.only.some((t) => (r.path || '').includes(t) || (r.serviceName || '').toLowerCase().includes(t.toLowerCase())),+ );+ }++ // Dedupe by URL: MCP servers (/api/mcp, /api/mcp-3d) are cataloged once per+ // tool but are a SINGLE payable endpoint — register each URL once (first+ // occurrence keeps the richest metadata).+ const byUrl = new Map();+ for (const r of resources.map(toRegistration)) {+ if (r.url && r.name && !byUrl.has(r.url)) byUrl.set(r.url, r);+ }+ const regs = [...byUrl.values()];+ const after = regs.slice(args.skip);+ const slice = after.slice(0, args.limit === Infinity ? after.length : args.limit);+ process.stdout.write(`${regs.length} resources in catalog · submitting ${args.live ? slice.length : 0}${args.limit !== Infinity ? ` (limit ${args.limit})` : ''}\n\n`);++ let ok = 0;+ let failed = 0;+ for (const reg of slice) {+ const label = `${reg.name} (${reg.http_method} ${new URL(reg.url).pathname})`;+ if (!args.live) {+ process.stdout.write(`• ${label} — $${reg.price_usd ?? '?'} ${reg.payment_asset} on ${reg.payment_network || '?'}\n`);+ continue;+ }+ try {+ const r = await fetch(REGISTER_URL, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(reg),+ });+ const text = await r.text();+ if (r.ok) {+ ok++;+ process.stdout.write(`✓ ${label} — ${r.status}\n`);+ } else if (r.status === 409 || /exists|duplicate|already/i.test(text)) {+ ok++;+ process.stdout.write(`= ${label} — already listed (${r.status})\n`);+ } else if (r.status === 429) {+ process.stdout.write(`\n⚠ Rate limited (10/hr/IP). Stopping — re-run later for the rest.\n`);+ break;+ } else {+ failed++;+ process.stdout.write(`✗ ${label} — ${r.status}: ${text.slice(0, 160)}\n`);+ }+ } catch (err) {+ failed++;+ process.stdout.write(`✗ ${label} — ${err.message}\n`);+ }+ }++ if (args.live) process.stdout.write(`\nDone. ${ok} listed/ok, ${failed} failed, ${Math.max(0, regs.length - slice.length)} not attempted.\n`);+ else process.stdout.write(`\nDry run only. Re-run with --live to submit (respecting the 10/hr/IP cap with --limit).\n`);+}++main().catch((err) => {+ process.stderr.write(`\n✗ ${err.message}\n`);+ process.exit(1);+});diff --git a/src/animation-canonical-rest.js b/src/animation-canonical-rest.jsindex cc7103990..a1f1ecbd2 100644--- a/src/animation-canonical-rest.js+++ b/src/animation-canonical-rest.js@@ -1,12 +1,16 @@// GENERATED by scripts/build-canonical-rest.mjs from public/avatars/cz.glb.// Do not edit by hand — re-run the generator instead.//-// Each entry is a canonical bone's local rest (bind-pose) quaternion [x,y,z,w]-// on the Avaturn reference rig the clip library is authored against. Consumed by-// src/animation-retarget.js to replay clip motion in a target rig's own rest-// frame (Ta = Tr · Sr⁻¹ · Sa), so clips authored for cz's A-pose drive a-// Mixamo T-pose (or any rig) without breaking limb poses. Values are verbatim-// from cz.glb so retargeting onto cz is identity → byte-for-byte round-trip.+// CANONICAL_REST — each canonical bone's LOCAL rest (bind-pose) quaternion+// [x,y,z,w] on the Avaturn reference rig the clip library is authored against.+// CANONICAL_REST_WORLD — the same bones' WORLD (model-space) bind rotations,+// composed up cz's scene graph. Both feed src/animation-retarget.js's bind+// correction q' = L·q·R (L = Rt·WT⁻¹·WS·Rs⁻¹, R = WS⁻¹·WT), which replays a+// clip bone's motion as the SAME world-space delta on a target rig of any rest+// pose — fixing the ~30° limb skew a local-only premultiply produced on+// non-cz rigs (A-pose vs T-pose), while still correcting the Hips up-axis+// convention. Local values are verbatim from cz.glb so retargeting onto cz is+// identity (L=R=I within FP noise) → byte-for-byte round-trip.export const CANONICAL_REST = Object.freeze({Head: [-0.11706881878098431, 9.438845082943482e-9, 3.72654613409334e-8, 0.993123804804428],@@ -62,3 +66,58 @@ export const CANONICAL_REST = Object.freeze({Spine1: [-0.03815628571181615, 2.0010687323521798e-8, 5.34807122500512e-9, 0.9992717837809081],Spine2: [-0.056998031890724846, 1.3546308636882866e-7, -8.861325315468363e-10, 0.9983742907149431],});++export const CANONICAL_REST_WORLD = Object.freeze({+ Head: [-0.005402766806732544, -1.5440620455356296e-7, 8.34223242528311e-10, 0.9999854049488961],+ Hips: [0.0010741148761599644, 6.537898515070053e-8, 7.022659074474357e-11, 0.9999994231384476],+ LeftArm: [0.4889318420664182, 0.5108287295941205, -0.5108290884863605, 0.48893078190839623],+ LeftFoot: [-0.00007112359875637768, 0.5349085331963127, 0.8448985998862468, -0.004383145577274271],+ LeftForeArm: [0.49521300584988104, 0.5047420653526237, -0.5047420379230214, 0.4952120815979495],+ LeftHand: [0.5009334720626235, 0.5016127781291206, -0.4977959877649929, 0.49964931327533474],+ LeftHandIndex1: [0.5480286232738694, 0.46388966319384123, -0.47756977349452234, 0.506357703809076],+ LeftHandIndex2: [0.5522711480640051, 0.4734474077351049, -0.46714980714345783, 0.5026083894226862],+ LeftHandIndex3: [0.5405471533897316, 0.46903549072233974, -0.4790521335412708, 0.5082553896043159],+ LeftHandMiddle1: [0.5069366564823887, 0.46312011824587895, -0.5184714785961669, 0.5096295836965867],+ LeftHandMiddle2: [0.5047591066222094, 0.46656986579426646, -0.5196237813564338, 0.5074661907650336],+ LeftHandMiddle3: [0.5066805225023663, 0.46639751835165716, -0.5160243364733309, 0.509379123507728],+ LeftHandPinky1: [0.4459394011607033, 0.4793433042957962, -0.5586434331057456, 0.5092009093395086],+ LeftHandPinky2: [0.4453638702749085, 0.48032344738196137, -0.5573549331147079, 0.5101920146245817],+ LeftHandPinky3: [0.4392981168466072, 0.4802964151504903, -0.5615019919023976, 0.5109286011992389],+ LeftHandRing1: [0.47371996160924823, 0.4931227775910745, -0.5418410288696247, 0.4886999364902444],+ LeftHandRing2: [0.48665266892609377, 0.49620490515614146, -0.5291888435031511, 0.48673303168821197],+ LeftHandRing3: [0.48945530931580683, 0.4902132045285772, -0.5280743092981476, 0.4911843263440915],+ LeftHandThumb1: [0.6991138207882592, 0.16132571576360077, -0.40704633814367386, 0.5652673372230799],+ LeftHandThumb2: [0.64766423234777, 0.2923511094450446, -0.5391393932239583, 0.4520957758831027],+ LeftHandThumb3: [0.6626872004096495, 0.3080994487427915, -0.5067905211225114, 0.45725679518685386],+ LeftLeg: [0.0006202111480182034, -0.020805293540463354, 0.9997832430476497, -0.00047118992773536965],+ LeftShoulder: [0.4605450937998788, 0.4559956590278878, -0.537559006794696, 0.5394409087622226],+ LeftToeBase: [-0.002764355526654178, 0.7195640056310856, 0.6944147145329627, -0.0028643286082629046],+ LeftUpLeg: [-0.00004987623525000119, 0.0021826506059020026, 0.9999975399461294, -0.00039198262713485737],+ Neck: [0.11170149382802401, -1.628868597421303e-7, -1.8309282630496044e-8, 0.9937418056399563],+ RightArm: [0.48893190585215524, -0.510828798312402, 0.5108290283825504, 0.48893071200502375],+ RightFoot: [0.00007112360405196955, 0.5349085398019146, 0.844898595705669, 0.004383145306035045],+ RightForeArm: [0.4952130023257164, -0.5047420673116668, 0.5047420415306929, 0.49521208229448166],+ RightHand: [0.5009334695181179, -0.5016127792807403, 0.49779599067075153, 0.49964931459617906],+ RightHandIndex1: [0.5480286139806538, -0.4638896746971551, 0.47756977858103167, 0.5063577013132781],+ RightHandIndex2: [0.5522711446711094, -0.4734474082706649, 0.4671498147721218, 0.5026083883587248],+ RightHandIndex3: [0.5405470934413514, -0.4690354263302402, 0.47905220274050364, 0.5082554503330304],+ RightHandMiddle1: [0.5069366680435416, -0.4631200623546733, 0.5184715098400317, 0.5096295939664325],+ RightHandMiddle2: [0.5047591061928465, -0.46656986723577604, 0.5196237819671778, 0.5074661920185282],+ RightHandMiddle3: [0.5066805195140975, -0.4663975225827095, 0.5160243369168757, 0.5093791249234989],+ RightHandPinky1: [0.44593939683725603, -0.4793433241517071, 0.5586434219640141, 0.5092009094272859],+ RightHandPinky2: [0.4453638073881448, -0.4803233923217868, 0.5573549834847424, 0.5101920690951159],+ RightHandPinky3: [0.4392981269307416, -0.4802964267888911, 0.5615019867791732, 0.5109285899785551],+ RightHandRing1: [0.473719957983008, -0.49312277921221886, 0.541841035805614, 0.4886999335659278],+ RightHandRing2: [0.48665266754747677, -0.4962049100848307, 0.5291888437972645, 0.4867330306200585],+ RightHandRing3: [0.4894553112113337, -0.49021320332208906, 0.5280743062058759, 0.4911843318554558],+ RightHandThumb1: [0.6991137732035737, -0.16132569450370315, 0.40704638897707807, 0.5652673641991798],+ RightHandThumb2: [0.6476641963757893, -0.2923511418798965, 0.5391394672107036, 0.45209571648691005],+ RightHandThumb3: [0.6626871862817486, -0.3080994479425299, 0.5067905521115058, 0.4572567801626834],+ RightLeg: [-0.0006202113471683521, -0.020805295090456907, 0.9997832430151556, 0.00047119017271936915],+ RightShoulder: [0.46054507521936333, -0.45599564278848104, 0.5375590232993736, 0.5394409245169026],+ RightToeBase: [0.0027643555231566678, 0.7195640416379069, 0.6944146772223956, 0.0028643286020973192],+ RightUpLeg: [0.000049925034443819034, 0.002182648459062353, 0.9999975399486299, 0.00039198198974856475],+ Spine: [-0.017258617754264162, -8.00818266828763e-8, 1.3823133775055108e-9, 0.9998510589648868],+ Spine1: [-0.055396652424023016, -5.997624651397324e-8, 3.32759956947242e-9, 0.9984644264570511],+ Spine2: [-0.11221710079276989, 7.513757486198981e-8, -8.485311473269302e-9, 0.9936837134066652],+});diff --git a/src/animation-retarget.js b/src/animation-retarget.jsindex 298d6d14a..904a3aadc 100644--- a/src/animation-retarget.js+++ b/src/animation-retarget.js@@ -16,7 +16,7 @@import { AnimationClip, Quaternion, Vector3 } from 'three';import { canonicalizeBoneName } from './glb-canonicalize.js';-import { CANONICAL_REST } from './animation-canonical-rest.js';+import { CANONICAL_REST, CANONICAL_REST_WORLD } from './animation-canonical-rest.js';// A clip retargets cleanly only when enough of its tracks find a home on the// target rig. Below this the motion would read as a few twitching joints rather@@ -42,6 +42,17 @@ const SOURCE_REST = new Map(Object.entries(CANONICAL_REST).map(([bone, q]) => [bone, new Quaternion(q[0], q[1], q[2], q[3])]),);+// World-space (model-frame) bind rotation of each canonical bone on the authoring+// rig. Paired with SOURCE_REST so the bind correction can preserve a clip bone's+// *world* motion delta (not just its local deviation) when the target rig rests+// in a different pose — see `bindCorrections`.+const SOURCE_WORLD_REST = new Map(+ Object.entries(CANONICAL_REST_WORLD).map(([bone, q]) => [+ bone,+ new Quaternion(q[0], q[1], q[2], q[3]),+ ]),+);+// A quaternion within this of identity (|w| ≈ 1) is treated as no rotation, so a// rig that already matches the authoring convention round-trips bit-for-bit.const BIND_EPSILON = 1e-6;@@ -145,35 +156,121 @@ export function canonicalRestMapFromRig(rig) {return map;}+// World (model-frame) bind rotation of a node: the pure-quaternion product of its+// ancestors' rotations down to `stopAt` (exclusive), times the node's own. Stops+// at the model root so a placement rotation the viewer applies to the whole avatar+// is excluded — the same frame SOURCE_WORLD_REST is measured in. Requires local+// rotations to be at bind pose (true at attach time).+function worldRestQuat(node, stopAt) {+ const q = node.quaternion.clone();+ for (let n = node.parent; n && n !== stopAt; n = n.parent) q.premultiply(n.quaternion);+ return q;+}+/**- * Per-bone bind correction `C = targetRest · sourceRest⁻¹`. Applying `C · q` to a- * clip keyframe replays the source bone's deviation-from-rest in the target- * bone's own rest frame, so a clip authored for one rest pose drives a rig with a- * different one (e.g. a Mixamo rig whose Hips bakes the up-axis as −90°X). Bones- * whose correction is identity are omitted, so a matching rig skips the work and- * round-trips unchanged.+ * World bind-rotation map by walking an Object3D graph — the world-frame companion+ * to {@link canonicalRestMapFromObject}, read in the same first-bone-wins order.+ * Excludes `root` so it matches {@link hipsParentWorldQuat}'s within-model frame.*- * @param {Map<string,import('three').Quaternion>|null} targetRest+ * @param {import('three').Object3D} root* @returns {Map<string,import('three').Quaternion>}*/-function bindCorrections(targetRest) {+export function canonicalWorldRestMapFromObject(root) {+ const map = new Map();+ const consider = (node) => {+ if (!node?.name) return;+ const canonical = canonicalizeBoneName(node.name);+ if (canonical && !map.has(canonical)) map.set(canonical, worldRestQuat(node, root));+ };+ const skinned = [];+ root.traverse((node) => {+ if (node.isSkinnedMesh) skinned.push(node);+ if (node.isBone) consider(node);+ });+ for (const sm of skinned) {+ for (const bone of sm.skeleton?.bones || []) consider(bone);+ }+ return map;+}++/**+ * World bind-rotation map from a GltfRig/MannequinRig. The rig is posed at the+ * origin (within-model == world), so we compose all the way to the top.+ *+ * @param {{ getBones: () => Array<{key:string,node:import('three').Object3D}> }} rig+ * @returns {Map<string,import('three').Quaternion>}+ */+export function canonicalWorldRestMapFromRig(rig) {+ const map = new Map();+ for (const { key, node } of rig.getBones?.() || []) {+ if (node && !map.has(key)) map.set(key, worldRestQuat(node, null));+ }+ return map;+}++/**+ * Per-bone bind correction `{L, R}` such that `q' = L · q · R` re-expresses a clip+ * bone's keyframe so it produces the SAME world-space rotation delta on a target+ * rig that rests in a different pose:+ *+ * L = Rt · WT⁻¹ · WS · Rs⁻¹ R = WS⁻¹ · WT+ *+ * where Rs/Rt are the source/target LOCAL bind rotations and WS/WT their WORLD+ * (model-frame) bind rotations. This is the standard world-delta-preserving+ * retarget (trgLocal = WTp⁻¹·WSp · q · WS⁻¹·WT, with the parent worlds derived as+ * WSp = WS·Rs⁻¹, WTp = WT·Rt⁻¹). It collapses to:+ * • the pure axis-convention reframe for the Hips (different parent frame, same+ * world rest — e.g. a Mixamo Hips baked at −90°X), and+ * • the correct limb reframe for an A-pose clip on a T-pose rig, which a+ * local-only `Rt·Rs⁻¹` premultiply skewed by ~30°.+ *+ * When world rests are unavailable we fall back to the prior local-only premultiply+ * (`L = Rt·Rs⁻¹`, `R = I`) so callers that don't supply them still work. Bones whose+ * correction is identity are omitted, so a matching rig skips the work and+ * round-trips unchanged.+ *+ * @param {Map<string,import('three').Quaternion>|null} targetRest target LOCAL bind+ * @param {Map<string,import('three').Quaternion>|null} [targetWorldRest] target WORLD bind+ * @returns {Map<string,{L:import('three').Quaternion,R:import('three').Quaternion|null}>}+ */+function bindCorrections(targetRest, targetWorldRest) {const out = new Map();if (!(targetRest instanceof Map)) return out;- for (const [canonical, sourceRest] of SOURCE_REST) {- const tr = targetRest.get(canonical);- if (!tr) continue;- const c = new Quaternion().multiplyQuaternions(tr, sourceRest.clone().invert());- if (1 - Math.abs(c.w) < BIND_EPSILON) continue; // identity → no correction- out.set(canonical, c);+ const haveWorld = targetWorldRest instanceof Map;+ for (const [canonical, Rs] of SOURCE_REST) {+ const Rt = targetRest.get(canonical);+ if (!Rt) continue;+ const WS = SOURCE_WORLD_REST.get(canonical);+ const WT = haveWorld ? targetWorldRest.get(canonical) : null;+ let L;+ let R = null;+ if (WS && WT) {+ // L = Rt · WT⁻¹ · WS · Rs⁻¹+ L = Rt.clone()+ .multiply(WT.clone().invert())+ .multiply(WS)+ .multiply(Rs.clone().invert());+ // R = WS⁻¹ · WT+ R = WS.clone().invert().multiply(WT);+ if (1 - Math.abs(R.w) < BIND_EPSILON) R = null; // identity post-factor+ } else {+ // Fallback: local-only premultiply (prior behaviour).+ L = Rt.clone().multiply(Rs.clone().invert());+ }+ const identityL = 1 - Math.abs(L.w) < BIND_EPSILON;+ if (identityL && !R) continue; // nothing to do → round-trips unchanged+ out.set(canonical, { L: identityL ? null : L, R });}return out;}-// Pre-multiply every [x,y,z,w] keyframe of a quaternion track by `c` in place:-// q ← c · q (deviation replayed in the target bone's rest frame).-function premultiplyQuaternionTrack(values, c) {+// Apply the bind correction `q ← L · q · R` to every [x,y,z,w] keyframe in place.+// Either factor may be null (identity).+function correctQuaternionTrack(values, { L, R }) {for (let i = 0; i < values.length; i += 4) {- _q.set(values[i], values[i + 1], values[i + 2], values[i + 3]).premultiply(c);+ _q.set(values[i], values[i + 1], values[i + 2], values[i + 3]);+ if (L) _q.premultiply(L);+ if (R) _q.multiply(R);values[i] = _q.x;values[i + 1] = _q.y;values[i + 2] = _q.z;@@ -212,7 +309,10 @@ function hipPositionCorrection(hipsParentWorldQuat, corrections) {q.invert();return 1 - Math.abs(q.w) < BIND_EPSILON ? null : q;}- return corrections.get('Hips') || null;+ // Fallback: the Hips correction's premultiply (parent-frame) factor, which for+ // the Hips carries the axis-convention reframe (its post-factor is identity+ // when source and target share a world rest).+ return corrections.get('Hips')?.L || null;}/**@@ -282,7 +382,7 @@ function clipHipBaselineY(clip) {export function retargetClip(clip, canonicalToNode, opts = {}) {const hipScale = Number.isFinite(opts.hipScale) && opts.hipScale > 0 ? opts.hipScale : 1;const minCoverage = opts.minCoverage ?? MIN_COVERAGE;- const corrections = bindCorrections(opts.targetRest);+ const corrections = bindCorrections(opts.targetRest, opts.targetWorldRest);const hipsPosCorrection = hipPositionCorrection(opts.hipsParentWorldQuat, corrections);const total = clip.tracks.length;const dropped = [];@@ -302,12 +402,13 @@ export function retargetClip(clip, canonicalToNode, opts = {}) {const next = track.clone();next.name = `${nodeName}.${property}`;if (property === 'quaternion') {- // Bind correction: replay the clip's deviation-from-rest in the target- // bone's own rest frame, so a clip authored for one rest pose (cz's- // A-pose) drives a differently-rigged avatar (a Mixamo T-pose, or a Hips- // baked at −90°X that would otherwise read as "lying down").+ // Bind correction q ← L·q·R: replay the clip bone's motion as the same+ // world-space delta on the target's rest pose, so a clip authored for one+ // rest pose (cz's A-pose) drives a differently-rigged avatar (a Mixamo+ // T-pose, or a Hips baked at −90°X that would otherwise read as "lying+ // down") without skewing limbs.const correction = corrections.get(canonical);- if (correction) premultiplyQuaternionTrack(next.values, correction);+ if (correction) correctQuaternionTrack(next.values, correction);} else if (property === 'position' && canonical === 'Hips') {// Root motion: the clip authors hip translation in the authoring rig's// world-Y-up frame; re-express it in the target's hips-parent frame so it@@ -342,6 +443,7 @@ export function retargetClip(clip, canonicalToNode, opts = {}) {export function retargetClipToRig(clip, rig, opts = {}) {const map = canonicalNodeMapFromRig(rig);const targetRest = canonicalRestMapFromRig(rig);+ const targetWorldRest = canonicalWorldRestMapFromRig(rig);let hipScale = 1;if (opts.scaleHips !== false) {const targetY = hipRestHeight(rig);@@ -364,6 +466,7 @@ export function retargetClipToRig(clip, rig, opts = {}) {hipScale,minCoverage: opts.minCoverage,targetRest,+ targetWorldRest,hipsParentWorldQuat: hipsParent,});}@@ -380,8 +483,14 @@ export function retargetClipToRig(clip, rig, opts = {}) {export function retargetClipToObject(clip, root, opts = {}) {const map = canonicalNodeMapFromObject(root);const targetRest = opts.targetRest || canonicalRestMapFromObject(root);+ const targetWorldRest = opts.targetWorldRest || canonicalWorldRestMapFromObject(root);const hipsParentWorld = opts.hipsParentWorldQuat || hipsParentWorldQuat(root);- return retargetClip(clip, map, { ...opts, targetRest, hipsParentWorldQuat: hipsParentWorld });+ return retargetClip(clip, map, {+ ...opts,+ targetRest,+ targetWorldRest,+ hipsParentWorldQuat: hipsParentWorld,+ });}/**diff --git a/src/avatar-studio-colorpicker.js b/src/avatar-studio-colorpicker.jsnew file mode 100644index 000000000..b9fb53552--- /dev/null+++ b/src/avatar-studio-colorpicker.js@@ -0,0 +1,368 @@+/**+ * Avatar Studio — advanced color picker popover+ *+ * A full-spectrum HSV picker that augments the fixed swatch grid in the Color+ * tab. Built on iro.js (MPL-2.0, lazy-loaded so it never weighs down first+ * paint) and wired to the same live-preview / commit path the swatches use:+ *+ * - onInput(hex) → live, fires continuously while dragging (no history)+ * - onChange(hex) → commit, fires when a value is settled (pushes history)+ *+ * Extras layered on top of the wheel:+ * - Hex entry field (type or paste any #rrggbb)+ * - Native EyeDropper — sample any pixel on screen, where supported+ * - Recent colors — the last dozen colors picked across the whole studio,+ * persisted in localStorage so a palette carries between sessions.+ *+ * One popover exists at a time; opening a second closes the first. Escape and+ * outside-clicks dismiss it, committing whatever color is showing.+ */++import { log } from './shared/log.js';++const RECENT_KEY = 'avatar-studio-recent-colors';+const RECENT_MAX = 12;+const HEX_RE = /^#?[0-9a-f]{6}$/i;++let iroPromise = null;+let activePopover = null;++function loadIro() {+ if (!iroPromise) {+ iroPromise = import('@jaames/iro').then((m) => m.default || m);+ }+ return iroPromise;+}++function normalizeHex(value) {+ if (typeof value !== 'string') return null;+ const v = value.trim();+ if (!HEX_RE.test(v)) return null;+ return (v[0] === '#' ? v : `#${v}`).toLowerCase();+}++// ── Recent colors (shared across slots, persisted) ───────────────────++export function getRecentColors() {+ try {+ const raw = JSON.parse(localStorage.getItem(RECENT_KEY) || '[]');+ if (!Array.isArray(raw)) return [];+ return raw.map(normalizeHex).filter(Boolean).slice(0, RECENT_MAX);+ } catch {+ return [];+ }+}++export function pushRecentColor(hex) {+ const norm = normalizeHex(hex);+ if (!norm) return;+ const next = [norm, ...getRecentColors().filter((c) => c !== norm)].slice(0, RECENT_MAX);+ try {+ localStorage.setItem(RECENT_KEY, JSON.stringify(next));+ } catch {+ /* storage full / blocked — recents are a nicety, never fatal */+ }+}++// ── CSS (injected once) ──────────────────────────────────────────────++let _cssInjected = false;+function ensureCss() {+ if (_cssInjected) return;+ _cssInjected = true;+ const style = document.createElement('style');+ style.textContent = `+ .as-cp {+ position: fixed; z-index: 320;+ width: 244px;+ background: var(--panel, #111);+ border: 1px solid var(--border-2, #2a2a2a);+ border-radius: 14px;+ padding: 14px;+ box-shadow: 0 24px 64px rgba(0,0,0,0.6), 0 0 0 1px rgba(255,255,255,0.02);+ display: flex; flex-direction: column; gap: 12px;+ font-family: inherit;+ opacity: 0; transform: translateY(-6px) scale(0.98);+ transition: opacity .14s ease, transform .14s ease;+ }+ .as-cp.in { opacity: 1; transform: translateY(0) scale(1); }+ .as-cp-head {+ display: flex; align-items: center; justify-content: space-between; gap: 8px;+ }+ .as-cp-title {+ font-size: 12px; font-weight: 600; color: var(--text, #fafafa);+ letter-spacing: .01em;+ }+ .as-cp-close {+ background: var(--panel-2, #161616); border: 1px solid var(--border-2, #2a2a2a);+ color: var(--text-2, #a1a1aa); width: 24px; height: 24px; border-radius: 999px;+ cursor: pointer; font: inherit; font-size: 13px; line-height: 1;+ display: inline-flex; align-items: center; justify-content: center;+ transition: color .15s, border-color .15s;+ }+ .as-cp-close:hover { color: var(--text, #fafafa); border-color: var(--text-3, #71717a); }+ .as-cp-wheel { display: flex; justify-content: center; }+ .as-cp-row { display: flex; align-items: center; gap: 8px; }+ .as-cp-hex {+ flex: 1; min-width: 0;+ background: var(--panel-2, #161616); border: 1px solid var(--border-2, #2a2a2a);+ border-radius: 8px; color: var(--text, #fafafa);+ padding: 7px 10px; font: 500 12px/1 ui-monospace, 'SF Mono', monospace;+ letter-spacing: .04em; text-transform: uppercase; outline: none;+ transition: border-color .15s;+ }+ .as-cp-hex:focus { border-color: var(--accent, #fff); }+ .as-cp-hex.bad { border-color: var(--danger, #f43f5e); }+ .as-cp-eye {+ flex-shrink: 0; width: 32px; height: 32px;+ background: var(--panel-2, #161616); border: 1px solid var(--border-2, #2a2a2a);+ border-radius: 8px; color: var(--text-2, #a1a1aa);+ cursor: pointer; display: inline-flex; align-items: center; justify-content: center;+ transition: color .15s, border-color .15s, background .15s;+ }+ .as-cp-eye:hover { color: var(--text, #fafafa); border-color: var(--text-3, #71717a); background: rgba(255,255,255,.03); }+ .as-cp-eye:focus-visible { box-shadow: 0 0 0 2px var(--accent, #fff); outline: none; }+ .as-cp-recent-label {+ font-size: 9px; text-transform: uppercase; letter-spacing: .08em;+ color: var(--text-3, #71717a); margin-bottom: -4px;+ }+ .as-cp-recent { display: grid; grid-template-columns: repeat(6, 1fr); gap: 6px; }+ .as-cp-recent button {+ aspect-ratio: 1/1; border-radius: 7px; border: 1px solid var(--border-2, #2a2a2a);+ cursor: pointer; padding: 0; transition: transform .12s, border-color .12s;+ outline: none;+ }+ .as-cp-recent button:hover { transform: translateY(-1px); border-color: var(--text-3, #71717a); }+ .as-cp-recent button:focus-visible { box-shadow: 0 0 0 2px var(--accent, #fff); }+ .as-cp-empty { font-size: 11px; color: var(--text-3, #71717a); }+ .IroColorPicker { user-select: none; }+ `;+ document.head.appendChild(style);+}++// ── Positioning ──────────────────────────────────────────────────────++function positionPopover(el, anchorEl) {+ const a = anchorEl.getBoundingClientRect();+ const w = el.offsetWidth || 244;+ const h = el.offsetHeight || 300;+ const margin = 8;+ let left = a.left + a.width / 2 - w / 2;+ left = Math.max(margin, Math.min(left, window.innerWidth - w - margin));+ // Prefer below the anchor; flip above if it would overflow the viewport.+ let top = a.bottom + margin;+ if (top + h > window.innerHeight - margin) {+ top = Math.max(margin, a.top - h - margin);+ }+ el.style.left = `${Math.round(left)}px`;+ el.style.top = `${Math.round(top)}px`;+}++// ── Public: open the popover ─────────────────────────────────────────++/**+ * Open the color popover anchored to an element.+ *+ * @param {Object} opts+ * @param {Element} opts.anchorEl element to position against+ * @param {string} [opts.title] header label (e.g. "Skin tone")+ * @param {string} [opts.current] starting hex (#rrggbb)+ * @param {Function} opts.onInput (hex) => void — live, no history+ * @param {Function} opts.onChange (hex) => void — commit a settled value+ * @param {Function} [opts.onClose] (hex) => void — fires once when dismissed+ * @returns {Promise<{close:Function}>}+ */+export async function openColorPopover({ anchorEl, title, current, onInput, onChange, onClose }) {+ ensureCss();+ closeActivePopover();++ const startHex = normalizeHex(current) || '#ffffff';+ let lastHex = startHex;++ const el = document.createElement('div');+ el.className = 'as-cp';+ el.setAttribute('role', 'dialog');+ el.setAttribute('aria-label', `${title || 'Custom'} color picker`);+ const hasEyeDropper = typeof window.EyeDropper === 'function';+ el.innerHTML = `+ <div class="as-cp-head">+ <span class="as-cp-title">${escapeHtml(title || 'Custom color')}</span>+ <button type="button" class="as-cp-close" aria-label="Close">×</button>+ </div>+ <div class="as-cp-wheel" data-wheel></div>+ <div class="as-cp-row">+ <input class="as-cp-hex" type="text" inputmode="text" spellcheck="false"+ maxlength="7" aria-label="Hex color" value="${startHex.toUpperCase()}" />+ ${hasEyeDropper ? `<button type="button" class="as-cp-eye" aria-label="Pick a color from the screen" title="Eyedropper">+ <svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m2 22 1-1h3l9-9"/><path d="M3 21v-3l9-9"/><path d="m15 6 3.4-3.4a2.1 2.1 0 0 1 3 3L21 9 18 6"/></svg>+ </button>` : ''}+ </div>+ <div class="as-cp-recent-label">Recent</div>+ <div class="as-cp-recent" data-recent></div>+ `;+ document.body.appendChild(el);++ const hexInput = el.querySelector('.as-cp-hex');+ const wheelHost = el.querySelector('[data-wheel]');++ let cp = null;+ let suppressInput = false; // guard hex-input feedback loops++ const commit = (hex) => {+ const norm = normalizeHex(hex);+ if (!norm) return;+ lastHex = norm;+ pushRecentColor(norm);+ renderRecent();+ onChange?.(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) {+ hexInput.classList.add('bad');+ return false;+ }+ hexInput.classList.remove('bad');+ lastHex = norm;+ if (cp) {+ suppressInput = true;+ cp.color.hexString = norm;+ suppressInput = false;+ }+ if (live) onInput?.(norm);+ else commit(norm);+ return true;+ };++ hexInput.addEventListener('input', () => {+ // Live-preview valid intermediate values without committing history.+ if (HEX_RE.test(hexInput.value.trim())) setFromHex(hexInput.value, { live: true });+ else hexInput.classList.add('bad');+ });+ hexInput.addEventListener('change', () => setFromHex(hexInput.value));+ hexInput.addEventListener('keydown', (e) => {+ if (e.key === 'Enter') { e.preventDefault(); if (setFromHex(hexInput.value)) hexInput.blur(); }+ });++ const eyeBtn = el.querySelector('.as-cp-eye');+ eyeBtn?.addEventListener('click', async () => {+ try {+ const dropper = new window.EyeDropper();+ const { sRGBHex } = await dropper.open();+ const norm = normalizeHex(sRGBHex);+ if (norm) {+ hexInput.value = norm.toUpperCase();+ setFromHex(norm);+ }+ } catch {+ /* user cancelled the eyedropper — no-op */+ }+ });++ function renderRecent() {+ const host = el.querySelector('[data-recent]');+ const recents = getRecentColors();+ if (!recents.length) {+ host.innerHTML = `<span class="as-cp-empty" style="grid-column:1/-1">Colors you pick appear here.</span>`;+ return;+ }+ host.innerHTML = recents+ .map((hex) => `<button type="button" data-hex="${hex}" style="background:${hex}" aria-label="Use ${hex.toUpperCase()}" title="${hex.toUpperCase()}"></button>`)+ .join('');+ host.querySelectorAll('button[data-hex]').forEach((b) => {+ b.addEventListener('click', () => {+ hexInput.value = b.dataset.hex.toUpperCase();+ setFromHex(b.dataset.hex);+ });+ });+ }+ renderRecent();++ // ── Lifecycle: position, focus, dismiss ──────────────────────────+ positionPopover(el, anchorEl);+ requestAnimationFrame(() => el.classList.add('in'));++ const reposition = () => positionPopover(el, anchorEl);+ window.addEventListener('resize', reposition);+ window.addEventListener('scroll', reposition, true);++ let closed = false;+ const close = () => {+ if (closed) return;+ closed = true;+ window.removeEventListener('resize', reposition);+ window.removeEventListener('scroll', reposition, true);+ document.removeEventListener('pointerdown', onOutside, true);+ document.removeEventListener('keydown', onKey, true);+ // Ensure the final shown color is committed (covers wheel-only picks+ // that ended without a dedicated input:end, plus close-by-outside-click).+ commit(lastHex);+ onClose?.(lastHex);+ el.classList.remove('in');+ setTimeout(() => { el.remove(); if (cp) try { cp.off(); } catch { /* ignore */ } }, 150);+ if (activePopover?.el === el) activePopover = null;+ // Return focus to the trigger for keyboard users.+ if (anchorEl && typeof anchorEl.focus === 'function') anchorEl.focus();+ };++ const onOutside = (e) => {+ if (!el.contains(e.target) && e.target !== anchorEl && !anchorEl.contains?.(e.target)) close();+ };+ const onKey = (e) => {+ if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); close(); }+ };+ // Defer outside-listener binding so the opening click doesn't close it.+ setTimeout(() => {+ if (closed) return;+ document.addEventListener('pointerdown', onOutside, true);+ document.addEventListener('keydown', onKey, true);+ }, 0);++ el.querySelector('.as-cp-close').addEventListener('click', close);++ activePopover = { el, close };+ return { close };+}++export function closeActivePopover() {+ if (activePopover) activePopover.close();+}++function escapeHtml(s) {+ return String(s ?? '').replace(/[&<>"']/g, (c) => (+ { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]+ ));+}diff --git a/src/avatar-studio.js b/src/avatar-studio.jsindex a800ee001..d7ae641d6 100644--- a/src/avatar-studio.js+++ b/src/avatar-studio.js@@ -26,6 +26,7 @@ import { renderSculptPanel, applyMorphsToRoot } from './avatar-sculpt.js';import { saveRemoteGlbToAccount, apiFetch } from './account.js';import { uploadAvatarSnapshot } from './voice/avatar-snapshot.js';import { optimizeAndValidateGlb } from './avatar-studio-optimize.js';+import { openColorPopover, closeActivePopover } from './avatar-studio-colorpicker.js';import {collapseAppearance,hydrateAppearance,@@ -113,6 +114,20 @@ const COLOR_SLOT_BY_ID = new Map(COLOR_SLOTS.map((s) => [s.id, s]));const HEX_RE = /^#[0-9a-f]{6}$/i;const BODY_TYPE = 'feminine';+// ── Looks — one-tap palettes that theme skin + hair + outfit together ──+// Every hue is drawn from the per-slot swatch palettes above, so a Look always+// lands on real, coherent material colors. Applied as a single history step.+const LOOKS = [+ { id: 'noir', name: 'Noir', colors: { skin: '#e0a878', hair: '#0e0e0e', outfit: '#101010' } },+ { id: 'sunset', name: 'Sunset', colors: { skin: '#f3c1a3', hair: '#6b4423', outfit: '#c08a1e' } },+ { id: 'arctic', name: 'Arctic', colors: { skin: '#ffe9d6', hair: '#b8b8b8', outfit: '#3b6ea5' } },+ { id: 'cyber', name: 'Cyber', colors: { skin: '#c08552', hair: '#9b5cc0', outfit: '#1e3a5f' } },+ { id: 'rose', name: 'Rosé', colors: { skin: '#f3c1a3', hair: '#3b2417', outfit: '#d4577e' } },+ { id: 'forest', name: 'Forest', colors: { skin: '#9c6b44', hair: '#3b2417', outfit: '#1f6b3a' } },+ { id: 'mono', name: 'Mono', colors: { skin: '#e0a878', hair: '#b8b8b8', outfit: '#f2f2f2' } },+ { id: 'ember', name: 'Ember', colors: { skin: '#9c6b44', hair: '#0e0e0e', outfit: '#7a1f2b' } },+];+// ── Garment layers (show/hide) ───────────────────────────────────────const LAYER_SLOTS = [{ id: 'outfit', label: 'Outfit', materials: ['Wolf3D_Outfit_Top', 'Wolf3D_Outfit_Bottom', 'Wolf3D_Outfit_Footwear'], strip: true },@@ -449,6 +464,9 @@ function renderTabs() {}function renderActivePanel() {+ // A re-render replaces the swatch DOM the popover is anchored to; close it+ // first so it never points at a detached node.+ closeActivePopover();const tab = TABS.find((t) => t.id === activeTab);const panel = $('as-panel');panel.setAttribute('aria-labelledby', `as-tab-${activeTab}`);@@ -580,25 +598,29 @@ function renderColorPanel(panel) {aria-label="${esc(slot.label)} default" data-slot="${slot.id}" data-hex=""title="Default"></button>${swatches}- <label class="as-swatch as-swatch-custom${customSel ? '' : ''}"- aria-label="${esc(slot.label)} custom color" title="Custom color"+ <label class="as-swatch as-swatch-custom" data-custom-slot="${slot.id}"+ role="button" tabindex="0" aria-haspopup="dialog"+ aria-label="${esc(slot.label)} custom color" title="Full-spectrum picker"${customSel ? 'style="border-color:var(--accent);box-shadow:0 0 0 2px var(--accent),0 0 0 4px rgba(0,0,0,0.6)"' : ''}><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 19l7-7 3 3-7 7-3-3z"/><path d="M18 13l-1.5-7.5L2 2l3.5 14.5L13 18l5-5z"/><path d="M2 2l7.586 7.586"/><circle cx="11" cy="11" r="2"/></svg>- <input type="color" data-slot="${slot.id}" value="${esc(current || '#ffffff')}" />+ <input type="color" data-slot="${slot.id}" value="${esc(current || '#ffffff')}" tabindex="-1" aria-hidden="true" /></label></div></div>`;}).join('');ensureLayerCss();+ ensureColorExtrasCss();panel.innerHTML = `+ ${looksBlockHtml()}${layersBlockHtml()}- <p class="ae-sculpt-note" style="margin-top:16px;">Tint skin, hair and outfit. Colors bake into your saved avatar.</p>+ <p class="ae-sculpt-note" style="margin-top:16px;">Tint skin, hair and outfit. Tap the rainbow chip for the full-spectrum picker. Colors bake into your saved avatar.</p>${groups}${ready ? '' : '<div class="as-empty" style="padding-top:8px;">Waiting for avatar to load…</div>'}`;bindColorPanel(panel);bindLayersBlock(panel);+ bindLooksBlock(panel);}// ── Layers (show/hide) ───────────────────────────────────────────────@@ -721,11 +743,131 @@ function bindColorPanel(panel) {panel.querySelectorAll('.as-swatch[data-slot]').forEach((btn) => {btn.addEventListener('click', () => setSlotColor(btn.dataset.slot, btn.dataset.hex || null));});+ // Native OS picker stays wired as a fallback for the advanced popover.panel.querySelectorAll('input[type="color"][data-slot]').forEach((input) => {const slot = input.dataset.slot;input.addEventListener('input', () => liveSlotColor(slot, input.value));input.addEventListener('change', () => setSlotColor(slot, input.value));});+ // Rainbow chip → full-spectrum iro.js popover (wheel + hex + eyedropper).+ panel.querySelectorAll('.as-swatch-custom[data-custom-slot]').forEach((label) => {+ const slot = label.dataset.customSlot;+ label.addEventListener('click', (e) => { e.preventDefault(); openCustomPicker(slot, label); });+ label.addEventListener('keydown', (e) => {+ if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); openCustomPicker(slot, label); }+ });+ });+}++// Open the advanced color picker for a slot. A whole open→drag→close session+// collapses to a single undo step: soft updates apply live while open, and one+// history entry is pushed on close only if the color actually changed.+function openCustomPicker(slotId, anchorEl) {+ const slot = COLOR_SLOT_BY_ID.get(slotId);+ if (!slot) return;+ const sessionStart = workingAppearance.colors[slotId] || null;+ openColorPopover({+ anchorEl,+ title: slot.label,+ current: sessionStart || '#ffffff',+ onInput: (hex) => liveSlotColor(slotId, hex),+ onChange: (hex) => softSetSlotColor(slotId, hex),+ onClose: () => endColorSession(slotId, sessionStart),+ }).catch((err) => {+ // iro failed to even open → fall back to the native OS color dialog.+ log.warn('[avatar-studio] color popover failed, using native picker', err);+ const input = anchorEl.querySelector('input[type="color"]');+ if (input) { try { input.showPicker(); } catch { input.click(); } }+ });+}++function softSetSlotColor(slotId, hex) {+ const slot = COLOR_SLOT_BY_ID.get(slotId);+ if (!slot || !HEX_RE.test(hex)) return;+ workingAppearance.colors[slotId] = hex.toLowerCase();+ applySlotColor(slot, hex);+ liveSlotColor(slotId, hex); // keep the group's current dot/label in sync+ renderChips();+ updateDirtyState();+ scheduleDraftSave();+}++function endColorSession(slotId, sessionStart) {+ const now = workingAppearance.colors[slotId] || null;+ if (now !== sessionStart) pushHistory();+ if (activeTab === 'color') renderActivePanel();+ updateDirtyState();+}++// ── Looks (one-tap palettes) ─────────────────────────────────────────++function looksBlockHtml() {+ const cards = LOOKS.map((look) => {+ const active = COLOR_SLOTS.every(+ (s) => (workingAppearance.colors[s.id] || null) === (look.colors[s.id] || null),+ );+ const grad = `linear-gradient(135deg, ${look.colors.skin} 0 34%, ${look.colors.hair} 34% 67%, ${look.colors.outfit} 67% 100%)`;+ return `<button class="as-look${active ? ' active' : ''}" type="button"+ data-look="${esc(look.id)}" aria-pressed="${active ? 'true' : 'false'}" title="${esc(look.name)} look">+ <span class="as-look-sw" style="background:${grad}"></span>+ <span class="as-look-name">${esc(look.name)}</span>+ </button>`;+ }).join('');+ return `+ <div class="as-looks">+ <div class="as-looks-head">+ <span class="as-color-title">Looks</span>+ <span class="as-looks-hint">One-tap palettes</span>+ </div>+ <div class="as-looks-row">${cards}</div>+ </div>`;+}++function bindLooksBlock(panel) {+ panel.querySelectorAll('.as-look[data-look]').forEach((btn) => {+ btn.addEventListener('click', () => {+ const look = LOOKS.find((l) => l.id === btn.dataset.look);+ if (look) applyLook(look);+ });+ });+}++function applyLook(look) {+ for (const slot of COLOR_SLOTS) {+ const hex = look.colors[slot.id];+ if (!hex) continue;+ workingAppearance.colors[slot.id] = hex.toLowerCase();+ applySlotColor(slot, hex);+ }+ pushHistory();+ renderChips();+ if (activeTab === 'color') renderActivePanel();+ updateDirtyState();+ scheduleDraftSave();+ setStatus('ok', `Applied the ${look.name} look.`);+}++let _colorExtrasCssInjected = false;+function ensureColorExtrasCss() {+ if (_colorExtrasCssInjected) return;+ _colorExtrasCssInjected = true;+ const style = document.createElement('style');+ style.textContent = `+ .as-looks { margin-bottom: 18px; }+ .as-looks-head { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; margin: 0 0 10px; }+ .as-looks-hint { font-size: 11px; color: var(--text-3, #71717a); }+ .as-looks-row { display: grid; grid-template-columns: repeat(auto-fill, minmax(64px, 1fr)); gap: 8px; }+ .as-look { display: flex; flex-direction: column; align-items: center; gap: 6px; background: var(--panel, #111); border: 1px solid var(--border, #1f1f1f); border-radius: 11px; padding: 8px 6px 7px; cursor: pointer; font-family: inherit; transition: border-color .15s, transform .12s, background .15s; }+ .as-look:hover { border-color: var(--text-3, #71717a); transform: translateY(-1px); background: rgba(255,255,255,.03); }+ .as-look:focus-visible { outline: none; border-color: var(--accent, #fff); box-shadow: 0 0 0 2px var(--accent, #fff); }+ .as-look.active { border-color: var(--accent, #fff); background: rgba(255,255,255,.05); }+ .as-look-sw { width: 100%; aspect-ratio: 1/1; border-radius: 8px; border: 1px solid rgba(255,255,255,.12); }+ .as-look-name { font-size: 11px; font-weight: 600; color: var(--text-2, #a1a1aa); }+ .as-look.active .as-look-name { color: var(--text, #fafafa); }+ .as-swatch-custom[role="button"] { display: inline-flex; align-items: center; justify-content: center; }+ .as-swatch-custom:focus-visible { outline: none; box-shadow: 0 0 0 2px var(--accent, #fff); }+ `;+ document.head.appendChild(style);}function setSlotColor(slotId, hex) {diff --git a/src/feature-tour/controls.js b/src/feature-tour/controls.jsindex 3b9cd1fd6..1615c74f1 100644--- a/src/feature-tour/controls.js+++ b/src/feature-tour/controls.js@@ -29,6 +29,7 @@ export class TourControls {</div></div><button class="tws-tour-btn tws-tour-btn--speed" data-act="speed" aria-label="Playback speed" title="Playback speed">1×</button>+ <button class="tws-tour-btn" data-act="roam" aria-label="Free roam — drive the guide yourself" title="Free roam" aria-pressed="false">🧭</button><button class="tws-tour-btn" data-act="mute" aria-label="Mute narration" title="Mute / unmute voice">🔊</button><button class="tws-tour-btn tws-tour-btn--exit" data-act="exit" aria-label="Exit tour" title="Exit tour">✕</button>`;@@ -38,6 +39,7 @@ export class TourControls {this.playBtn = bar.querySelector('[data-act="toggle"]');this.muteBtn = bar.querySelector('[data-act="mute"]');this.speedBtn = bar.querySelector('[data-act="speed"]');+ this.roamBtn = bar.querySelector('[data-act="roam"]');this.chapterEl = bar.querySelector('.tws-tour-chapter');this.countEl = bar.querySelector('.tws-tour-count');this.track = bar.querySelector('.tws-tour-track');@@ -51,6 +53,7 @@ export class TourControls {else if (act === 'next') this.handlers.onNext?.();else if (act === 'toggle') this.handlers.onToggle?.();else if (act === 'speed') this.handlers.onSpeed?.();+ else if (act === 'roam') this.handlers.onRoam?.();else if (act === 'mute') this.handlers.onMute?.();else if (act === 'exit') this.handlers.onExit?.();});@@ -104,6 +107,13 @@ export class TourControls {this.menuBtn.classList.toggle('is-active', open);}+ setRoam(on) {+ this.roamBtn.setAttribute('aria-pressed', on ? 'true' : 'false');+ this.roamBtn.classList.toggle('is-active', on);+ this.roamBtn.setAttribute('title', on ? 'Rejoin the tour' : 'Free roam');+ this.bar.classList.toggle('is-roaming', on);+ }+dispose() {this.bar?.remove();this.bar = null;diff --git a/src/feature-tour/director.js b/src/feature-tour/director.jsindex 349f6661e..ecfad36b8 100644--- a/src/feature-tour/director.js+++ b/src/feature-tour/director.js@@ -31,6 +31,7 @@ import { Spotlight } from './spotlight.js';import { Narrator } from './narrator.js';import { TourControls } from './controls.js';import { ChapterPanel } from './chapters.js';+import { FreeRoam } from './free-roam.js';const ADVANCE_BEAT_MS = 900; // pause between finishing a stop and moving onconst Z_BEAM = 2147483280;@@ -49,6 +50,7 @@ export class TourDirector {this.speed = 1;this.mounted = false;this.offRoute = false;+ this.roam = false;this._runToken = 0;this._advanceTimer = 0;this._seenSections = new Set();@@ -135,11 +137,17 @@ export class TourDirector {async _mount() {if (this.mounted) return;this.mounted = true;+ // The site-wide corner companion is the same kind of avatar — during the+ // tour it would just be a second body on screen, so stand it down (and its+ // click-to-walk, which would otherwise fight free roam) and bring it back+ // when the tour ends.+ this._suppressCompanion();this._buildBeam();this.spotlight = new Spotlight();this.narrator = new Narrator();this.avatar = new GuideAvatar();await this.avatar.mount();+ this.freeRoam = new FreeRoam(this.avatar);this.controls = new TourControls({onMenu: () => this.panel?.toggle(),onPrev: () => this._go(this.pos - 1),@@ -147,6 +155,7 @@ export class TourDirector {onToggle: () => this._togglePause(),onSeek: (i) => this._go(i),onSpeed: () => this._cycleSpeed(),+ onRoam: () => this._toggleRoam(),onMute: () => this._toggleMute(),onExit: () => this.exit(),});@@ -231,6 +240,12 @@ export class TourDirector {// anything in flight, then runs the stop here or navigates if it's off-page._go(pos) {if (!this.playlist.length) return;+ if (this.roam) {+ // Any explicit navigation leaves free roam and resumes the guided tour.+ this.roam = false;+ this.freeRoam?.disable();+ this.controls?.setRoam(false);+ }const clamped = Math.max(0, Math.min(this.playlist.length - 1, pos));this._runToken++;clearTimeout(this._advanceTimer);@@ -256,6 +271,7 @@ export class TourDirector {}_togglePause() {+ if (this.roam) return this._exitRoam(); // play rejoins the tour from roamthis.paused = !this.paused;writeState({ paused: this.paused });this.controls.setPaused(this.paused);@@ -327,6 +343,73 @@ export class TourDirector {}}+ // ── Free roam ───────────────────────────────────────────────────────────────+ // Hand the stage to the visitor: freeze the guided sequence and let them drive+ // the guide around the page (free-roam.js). Toggling off — or any navigation /+ // play — rejoins the tour at the current stop.+ _toggleRoam() {+ this.roam ? this._exitRoam() : this._enterRoam();+ }++ _enterRoam() {+ if (this.roam) return;+ this.roam = true;+ this._runToken++; // freeze whatever the guide was doing+ clearTimeout(this._advanceTimer);+ this.narrator?.cancel();+ this._stopBeam();+ this.spotlight?.highlight(null);+ this.avatar?.hideBubble();+ this.panel?.close();+ this.controls?.setRoam(true);+ this.freeRoam?.enable();+ }++ _exitRoam() {+ if (!this.roam) return;+ this.roam = false;+ this.freeRoam?.disable();+ this.controls?.setRoam(false);+ // Rejoining the tour means playing again from the current stop.+ this.paused = false;+ this.controls?.setPaused(false);+ writeState({ paused: false });+ this._go(this.pos);+ }++ // ── Corner-companion suppression (de-dupe the on-screen avatar) ──────────────+ _suppressCompanion() {+ const w = window.__walkCompanion;+ if (!w) return;+ this._companionWasOn = !!(w.instance?.mounted || (w.isEnabled && w.isEnabled()));+ const hide = () => {+ try {+ if (w.instance?.mounted) w.instance.unmount();+ } catch {+ /* companion mid-mount — the change listener will catch it */+ }+ };+ hide();+ // The companion auto-mounts on load (and on playground return); re-hide it+ // whenever it reappears while the tour owns the screen.+ this._onCompanionChange = hide;+ window.addEventListener('walk-companion:change', this._onCompanionChange);+ }++ _restoreCompanion() {+ if (this._onCompanionChange) {+ window.removeEventListener('walk-companion:change', this._onCompanionChange);+ this._onCompanionChange = null;+ }+ const w = window.__walkCompanion;+ if (!w || !this._companionWasOn) return;+ try {+ if (!w.instance?.mounted) (w.instance ? w.instance.mount() : w.enable?.());+ } catch {+ /* non-fatal — the companion will re-mount on the next page load */+ }+ }+// Playlist position for an absolute stop index — exact match, else nearest._posForAbs(abs) {const p = this.playlist.indexOf(abs);diff --git a/src/feature-tour/free-roam.js b/src/feature-tour/free-roam.jsnew file mode 100644index 000000000..7e42c69c3--- /dev/null+++ b/src/feature-tour/free-roam.js@@ -0,0 +1,177 @@+// free-roam.js — hand the stage to the visitor. When the guided tour is paused+// into "free roam", this lets you drive the guide around the page yourself:+// · Click any empty patch of the page → the guide walks there.+// · Grab the guide and drag it anywhere.+// · Drag it to the top or bottom edge → the page scrolls under it, so you can+// walk it up and down the whole document, not just the current viewport.+// It reuses the GuideAvatar's own walk choreography (walkTo / place / settle),+// so the rig animates and faces its heading exactly as it does on the tour.+//+// Activation mirrors the corner companion's click-to-walk contract: we listen in+// the capture phase but only ever act on empty space (never links, buttons,+// inputs, canvases or [data-walk-block]) and never call preventDefault on a real+// page interaction — so normal clicking is provably untouched. Dragging the+// guide itself does preventDefault, because the guide has no page behaviour to+// preserve.++const EDGE = 96; // px band at top/bottom of the viewport that auto-scrolls+const SCROLL_MAX = 22; // px per frame at the very edge+const RIPPLE_MS = 600;+const Z_FX = 2147483090; // under the spotlight (…100), over the page++// Elements whose clicks belong to the page, never to "walk there".+const INTERACTIVE = 'a,button,input,textarea,select,label,summary,[role="button"],[contenteditable],[contenteditable="true"],canvas,video,iframe,[data-walk-block]';++export function isInteractiveTarget(el) {+ return !!(el && el.closest && el.closest(INTERACTIVE));+}++export class FreeRoam {+ constructor(avatar) {+ this.avatar = avatar;+ this.enabled = false;+ this.dragging = false;+ this._grab = { x: 0, y: 0 };+ this._ptr = { x: 0, y: 0 };+ this._scrollRaf = 0;+ this._reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;+ this._onDown = this._onDown.bind(this);+ this._onMove = this._onMove.bind(this);+ this._onUp = this._onUp.bind(this);+ ensureStyles();+ }++ enable() {+ if (this.enabled) return;+ this.enabled = true;+ this.avatar.setInteractive(true);+ document.addEventListener('pointerdown', this._onDown, true);+ this._hint = makeHint();+ }++ disable() {+ if (!this.enabled) return;+ this.enabled = false;+ this._endDrag();+ document.removeEventListener('pointerdown', this._onDown, true);+ this.avatar.setInteractive(false);+ this.avatar.settle();+ this._hint?.remove();+ this._hint = null;+ }++ // ── Pointer handling ────────────────────────────────────────────────────────+ _onDown(e) {+ if (!this.enabled || e.button !== 0 || e.altKey || e.metaKey || e.ctrlKey || e.shiftKey) return;+ const host = this.avatar.host;+ if (host && host.contains(e.target)) {+ // Grab the guide itself → drag.+ const r = host.getBoundingClientRect();+ this._grab = { x: e.clientX - r.left, y: e.clientY - r.top };+ this._ptr = { x: e.clientX, y: e.clientY };+ this.dragging = true;+ document.addEventListener('pointermove', this._onMove, true);+ document.addEventListener('pointerup', this._onUp, true);+ document.addEventListener('pointercancel', this._onUp, true);+ this._startScrollLoop();+ this._dismissHint();+ e.preventDefault();+ return;+ }+ if (isInteractiveTarget(e.target)) return; // leave real page clicks alone+ // Click on empty space → walk the guide there, centered under the click.+ const s = this.avatar.size();+ this.avatar.walkTo({ x: e.clientX - s.w / 2, y: e.clientY - s.h / 2 });+ if (!this._reduced) ripple(e.clientX, e.clientY);+ this._dismissHint();+ }++ _onMove(e) {+ if (!this.dragging) return;+ this._ptr = { x: e.clientX, y: e.clientY };+ this.avatar.place({ x: e.clientX - this._grab.x, y: e.clientY - this._grab.y });+ }++ _onUp() {+ this._endDrag();+ }++ _endDrag() {+ cancelAnimationFrame(this._scrollRaf);+ this._scrollRaf = 0;+ if (!this.dragging) return;+ this.dragging = false;+ document.removeEventListener('pointermove', this._onMove, true);+ document.removeEventListener('pointerup', this._onUp, true);+ document.removeEventListener('pointercancel', this._onUp, true);+ this.avatar.settle();+ }++ // While dragging near the top/bottom edge, scroll the page and keep the guide+ // pinned under the pointer so it appears to walk the document up/down.+ _startScrollLoop() {+ if (this._reduced) return;+ const tick = () => {+ if (!this.dragging) return;+ const y = this._ptr.y;+ const h = window.innerHeight;+ let dy = 0;+ if (y < EDGE) dy = -SCROLL_MAX * (1 - y / EDGE);+ else if (y > h - EDGE) dy = SCROLL_MAX * (1 - (h - y) / EDGE);+ if (dy) {+ window.scrollBy(0, dy);+ this.avatar.place({ x: this._ptr.x - this._grab.x, y: this._ptr.y - this._grab.y });+ }+ this._scrollRaf = requestAnimationFrame(tick);+ };+ this._scrollRaf = requestAnimationFrame(tick);+ }++ _dismissHint() {+ if (!this._hint) return;+ this._hint.classList.remove('is-in');+ const el = this._hint;+ this._hint = null;+ setTimeout(() => el.remove(), 300);+ }+}++// ── FX ─────────────────────────────────────────────────────────────────────────+function ripple(x, y) {+ const r = document.createElement('div');+ r.className = 'tws-roam-ripple';+ r.style.left = x + 'px';+ r.style.top = y + 'px';+ document.body.appendChild(r);+ setTimeout(() => r.remove(), RIPPLE_MS);+}++function makeHint() {+ const h = document.createElement('div');+ h.className = 'tws-roam-hint';+ h.setAttribute('role', 'status');+ h.innerHTML =+ '<span class="tws-roam-hint__dot"></span>Free roam — click anywhere to walk me there, or drag me around. Press ▶ to rejoin the tour.';+ document.body.appendChild(h);+ requestAnimationFrame(() => h.classList.add('is-in'));+ return h;+}++let _stylesInjected = false;+function ensureStyles() {+ if (_stylesInjected) return;+ _stylesInjected = true;+ const style = document.createElement('style');+ style.id = 'tws-tour-roam-style';+ style.textContent = `+.tws-tour-guide.is-roam{pointer-events:auto;cursor:grab}+.tws-tour-guide.is-roam:active{cursor:grabbing}+.tws-roam-ripple{position:fixed;z-index:${Z_FX};width:14px;height:14px;margin:-7px 0 0 -7px;border-radius:50%;border:2px solid rgba(122,162,255,.9);pointer-events:none;animation:tws-roam-ripple ${RIPPLE_MS}ms ease-out forwards}+@keyframes tws-roam-ripple{0%{transform:scale(.4);opacity:.9}100%{transform:scale(3.4);opacity:0}}+.tws-roam-hint{position:fixed;left:50%;top:18px;transform:translateX(-50%) translateY(-12px);z-index:${Z_FX};display:flex;align-items:center;gap:9px;max-width:min(560px,92vw);padding:10px 16px;background:rgba(14,16,22,.94);backdrop-filter:blur(10px);border:1px solid rgba(122,162,255,.3);border-radius:99px;color:#e7eaf2;font:600 13px/1.3 system-ui,-apple-system,'Segoe UI',sans-serif;box-shadow:0 12px 34px rgba(0,0,0,.45);opacity:0;transition:opacity .3s ease,transform .3s ease;pointer-events:none}+.tws-roam-hint.is-in{opacity:1;transform:translateX(-50%) translateY(0)}+.tws-roam-hint__dot{width:8px;height:8px;border-radius:50%;background:linear-gradient(135deg,#7aa2ff,#9d7bff);box-shadow:0 0 10px rgba(122,162,255,.8);flex:0 0 auto}+@media (prefers-reduced-motion:reduce){.tws-roam-hint{transition:opacity .2s ease}.tws-roam-ripple{display:none}}+`;+ document.head.appendChild(style);+}diff --git a/src/feature-tour/guide-avatar.js b/src/feature-tour/guide-avatar.jsindex 816014aef..948cf036e 100644--- a/src/feature-tour/guide-avatar.js+++ b/src/feature-tour/guide-avatar.js@@ -191,6 +191,44 @@ export class GuideAvatar {this.controller?.playWave();}+ // ── Free-roam hooks ─────────────────────────────────────────────────────────+ // The canvas host is pointer-events:none during the guided tour so it never+ // eats page clicks; free-roam flips it interactive so the guide can be grabbed.+ setInteractive(on) {+ if (!this.host) return;+ this.host.style.pointerEvents = on ? 'auto' : 'none';+ this.host.classList.toggle('is-roam', !!on);+ }++ // Footprint of the avatar host, for centering it under a pointer.+ size() {+ const r = this.host?.getBoundingClientRect();+ return { w: r?.width || CANVAS_W, h: r?.height || CANVAS_H };+ }++ // Instant placement (drag / edge-scroll follow): clamp to the viewport, face+ // the direction of travel, run the walk cycle, and auto-settle to idle shortly+ // after movement stops so a parked guide isn't stuck mid-stride.+ place(pos) {+ const s = this.size();+ const x = clamp(pos.x, MARGIN, window.innerWidth - s.w - MARGIN);+ const y = clamp(pos.y, MARGIN, window.innerHeight - s.h - MARGIN);+ const dx = x - this._pos.x;+ if (Math.abs(dx) > 1) this._targetYaw = clamp((dx / window.innerWidth) * 2, -0.7, 0.7);+ this.controller?.setState('walk');+ this._walking = true;+ clearTimeout(this._settleTimer);+ this._settleTimer = setTimeout(() => this.settle(), 180);+ this._setPos({ x, y }, false);+ }++ settle() {+ clearTimeout(this._settleTimer);+ this._walking = false;+ this._targetYaw = 0;+ this.controller?.setState('idle');+ }+_spotBeside(rect) {const gap = 22;const rightX = rect.left + rect.width + gap;diff --git a/src/runtime/lipsync.js b/src/runtime/lipsync.jsindex f3d81d08f..25951082a 100644--- a/src/runtime/lipsync.js+++ b/src/runtime/lipsync.js@@ -101,70 +101,97 @@ function _resetMap(map) {}}+// The viseme active at `elapsedMs` in a sorted [{viseme,startMs,endMs}] sequence,+// or null in the gaps. Linear scan — sequences are short (one utterance).+export function activeVisemeAt(sequence, elapsedMs) {+ for (const entry of sequence) {+ if (elapsedMs >= entry.startMs && elapsedMs < entry.endMs) return entry.viseme;+ }+ return null;+}+/**- * Drive jaw/mouth morph targets in sync with speech text via a phoneme heuristic.- * Supports the ARKit viseme_* morph targets that three.ws avatars ship with (and the same names exported by Mixamo / VRM), plus jawOpen / mouthOpen fallbacks.+ * Build a morph driver bound to an avatar's mouth/jaw blendshapes. Returns null+ * when the avatar has none. `step(targetViseme)` lerps one frame toward the given+ * viseme (or rest when null); `reset()` zeroes every morph. Shared by the text+ * heuristic ({@link startLipsync}) and the neural timestamp lane (neural-tts.js).*- * @param {string} text — the spoken text- * @param {import('three').Object3D} root — avatar root (or scene) to traverse for morph targets- * @returns {{ stop(): void }}+ * @param {import('three').Object3D} root+ * @returns {{ mode:'arkit'|'jaw', step(target:string|null):void, reset():void }|null}*/-export function startLipsync(text, root) {- if (!text || !root) return { stop: () => {} };-+export function createVisemeDriver(root) {const result = _buildMorphMap(root);- if (!result) return { stop: () => {} };-+ if (!result) return null;const { mode, map } = result;- const sequence = _tokenize(text);-- const startTime = performance.now();const weights = new Map();for (const name of map.keys()) weights.set(name, 0);-- let rafId;- let stopped = false;-- const tick = () => {- if (stopped) return;- const elapsed = performance.now() - startTime;-- let targetViseme = null;- for (const entry of sequence) {- if (elapsed >= entry.startMs && elapsed < entry.endMs) {- targetViseme = entry.viseme;- break;- }- }-- if (mode === 'arkit') {- for (const [name, targets] of map.entries()) {- const goal = name === targetViseme ? 1 : 0;- const cur = weights.get(name);- const next = cur + (goal - cur) * LERP_FACTOR;- weights.set(name, next);- _setMorph(targets, next);- }- } else {- const goal = targetViseme ? 0.7 : 0;+ return {+ mode,+ step(targetViseme) {+ // 'arkit' rigs hit the exact viseme morph; 'jaw'-only rigs open the jaw+ // for any active viseme (a single morph can't shape phonemes).for (const [name, targets] of map.entries()) {+ const goal = mode === 'arkit' ? (name === targetViseme ? 1 : 0) : targetViseme ? 0.7 : 0;const cur = weights.get(name);const next = cur + (goal - cur) * LERP_FACTOR;weights.set(name, next);_setMorph(targets, next);}- }+ },+ reset() {+ for (const name of weights.keys()) weights.set(name, 0);+ _resetMap(map);+ },+ };+}+/**+ * Drive mouth morphs from a timed viseme sequence against a caller-supplied clock.+ * The clock decouples timing from wall-time: the text heuristic ticks on+ * `performance.now`, while the neural lane ticks on `audio.currentTime` so visemes+ * stay locked to playback even if the audio starts late or stalls.+ *+ * @param {import('three').Object3D} root+ * @param {Array<{viseme:string,startMs:number,endMs:number}>} sequence+ * @param {() => number} elapsedMs — current elapsed time, in ms+ * @returns {{ stop(): void }}+ */+export function playVisemeSequence(root, sequence, elapsedMs = () => 0) {+ const driver = createVisemeDriver(root);+ if (!driver || !sequence?.length) return { stop: () => {} };++ let rafId;+ let stopped = false;+ const tick = () => {+ if (stopped) return;+ driver.step(activeVisemeAt(sequence, elapsedMs()));rafId = requestAnimationFrame(tick);};-rafId = requestAnimationFrame(tick);return {stop() {stopped = true;if (rafId !== undefined) cancelAnimationFrame(rafId);- _resetMap(map);+ driver.reset();},};}++/**+ * Drive jaw/mouth morph targets in sync with speech text via a phoneme heuristic.+ * Supports the ARKit viseme_* morph targets that three.ws avatars ship with (and+ * the same names exported by Mixamo / VRM), plus jawOpen / mouthOpen fallbacks.+ * Used when the TTS lane gives no real timing (browser SpeechSynthesis); the+ * neural lane uses {@link playVisemeSequence} with actual phoneme timestamps.+ *+ * @param {string} text — the spoken text+ * @param {import('three').Object3D} root — avatar root (or scene) to traverse for morph targets+ * @returns {{ stop(): void }}+ */+export function startLipsync(text, root) {+ if (!text || !root) return { stop: () => {} };+ const sequence = _tokenize(text);+ const t0 = performance.now();+ return playVisemeSequence(root, sequence, () => performance.now() - t0);+}diff --git a/src/walk-companion-narrator.js b/src/walk-companion-narrator.jsnew file mode 100644index 000000000..48473cba9--- /dev/null+++ b/src/walk-companion-narrator.js@@ -0,0 +1,517 @@+// Section narration for the corner companion (Task 34).+// ======================================================+// As the visitor scrolls three.ws, the companion avatar "reads" the page section+// currently nearest it: a tasteful caption bubble rises beside the avatar, and —+// only when the visitor opts in — the same copy is spoken aloud through the real+// /api/tts/speak endpoint. This is the in-site sibling of the Chrome extension's+// content-narrator.js (task 09); it reuses that module's section model+// (author-marked → heading fallback, per-section debounce, custom scripts) but+// renders the bubble directly over the SDK companion instead of postMessaging an+// iframe.+//+// WHY a dedicated bubble (not the SDK's greeting bubble):+// The SDK's own `.walk-companion-bubble` is owned by the greeting/invite flow —+// reusing it would let a greeting timeout wipe a narration mid-read and vice+// versa. We mount our own caption element into the host, styled to match the+// SDK bubble but stacked above it, and drive it independently. It carries+// aria-live="polite" so assistive tech announces each section as the avatar+// reaches it — captions are the accessible, always-on channel; audio is opt-in.+//+// SECTION DETECTION (mirrors content-narrator.js):+// 1. Author-marked sections: every [data-walk-narrate] whose value isn't+// "skip". Authors mark exactly what should be read. An optional+// [data-walk-script] supplies hand-written copy (better than innerText).+// 2. Fallback for unmarked pages: headings + substantial blocks under the+// page's main/article region, with nav/header/footer chrome excluded.+// An IntersectionObserver tracks which section is most in view; a 600ms debounce+// (matching the extension) ensures each section narrates once as it settles into+// view, not on every scroll tick.+//+// SETTING: a three-state toggle persisted under the companion's own key+// convention (`${prefix}:companion:narrate`): "off" → silent, "caption" →+// captions only (default), "voice" → captions + spoken audio. Surfaced as a+// small round control slotted into the companion chrome alongside the+// trails/click-to-walk toggles, cycled on click. Default is caption-only so the+// avatar never speaks audio without an explicit opt-in — and even when "voice"+// is selected, the first audible clip is only attempted after a real user+// gesture (the toggle click that enabled it, or any subsequent interaction),+// honouring browser autoplay policy.+//+// MOTION: under prefers-reduced-motion the caption appears without slide/fade+// transitions (it still appears — the information is not motion). Audio is+// independent of the motion preference; it's gated solely by the voice opt-in.+//+// This module is owned by src/walk-companion.js, which calls installNarrator()+// once on load. Side-effect free on import.++import { prefersReducedMotion } from '../walk-sdk/src/internal/storage.js';++// ── Tunables (aligned with the extension's content-narrator.js) ────────────────+const SECTION_DEBOUNCE_MS = 600; // settle time before a newly-visible section reads+const MAX_CHARS = 400; // cap spoken/captioned copy so a clip is short & cheap+const MIN_SECTION_CHARS = 24; // ignore trivially short blocks in the fallback scan+const VISIBILITY_RATIO = 0.55; // a section must be this in-view to become active+const CAPTION_HOLD_MS = 5600; // how long a caption lingers when there's no audio+const RESCAN_DEBOUNCE_MS = 400; // coalesce DOM-mutation/route-change rescans+const TTS_VOICE = 'nova'; // default OpenAI/NVIDIA voice id the endpoint accepts++// The three narration modes, in cycle order. "caption" is the safe default:+// always-on text, never any audio. "voice" layers spoken audio on top. "off"+// silences everything.+const MODES = ['caption', 'voice', 'off'];+const MODE_LABELS = {+ off: 'Narration: off',+ caption: 'Narration: captions',+ voice: 'Narration: captions + voice',+};+const MODE_GLYPH = { off: '💬', caption: '💬', voice: '🔊' };++// ── Persistence (mirrors the companion's `${prefix}:companion:*` convention) ───+let PREF_KEY = 'walk:companion:narrate';++function readMode() {+ try {+ const v = localStorage.getItem(PREF_KEY);+ if (v && MODES.includes(v)) return v;+ } catch {+ /* private mode / disabled storage — fall through to default */+ }+ return 'caption'; // captions on, audio off, until the visitor opts in+}+function writeMode(mode) {+ try {+ localStorage.setItem(PREF_KEY, mode);+ } catch {+ /* private mode / disabled storage — in-memory only */+ }+}++// ── Section discovery ──────────────────────────────────────────────────────────+// Chrome we never narrate: site nav/header/footer and explicitly-hidden nodes.+const CHROME_SELECTOR = 'nav, header, footer, aside, [role="navigation"], [aria-hidden="true"], .walk-companion';++function textOf(el) {+ return (el.innerText || el.textContent || '').replace(/\s+/g, ' ').trim();+}++function isChrome(el) {+ if (el.closest(CHROME_SELECTOR)) return true;+ try {+ const cs = getComputedStyle(el);+ if (cs.display === 'none' || cs.visibility === 'hidden') return true;+ } catch {+ /* detached node — treat as chrome */+ return true;+ }+ return false;+}++// Resolve the readable sections for the current page.+// · If the author marked sections with [data-walk-narrate], honour exactly+// those (skipping value "skip" and chrome). Marked sections may be short —+// authors opted them in deliberately — so no min-length filter applies.+// · Otherwise fall back to headings + substantial blocks in the main region.+function findSections() {+ const marked = Array.from(document.querySelectorAll('[data-walk-narrate]')).filter(+ (el) => el.getAttribute('data-walk-narrate') !== 'skip' && !isChrome(el) && extractText(el),+ );+ if (marked.length > 0) return marked;++ const root = document.querySelector('main, article, [role="main"]') || document.body;+ const candidates = Array.from(root.querySelectorAll('h1, h2, h3, p, li, blockquote'));+ return candidates.filter((el) => !isChrome(el) && textOf(el).length >= MIN_SECTION_CHARS);+}++// The copy read for a section: a hand-written [data-walk-script] when present+// (better than raw text), else the section's own text, capped to MAX_CHARS.+function extractText(el) {+ const script = el.getAttribute && el.getAttribute('data-walk-script');+ if (script && script.trim()) return script.trim().slice(0, MAX_CHARS);+ return textOf(el).slice(0, MAX_CHARS);+}++// ── Caption bubble ─────────────────────────────────────────────────────────────+// A live-region caption mounted into the companion host, stacked above the SDK's+// own greeting bubble so the two never overwrite each other. Styled to match the+// SDK bubble (same surface/typography) using design tokens where they apply.+const CAPTION_STYLE_ID = 'walk-companion-narrate-style';+function ensureCaptionStyles() {+ if (document.getElementById(CAPTION_STYLE_ID)) return;+ const s = document.createElement('style');+ s.id = CAPTION_STYLE_ID;+ s.textContent = `+.walk-companion-caption{position:absolute;left:50%;bottom:calc(100% - 30px);z-index:4;transform:translateX(-50%) translateY(8px);max-width:240px;width:max-content;background:var(--surface-glass,rgba(18,20,28,.95));backdrop-filter:blur(var(--blur-sm,8px));-webkit-backdrop-filter:blur(var(--blur-sm,8px));color:var(--ink-bright,#f2f4f8);font:var(--weight-medium,500) var(--text-sm,12.5px)/var(--leading-tight,1.4) var(--font-body,system-ui,-apple-system,'Segoe UI',sans-serif);padding:8px 11px;border-radius:var(--radius-md,12px);border:1px solid var(--stroke-strong,rgba(255,255,255,.14));box-shadow:var(--shadow-2,0 10px 28px rgba(0,0,0,.35));pointer-events:none;opacity:0;transition:opacity .3s ease,transform .3s ease;text-align:left}+.walk-companion-caption.is-in{opacity:1;transform:translateX(-50%) translateY(0)}+.walk-companion-caption::after{content:'';position:absolute;left:50%;top:100%;transform:translateX(-50%);border:6px solid transparent;border-top-color:var(--surface-glass,rgba(18,20,28,.95))}+.walk-companion-caption .wcn-speaker{display:inline-block;margin-right:5px;opacity:.7;font-size:11px}+@media (max-width:520px){.walk-companion-caption{font-size:11.5px;max-width:170px}}+@media (prefers-reduced-motion:reduce){.walk-companion-caption{transition:none}}+.walk-companion-narrate{position:absolute;top:2px;right:106px;z-index:3;width:22px;height:22px;border:none;border-radius:50%;background:rgba(12,14,20,.55);color:#fff;font-size:12px;line-height:1;cursor:pointer;pointer-events:auto;opacity:0;transition:opacity .2s ease,background .2s ease;display:grid;place-items:center;padding:0}+.walk-companion:hover .walk-companion-narrate,.walk-companion:focus-within .walk-companion-narrate{opacity:1}+.walk-companion-narrate:hover{background:rgba(122,162,255,.85)}+.walk-companion-narrate:focus-visible{outline:2px solid #7aa2ff;outline-offset:2px;opacity:1}+@media (pointer:coarse){.walk-companion-narrate{opacity:1;right:114px}}+`;+ document.head.appendChild(s);+}++function createCaption(getHost) {+ let el = null;+ let hideTimer = 0;++ function mount() {+ const host = getHost();+ if (!host) return null;+ if (el && el.isConnected && el.parentNode === host) return el;+ // Host changed (avatar swap / playground round-trip) — remint the caption.+ el = document.createElement('div');+ el.className = 'walk-companion-caption';+ el.setAttribute('role', 'status');+ el.setAttribute('aria-live', 'polite');+ el.setAttribute('aria-atomic', 'true');+ el.hidden = true;+ host.appendChild(el);+ return el;+ }++ function show(text, { speaker = false, hold = CAPTION_HOLD_MS } = {}) {+ const node = mount();+ if (!node || !text) return;+ clearTimeout(hideTimer);+ // A small speaker glyph signals when audio accompanies the caption.+ node.textContent = '';+ if (speaker) {+ const icon = document.createElement('span');+ icon.className = 'wcn-speaker';+ icon.setAttribute('aria-hidden', 'true');+ icon.textContent = '🔊';+ node.appendChild(icon);+ }+ node.appendChild(document.createTextNode(text));+ node.hidden = false;+ // Force reflow so the entry transition fires when toggling .is-in.+ void node.offsetWidth;+ node.classList.add('is-in');+ if (hold > 0) {+ hideTimer = window.setTimeout(() => hide(), hold);+ }+ }++ function hide() {+ clearTimeout(hideTimer);+ if (!el) return;+ el.classList.remove('is-in');+ const node = el;+ window.setTimeout(() => {+ if (node && !node.classList.contains('is-in')) node.hidden = true;+ }, prefersReducedMotion() ? 0 : 300);+ }++ function dispose() {+ clearTimeout(hideTimer);+ el?.remove();+ el = null;+ }++ return { show, hide, dispose };+}++// ── Spoken audio (real TTS, opt-in, autoplay-policy aware) ──────────────────────+// Fetches a full clip from POST /api/tts/speak and plays it. Never autoplays+// before a user gesture: the install flips a "gesture seen" flag on the first+// pointer/key interaction, and the very act of choosing "voice" is itself a+// gesture. If playback is rejected by autoplay policy we degrade silently to the+// caption (which is already on screen) — no fake audio, no error noise.+function createSpeaker() {+ let audio = null;+ let controller = null;+ let objectUrl = null;++ function cancel() {+ if (controller) {+ controller.abort();+ controller = null;+ }+ if (audio) {+ audio.pause();+ audio.onended = null;+ audio.onerror = null;+ audio.src = '';+ audio = null;+ }+ if (objectUrl) {+ URL.revokeObjectURL(objectUrl);+ objectUrl = null;+ }+ }++ // Returns true if a clip began playing, false if it was unavailable/blocked.+ async function speak(text, { onEnd } = {}) {+ cancel();+ controller = new AbortController();+ let blob;+ try {+ const res = await fetch('/api/tts/speak', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({ text, voice: TTS_VOICE, format: 'mp3' }),+ signal: controller.signal,+ });+ if (!res.ok) {+ onEnd?.();+ return false;+ }+ blob = await res.blob();+ } catch {+ // Network failure or aborted by a newer section — treat as no audio.+ onEnd?.();+ return false;+ }+ if (!blob || blob.size === 0) {+ onEnd?.();+ return false;+ }+ objectUrl = URL.createObjectURL(blob);+ audio = new Audio(objectUrl);+ audio.onended = () => {+ cancel();+ onEnd?.();+ };+ audio.onerror = () => {+ cancel();+ onEnd?.();+ };+ try {+ await audio.play();+ return true;+ } catch {+ // Autoplay blocked (no gesture yet) — the caption already conveys it.+ cancel();+ onEnd?.();+ return false;+ }+ }++ return { speak, cancel };+}++// ── Settings toggle (slotted into the companion chrome) ────────────────────────+// Matches the trails/click-to-walk sibling buttons: a small round control in the+// host's top-right cluster, revealed on hover/focus, cycling off → caption →+// voice on click. aria-pressed reflects whether narration is active (not off).+function syncToggleVisual(btn, mode) {+ btn.title = MODE_LABELS[mode];+ btn.setAttribute('aria-label', MODE_LABELS[mode]);+ btn.setAttribute('aria-pressed', mode === 'off' ? 'false' : 'true');+ btn.textContent = MODE_GLYPH[mode];+ const active = mode !== 'off';+ btn.style.background = active ? 'rgba(122,162,255,.45)' : 'rgba(12,14,20,.55)';+ btn.style.color = active ? '#fff' : 'rgba(255,255,255,.5)';+}++function ensureToggle(host, getMode, onCycle) {+ if (!host || host.querySelector('.walk-companion-narrate')) return;+ const btn = document.createElement('button');+ btn.type = 'button';+ btn.className = 'walk-companion-narrate';+ syncToggleVisual(btn, getMode());+ btn.addEventListener('click', (e) => {+ e.stopPropagation();+ const next = onCycle();+ syncToggleVisual(btn, next);+ });+ host.appendChild(btn);+}++// ── Public install ─────────────────────────────────────────────────────────────+/**+ * Wire section narration to the companion.+ * @param {object} opts+ * @param {() => (object|null)} opts.getInstance returns the live WalkCompanion+ * instance (with .host, .mounted).+ * @param {() => (HTMLElement|null)} [opts.getHostEl] returns the companion host+ * for mounting the caption + settings toggle (defaults to getInstance().host).+ * @param {string} [opts.storageKey] localStorage key for the narration mode.+ * @returns {() => void} uninstall function.+ */+export function installNarrator({ getInstance, getHostEl, storageKey } = {}) {+ if (typeof document === 'undefined') return () => {};+ if (storageKey) PREF_KEY = storageKey;+ const resolveInst = typeof getInstance === 'function' ? getInstance : () => null;+ const resolveHost = () => {+ try {+ return (typeof getHostEl === 'function' ? getHostEl() : resolveInst()?.host) || null;+ } catch {+ return null;+ }+ };++ ensureCaptionStyles();++ let mode = readMode();+ const caption = createCaption(resolveHost);+ const speaker = createSpeaker();++ // Autoplay-policy gate: audio is only attempted after a real user gesture.+ // Choosing "voice" is itself a gesture, and we also flip this on the first+ // pointer/key interaction so a page that loads with "voice" already saved+ // waits for the visitor to touch the page before the avatar speaks.+ let userGestureSeen = false;+ const markGesture = () => {+ userGestureSeen = true;+ };+ document.addEventListener('pointerdown', markGesture, { capture: true, once: true });+ document.addEventListener('keydown', markGesture, { capture: true, once: true });++ // ── Observer + active-section tracking ──────────────────────────────────────+ let observer = null;+ let currentSection = null;+ let debounceTimer = 0;+ let sections = [];++ function setMode(next) {+ if (!MODES.includes(next)) return mode;+ mode = next;+ writeMode(mode);+ if (mode === 'off') {+ // Silence immediately: stop any clip and drop the caption.+ speaker.cancel();+ caption.hide();+ } else if (mode === 'caption') {+ // Keep the caption, mute audio at once.+ speaker.cancel();+ }+ return mode;+ }++ function cycleMode() {+ // Cycling via the toggle counts as the opt-in gesture for audio.+ markGesture();+ const idx = MODES.indexOf(mode);+ return setMode(MODES[(idx + 1) % MODES.length]);+ }++ function narrate(el) {+ const text = extractText(el);+ if (!text || mode === 'off') return;++ const wantVoice = mode === 'voice' && userGestureSeen;+ // Caption is the always-on channel; show it immediately. When audio is+ // coming we mark the speaker glyph and hold the caption open until the+ // clip ends (the speaker's onEnd hides it); otherwise it auto-dismisses.+ if (wantVoice) {+ caption.show(text, { speaker: true, hold: 0 });+ speaker.speak(text, {+ onEnd: () => {+ // Only retract if this is still the active section's caption.+ if (currentSection === el) caption.hide();+ },+ });+ } else {+ speaker.cancel();+ caption.show(text, { speaker: false, hold: CAPTION_HOLD_MS });+ }+ }++ function onSectionVisible(el) {+ if (el === currentSection) return;+ clearTimeout(debounceTimer);+ debounceTimer = window.setTimeout(() => {+ currentSection = el;+ narrate(el);+ }, SECTION_DEBOUNCE_MS);+ }++ function buildObserver() {+ observer?.disconnect();+ sections = findSections();+ if (sections.length === 0) {+ observer = null;+ return;+ }+ observer = new IntersectionObserver(+ (entries) => {+ let best = null;+ for (const entry of entries) {+ if (entry.isIntersecting && entry.intersectionRatio >= VISIBILITY_RATIO) {+ if (!best || entry.intersectionRatio > best.intersectionRatio) best = entry;+ }+ }+ if (best) onSectionVisible(best.target);+ },+ { threshold: [VISIBILITY_RATIO, 0.75, 1] },+ );+ for (const el of sections) observer.observe(el);+ }++ // Rescan when the DOM changes substantially (route swaps in the SPA, lazy+ // content). Debounced so a burst of mutations costs one rescan. We compare+ // the section set so a no-op mutation doesn't churn the observer.+ let rescanTimer = 0;+ function scheduleRescan() {+ clearTimeout(rescanTimer);+ rescanTimer = window.setTimeout(() => {+ const next = findSections();+ const changed =+ next.length !== sections.length || next.some((el, i) => el !== sections[i]);+ if (changed) {+ currentSection = null;+ buildObserver();+ }+ }, RESCAN_DEBOUNCE_MS);+ }++ const mutationObserver = new MutationObserver(scheduleRescan);++ function startObserving() {+ buildObserver();+ try {+ mutationObserver.observe(document.body, { childList: true, subtree: true });+ } catch {+ /* no body yet — the poll below will retry via tryWire */+ }+ }++ if (document.body) {+ startObserving();+ } else {+ document.addEventListener('DOMContentLoaded', startObserving, { once: true });+ }++ // ── Wire the toggle into the host (re-assert across avatar/host swaps) ───────+ let tries = 0;+ let wireTimer = 0;+ function tryWire() {+ const host = resolveHost();+ if (host) ensureToggle(host, () => mode, cycleMode);+ if (!sections.length && document.body) buildObserver();+ if (tries++ < 600) wireTimer = window.setTimeout(tryWire, 500);+ }+ tryWire();++ // Expose a small programmatic surface so the host/console can drive narration.+ const api = {+ get mode() {+ return mode;+ },+ setMode,+ cycleMode,+ rescan: scheduleRescan,+ };++ function uninstall() {+ clearTimeout(debounceTimer);+ clearTimeout(rescanTimer);+ clearTimeout(wireTimer);+ observer?.disconnect();+ mutationObserver.disconnect();+ document.removeEventListener('pointerdown', markGesture, { capture: true });+ document.removeEventListener('keydown', markGesture, { capture: true });+ speaker.cancel();+ caption.dispose();+ resolveHost()?.querySelector('.walk-companion-narrate')?.remove();+ }++ return { uninstall, api };+}diff --git a/src/walk-companion.js b/src/walk-companion.jsindex 598dd1ee8..06f595742 100644--- a/src/walk-companion.js+++ b/src/walk-companion.js@@ -16,6 +16,7 @@ import { createWalkCompanion } from '../walk-sdk/src/companion.js';import { installTransitions } from './walk-companion-transitions.js';import { createWalkTrails2D, createTrailSetting, TRAIL_STYLE_LABELS } from './walk-trails.js';import { installClickToWalk } from './walk-companion-click-to-walk.js';+import { installNarrator } from './walk-companion-narrator.js';const walk = createWalkCompanion({// Static GLBs and the animation manifest are served from this origin.@@ -255,4 +256,23 @@ installClickToWalk({storageKey: C2W_KEY,});+// ── Section narration (Task 34) ──────────────────────────────────────────────+// As the companion walks the page, it reads the section nearest it: a caption+// bubble (always-on, aria-live) and — strictly opt-in — spoken audio from the+// real /api/tts/speak endpoint. Authors mark what to read with+// [data-walk-narrate] (and optional [data-walk-script] copy); unmarked pages+// fall back to heading/paragraph detection. An IntersectionObserver picks the+// most-visible section, debounced so each narrates once. The off/caption/voice+// mode persists under the companion's own key namespace+// (`${prefix}:companion:narrate`); its settings pill slots into the same chrome+// as the trails/click-to-walk toggles. We pass the live instance getter so it+// survives avatar swaps and playground round-trips. Default is caption-only —+// audio never plays without an explicit opt-in and a real user gesture.+const NARRATE_KEY = `${(walk.config?.keys?.enabled || 'three:companion:enabled').split(':')[0]}:companion:narrate`;+installNarrator({+ getInstance: () => walk.instance,+ getHostEl: companionHost,+ storageKey: NARRATE_KEY,+});+walk.bootstrap();diff --git a/src/walk-npcs.js b/src/walk-npcs.jsnew file mode 100644index 000000000..2364fc67b--- /dev/null+++ b/src/walk-npcs.js@@ -0,0 +1,816 @@+// /walk — NPC companion avatars (Task 19)+//+// Populates the walk environment with a small cast of autonomous companions so+// the world feels alive even when you roam it alone. Each NPC is a *real*+// rigged GLB avatar from /avatars/, driven by the project's AnimationManager+// (the same idle / walk / wave / point clip library the player avatar uses),+// and steered by a tiny per-type finite-state machine:+//+// greeter — holds station near spawn; turns to face the player and waves ++// speaks a greeting when they come within range, then settles.+// wanderer — strolls a loop of waypoints, pausing to idle between legs.+// guide — leads toward a landmark: walks ahead, slows/waits when the+// player lags, points + narrates on arrival, then picks a new one.+//+// Dialogue is real and per-environment, loaded from+// public/environments/<env>/dialogue.json. When a line is spoken a token-styled+// speech bubble is projected above the NPC's head and (best-effort) voiced via+// the real /api/tts/speak endpoint — failures degrade silently to text only.+//+// The host (src/walk.js) owns spawn/despawn around environment swaps. Every+// GLB, mixer, material, and DOM node an NPC creates is released on despawn so+// swapping worlds never leaks geometry or audio.++import { Box3, Group, Vector3 } from 'three';+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+import { clone as cloneSkinnedScene } from 'three/addons/utils/SkeletonUtils.js';+import { AnimationManager } from './animation-manager.js';+import { log } from './shared/log.js';++// ── Clip names (must exist in /animations/clips + the manifest) ────────────+const CLIP_IDLE = 'idle';+const CLIP_WALK = 'av-walk-feminine';+const CLIP_WAVE = 'wave';+const CLIP_POINT = 'reaction'; // the registry-sanctioned "point" clip (see walk-gestures)++// ── Tuning ─────────────────────────────────────────────────────────────────+const MAX_NPCS = 4; // hard cap regardless of config length+const NPC_WALK_SPEED = 1.25; // m/s — a relaxed stroll, slower than the player+const NPC_NATURAL_WALK_SPEED = 1.5; // matches walk.js clip cadence for foot-plant sync+const NPC_TURN_LERP = 0.14; // facing smoothing toward heading+const GREET_RANGE = 4.0; // m — player enters → greeter waves + speaks+const GREET_RELEASE = 6.0; // m — hysteresis so the greeting doesn't retrigger on the edge+const GREET_COOLDOWN = 9.0; // s — minimum gap between a greeter's greetings+const WANDER_PAUSE = [1.8, 4.5]; // s — idle dwell range between wander legs+const WANDER_RADIUS = 8.5; // m — keep wander waypoints inside the walkable disc+const ARRIVE_DIST = 0.55; // m — "reached the waypoint" threshold+const GUIDE_WAIT_DIST = 6.5; // m — guide pauses if the player falls this far behind+const GUIDE_ARRIVE = 1.4; // m — guide considers a landmark reached+const GUIDE_NARRATE_COOLDOWN = 6.0; // s — min gap between guide narration lines+const SPEAK_COOLDOWN = 5.5; // s — global per-NPC speech throttle+const BUBBLE_DURATION = 4800; // ms — speech bubble lifetime+const BUBBLE_MAX_LEN = 120; // chars+const TTS_VOICE = 'alloy'; // a neutral catalog voice (api/_lib/tts-voices)++// Default NPC cast, used when an environment supplies no explicit `npcs`. Each+// references a real rigged GLB shipped in /public/avatars/. The greeter sits at+// spawn; the wanderer and guide get sensible roaming starts.+const DEFAULT_CAST = Object.freeze([+ { type: 'greeter', avatarUrl: '/avatars/michelle.glb', pos: [2.4, 0, 2.4] },+ { type: 'wanderer', avatarUrl: '/avatars/xbot.glb', pos: [-4.5, 0, 3.0] },+ { type: 'guide', avatarUrl: '/avatars/realistic-female.glb', pos: [4.0, 0, -3.5] },+]);++// Landmarks the guide can lead toward when an environment defines none. These+// are points on the walkable disc (the world is a 12 m radius ground), spread+// so the guide always has somewhere coherent to go.+const DEFAULT_LANDMARKS = Object.freeze([+ { name: 'the north overlook', pos: [0, 0, -8] },+ { name: 'the east path', pos: [8, 0, 0] },+ { name: 'the south clearing', pos: [0, 0, 8] },+ { name: 'the west edge', pos: [-8, 0, 0] },+]);++const UP = new Vector3(0, 1, 0);++// Shortest-arc angle lerp (radians) — shared by every NPC's facing update.+function lerpAngle(a, b, t) {+ let diff = ((b - a + Math.PI) % (Math.PI * 2)) - Math.PI;+ if (diff < -Math.PI) diff += Math.PI * 2;+ return a + diff * t;+}++function clamp(n, lo, hi) {+ return Math.max(lo, Math.min(hi, n));+}++function randRange([lo, hi]) {+ return lo + Math.random() * (hi - lo);+}++// Per-URL GLTF template cache shared across NPCs so two NPCs on the same model+// fetch the GLB once. SkeletonUtils.clone() gives each NPC its own bone+// hierarchy from the shared template.+const _templateCache = new Map(); // url → Promise<THREE.Object3D>+function loadTemplate(url) {+ let p = _templateCache.get(url);+ if (!p) {+ const loader = new GLTFLoader();+ p = loader.loadAsync(url).then((gltf) => gltf.scene);+ _templateCache.set(url, p);+ }+ return p;+}++// Sanitize NPC text for innerHTML insertion into the bubble.+function escapeHtml(s) {+ return String(s).replace(+ /[<>&"']/g,+ (c) => ({ '<': '<', '>': '>', '&': '&', '"': '"', "'": ''' })[c],+ );+}++/**+ * A single autonomous companion: a cloned GLB body, its own animation manager,+ * a token-styled speech bubble, and an FSM driven by `update(dt, ctx)`.+ */+class NPC {+ /**+ * @param {object} cfg { type, avatarUrl, pos:[x,y,z], name? }+ * @param {object} deps { scene, camera, renderer, getGroundY, dialogue, landmarks, animationDefs, ttsEnabled }+ */+ constructor(cfg, deps) {+ this.type = cfg.type;+ this.avatarUrl = cfg.avatarUrl;+ this.name = cfg.name || NPC.defaultName(cfg.type);+ this.deps = deps;++ this.rig = new Group();+ const [px, py, pz] = cfg.pos || [0, 0, 0];+ this.rig.position.set(px, py, pz);+ this.spawn = new Vector3(px, py, pz);+ deps.scene.add(this.rig);++ this._body = null; // cloned skinned scene+ this._anim = new AnimationManager();+ this._ready = false;+ this._disposed = false;++ this.yaw = Math.random() * Math.PI * 2;+ this.rig.quaternion.setFromAxisAngle(UP, this.yaw);+ this.motion = 'idle'; // 'idle' | 'walk'+ this._supportsClips = false;++ // FSM bookkeeping.+ this.state = 'idle';+ this._stateTimer = 0;+ this._target = null; // Vector3 destination, or null+ this._lastSpeakAt = -Infinity;+ this._lastGreetAt = -Infinity;+ this._lastNarrateAt = -Infinity;+ this._playerInRange = false;+ this._wantWave = false;+ this._currentLandmark = null;++ // Speech bubble DOM (token-styled, projected each frame).+ this._bubble = null;+ this._bubbleTimer = null;++ // Floating name label.+ this._label = this._createLabel();++ // Scratch reused per-frame to avoid GC churn.+ this._scratchDir = new Vector3();+ this._scratchHead = new Vector3();++ this._build(cfg);+ }++ static defaultName(type) {+ if (type === 'greeter') return 'Iris';+ if (type === 'guide') return 'Atlas';+ return 'Nova';+ }++ async _build(cfg) {+ let template;+ try {+ template = await loadTemplate(cfg.avatarUrl);+ } catch (err) {+ log.warn('[walk-npcs] failed to load NPC avatar', cfg.avatarUrl, err?.message || err);+ return;+ }+ if (this._disposed) return;++ const body = cloneSkinnedScene(template);+ body.traverse((n) => {+ if (n.isMesh) {+ n.castShadow = true;+ n.receiveShadow = false;+ if (n.material && 'envMapIntensity' in n.material) n.material.envMapIntensity = 0.85;+ }+ });+ // Drop the body's feet onto the rig origin so y=0 is the ground.+ const box = new Box3().setFromObject(body);+ body.position.y -= box.min.y;+ this.rig.add(body);+ this._body = body;++ this._anim.attach(body, { avatarUrl: cfg.avatarUrl });+ this._anim.setAnimationDefs(this.deps.animationDefs);+ this._supportsClips = this._anim.supportsCanonicalClips();++ try {+ await this._anim.loadAll();+ if (this._disposed) return;+ await this._anim.crossfadeTo(CLIP_IDLE, 0);+ } catch (err) {+ log.warn('[walk-npcs] NPC animation load failed', cfg.avatarUrl, err?.message || err);+ }++ // Seed the FSM per type.+ if (this.type === 'wanderer') this._enterWander();+ else if (this.type === 'guide') this._enterGuide();+ else this._enterStation();++ this._ready = true;+ }++ // ── State entries ────────────────────────────────────────────────────────+ _enterStation() {+ this.state = 'station';+ this._target = null;+ this._setMotion('idle');+ }+ _enterWander() {+ this.state = 'wander';+ this._target = this._pickWanderPoint();+ this._setMotion('walk');+ }+ _enterWanderPause() {+ this.state = 'wander-pause';+ this._target = null;+ this._stateTimer = randRange(WANDER_PAUSE);+ this._setMotion('idle');+ }+ _enterGuide() {+ this.state = 'guide-lead';+ this._currentLandmark = this._pickLandmark();+ this._target = this._currentLandmark ? new Vector3(...this._currentLandmark.pos) : null;+ this._setMotion(this._target ? 'walk' : 'idle');+ }++ _pickWanderPoint() {+ const a = Math.random() * Math.PI * 2;+ const r = 2 + Math.random() * (WANDER_RADIUS - 2);+ return new Vector3(Math.cos(a) * r, 0, Math.sin(a) * r);+ }++ _pickLandmark() {+ const list = this.deps.landmarks?.length ? this.deps.landmarks : DEFAULT_LANDMARKS;+ // Avoid immediately repeating the same landmark.+ let next = list[Math.floor(Math.random() * list.length)];+ if (list.length > 1 && this._currentLandmark && next.name === this._currentLandmark.name) {+ next = list[(list.indexOf(next) + 1) % list.length];+ }+ return next;+ }++ // ── Animation helpers ──────────────────────────────────────────────────+ _setMotion(motion) {+ if (motion === this.motion) return;+ this.motion = motion;+ if (!this._supportsClips) return;+ this._anim.crossfadeTo(motion === 'walk' ? CLIP_WALK : CLIP_IDLE, 0.22);+ }++ // Wave / point as an additive upper-body overlay so the legs keep their+ // locomotion. Falls back to a full crossfade only if the rig can't overlay.+ _playOverlay(clip) {+ if (!this._supportsClips) return;+ this._anim.playOverlay(clip, { loop: false, upperBodyOnly: true, crossfade: 0.2 });+ }++ // ── Per-frame FSM + locomotion ─────────────────────────────────────────+ /**+ * @param {number} dt seconds+ * @param {{ playerPos: Vector3 }} ctx live player state+ */+ update(dt, ctx) {+ if (this._disposed) return;+ this._anim.update(dt);+ if (!this._ready) {+ this._positionLabel();+ this._positionBubble();+ return;+ }++ const playerPos = ctx.playerPos;+ const distToPlayer = this.rig.position.distanceTo(playerPos);++ switch (this.type) {+ case 'greeter':+ this._tickGreeter(dt, playerPos, distToPlayer);+ break;+ case 'wanderer':+ this._tickWanderer(dt);+ break;+ case 'guide':+ this._tickGuide(dt, playerPos, distToPlayer);+ break;+ }++ this._stepToward(dt);+ this._positionLabel();+ this._positionBubble();+ }++ _tickGreeter(dt, playerPos, dist) {+ // Always face the player when they're nearby so the greeter reads as+ // attentive rather than staring into space.+ if (dist < GREET_RELEASE) this._faceToward(playerPos);++ const now = performance.now() / 1000;+ if (!this._playerInRange && dist < GREET_RANGE) {+ this._playerInRange = true;+ if (now - this._lastGreetAt > GREET_COOLDOWN) {+ this._lastGreetAt = now;+ this._playOverlay(CLIP_WAVE);+ this._speak(this._line('greeter'));+ }+ } else if (this._playerInRange && dist > GREET_RELEASE) {+ this._playerInRange = false; // hysteresis — re-arm only after leaving+ }+ // Greeter never roams; it stays parked at its station in idle.+ this._target = null;+ }++ _tickWanderer(dt) {+ if (this.state === 'wander-pause') {+ this._stateTimer -= dt;+ if (this._stateTimer <= 0) this._enterWander();+ return;+ }+ if (!this._target) {+ this._enterWander();+ return;+ }+ const d = Math.hypot(+ this._target.x - this.rig.position.x,+ this._target.z - this.rig.position.z,+ );+ if (d < ARRIVE_DIST) this._enterWanderPause();+ }++ _tickGuide(dt, playerPos, dist) {+ const now = performance.now() / 1000;+ if (this.state === 'guide-wait') {+ // Stand and face the player until they catch back up.+ this._faceToward(playerPos);+ this._target = null;+ if (dist < GUIDE_WAIT_DIST - 1.5) {+ this.state = 'guide-lead';+ this._target = this._currentLandmark+ ? new Vector3(...this._currentLandmark.pos)+ : null;+ this._setMotion(this._target ? 'walk' : 'idle');+ }+ return;+ }++ // Leading: if the player drops too far back, hold position and wait.+ if (dist > GUIDE_WAIT_DIST) {+ this.state = 'guide-wait';+ this._target = null;+ this._setMotion('idle');+ if (now - this._lastNarrateAt > GUIDE_NARRATE_COOLDOWN) {+ this._lastNarrateAt = now;+ this._speak(this._line('guide-wait'));+ }+ return;+ }++ const lm = this._currentLandmark;+ if (!lm) {+ this._enterGuide();+ return;+ }+ const reached =+ Math.hypot(lm.pos[0] - this.rig.position.x, lm.pos[2] - this.rig.position.z) <+ GUIDE_ARRIVE;+ if (reached) {+ // Arrived: face the player, point at the landmark, narrate, then move on.+ this._faceToward(playerPos);+ this._setMotion('idle');+ this._target = null;+ if (now - this._lastNarrateAt > GUIDE_NARRATE_COOLDOWN) {+ this._lastNarrateAt = now;+ this._playOverlay(CLIP_POINT);+ this._speak(this._line('guide-arrive', { landmark: lm.name }));+ }+ this.state = 'guide-pause';+ this._stateTimer = 3.2;+ return;+ }+ if (this.state === 'guide-pause') {+ this._stateTimer -= dt;+ if (this._stateTimer <= 0) this._enterGuide();+ return;+ }+ // Keep leading toward the landmark; stay ahead of the player.+ this._target = new Vector3(lm.pos[0], 0, lm.pos[2]);+ this._setMotion('walk');+ }++ // Move toward `_target` on the XZ plane at NPC_WALK_SPEED, snapping Y to the+ // ground each frame, and sync clip cadence to actual speed so feet plant.+ _stepToward(dt) {+ if (!this._target) {+ this._snapGround();+ this._syncCadence(0);+ return;+ }+ const dir = this._scratchDir.set(+ this._target.x - this.rig.position.x,+ 0,+ this._target.z - this.rig.position.z,+ );+ const dist = dir.length();+ if (dist < 1e-3) {+ this._snapGround();+ this._syncCadence(0);+ return;+ }+ dir.normalize();+ const step = Math.min(NPC_WALK_SPEED * dt, dist);+ this.rig.position.x += dir.x * step;+ this.rig.position.z += dir.z * step;+ // Keep inside the walkable disc.+ const r = Math.hypot(this.rig.position.x, this.rig.position.z);+ if (r > WANDER_RADIUS + 2) {+ const k = (WANDER_RADIUS + 2) / r;+ this.rig.position.x *= k;+ this.rig.position.z *= k;+ }+ this._snapGround();++ // Face the direction of travel.+ const wantYaw = Math.atan2(dir.x, dir.z);+ this.yaw = lerpAngle(this.yaw, wantYaw, NPC_TURN_LERP);+ this.rig.quaternion.setFromAxisAngle(UP, this.yaw);+ this._syncCadence(step / dt);+ }++ _faceToward(target) {+ const dx = target.x - this.rig.position.x;+ const dz = target.z - this.rig.position.z;+ if (Math.abs(dx) < 1e-4 && Math.abs(dz) < 1e-4) return;+ const wantYaw = Math.atan2(dx, dz);+ this.yaw = lerpAngle(this.yaw, wantYaw, NPC_TURN_LERP);+ this.rig.quaternion.setFromAxisAngle(UP, this.yaw);+ }++ _snapGround() {+ const y = this.deps.getGroundY?.(this.rig.position.x, this.rig.position.z);+ if (typeof y === 'number' && Number.isFinite(y)) this.rig.position.y = y;+ }++ // Match the walk clip's timeScale to actual ground speed (mirrors walk.js so+ // the NPC doesn't appear to skate). Idle holds timeScale at 1.+ _syncCadence(speed) {+ const mixer = this._anim.mixer;+ if (!mixer) return;+ mixer.timeScale =+ this.motion === 'walk' ? clamp(speed / NPC_NATURAL_WALK_SPEED, 0.5, 1.6) : 1.0;+ }++ // ── Dialogue ───────────────────────────────────────────────────────────+ // Pull a real line from the environment's dialogue table for this slot.+ // Falls back to a coin-agnostic generic line if a slot is empty so an NPC+ // never speaks an empty bubble.+ _line(slot, vars = {}) {+ const table = this.deps.dialogue || {};+ const pool = Array.isArray(table[slot]) && table[slot].length ? table[slot] : null;+ const generic = NPC._GENERIC[slot] || NPC._GENERIC.greeter;+ const src = pool || generic;+ let line = src[Math.floor(Math.random() * src.length)];+ for (const [k, v] of Object.entries(vars)) {+ line = line.replace(new RegExp(`\\{${k}\\}`, 'g'), v);+ }+ return line;+ }++ _speak(text) {+ if (!text) return;+ const now = performance.now() / 1000;+ if (now - this._lastSpeakAt < SPEAK_COOLDOWN) return;+ this._lastSpeakAt = now;+ this._showBubble(text);+ if (this.deps.ttsEnabled) this._voice(text);+ }++ // Best-effort TTS through the real /api/tts/speak endpoint. Any failure+ // (rate limit, no provider, offline) degrades silently to the text bubble.+ async _voice(text) {+ try {+ const res = await fetch('/api/tts/speak', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ text: text.slice(0, 240), voice: TTS_VOICE, format: 'mp3' }),+ });+ if (!res.ok) return;+ const buf = await res.arrayBuffer();+ if (this._disposed || !buf.byteLength) return;+ const blob = new Blob([buf], { type: res.headers.get('content-type') || 'audio/mpeg' });+ const url = URL.createObjectURL(blob);+ const audio = new Audio(url);+ audio.volume = 0.85;+ audio.addEventListener('ended', () => URL.revokeObjectURL(url), { once: true });+ // Autoplay may be blocked until the user interacts; the catch keeps it quiet.+ audio.play().catch(() => URL.revokeObjectURL(url));+ } catch {+ /* network/provider unavailable — bubble already shows the line */+ }+ }++ // ── Speech bubble (token-styled, projected) ─────────────────────────────+ _showBubble(text) {+ const clean = escapeHtml(text).slice(0, BUBBLE_MAX_LEN);+ if (!this._bubble) this._bubble = this._createBubble();+ this._bubbleText.innerHTML = clean;+ this._bubble.style.display = '';+ // Re-trigger the enter transition.+ this._bubble.style.opacity = '0';+ this._bubble.style.transform = 'translate(-50%,-100%) scale(0.7)';+ requestAnimationFrame(() => {+ if (!this._bubble) return;+ this._bubble.style.opacity = '1';+ this._bubble.style.transform = 'translate(-50%,-100%) scale(1)';+ });+ clearTimeout(this._bubbleTimer);+ this._bubbleTimer = setTimeout(() => {+ if (!this._bubble) return;+ this._bubble.style.opacity = '0';+ this._bubble.style.transform = 'translate(-50%,-100%) scale(0.85)';+ }, BUBBLE_DURATION);+ }++ _createBubble() {+ const wrap = document.createElement('div');+ wrap.className = 'walk-npc-bubble';+ wrap.setAttribute('role', 'status');+ wrap.setAttribute('aria-live', 'polite');+ wrap.style.cssText = [+ 'position:fixed',+ 'z-index:4',+ 'pointer-events:none',+ 'max-width:220px',+ 'padding:8px 13px',+ 'background:var(--surface-glass, rgba(10,10,10,0.82))',+ 'color:var(--text-1, #fafafa)',+ 'border:1px solid var(--border-1, rgba(255,255,255,0.12))',+ 'border-radius:var(--radius-lg, 14px)',+ 'backdrop-filter:blur(8px)',+ '-webkit-backdrop-filter:blur(8px)',+ 'font-family:inherit',+ 'font-size:var(--text-sm, 12px)',+ 'line-height:1.45',+ 'word-break:break-word',+ 'white-space:pre-wrap',+ 'transform:translate(-50%,-100%) scale(0.7)',+ 'opacity:0',+ 'transition:opacity 0.25s ease, transform 0.25s ease',+ 'will-change:transform,opacity',+ ].join(';');+ this._bubbleText = document.createElement('span');+ wrap.appendChild(this._bubbleText);+ // A small speaker name caption so it's clear who is talking.+ const cap = document.createElement('span');+ cap.textContent = this.name;+ cap.style.cssText =+ 'display:block;margin-top:3px;font-size:var(--text-2xs,11px);opacity:0.55;font-weight:600;letter-spacing:0.02em';+ wrap.appendChild(cap);+ // Arrow.+ const arrow = document.createElement('div');+ arrow.style.cssText = [+ 'position:absolute',+ 'bottom:-6px',+ 'left:50%',+ 'transform:translateX(-50%)',+ 'width:0',+ 'height:0',+ 'border-left:6px solid transparent',+ 'border-right:6px solid transparent',+ 'border-top:6px solid var(--bg-0, rgba(10,10,10,0.82))',+ ].join(';');+ wrap.appendChild(arrow);+ document.body.appendChild(wrap);+ return wrap;+ }++ _createLabel() {+ const el = document.createElement('div');+ el.className = 'walk-npc-label';+ el.textContent = this.name;+ el.style.cssText = [+ 'position:fixed',+ 'z-index:3',+ 'left:0',+ 'top:0',+ 'pointer-events:none',+ 'padding:2px 8px',+ 'border-radius:var(--radius-pill, 999px)',+ 'background:rgba(10,10,10,0.55)',+ 'border:1px solid var(--border-1, rgba(255,255,255,0.12))',+ 'color:var(--text-2, rgba(255,255,255,0.78))',+ 'font-family:inherit',+ 'font-size:var(--text-2xs, 11px)',+ 'font-weight:600',+ 'white-space:nowrap',+ 'transform:translate(-50%,-100%)',+ 'backdrop-filter:blur(6px)',+ '-webkit-backdrop-filter:blur(6px)',+ ].join(';');+ document.body.appendChild(el);+ return el;+ }++ _headScreen() {+ const head = this._scratchHead.set(+ this.rig.position.x,+ this.rig.position.y + 2.05,+ this.rig.position.z,+ );+ head.project(this.deps.camera);+ const onScreen = head.z > -1 && head.z < 1;+ const w = this.deps.renderer.domElement.clientWidth;+ const h = this.deps.renderer.domElement.clientHeight;+ return {+ onScreen,+ x: (head.x * 0.5 + 0.5) * w,+ y: (-head.y * 0.5 + 0.5) * h,+ };+ }++ _positionLabel() {+ if (!this._label) return;+ const s = this._headScreen();+ if (!s.onScreen) {+ this._label.style.display = 'none';+ return;+ }+ this._label.style.display = '';+ this._label.style.transform = `translate(-50%,-100%) translate(${s.x}px, ${s.y - 6}px)`;+ }++ _positionBubble() {+ if (!this._bubble || this._bubble.style.display === 'none') return;+ const s = this._headScreen();+ if (!s.onScreen) {+ this._bubble.style.display = 'none';+ return;+ }+ this._bubble.style.left = `${s.x}px`;+ this._bubble.style.top = `${s.y - 30}px`;+ }++ dispose() {+ this._disposed = true;+ clearTimeout(this._bubbleTimer);+ try {+ this._anim.dispose();+ } catch (e) {+ log.warn('[walk-npcs] anim dispose failed:', e);+ }+ if (this._body) {+ disposeObject3D(this._body);+ this.rig.remove(this._body);+ this._body = null;+ }+ this.deps.scene.remove(this.rig);+ this._label?.remove();+ this._bubble?.remove();+ this._label = null;+ this._bubble = null;+ }+}++// Coin-agnostic fallback dialogue, used when an environment ships no line for a+// slot. No coin is referenced anywhere — these are pure ambience.+NPC._GENERIC = Object.freeze({+ greeter: [+ 'Hey there — welcome in. Take a look around.',+ 'Good to see you. Wander wherever you like.',+ 'Welcome! The whole space is open to explore.',+ ],+ 'guide-wait': [+ 'Take your time — I will wait here.',+ 'No rush. I will hold up for you.',+ 'I will pause here until you catch up.',+ ],+ 'guide-arrive': [+ 'Here we are — {landmark}.',+ 'This is {landmark}. Worth a look.',+ 'And this is {landmark}.',+ ],+});++/** Recursively dispose geometry + materials of a subtree (mirrors walk.js). */+function disposeObject3D(root) {+ root.traverse((n) => {+ if (n.isMesh) {+ n.geometry?.dispose?.();+ const mats = Array.isArray(n.material) ? n.material : [n.material];+ for (const mat of mats) {+ if (!mat) continue;+ for (const v of Object.values(mat)) {+ if (v && v.isTexture) v.dispose();+ }+ mat.dispose?.();+ }+ }+ });+}++/**+ * The NPC system the host (src/walk.js) owns: it spawns a capped cast for the+ * current environment, drives every NPC's FSM from the render tick, and tears+ * the cast down (GLB + mixer + DOM) on environment swap.+ *+ * @param {object} opts+ * @param {THREE.Scene} opts.scene+ * @param {THREE.Camera} opts.camera+ * @param {THREE.WebGLRenderer} opts.renderer+ * @param {(x:number,z:number)=>number} opts.getGroundY terrain height sampler+ * @param {Array} opts.animationDefs shared clip defs (idle/walk/wave/reaction must be present)+ * @param {boolean} [opts.ttsEnabled=true] whether NPCs voice their lines+ */+export function createWalkNpcs(opts) {+ const { scene, camera, renderer, getGroundY, animationDefs } = opts;+ let ttsEnabled = opts.ttsEnabled !== false;++ /** @type {NPC[]} */+ let npcs = [];+ let enabled = true;+ const _playerPos = new Vector3();++ // Ensure the clips NPCs need are registered in the shared defs. The host's+ // defs already carry idle/walk; gesture defs (wave/reaction) are appended by+ // the gesture system, but NPCs may spawn before the user opens gestures — so+ // guarantee them here.+ function ensureNpcClipDefs() {+ const need = [+ { name: CLIP_WAVE, url: `/animations/clips/${CLIP_WAVE}.json`, loop: false },+ { name: CLIP_POINT, url: `/animations/clips/${CLIP_POINT}.json`, loop: false },+ ];+ for (const def of need) {+ if (!animationDefs.some((d) => d.name === def.name)) animationDefs.push(def);+ }+ }++ /**+ * Spawn the cast for an environment. Despawns any existing cast first.+ * @param {object} env { cast?:Array, landmarks?:Array, dialogue?:object }+ */+ function spawn(env = {}) {+ despawn();+ if (!enabled) return;+ ensureNpcClipDefs();++ const cast = (Array.isArray(env.cast) && env.cast.length ? env.cast : DEFAULT_CAST).slice(+ 0,+ MAX_NPCS,+ );+ const landmarks = Array.isArray(env.landmarks) && env.landmarks.length ? env.landmarks : null;+ const dialogue = env.dialogue || {};++ for (const cfg of cast) {+ if (!cfg?.avatarUrl || !cfg?.type) continue;+ npcs.push(+ new NPC(cfg, {+ scene,+ camera,+ renderer,+ getGroundY,+ dialogue,+ landmarks,+ animationDefs,+ ttsEnabled,+ }),+ );+ }+ }++ function despawn() {+ for (const npc of npcs) npc.dispose();+ npcs = [];+ }++ /**+ * Advance every NPC. Call from the render tick.+ * @param {number} dt+ * @param {{x:number,y:number,z:number}} playerPos+ */+ function update(dt, playerPos) {+ if (!enabled || npcs.length === 0) return;+ _playerPos.set(playerPos.x, playerPos.y, playerPos.z);+ for (const npc of npcs) npc.update(dt, { playerPos: _playerPos });+ }++ function setEnabled(on) {+ enabled = !!on;+ if (!enabled) despawn();+ }+ function isEnabled() {+ return enabled;+ }+ function setTtsEnabled(on) {+ ttsEnabled = !!on;+ for (const npc of npcs) npc.deps.ttsEnabled = ttsEnabled;+ }+ function count() {+ return npcs.length;+ }++ return { spawn, despawn, update, setEnabled, isEnabled, setTtsEnabled, count };+}diff --git a/src/walk.js b/src/walk.jsindex 043c6e69c..a6c5434d0 100644--- a/src/walk.js+++ b/src/walk.js@@ -64,6 +64,7 @@ import {import { log } from './shared/log.js';import { createWalkTrails3D, createTrailSetting, TRAIL_STYLE_LABELS } from './walk-trails.js';import { createWalkSession, showWelcomeBackToast } from './walk-session.js';+import { createWalkNpcs } from './walk-npcs.js';const AVATAR_URL_DEFAULT = '/avatars/default.glb';@@ -466,6 +467,24 @@ const trailSetting = createTrailSetting(TRAIL_KEY, 'footprints');/** @type {ReturnType<typeof createWalkTrails3D>|null} */let trails = null;+// ── NPC companions (Task 19) ───────────────────────────────────────────────+// A small cast of autonomous companions — a greeter, a wanderer, and a guide —+// that make each environment feel inhabited. Built once the avatar + animation+// clips load (so NPCs share the resolved clip library), spawned/despawned per+// environment with its own dialogue table, and ticked in the render loop. The+// on/off choice is persisted with the same namespaced-key convention as the+// other walk settings, and the toggle lives in the controls overlay.+const NPC_KEY = 'walk:npcs';+let npcsEnabled = (() => {+ try {+ return localStorage.getItem(NPC_KEY) !== '0';+ } catch {+ return true;+ }+})();+/** @type {ReturnType<typeof createWalkNpcs>|null} */+let walkNpcs = null;+// Avatar accent → trail colour. The walk avatar is a raw GLB, so we read any// authored meta accent (gltf.userData / scene.userData), else fall back to the// brand --accent token (handled inside the trail system).@@ -967,6 +986,14 @@ const helpOverlay = (() => {${TRAIL_STYLE_LABELS[trailSetting.get()]}</button></div>+ <div style="margin:14px 0 0;padding-top:14px;border-top:1px solid rgba(255,255,255,0.1);display:flex;align-items:center;justify-content:space-between" data-help-keep>+ <span style="font-size:14px">NPC companions</span>+ <button type="button" id="walk-npc-toggle" role="switch" data-help-keep+ aria-checked="${npcsEnabled}"+ style="appearance:none;border:1px solid rgba(255,255,255,0.2);background:${npcsEnabled ? 'var(--accent,#7c5cff)' : 'rgba(255,255,255,0.08)'};color:#fff;border-radius:999px;padding:5px 14px;font:inherit;font-size:13px;cursor:pointer">+ ${npcsEnabled ? 'On' : 'Off'}+ </button>+ </div><p style="margin:20px 0 0;font-size:12px;color:#666">Click the canvas to lock the mouse for first-person look.</p></div>`;document.body.appendChild(el);@@ -1004,6 +1031,32 @@ if (trailToggle) {});}+// NPC companions on/off. Persisted; applied live — turning them on respawns the+// current environment's cast, turning them off despawns and releases every NPC.+const npcToggle = helpOverlay.querySelector('#walk-npc-toggle');+if (npcToggle) {+ npcToggle.addEventListener('click', () => {+ npcsEnabled = !npcsEnabled;+ try {+ localStorage.setItem(NPC_KEY, npcsEnabled ? '1' : '0');+ } catch {}+ npcToggle.setAttribute('aria-checked', String(npcsEnabled));+ npcToggle.textContent = npcsEnabled ? 'On' : 'Off';+ npcToggle.style.background = npcsEnabled+ ? 'var(--accent,#7c5cff)'+ : 'rgba(255,255,255,0.08)';+ if (walkNpcs) {+ walkNpcs.setEnabled(npcsEnabled);+ if (npcsEnabled && walkManifest) {+ const meta = getEnvironment(walkManifest, currentEnvName);+ if (meta) applyNpcsForEnv(meta, envApplyToken);+ }+ }+ setStatus(`NPC companions: ${npcsEnabled ? 'on' : 'off'}`);+ haptics.buzz(6);+ });+}+let helpVisible = false;function toggleHelp() {helpVisible = !helpVisible;@@ -1396,6 +1449,19 @@ async function loadAvatar() {setStatus('Ready — drag to look around');setupGestures();+ // Stand up the NPC companion system now that the clip library is resolved.+ // initEnvironments() (which runs after the avatar boots) populates the first+ // world's NPCs via applyNpcsForEnv(); subsequent env swaps respawn them.+ walkNpcs = createWalkNpcs({+ scene,+ camera,+ renderer,+ getGroundY: (x, z) => (arActive ? GROUND_Y : terrain.heightAt(x, z)),+ animationDefs,+ ttsEnabled: true,+ });+ walkNpcs.setEnabled(npcsEnabled);+// Auto-hide help hints after 5 seconds — fade first, then remove from layout// so the transition in temporary.html's #walk-help { transition: opacity } plays.if (helpEl) {@@ -2252,6 +2318,10 @@ function tick() {}updateRemotePlayers(dt);+ // 4a. Advance the NPC companions' FSMs (greeter waves on approach, wanderer+ // roams, guide leads toward a landmark) against the live player position.+ if (walkNpcs && avatar) walkNpcs.update(dt, avatarRig.position);+// 4b. Animate the coin totem (billboard + bob + ring spin) when present.if (coinTotem) coinTotem.update(dt);@@ -3529,6 +3599,40 @@ async function loadEnvScenery(meta, token) {if ('environmentIntensity' in scene) scene.environmentIntensity = meta.envIntensity || 1;}+// Per-environment NPC dialogue tables, cached so re-entering a world doesn't+// re-fetch. Each table is the parsed public/environments/<env>/dialogue.json+// (greeter / guide lines + landmarks); a missing or malformed file degrades to+// the NPC system's built-in coin-agnostic fallback copy.+const _npcDialogueCache = new Map(); // envName → { greeter, 'guide-arrive', 'guide-wait', landmarks }++async function loadEnvDialogue(meta) {+ if (_npcDialogueCache.has(meta.name)) return _npcDialogueCache.get(meta.name);+ let table = {};+ try {+ const res = await fetch(`/environments/${meta.name}/dialogue.json`, { cache: 'force-cache' });+ if (res.ok) table = await res.json();+ } catch (err) {+ log.warn('[walk] NPC dialogue unavailable for', meta.name, err?.message || err);+ }+ _npcDialogueCache.set(meta.name, table);+ return table;+}++// Spawn the NPC cast for an environment. The dialogue table supplies the spoken+// lines and the guide's landmarks; the cast itself defaults to the built-in+// greeter/wanderer/guide trio unless the table provides an explicit `npcs` list.+// Guarded by `token` so a rapid env re-selection discards a superseded spawn.+async function applyNpcsForEnv(meta, token) {+ if (!walkNpcs) return;+ const table = await loadEnvDialogue(meta);+ if (token !== envApplyToken) return; // a newer swap already took over+ walkNpcs.spawn({+ cast: Array.isArray(table.npcs) ? table.npcs : null,+ landmarks: Array.isArray(table.landmarks) ? table.landmarks : null,+ dialogue: table,+ });+}+// Full environment swap. The first paint applies instantly; later swaps fade to// the new sky's horizon colour for ~300 ms so the world change is seamless.async function applyEnvironment(name, { initial = false } = {}) {@@ -3542,6 +3646,7 @@ async function applyEnvironment(name, { initial = false } = {}) {if (initial) {applyEnvironmentMeta(meta);await loadEnvScenery(meta, token);+ applyNpcsForEnv(meta, token);return;}await fadeWorld(skyFadeColor(meta), 1);@@ -3549,6 +3654,7 @@ async function applyEnvironment(name, { initial = false } = {}) {applyEnvironmentMeta(meta);await loadEnvScenery(meta, token);if (token !== envApplyToken) return;+ applyNpcsForEnv(meta, token);await fadeWorld(null, 0);}diff --git a/tests/animation-retarget.test.js b/tests/animation-retarget.test.jsindex e0edc4484..d1791d67a 100644--- a/tests/animation-retarget.test.js+++ b/tests/animation-retarget.test.js@@ -37,7 +37,7 @@ import {scaleClipSpeed,MIN_COVERAGE,} from '../src/animation-retarget.js';-import { CANONICAL_REST } from '../src/animation-canonical-rest.js';+import { CANONICAL_REST, CANONICAL_REST_WORLD } from '../src/animation-canonical-rest.js';import { canonicalizeBoneName } from '../src/glb-canonicalize.js';import { loadBoneGraph } from './_helpers/glb-bone-graph.js';@@ -494,3 +494,85 @@ describe('cross-rig locomotion invariants (real GLB)', () => {}});});++describe('world-delta correctness — limb retarget preserves world motion', () => {+ // The bug this guards: a local-only premultiply correction (Rt·Rs⁻¹·q) replays a+ // clip bone's deviation in the wrong frame, skewing limbs by ~30° on a rig whose+ // rest pose differs from the cz authoring rig. The world-aware correction+ // (q ← L·q·R) must instead reproduce the SAME world-space rotation delta on any+ // rest pose. Oracle is three's getWorldQuaternion — independent of the module's+ // own world-rest math, so the test can't pass by sharing the bug.+ const Rs = new Quaternion().fromArray(CANONICAL_REST.LeftArm); // cz LeftArm local rest+ const WS = new Quaternion().fromArray(CANONICAL_REST_WORLD.LeftArm); // …world rest++ // A target rig whose LeftArm rests deep down-and-in, under rotated Hips/Spine —+ // a rest pose far from cz, so a local-only correction would visibly skew it.+ function buildTarget() {+ const root = new Object3D();+ const hips = Object.assign(new Bone(), { name: 'Hips' });+ hips.quaternion.setFromEuler(new Euler(0.12, 0.25, -0.08));+ const spine = Object.assign(new Bone(), { name: 'Spine' });+ spine.quaternion.setFromEuler(new Euler(0.05, 0, 0.18));+ const arm = Object.assign(new Bone(), { name: 'LeftArm' });+ arm.quaternion.setFromEuler(new Euler(0.2, -0.3, -1.1));+ spine.add(arm);+ hips.add(spine);+ root.add(hips);+ root.updateMatrixWorld(true);+ return { root, arm, restLocal: arm.quaternion.clone() };+ }++ // A clip keyframe: cz's LeftArm rotated by world delta D, as its absolute local+ // rotation (sourceParentWorld = WS·Rs⁻¹ ⇒ local = parent⁻¹·D·WS).+ function clipForWorldDelta(D) {+ const parentWorld = WS.clone().multiply(Rs.clone().invert());+ const S = parentWorld.clone().invert().multiply(D).multiply(WS);+ return new AnimationClip('m', 1, [+ new QuaternionKeyframeTrack(+ 'LeftArm.quaternion',+ [0, 1],+ [S.x, S.y, S.z, S.w, S.x, S.y, S.z, S.w],+ ),+ ]);+ }++ const worldDirErr = (a, b) => {+ const probe = new Vector3(0, 1, 0);+ return (+ (probe.clone().applyQuaternion(a).angleTo(probe.clone().applyQuaternion(b)) * 180) / Math.PI+ );+ };++ it('reproduces a known world-space arm motion on a foreign rest pose (≈0° error)', () => {+ const D = new Quaternion().setFromAxisAngle(new Vector3(1, 0, 0), (40 * Math.PI) / 180);+ const clip = clipForWorldDelta(D);+ const { root, arm } = buildTarget();+ const restWorld = arm.getWorldQuaternion(new Quaternion()); // bind world (oracle)+ const expected = D.clone().multiply(restWorld); // same world delta on target rest++ const out = retargetClipToObject(clip, root, { minCoverage: 0 }).clip;+ const t = out.tracks.find((x) => x.name === 'LeftArm.quaternion');+ arm.quaternion.set(t.values[0], t.values[1], t.values[2], t.values[3]);+ root.updateMatrixWorld(true);+ const actual = arm.getWorldQuaternion(new Quaternion());++ expect(worldDirErr(actual, expected)).toBeLessThan(0.5);+ });++ it('the old local-only premultiply (Rt·Rs⁻¹·q) would skew this badly (>5°) — test is discriminating', () => {+ const D = new Quaternion().setFromAxisAngle(new Vector3(1, 0, 0), (40 * Math.PI) / 180);+ const clip = clipForWorldDelta(D);+ const { root, arm, restLocal } = buildTarget();+ const restWorld = arm.getWorldQuaternion(new Quaternion());+ const expected = D.clone().multiply(restWorld);++ // Reconstruct the prior behaviour: C·q with C = Rt·Rs⁻¹ (no world term).+ const S = new Quaternion(clip.tracks[0].values[0], clip.tracks[0].values[1], clip.tracks[0].values[2], clip.tracks[0].values[3]);+ const buggy = restLocal.clone().multiply(Rs.clone().invert()).multiply(S);+ arm.quaternion.copy(buggy);+ root.updateMatrixWorld(true);+ const actual = arm.getWorldQuaternion(new Quaternion());++ expect(worldDirErr(actual, expected)).toBeGreaterThan(5);+ });+});diff --git a/tests/api/avatars-glb-proxy.test.js b/tests/api/avatars-glb-proxy.test.jsindex 270e731cc..073b9977e 100644--- a/tests/api/avatars-glb-proxy.test.js+++ b/tests/api/avatars-glb-proxy.test.js@@ -1,12 +1,19 @@-// Tests for the /api/avatars/:id/:action dispatcher's GLB proxy resolution.+// Tests for the /api/avatars/:id/:action dispatcher's GLB proxy routing.//-// Two behaviours are covered, both offline via the demo-avatar fixture (the-// demo branch 302-redirects without touching R2 or the DB):-// 1. A `.glb`-terminating action (`model.glb`, `<uuid>.glb`, …) resolves to-// the same GLB proxy as the bare `glb` action — so glТF viewers / NFT-// marketplaces that sniff the URL extension can load three.ws avatars.-// 2. The demo branch redirects to the fixture's `glbUrl` (regression guard:-// it previously read a non-existent `demo.url` and 404'd every demo).+// The valuable, provider-independent behaviour here is the URL routing the+// dispatcher performs before any storage work:+// 1. A `.glb`-terminating action (`model.glb`, `<uuid>.glb`, …) is normalised+// to the bare `glb` action — so glTF viewers / NFT marketplaces that sniff+// the URL extension load three.ws avatars unchanged.+// 2. That normalisation must NOT swallow `glb-versions` (no `.glb` suffix), and+// unknown actions / malformed ids must 404 cleanly rather than 500.+//+// The bare `glb` action streams the GLB bytes from R2 (200, model/gltf-binary).+// We assert the routing via the CORS preflight, which the glb proxy answers with+// a wildcard 204 BEFORE touching the DB or R2 — keeping the suite fully offline.+// (A previous incarnation 302-redirected a hardcoded demo-avatar fixture; that+// seed data was removed in a platform audit pass, so the suite now exercises the+// real handler path instead of the deleted demo branch.)//// DB, R2, auth, and the zauth SDK are mocked so the suite runs with no network.@@ -14,12 +21,14 @@ import { describe, it, expect, vi } from 'vitest';vi.mock('../../api/_lib/zauth.js', () => ({ instrument: () => false, drain: async () => {} }));vi.mock('../../api/_lib/sentry.js', () => ({ captureException: () => {} }));-// Any DB/R2 access means the demo short-circuit was skipped — fail loudly.+// The routing paths under test (CORS preflight, anonymous 401, dispatcher 404s)+// all resolve before any storage access — so a DB or R2 hit means a path+// short-circuited later than expected. Fail loudly if one is reached.vi.mock('../../api/_lib/db.js', () => ({- sql: () => { throw new Error('DB should not be queried for a demo avatar'); },+ sql: () => { throw new Error('DB should not be queried on a routing-only path'); },}));vi.mock('../../api/_lib/r2.js', () => ({- r2: { send: () => { throw new Error('R2 should not be hit for a demo avatar'); } },+ r2: { send: () => { throw new Error('R2 should not be hit on a routing-only path'); } },publicUrl: (key) => `https://cdn.test/${key}`,}));// No credentials on any request → every auth path resolves anonymous.@@ -31,15 +40,16 @@ vi.mock('../../api/_lib/auth.js', () => ({}));import handler from '../../api/avatars/[id]/[action].js';-import { DEMO_AVATARS } from '../../api/_lib/demo-avatars.js';-const DEMO = DEMO_AVATARS[0]; // avatar_demo_disk_cz → https://three.ws/avatars/cz.glb+// A syntactically valid avatar UUID — the dispatcher 404s any non-uuid id before+// dispatching, so the demo-style `avatar_demo_*` ids no longer reach a handler.+const ID = '11111111-1111-4111-8111-111111111111';function makeReq({ id, action, method = 'GET' } = {}) {return {method,url: `/api/avatars/${id}/${action}`,- headers: { host: 'three.ws' },+ headers: { host: 'three.ws', origin: 'https://example.com' },query: { id, action },};}@@ -48,11 +58,16 @@ function makeRes() {return {statusCode: 200,_h: {},+ body: undefined,headersSent: false,writableEnded: false,setHeader(k, v) { this._h[k.toLowerCase()] = v; },getHeader(k) { return this._h[k.toLowerCase()]; },- end() { this.writableEnded = true; this.headersSent = true; },+ end(chunk) {+ if (chunk !== undefined) this.body = chunk;+ this.writableEnded = true;+ this.headersSent = true;+ },};}@@ -63,40 +78,46 @@ async function invoke(opts) {return res;}-describe('GET /api/avatars/:id/:action — GLB proxy resolution', () => {- it('redirects the bare `glb` action to the demo fixture glbUrl', async () => {- const res = await invoke({ id: DEMO.avatarId, action: 'glb' });- expect(res.statusCode).toBe(302);- expect(res.getHeader('location')).toBe(DEMO.glbUrl);+describe('GET /api/avatars/:id/:action — GLB proxy routing', () => {+ it('answers the bare `glb` preflight with a wildcard 204 (no DB/R2 touched)', async () => {+ const res = await invoke({ id: ID, action: 'glb', method: 'OPTIONS' });+ expect(res.statusCode).toBe(204);+ expect(res.getHeader('access-control-allow-origin')).toBe('*');});- it('resolves a `model.glb` action to the same GLB proxy', async () => {- const res = await invoke({ id: DEMO.avatarId, action: 'model.glb' });- expect(res.statusCode).toBe(302);- expect(res.getHeader('location')).toBe(DEMO.glbUrl);+ it('normalises a `model.glb` action to the glb proxy (same wildcard preflight)', async () => {+ const res = await invoke({ id: ID, action: 'model.glb', method: 'OPTIONS' });+ expect(res.statusCode).toBe(204);+ expect(res.getHeader('access-control-allow-origin')).toBe('*');});- it('resolves a `<uuid>.glb` action (case-insensitive suffix) to the GLB proxy', async () => {- const res = await invoke({ id: DEMO.avatarId, action: `${DEMO.avatarId}.GLB` });- expect(res.statusCode).toBe(302);- expect(res.getHeader('location')).toBe(DEMO.glbUrl);+ it('normalises a `<uuid>.GLB` action case-insensitively to the glb proxy', async () => {+ const res = await invoke({ id: ID, action: `${ID}.GLB`, method: 'OPTIONS' });+ expect(res.statusCode).toBe(204);+ expect(res.getHeader('access-control-allow-origin')).toBe('*');});- it('serves wildcard CORS so third-party hosts can fetch the bytes', async () => {- const res = await invoke({ id: DEMO.avatarId, action: 'model.glb' });- expect(res.getHeader('access-control-allow-origin')).toBe('*');+ it('exposes the byte headers third-party hosts need on the preflight', async () => {+ const res = await invoke({ id: ID, action: 'model.glb', method: 'OPTIONS' });+ expect(res.getHeader('access-control-expose-headers')).toContain('content-length');});it('does not treat `glb-versions` as the glb proxy', async () => {- // glb-versions requires auth; with no session/bearer it must 401, proving- // the `.glb` normalization did not swallow it into the glb handler (which- // would have 302'd the demo instead).- const res = await invoke({ id: DEMO.avatarId, action: 'glb-versions' });+ // glb-versions has no `.glb` suffix, so the normalisation must leave it+ // alone. It auth-gates before any DB work, so an anonymous request 401s —+ // proving it routed to handleGlbVersions, not the wildcard glb proxy (which+ // would have answered 204/200 with no auth).+ const res = await invoke({ id: ID, action: 'glb-versions' });expect(res.statusCode).toBe(401);});it('404s an unknown action', async () => {- const res = await invoke({ id: DEMO.avatarId, action: 'not-a-real-action' });+ const res = await invoke({ id: ID, action: 'not-a-real-action' });+ expect(res.statusCode).toBe(404);+ });++ it('404s a malformed (non-uuid) avatar id before dispatching', async () => {+ const res = await invoke({ id: 'avatar_demo_disk_cz', action: 'glb' });expect(res.statusCode).toBe(404);});});diff --git a/tests/api/resilience.test.js b/tests/api/resilience.test.jsnew file mode 100644index 000000000..c5179ae5f--- /dev/null+++ b/tests/api/resilience.test.js@@ -0,0 +1,75 @@+/**+ * Shared resilience helper (api/_lib/resilience.js) — the cockatiel-backed+ * circuit breaker that external call sites use to fail fast and degrade during an+ * upstream outage. These pin the contract: success passes through, failures+ * degrade to the fallback, and after `threshold` consecutive failures the circuit+ * opens and stops invoking the operation entirely.+ */++import { describe, it, expect, beforeEach } from 'vitest';+import { withBreaker, isCircuitError, _resetBreakers } from '../../api/_lib/resilience.js';+import { BrokenCircuitError } from 'cockatiel';++beforeEach(() => _resetBreakers());++describe('withBreaker', () => {+ it('returns the operation result on success', async () => {+ expect(await withBreaker('t:ok', async () => 42, { fallback: -1 })).toBe(42);+ });++ it('degrades to the fallback when the operation throws', async () => {+ const r = await withBreaker('t:fail', async () => {+ throw new Error('boom');+ }, { fallback: 'fb' });+ expect(r).toBe('fb');+ });++ it('supports a fallback factory that sees the error', async () => {+ const r = await withBreaker(+ 't:fail2',+ async () => {+ throw new Error('boom');+ },+ { fallback: (e) => `caught:${e.message}` },+ );+ expect(r).toBe('caught:boom');+ });++ it('opens the circuit after `threshold` consecutive failures and stops calling the op', async () => {+ let calls = 0;+ const op = async () => {+ calls++;+ throw new Error('down');+ };+ const run = () =>+ withBreaker('t:breaker', op, { fallback: null, threshold: 3, halfOpenAfterMs: 60_000 });++ await run();+ await run();+ await run(); // 3rd consecutive failure → circuit opens+ expect(calls).toBe(3);++ const r = await run(); // open → short-circuits WITHOUT invoking op+ expect(r).toBeNull();+ expect(calls).toBe(3);+ });++ it('flags an open-circuit rejection via isCircuitError', async () => {+ const op = async () => {+ throw new Error('down');+ };+ const opts = { threshold: 2, halfOpenAfterMs: 60_000, fallback: (e) => e };+ await withBreaker('t:flag', op, opts);+ await withBreaker('t:flag', op, opts); // opens+ const err = await withBreaker('t:flag', op, opts); // open → returns the circuit error+ expect(err).toBeInstanceOf(BrokenCircuitError);+ expect(isCircuitError(err)).toBe(true);+ });++ it('isolates breakers by name (one open upstream does not trip another)', async () => {+ const bad = () => withBreaker('t:bad', async () => { throw new Error('x'); }, { fallback: 'fb', threshold: 1, halfOpenAfterMs: 60_000 });+ await bad(); // opens t:bad+ // A different name is unaffected and still executes.+ expect(await withBreaker('t:good', async () => 'ok', { fallback: 'fb' })).toBe('ok');+ });+});diff --git a/tests/axiom-ingest.test.js b/tests/axiom-ingest.test.jsnew file mode 100644index 000000000..e2b388a3b--- /dev/null+++ b/tests/axiom-ingest.test.js@@ -0,0 +1,96 @@+// api/_lib/axiom.js — Axiom event ingest for payment/business metrics.+//+// The module gates on AXIOM_TOKEN + AXIOM_DATASET and is a strict no-op until+// both are set (local/CI/pre-account), mirroring the SENTRY_DSN gate. When set,+// it fires one authenticated POST per event and never throws. These tests cover+// both states by resetting the module registry between env configs (cfg() caches+// once per module load), with global.fetch stubbed so no network is hit.++import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';++const REAL_FETCH = global.fetch;+const SAVED = { token: process.env.AXIOM_TOKEN, dataset: process.env.AXIOM_DATASET, url: process.env.AXIOM_URL };++function stubFetch() {+ const fn = vi.fn(async () => ({ ok: true, status: 200 }));+ global.fetch = fn;+ return fn;+}++beforeEach(() => {+ vi.resetModules();+ delete process.env.AXIOM_TOKEN;+ delete process.env.AXIOM_DATASET;+ delete process.env.AXIOM_URL;+});++afterEach(() => {+ global.fetch = REAL_FETCH;+ process.env.AXIOM_TOKEN = SAVED.token;+ process.env.AXIOM_DATASET = SAVED.dataset;+ process.env.AXIOM_URL = SAVED.url;+});++describe('axiom ingest — disabled (no env)', () => {+ it('axiomEnabled() is false and nothing is sent', async () => {+ const fetchSpy = stubFetch();+ const { axiomEnabled, recordPaymentMetric, ingestEvent } = await import('../api/_lib/axiom.js');+ expect(axiomEnabled()).toBe(false);+ recordPaymentMetric({ kind: 'avatar_payout', status: 'ok', amountUsd: 5 });+ ingestEvent({ type: 'test' });+ expect(fetchSpy).not.toHaveBeenCalled();+ });+});++describe('axiom ingest — enabled', () => {+ beforeEach(() => {+ process.env.AXIOM_TOKEN = 'xaat-test-token';+ process.env.AXIOM_DATASET = 'threews-payments';+ });++ it('axiomEnabled() is true', async () => {+ stubFetch();+ const { axiomEnabled } = await import('../api/_lib/axiom.js');+ expect(axiomEnabled()).toBe(true);+ });++ it('POSTs to the dataset ingest URL with Bearer auth', async () => {+ const fetchSpy = stubFetch();+ const { recordPaymentMetric } = await import('../api/_lib/axiom.js');+ recordPaymentMetric({ kind: 'avatar_payout', status: 'ok', network: 'mainnet', amountUsd: 5, latencyMs: 1200, signature: 'SIG_1' });+ expect(fetchSpy).toHaveBeenCalledOnce();+ const [url, opts] = fetchSpy.mock.calls[0];+ expect(url).toBe('https://api.axiom.co/v1/datasets/threews-payments/ingest');+ expect(opts.method).toBe('POST');+ expect(opts.headers.authorization).toBe('Bearer xaat-test-token');+ expect(opts.headers['content-type']).toBe('application/json');+ expect(opts.keepalive).toBe(true);+ });++ it('builds a payment event row with envelope fields', async () => {+ const fetchSpy = stubFetch();+ const { recordPaymentMetric } = await import('../api/_lib/axiom.js');+ recordPaymentMetric({ kind: 'avatar_payout', status: 'failed', network: 'mainnet', amountUsd: 5, latencyMs: 800, reason: 'rpc timeout' });+ const body = JSON.parse(fetchSpy.mock.calls[0][1].body);+ expect(Array.isArray(body)).toBe(true);+ expect(body).toHaveLength(1);+ const row = body[0];+ expect(row).toMatchObject({ type: 'payment', kind: 'avatar_payout', status: 'failed', network: 'mainnet', amount_usd: 5, latency_ms: 800, reason: 'rpc timeout' });+ expect(typeof row._time).toBe('string');+ expect(row.environment).toBeTruthy();+ });++ it('honors AXIOM_URL host override (EU/self-host)', async () => {+ process.env.AXIOM_URL = 'https://api.eu.axiom.co';+ const fetchSpy = stubFetch();+ const { ingestEvent } = await import('../api/_lib/axiom.js');+ ingestEvent({ type: 'test' });+ expect(fetchSpy.mock.calls[0][0]).toBe('https://api.eu.axiom.co/v1/datasets/threews-payments/ingest');+ });++ it('never throws when fetch rejects (fire-and-forget)', async () => {+ global.fetch = vi.fn(async () => { throw new Error('network down'); });+ const { recordPaymentMetric } = await import('../api/_lib/axiom.js');+ expect(() => recordPaymentMetric({ kind: 'x402', status: 'ok' })).not.toThrow();+ });+});diff --git a/tests/execution-engine-submit.test.js b/tests/execution-engine-submit.test.jsnew file mode 100644index 000000000..58025827b--- /dev/null+++ b/tests/execution-engine-submit.test.js@@ -0,0 +1,107 @@+// submitProtected — engine-primitive tests for the two behaviors that 19 money+// paths now depend on after migrating off hand-rolled send/confirm:+// 1. It strips any caller-supplied ComputeBudget instructions and sets exactly+// its own (a duplicate ComputeBudget ix makes the runtime reject the tx).+// 2. It signs with the fee-payer PLUS any opts.extraSigners (e.g. a mint).+// The Connection is a hand-built mock — no RPC. We capture the raw bytes handed+// to sendRawTransaction and deserialize them to assert on the real wire tx.++import { describe, it, expect, vi } from 'vitest';+import {+ Keypair,+ PublicKey,+ VersionedTransaction,+ SystemProgram,+ ComputeBudgetProgram,+ TransactionInstruction,+} from '@solana/web3.js';+import { submitProtected } from '../api/_lib/execution-engine.js';++const COMPUTE_BUDGET_PROGRAM = 'ComputeBudget111111111111111111111111111111';++function mockConnection(captured) {+ return {+ getLatestBlockhash: vi.fn(async () => ({+ blockhash: '11111111111111111111111111111111',+ lastValidBlockHeight: 1000,+ })),+ simulateTransaction: vi.fn(async () => ({ value: { err: null, unitsConsumed: 50_000, logs: [] } })),+ getRecentPrioritizationFees: vi.fn(async () => [{ prioritizationFee: 1000 }]),+ sendRawTransaction: vi.fn(async (raw) => {+ captured.raw = raw;+ return 'sigSENT';+ }),+ confirmTransaction: vi.fn(async () => ({ value: { err: null }, context: { slot: 7 } })),+ getSignatureStatus: vi.fn(async () => ({ value: { err: null, confirmationStatus: 'confirmed', slot: 7 } })),+ };+}++function decodeSent(captured) {+ const vtx = VersionedTransaction.deserialize(captured.raw);+ const keys = vtx.message.staticAccountKeys.map((k) => k.toBase58());+ const programIds = vtx.message.compiledInstructions.map((ix) => keys[ix.programIdIndex]);+ const nonEmptySigs = vtx.signatures.filter((s) => s.some((b) => b !== 0)).length;+ return { vtx, programIds, nonEmptySigs };+}++describe('submitProtected', () => {+ it('strips caller ComputeBudget ixs and sets exactly one limit + one price', async () => {+ const captured = {};+ const conn = mockConnection(captured);+ const payer = Keypair.generate();+ const dest = Keypair.generate().publicKey;+ // Caller passes its OWN compute-budget ixs plus a transfer — they must be dropped.+ const instructions = [+ ComputeBudgetProgram.setComputeUnitLimit({ units: 999_999 }),+ ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 12345 }),+ SystemProgram.transfer({ fromPubkey: payer.publicKey, toPubkey: dest, lamports: 1000 }),+ ];+ const res = await submitProtected({ network: 'mainnet', connection: conn, payer, instructions });+ // The returned signature is the tx's own derived signature, not the RPC echo.+ expect(typeof res.signature).toBe('string');+ expect(res.signature.length).toBeGreaterThan(40);+ expect(conn.sendRawTransaction).toHaveBeenCalled();++ const { programIds } = decodeSent(captured);+ const cbCount = programIds.filter((p) => p === COMPUTE_BUDGET_PROGRAM).length;+ // Exactly the engine's two (limit + price) — the caller's duplicates are gone.+ expect(cbCount).toBe(2);+ // The transfer survived.+ expect(programIds).toContain('11111111111111111111111111111111');+ });++ it('signs with the fee-payer plus extraSigners', async () => {+ const captured = {};+ const conn = mockConnection(captured);+ const payer = Keypair.generate();+ const extra = Keypair.generate();+ // An instruction that requires `extra` to sign (extra is a signer account).+ const ix = new TransactionInstruction({+ programId: new PublicKey('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'),+ keys: [{ pubkey: extra.publicKey, isSigner: true, isWritable: false }],+ data: Buffer.from('hi'),+ });+ await submitProtected({+ network: 'mainnet',+ connection: conn,+ payer,+ instructions: [ix],+ opts: { extraSigners: [extra] },+ });+ const { nonEmptySigs } = decodeSent(captured);+ // Both the fee-payer and the extra signer produced signatures.+ expect(nonEmptySigs).toBe(2);+ });++ it('throws SIM_FAILED when the pre-broadcast simulation reverts', async () => {+ const captured = {};+ const conn = mockConnection(captured);+ conn.simulateTransaction = vi.fn(async () => ({ value: { err: { InstructionError: [0, 'Custom'] }, logs: [] } }));+ const payer = Keypair.generate();+ const ix = SystemProgram.transfer({ fromPubkey: payer.publicKey, toPubkey: Keypair.generate().publicKey, lamports: 1 });+ await expect(+ submitProtected({ network: 'mainnet', connection: conn, payer, instructions: [ix] }),+ ).rejects.toMatchObject({ code: 'SIM_FAILED' });+ expect(conn.sendRawTransaction).not.toHaveBeenCalled();+ });+});diff --git a/vercel.json b/vercel.jsonindex 9175daa73..2d8edd2eb 100644--- a/vercel.json+++ b/vercel.json@@ -1633,19 +1633,19 @@},{"src": "/collection",- "dest": "/pages/collection.html"+ "dest": "/collection.html"},{"src": "/collection/",- "dest": "/pages/collection.html"+ "dest": "/collection.html"},{"src": "/marketplace/analytics",- "dest": "/pages/marketplace-analytics.html"+ "dest": "/marketplace-analytics.html"},{"src": "/marketplace/analytics/",- "dest": "/pages/marketplace-analytics.html"+ "dest": "/marketplace-analytics.html"},{"src": "/marketplace",