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
Wire IBM demo routes/serving, viewer framing module, agent wallet endpoints
nirholas550675e5a0a5
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f78e53f59..d92279c05 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr## 2026-06-17+- **x402 Live Demo (IBM × three.ws)** (`/ibm/x402-demo`) — A self-contained x402 micropayment demo: pay $0.001 USDC from your own wallet — MetaMask on Base or Phantom on Solana — to call a real three.ws data API. Watch the live HTTP 402 challenge, sign a gasless authorization, and see the on-chain settlement receipt. No backend, no account; built as the public face of the IBM × three.ws partnership.- **Agent profiles now show the agent's real avatar — no more stray model over the name** — On an agent's profile page, agents that ship their own 3D avatar were briefly showing the plain mannequin in the headshot while a second copy of their real avatar rendered loose over the agent's name. Both are fixed: the headshot now loads the agent's own model directly in place, and opening it full-screen shows that same model. Agents using the default body are unchanged. `[fix]`- **Agents placed from an iPhone now land in the right real-world spot for everyone** — iPhone Safari can't use WebXR, so placing an agent in the real world relies on the phone's motion sensors and GPS. Until now it leaned on a relative gyro reading with no fixed sense of north, which meant an agent you pinned could show up rotated — or facing the wrong way — for other people standing at the same spot. IRL now reads the iPhone's true compass heading when you pin, so your agent is anchored to a real-world direction: pan your phone and it stays planted on its actual bearing instead of sliding with the camera, and walk toward it and it holds its place and grows as you approach. Everyone nearby sees it in the same orientation you intended. If your compass needs calibrating we still place the agent and tell you it may look rotated to others, rather than failing silently — and Android, which already had richer world-anchoring, is unchanged. (`/irl`) `[improvement, fix]`- **An inbox for your IRL agents — see who tapped, messaged, or paid, and reply** — Your IRL Agents dashboard now has an Inbox: a live, chronological feed of everyone who met your placed agents in real life. Each entry shows what happened — a view, a tap, a message, or a payment — where it happened, and how long ago. Payments show the exact amount and link straight to the block-explorer receipt, and you can reply to anyone who left your agent a message; if they were signed in, your reply lands in their notifications. Unread counts appear on the Inbox button and on each agent's card, the feed refreshes itself every few seconds, and opening the inbox marks everything read. High-signal events (a payment or a message) also ping you in the notification bell, so you find out the moment a stranger across the city engages your agent. (`/dashboard/irl-placements`) `[feature]`diff --git a/api/_lib/agent-wallet.js b/api/_lib/agent-wallet.jsindex 0f785cbe8..de253bd4e 100644--- a/api/_lib/agent-wallet.js+++ b/api/_lib/agent-wallet.js@@ -515,6 +515,20 @@ export async function recoverSolanaAgentKeypair(encryptedSecret, audit = null) {status: 'ok',meta: { address: kp.publicKey.toBase58(), ...(audit.meta || {}) },});+ // Mirror into the owner-viewable custody trail so every decrypt of a+ // custodial key is traceable with its reason, alongside withdraws and+ // limit changes. Fire-and-forget — never block or fail the signing path.+ import('./agent-trade-guards.js')+ .then(({ recordCustodyEvent }) =>+ recordCustodyEvent({+ agentId: audit.agentId,+ userId: audit.userId ?? null,+ eventType: 'key_recover',+ reason: audit.reason || 'sign',+ meta: { address: kp.publicKey.toBase58(), ...(audit.meta || {}) },+ }),+ )+ .catch(() => {});}return kp;}diff --git a/api/agents/[id].js b/api/agents/[id].jsindex 4d6360519..e8da56b1d 100644--- a/api/agents/[id].js+++ b/api/agents/[id].js@@ -45,6 +45,14 @@ export default wrap(async function handler(req, res) {return error(res, 404, 'not_found', 'agent not found');}+ // /wallet/withdraw is the documented sweep route; it acts on the custodial+ // Solana wallet, so it shares the solana-wallet handler (also reachable at+ // /solana/withdraw). The EVM wallet link handler owns every other /wallet/*.+ if (sub === 'wallet' && action === 'withdraw') {+ const mod = await import('./solana-wallet.js');+ return mod.default(req, res, id, 'withdraw');+ }+if (sub === 'wallet') return handleWallet(req, res, id, action);if (sub === 'solana') {diff --git a/api/agents/solana-wallet.js b/api/agents/solana-wallet.jsindex 7990eb775..5b8011580 100644--- a/api/agents/solana-wallet.js+++ b/api/agents/solana-wallet.js@@ -5,14 +5,43 @@ import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.import { sql } from '../_lib/db.js';import { cors, json, method, error, readJson, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';-import { generateSolanaAgentWallet } from '../_lib/agent-wallet.js';+import { generateSolanaAgentWallet, recoverSolanaAgentKeypair } from '../_lib/agent-wallet.js';import { solanaConnection, solanaPublicConnection } from '../_lib/agent-pumpfun.js';import { reverseLookupAddress } from '../../src/solana/sns.js';-import { Keypair, PublicKey, LAMPORTS_PER_SOL } from '@solana/web3.js';-import { webcrypto } from 'node:crypto';+import {+ Keypair, PublicKey, LAMPORTS_PER_SOL, SystemProgram,+ TransactionMessage, VersionedTransaction,+} from '@solana/web3.js';+import {+ getAssociatedTokenAddressSync, createTransferCheckedInstruction,+ createAssociatedTokenAccountIdempotentInstruction, getMint,+ TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,+} from '@solana/spl-token';+import { webcrypto, randomUUID } from 'node:crypto';import { env } from '../_lib/env.js';import { recordEvent } from '../_lib/usage.js';import { cacheGet, cacheSet } from '../_lib/cache.js';+import { logAudit } from '../_lib/audit.js';+import { explorerTxUrl } from '../_lib/avatar-wallet.js';+import {+ validateSolanaAddress, enforceSpendLimit, SpendLimitError, lamportsToUsd,+ getSpendLimits, setSpendLimits, listCustodyEvents, updateCustodyEvent,+ getDailySpendUsd,+} from '../_lib/agent-trade-guards.js';++// USDC mints per cluster — the only SPL token we can price 1:1 for the spend+// ceiling without an external quote. $THREE is the only coin; USDC is the+// payment-rail asset, not a coin we promote.+const USDC_MINT_BY_CLUSTER = {+ mainnet: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',+ devnet: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU',+};++// SOL "max" headroom: keep the account rent-exempt and leave fee budget so a+// sweep can never brick the wallet or fail on fees.+const SOL_FEE_RESERVE_LAMPORTS = 15_000n; // ~3× a single-signature base fee+const RENT_EXEMPT_FALLBACK_LAMPORTS = 890_880n; // getMinimumBalanceForRentExemption(0)+const TOKEN_ACCOUNT_RENT_FALLBACK_LAMPORTS = 2_039_280n; // 165-byte SPL token accountconst subtle = globalThis.crypto?.subtle || webcrypto.subtle;const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]+$/;@@ -430,10 +459,535 @@ async function handleWallet(req, res, id) {});}+// ── owner gate ──────────────────────────────────────────────────────────────+// Shared loader for the owner-only custody handlers: auth → load agent → verify+// ownership → return the custodial wallet's address + encrypted secret + meta.+// Returns { error } (already-shaped) on any failure so callers can early-return.+async function loadOwnedWallet(req, res, id) {+ const auth = await resolveAuth(req);+ if (!auth) return { error: error(res, 401, 'unauthorized', 'sign in required') };++ const [row] = await sql`SELECT id, user_id, meta FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL`;+ if (!row) return { error: error(res, 404, 'not_found', 'agent not found') };+ if (row.user_id !== auth.userId) return { error: error(res, 403, 'forbidden', 'not your agent') };++ const meta = { ...(row.meta || {}) };+ return { auth, meta, address: meta.solana_address || null, encryptedSecret: meta.encrypted_solana_secret || null };+}++// ── withdraw / sweep ──────────────────────────────────────────────────────────+// POST /api/agents/:id/solana/withdraw (also aliased at /api/agents/:id/wallet/withdraw)+// Owner-authenticated. Sweeps SOL or a held SPL token from the agent's custodial+// wallet to an owner-chosen address, signed server-side. Idempotent, governed by+// the shared spend policy, rent + fee reserved on a SOL "max".+async function handleWithdraw(req, res, id) {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const owned = await loadOwnedWallet(req, res, id);+ if (owned.error) return;+ const { auth, meta, address: fromAddress, encryptedSecret } = owned;++ // Owner-only daily withdraw cap + per-IP burst guard.+ const rlUser = await limits.withdrawalPerUser(auth.userId);+ if (!rlUser.success) return rateLimited(res, rlUser);+ const rlIp = await limits.authIp(clientIp(req));+ if (!rlIp.success) return rateLimited(res, rlIp);++ if (!fromAddress || !encryptedSecret) {+ return error(res, 404, 'not_found', 'agent has no solana wallet to withdraw from');+ }++ let body;+ try {+ body = await readJson(req);+ } catch (e) {+ return error(res, e?.status === 415 ? 415 : 400, 'bad_request', e?.message || 'invalid request body');+ }++ const network = body.network === 'devnet' ? 'devnet' : 'mainnet';+ const asset = typeof body.asset === 'string' && body.asset.trim() ? body.asset.trim() : 'SOL';+ const simulate = body.simulate === true;+ const idempotencyKey =+ typeof body.idempotency_key === 'string' && body.idempotency_key.trim()+ ? body.idempotency_key.trim().slice(0, 128)+ : randomUUID();++ // 1. Validate destination — base58, on-curve, not the wallet itself.+ const dest = validateSolanaAddress(body.destination);+ if (!dest.valid) {+ return error(res, 400, 'invalid_destination', `destination is not a valid Solana address (${dest.reason})`);+ }+ if (!dest.onCurve) {+ return error(res, 400, 'invalid_destination', 'destination is a program address (off-curve) — funds sent there may be unrecoverable');+ }+ if (dest.base58 === fromAddress) {+ return error(res, 400, 'invalid_destination', 'destination is the agent wallet itself');+ }++ const isMax = body.amount === 'max' || body.amount === 'MAX';+ const amountNum = isMax ? null : Number(body.amount);+ if (!isMax && (!Number.isFinite(amountNum) || amountNum <= 0)) {+ return error(res, 400, 'invalid_amount', 'amount must be a positive number or "max"');+ }++ // 2. Fast-path idempotency check — a retry of a finished/in-flight withdraw.+ {+ const [existing] = await sql`+ SELECT id, status, signature FROM agent_custody_events+ WHERE agent_id = ${id} AND idempotency_key = ${idempotencyKey}+ `;+ if (existing) {+ if (existing.status === 'confirmed') {+ return json(res, 200, { data: { replayed: true, signature: existing.signature, explorer: explorerTxUrl(existing.signature, network), network } });+ }+ if (existing.status === 'pending') {+ return error(res, 409, 'withdrawal_in_progress', 'a withdrawal with this id is already in flight — check the audit log before retrying', { signature: existing.signature || null });+ }+ return error(res, 409, 'withdrawal_failed', 'this withdrawal id already failed — retry with a fresh idempotency key', { signature: existing.signature || null });+ }+ }++ const conn = solanaConnection(network);+ const fromPk = new PublicKey(fromAddress);++ let lamports = null; // SOL amount being sent (lamports) — null for SPL+ let amountRaw = null; // SPL token base units — null for SOL+ let decimals = 9;+ let humanAmount = null;+ let usdValue = null;+ let priceNote = null;+ let tokenProgramId = null;+ let mintPk = null;+ let sourceAta = null;+ let destAta = null;+ let destAtaExists = true;++ let balanceLamports;+ try {+ balanceLamports = BigInt(await conn.getBalance(fromPk, 'confirmed'));+ } catch (e) {+ return error(res, 502, 'rpc_error', 'could not read the wallet balance — try again');+ }++ if (asset === 'SOL') {+ let rentReserve;+ try {+ rentReserve = BigInt(await conn.getMinimumBalanceForRentExemption(0));+ } catch {+ rentReserve = RENT_EXEMPT_FALLBACK_LAMPORTS;+ }+ if (isMax) {+ const spendable = balanceLamports - rentReserve - SOL_FEE_RESERVE_LAMPORTS;+ if (spendable <= 0n) {+ return error(res, 400, 'insufficient_balance', 'not enough SOL to withdraw after reserving rent and network fees');+ }+ lamports = spendable;+ } else {+ lamports = BigInt(Math.round(amountNum * 1e9));+ if (lamports <= 0n) return error(res, 400, 'invalid_amount', 'amount rounds to zero lamports');+ if (balanceLamports - lamports < rentReserve + SOL_FEE_RESERVE_LAMPORTS) {+ return error(res, 400, 'insufficient_balance', 'amount leaves too little SOL to cover rent and network fees — lower it or use "max"');+ }+ }+ humanAmount = Number(lamports) / 1e9;+ try {+ usdValue = await lamportsToUsd(lamports);+ } catch {+ usdValue = null;+ priceNote = 'sol_price_unavailable';+ }+ } else {+ // SPL token — resolve the mint, its token program, decimals, and balances.+ const mintCheck = validateSolanaAddress(asset);+ if (!mintCheck.valid) return error(res, 400, 'invalid_asset', 'asset must be "SOL" or a valid SPL mint address');+ mintPk = mintCheck.pubkey;++ let mintAcc;+ try {+ mintAcc = await conn.getAccountInfo(mintPk);+ } catch {+ mintAcc = null;+ }+ if (!mintAcc) return error(res, 400, 'invalid_asset', 'token mint not found on this network');+ tokenProgramId = mintAcc.owner.equals(TOKEN_2022_PROGRAM_ID) ? TOKEN_2022_PROGRAM_ID : TOKEN_PROGRAM_ID;++ let mintInfo;+ try {+ mintInfo = await getMint(conn, mintPk, 'confirmed', tokenProgramId);+ } catch {+ return error(res, 400, 'invalid_asset', 'could not read the token mint');+ }+ decimals = mintInfo.decimals;++ sourceAta = getAssociatedTokenAddressSync(mintPk, fromPk, false, tokenProgramId, ASSOCIATED_TOKEN_PROGRAM_ID);+ let tokenBalRaw;+ try {+ const bal = await conn.getTokenAccountBalance(sourceAta);+ tokenBalRaw = BigInt(bal.value.amount);+ } catch {+ return error(res, 400, 'insufficient_balance', 'the agent holds none of this token');+ }+ if (tokenBalRaw <= 0n) return error(res, 400, 'insufficient_balance', 'the agent holds none of this token');++ amountRaw = isMax ? tokenBalRaw : BigInt(Math.round(amountNum * 10 ** decimals));+ if (amountRaw <= 0n) return error(res, 400, 'invalid_amount', 'amount rounds to zero token units');+ if (amountRaw > tokenBalRaw) return error(res, 400, 'insufficient_balance', 'amount exceeds the agent token balance');+ humanAmount = Number(amountRaw) / 10 ** decimals;++ // The agent pays the network fee and (if needed) rent to open the+ // recipient's token account. Make sure it holds enough SOL.+ destAta = getAssociatedTokenAddressSync(mintPk, dest.pubkey, false, tokenProgramId, ASSOCIATED_TOKEN_PROGRAM_ID);+ let destInfo;+ try {+ destInfo = await conn.getAccountInfo(destAta);+ } catch {+ destInfo = null;+ }+ destAtaExists = !!destInfo;+ let ataRent = 0n;+ if (!destAtaExists) {+ try {+ ataRent = BigInt(await conn.getMinimumBalanceForRentExemption(165));+ } catch {+ ataRent = TOKEN_ACCOUNT_RENT_FALLBACK_LAMPORTS;+ }+ }+ if (balanceLamports < SOL_FEE_RESERVE_LAMPORTS + ataRent) {+ return error(res, 400, 'insufficient_sol_for_fees', 'the agent needs a little SOL to pay the network fee' + (destAtaExists ? '' : ' and open the recipient token account'));+ }++ // Only USDC is priced 1:1 for the USD ceiling; other SPL tokens are+ // governed by the withdraw allowlist (see agent-trade-guards.js header).+ if (mintPk.toBase58() === USDC_MINT_BY_CLUSTER[network]) {+ usdValue = humanAmount;+ } else {+ usdValue = null;+ priceNote = 'spl_unpriced_allowlist_only';+ }+ }++ // 3. Enforce the shared spend policy (allowlist + per-tx + daily ceiling).+ try {+ await enforceSpendLimit({ agentId: id, meta, category: 'withdraw', usdValue, destination: dest.base58, network });+ } catch (e) {+ if (e instanceof SpendLimitError) {+ return error(res, e.status, e.code, e.message, { detail: e.detail });+ }+ console.error('[withdraw] spend-limit check failed', e?.message);+ return error(res, 502, 'limit_check_failed', 'could not verify the agent spend limits — try again');+ }++ // 4. Build the (unsigned) transaction.+ let blockhashCtx;+ try {+ blockhashCtx = await conn.getLatestBlockhash('confirmed');+ } catch {+ return error(res, 502, 'rpc_error', 'could not fetch a recent blockhash — try again');+ }+ const ixs = [];+ if (asset === 'SOL') {+ ixs.push(SystemProgram.transfer({ fromPubkey: fromPk, toPubkey: dest.pubkey, lamports: lamports }));+ } else {+ if (!destAtaExists) {+ ixs.push(createAssociatedTokenAccountIdempotentInstruction(+ fromPk, destAta, dest.pubkey, mintPk, tokenProgramId, ASSOCIATED_TOKEN_PROGRAM_ID,+ ));+ }+ ixs.push(createTransferCheckedInstruction(+ sourceAta, mintPk, destAta, fromPk, amountRaw, decimals, [], tokenProgramId,+ ));+ }+ const message = new TransactionMessage({+ payerKey: fromPk,+ recentBlockhash: blockhashCtx.blockhash,+ instructions: ixs,+ }).compileToV0Message();+ const vtx = new VersionedTransaction(message);++ // 5. Simulate-only path — never touches the key, never sends, never records.+ if (simulate) {+ let sim;+ try {+ sim = await conn.simulateTransaction(vtx, { sigVerify: false, replaceRecentBlockhash: true });+ } catch (e) {+ return error(res, 502, 'simulation_failed', e?.message || 'simulation failed');+ }+ return json(res, 200, {+ data: {+ simulated: true, asset, network, destination: dest.base58,+ amount: humanAmount, lamports: lamports != null ? String(lamports) : null,+ amount_raw: amountRaw != null ? String(amountRaw) : null,+ usd: usdValue, note: priceNote,+ err: sim.value?.err ?? null, units_consumed: sim.value?.unitsConsumed ?? null,+ logs: sim.value?.logs ?? null,+ },+ });+ }++ // 6. Claim the idempotency slot — this row is also the spend-ledger entry.+ const claim = await sql`+ INSERT INTO agent_custody_events+ (agent_id, user_id, event_type, category, network, asset,+ amount_lamports, amount_raw, usd, destination, status, idempotency_key, meta)+ VALUES (+ ${id}, ${auth.userId}, 'spend', 'withdraw', ${network}, ${asset},+ ${lamports != null ? String(lamports) : null},+ ${amountRaw != null ? String(amountRaw) : null},+ ${usdValue ?? null}, ${dest.base58}, 'pending', ${idempotencyKey},+ ${JSON.stringify({ human_amount: humanAmount, note: priceNote })}::jsonb+ )+ ON CONFLICT (agent_id, idempotency_key) WHERE idempotency_key IS NOT NULL DO NOTHING+ RETURNING id+ `;+ if (!claim.length) {+ // Lost the race to a concurrent identical request — defer to it.+ return error(res, 409, 'withdrawal_in_progress', 'a withdrawal with this id is already in flight — check the audit log before retrying');+ }+ const claimId = claim[0].id;++ // 7. Recover the key (audit-logged) and sign.+ let keypair;+ try {+ keypair = await recoverSolanaAgentKeypair(encryptedSecret, {+ agentId: id, userId: auth.userId, reason: 'withdraw',+ meta: { asset, destination: dest.base58, network, custody_event_id: claimId },+ });+ } catch (e) {+ await updateCustodyEvent(claimId, { status: 'failed', meta: { error: 'key_recover_failed' } }).catch(() => {});+ console.error('[withdraw] key recovery failed', e?.message);+ return error(res, 500, 'key_recover_failed', 'could not access the agent wallet key — no funds were moved');+ }+ vtx.sign([keypair]);++ // 8. Submit + confirm. On an ambiguous confirm (timeout) re-check the chain+ // before deciding — never mark failed if the tx may have landed.+ let signature;+ try {+ signature = await conn.sendRawTransaction(vtx.serialize(), { skipPreflight: false, maxRetries: 3 });+ } catch (e) {+ await updateCustodyEvent(claimId, { status: 'failed', meta: { error: 'send_failed', message: e?.message?.slice(0, 200) } }).catch(() => {});+ logAudit({ userId: auth.userId, action: 'custody.withdraw_failed', resourceId: id, meta: { asset, destination: dest.base58, reason: 'send_failed' }, req });+ return error(res, 502, 'send_failed', 'the withdrawal could not be submitted and no funds were transferred — try again');+ }++ let confirmed = true;+ try {+ const r = await conn.confirmTransaction(+ { signature, blockhash: blockhashCtx.blockhash, lastValidBlockHeight: blockhashCtx.lastValidBlockHeight },+ 'confirmed',+ );+ if (r?.value?.err) confirmed = false;+ } catch {+ // Confirmation timed out — re-check the signature status directly.+ try {+ const st = await conn.getSignatureStatus(signature, { searchTransactionHistory: true });+ const s = st?.value?.confirmationStatus;+ confirmed = !st?.value?.err && (s === 'confirmed' || s === 'finalized');+ } catch {+ confirmed = false;+ }+ }++ if (!confirmed) {+ // Submitted but not provably confirmed. Leave the row 'pending' (NOT+ // failed) so a same-key retry returns in_progress instead of double-+ // sending; hand the user the signature to verify on-chain.+ await updateCustodyEvent(claimId, { signature, meta: { confirm: 'unconfirmed' } }).catch(() => {});+ logAudit({ userId: auth.userId, action: 'custody.withdraw_unconfirmed', resourceId: id, meta: { asset, destination: dest.base58, signature }, req });+ return error(res, 202, 'withdrawal_unconfirmed', 'the withdrawal was submitted but not yet confirmed — check the explorer link before retrying', { signature, explorer: explorerTxUrl(signature, network) });+ }++ await updateCustodyEvent(claimId, { status: 'confirmed', signature }).catch(() => {});+ logAudit({ userId: auth.userId, action: 'custody.withdraw', resourceId: id, meta: { asset, destination: dest.base58, amount: humanAmount, usd: usdValue, signature, network }, req });++ // Invalidate the cached balance so the wallet card reflects the sweep at once.+ await cacheSet(`sol:bal:${fromAddress}:${network}`, null, 1).catch(() => {});++ // 9. Re-read balances for the response.+ let newSol = null;+ try {+ newSol = (await conn.getBalance(fromPk, 'confirmed')) / 1e9;+ } catch { /* best-effort */ }+ let newTokenBalance = null;+ if (asset !== 'SOL' && sourceAta) {+ try {+ const b = await conn.getTokenAccountBalance(sourceAta);+ newTokenBalance = b?.value?.uiAmount ?? null;+ } catch { /* ATA may now be empty/closed */ }+ }++ return json(res, 200, {+ data: {+ replayed: false,+ signature,+ explorer: explorerTxUrl(signature, network),+ asset, network, destination: dest.base58,+ amount: humanAmount,+ lamports: lamports != null ? String(lamports) : null,+ amount_raw: amountRaw != null ? String(amountRaw) : null,+ usd: usdValue,+ note: priceNote,+ new_balance_sol: newSol,+ new_token_balance: newTokenBalance,+ },+ });+}++// ── holdings ────────────────────────────────────────────────────────────────+// GET /api/agents/:id/solana/holdings — owner-only list of withdrawable assets+// (SOL + every SPL token the wallet holds with a non-zero balance). Powers the+// Withdraw tab's asset picker so it only ever offers real holdings.+async function handleHoldings(req, res, id) {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;++ const owned = await loadOwnedWallet(req, res, id);+ if (owned.error) return;+ const { auth, address } = owned;++ const rl = await limits.walletRead(auth.userId);+ if (!rl.success) return rateLimited(res, rl);++ if (!address) return error(res, 404, 'not_found', 'agent has no solana wallet');++ const url = new URL(req.url, 'http://x');+ const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';+ const conn = solanaConnection(network);+ const owner = new PublicKey(address);++ let sol = null;+ try {+ sol = (await conn.getBalance(owner, 'confirmed')) / 1e9;+ } catch {+ return error(res, 502, 'rpc_error', 'could not read the wallet balance — try again');+ }++ const tokens = [];+ const usdcMint = USDC_MINT_BY_CLUSTER[network];+ for (const programId of [TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID]) {+ let resp;+ try {+ resp = await conn.getParsedTokenAccountsByOwner(owner, { programId });+ } catch {+ continue; // one token program failing shouldn't blank the whole list+ }+ for (const { account } of resp.value) {+ const info = account.data?.parsed?.info;+ const amt = info?.tokenAmount;+ if (!info || !amt || !(Number(amt.uiAmount) > 0)) continue;+ tokens.push({+ mint: info.mint,+ ui_amount: amt.uiAmount,+ amount_raw: amt.amount,+ decimals: amt.decimals,+ token_program: programId.toBase58(),+ is_usdc: info.mint === usdcMint,+ });+ }+ }+ tokens.sort((a, b) => Number(b.ui_amount) - Number(a.ui_amount));++ return json(res, 200, { data: { address, network, sol, tokens } });+}++// ── custody audit trail ───────────────────────────────────────────────────────+// GET /api/agents/:id/solana/custody — owner-only feed of sensitive custody+// events (key recovery, withdraws, spends, limit changes) for this agent wallet.+async function handleCustody(req, res, id) {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;++ const owned = await loadOwnedWallet(req, res, id);+ if (owned.error) return;+ const { auth } = owned;++ const rl = await limits.auditLogRead(auth.userId);+ if (!rl.success) return rateLimited(res, rl);++ const url = new URL(req.url, 'http://x');+ const limit = Math.min(200, Math.max(1, parseInt(url.searchParams.get('limit') || '50', 10) || 50));+ const beforeRaw = url.searchParams.get('before');+ const beforeId = beforeRaw && /^\d+$/.test(beforeRaw) ? beforeRaw : null;+ const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : url.searchParams.get('network') === 'mainnet' ? 'mainnet' : null;++ const events = await listCustodyEvents(id, { limit, beforeId, network });+ const items = events.map((e) => ({+ id: String(e.id),+ event_type: e.event_type,+ category: e.category,+ network: e.network,+ asset: e.asset,+ amount_lamports: e.amount_lamports != null ? String(e.amount_lamports) : null,+ amount_raw: e.amount_raw != null ? String(e.amount_raw) : null,+ usd: e.usd != null ? Number(e.usd) : null,+ destination: e.destination,+ signature: e.signature,+ explorer: e.signature ? explorerTxUrl(e.signature, e.network) : null,+ reason: e.reason,+ status: e.status,+ created_at: e.created_at,+ }));+ const nextCursor = items.length === limit ? items[items.length - 1].id : null;+ return json(res, 200, { data: { items, next_cursor: nextCursor } });+}++// ── spend limits ────────────────────────────────────────────────────────────+// GET/PUT /api/agents/:id/solana/limits — owner-only read + edit of the shared+// per-agent spend policy. Includes today's spend so the hub can show headroom.+async function handleLimits(req, res, id) {+ if (cors(req, res, { methods: 'GET,PUT,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET', 'PUT'])) return;++ const owned = await loadOwnedWallet(req, res, id);+ if (owned.error) return;+ const { auth, meta } = owned;++ const rl = await limits.walletRead(auth.userId);+ if (!rl.success) return rateLimited(res, rl);++ const url = new URL(req.url, 'http://x');+ const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';++ if (req.method === 'PUT') {+ let body;+ try {+ body = await readJson(req);+ } catch (e) {+ return error(res, e?.status === 415 ? 415 : 400, 'bad_request', e?.message || 'invalid request body');+ }+ // Validate allowlist entries up-front so the user gets a clear rejection+ // instead of silent dropping inside normalizeSpendLimits.+ if (Array.isArray(body.withdraw_allowlist)) {+ const bad = body.withdraw_allowlist.find((a) => !validateSolanaAddress(a).valid);+ if (bad !== undefined) return error(res, 400, 'invalid_address', `withdraw_allowlist contains an invalid Solana address: ${String(bad).slice(0, 60)}`);+ }+ let limitsOut;+ try {+ limitsOut = await setSpendLimits(id, auth.userId, body, { req });+ } catch (e) {+ if (e?.status) return error(res, e.status, e.code || 'error', e.message);+ throw e;+ }+ const spentUsd = await getDailySpendUsd(id, network).catch(() => 0);+ return json(res, 200, { data: { limits: limitsOut, spent_today_usd: spentUsd } });+ }++ const limitsOut = getSpendLimits(meta);+ const spentUsd = await getDailySpendUsd(id, network).catch(() => 0);+ return json(res, 200, { data: { limits: limitsOut, spent_today_usd: spentUsd } });+}+// ── dispatcher ────────────────────────────────────────────────────────────────export default async function handler(req, res, id, action) {if (action === 'activity') return handleActivity(req, res, id);if (action === 'airdrop') return handleAirdrop(req, res, id);+ if (action === 'withdraw') return handleWithdraw(req, res, id);+ if (action === 'holdings') return handleHoldings(req, res, id);+ if (action === 'custody') return handleCustody(req, res, id);+ if (action === 'limits') return handleLimits(req, res, id);return handleWallet(req, res, id);}++export { handleWithdraw };diff --git a/api/irl/pins.js b/api/irl/pins.jsindex c91ebacc7..fd8a5aff4 100644--- a/api/irl/pins.js+++ b/api/irl/pins.js@@ -614,6 +614,14 @@ export default wrap(async (req, res) => {// feed and no realtime broadcast of pins: the radius is hard-capped small, the// caller's own lat/lng is required, and the read is IP rate-limited above so a// scripted grid-sweep can't reconstruct the map.+ //+ // PRIVACY CONTRACT (L4): the caller's own lat/lng are used ONLY to run the+ // proximity query and are NEVER logged. A proximity READ is not persisted —+ // the only stored coordinates are the deliberate placements in irl_pins; the+ // rate-limit counter keys on IP, not position. Do not add any console log of+ // req.query / lat / lng on this path. Privacy-minded clients additionally+ // coarsen the origin they send (see discoveryOrigin() in src/irl.js), so the+ // exact device position need never reach the server at all.if (req.method === 'GET') {const lat = parseFloat(req.query.lat);const lng = parseFloat(req.query.lng);diff --git a/data/changelog.json b/data/changelog.jsonindex b7e80ebc5..84592a2c5 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,13 @@{"$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-17",+ "title": "Try x402 live — pay a tenth of a cent to call a real API from your own wallet",+ "summary": "There's now a live, self-contained x402 demo you can try in a browser. Pay $0.001 USDC from your own wallet — MetaMask on Base or Phantom on Solana — and call a real three.ws data API. The page reads the live HTTP 402 price the server quotes, runs the paid call once your wallet signs a gasless authorization, and shows the response next to an on-chain transaction receipt you can open on Basescan or Solscan. Nothing is mocked and there's no account or backend. The same eight-line embed it runs on — one script tag from three.ws plus any button carrying a data-x402-endpoint — is copy-pasteable into any site, so a developer can add a working pay-per-call paywall in minutes. Built with IBM as the public face of the partnership and designed to host cleanly on a strict-CSP enterprise page.",+ "tags": ["feature", "sdk"],+ "link": "/ibm/x402-demo"+ },{"date": "2026-06-17","title": "IRL: a pinned agent stays rock-steady even when your phone's compass glitches",diff --git a/data/pages.json b/data/pages.jsonindex fc6acdcd3..2aba8a734 100644--- a/data/pages.json+++ b/data/pages.json@@ -608,6 +608,14 @@"changefreq": "daily","added": "2026-05-25"},+ {+ "path": "/ibm/x402-demo",+ "title": "x402 Live Demo (IBM × three.ws)",+ "description": "A self-contained x402 micropayment demo: pay $0.001 USDC from your own wallet — MetaMask on Base or Phantom on Solana — to call a real three.ws data API. Watch the live HTTP 402 challenge, sign a gasless authorization, and see the on-chain settlement receipt. No backend, no account; built as the public face of the IBM × three.ws partnership.",+ "priority": 0.7,+ "changefreq": "monthly",+ "added": "2026-06-17"+ },{"path": "/lookup","title": "Agent Lookup",diff --git a/pages/ibm/x402-demo.html b/pages/ibm/x402-demo.htmlindex 2c324c076..d1aea85e3 100644--- a/pages/ibm/x402-demo.html+++ b/pages/ibm/x402-demo.html@@ -374,8 +374,8 @@ a:focus-visible{outline-offset:3px}<div class="demo-body"><!-- live 402 preview -->- <div class="preview" aria-live="polite" aria-busy="true">- <div class="preview-label" id="pvLabel"><span class="dot"></span><span id="pvLabelText">Reading the server's 402 challenge…</span></div>+ <div class="preview" role="region" aria-label="Live HTTP 402 payment challenge" aria-live="polite" aria-busy="true">+ <div class="preview-label" id="pvLabel"><span class="dot" aria-hidden="true"></span><span id="pvLabelText">Reading the server's 402 challenge…</span></div><div id="pvRows"><div class="preview-row"><span class="sk" style="width:38%"></span></div><div class="preview-row"><span class="sk" style="width:54%"></span></div>@@ -387,7 +387,7 @@ a:focus-visible{outline-offset:3px}<div class="field-row"><div class="field-wrap"><label for="ticker">Ticker to check</label>- <input id="ticker" class="field" value="GRANITE" maxlength="32" autocomplete="off" spellcheck="false" inputmode="latin" aria-describedby="tickerHint">+ <input id="ticker" class="field" value="GRANITE" maxlength="32" autocomplete="off" spellcheck="false" autocapitalize="characters" inputmode="text" aria-describedby="tickerHint"><div class="field-hint" id="tickerHint">A–Z and 0–9, up to 32 characters.</div></div><button id="payBtn" class="btn" type="button"><span class="spin" aria-hidden="true"></span><span class="label">Pay $0.001 & run</span> <span class="arrow" aria-hidden="true">→</span></button>diff --git a/pages/irl.html b/pages/irl.htmlindex 352773666..16364b7bf 100644--- a/pages/irl.html+++ b/pages/irl.html@@ -212,6 +212,8 @@.irl-share-btn:active { transform: scale(0.96); }.irl-share-btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }.irl-share-btn[disabled] { opacity: 0.6; cursor: progress; }+ /* L3 — icon-only "Location & privacy" control sits beside Share */+ .irl-privacy-btn { padding: 6px; display: inline-flex; align-items: center; justify-content: center; margin-right: 8px; }/* ── Joystick ────────────────────────────────────────────── */#irl-joystick {@@ -1611,6 +1613,9 @@unless the live stream is up and more than just you are here. --><span id="irl-presence-chip" class="irl-presence-chip" hidden role="status" aria-live="polite"></span></div>+ <button class="irl-share-btn irl-privacy-btn" id="irl-privacy-btn" type="button" aria-label="Location & privacy" title="Location & privacy">+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><path d="m9 12 2 2 4-4"/></svg>+ </button><button class="irl-share-btn" id="irl-share-btn" type="button" aria-label="Share">Share</button></header>diff --git a/public/changelog.json b/public/changelog.jsonindex b14abb74b..8dba3aaac 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,11 +1,21 @@{- "generated_at": "2026-06-17T12:06:13.152Z",+ "generated_at": "2026-06-17T12:09:48.286Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws","url": "https://three.ws"},"entries": [+ {+ "date": "2026-06-17",+ "type": "launch",+ "title": "x402 Live Demo (IBM × three.ws)",+ "summary": "A self-contained x402 micropayment demo: pay $0.001 USDC from your own wallet — MetaMask on Base or Phantom on Solana — to call a real three.ws data API. Watch the live HTTP 402 challenge, sign a gasless authorization, and see the on-chain settlement receipt. No backend, no account; built as the public face of the IBM × three.ws partnership.",+ "link": "/ibm/x402-demo",+ "tags": [+ "launch"+ ]+ },{"date": "2026-06-17","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 230e9d194..05beab370 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -6,6 +6,14 @@<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/><description>What's new on three.ws — features, improvements, and releases, newest first.</description><language>en</language>+ <item>+ <title>x402 Live Demo (IBM × three.ws)</title>+ <link>https://three.ws/ibm/x402-demo</link>+ <guid isPermaLink="false">2026-06-17:x402 Live Demo (IBM × three.ws)</guid>+ <pubDate>Wed, 17 Jun 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>A self-contained x402 micropayment demo: pay $0.001 USDC from your own wallet — MetaMask on Base or Phantom on Solana — to call a real three.ws data API. Watch the live HTTP 402 challenge, sign a gasless authorization, and see the on-chain settlement receipt. No backend, no account; built as the public face of the IBM × three.ws partnership.</description>+ </item><item><title>Agent profiles now show the agent's real avatar — no more stray model over the name</title><link>https://three.ws/changelog</link>diff --git a/public/features.json b/public/features.jsonindex b9eee85fe..38a90b3bc 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-17T12:06:13.120Z",+ "generated_at": "2026-06-17T12:09:48.162Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",@@ -746,6 +746,16 @@"tags": [],"showcase": false},+ {+ "path": "/ibm/x402-demo",+ "title": "x402 Live Demo (IBM × three.ws)",+ "description": "A self-contained x402 micropayment demo: pay $0.001 USDC from your own wallet — MetaMask on Base or Phantom on Solana — to call a real three.ws data API. Watch the live HTTP 402 challenge, sign a gasless authorization, and see the on-chain settlement receipt. No backend, no account; built as the public face of the IBM × three.ws partnership.",+ "added": "2026-06-17",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },{"path": "/lookup","title": "Agent Lookup",diff --git a/public/llms-full.txt b/public/llms-full.txtindex cfacfef12..becc9f543 100644--- a/public/llms-full.txt+++ b/public/llms-full.txt@@ -452,6 +452,12 @@ URL: https://three.ws/bazaarSearch and browse the x402 facilitator catalog. Filter by network, price, and extensions. Pay any service in one click.+### x402 Live Demo (IBM × three.ws)++URL: https://three.ws/ibm/x402-demo++A self-contained x402 micropayment demo: pay $0.001 USDC from your own wallet — MetaMask on Base or Phantom on Solana — to call a real three.ws data API. Watch the live HTTP 402 challenge, sign a gasless authorization, and see the on-chain settlement receipt. No backend, no account; built as the public face of the IBM × three.ws partnership.+### Agent LookupURL: https://three.ws/lookupdiff --git a/public/llms.txt b/public/llms.txtindex 2c682f862..accd2f4c9 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -96,6 +96,7 @@ On-chain features: pay-per-call, token launches, vanity wallets.- [Coin Intelligence](https://three.ws/coin-intel): Every pump.fun launch watched and classified in real time — organic vs bundle, the wallets behind it, a transparent quality score, and a model that learns which signals predict winners.- [watsonx Constellation](https://three.ws/constellation): Live Solana tokens in a 3D galaxy, positioned in semantic space by IBM Granite embeddings on watsonx.ai. Click a star for a live IBM Granite analysis.- [x402 Bazaar](https://three.ws/bazaar): Search and browse the x402 facilitator catalog. Filter by network, price, and extensions. Pay any service in one click.+- [x402 Live Demo (IBM × three.ws)](https://three.ws/ibm/x402-demo): A self-contained x402 micropayment demo: pay $0.001 USDC from your own wallet — MetaMask on Base or Phantom on Solana — to call a real three.ws data API. Watch the live HTTP 402 challenge, sign a gasless authorization, and see the on-chain settlement receipt. No backend, no account; built as the public face of the IBM × three.ws partnership.- [Agent Lookup](https://three.ws/lookup): Resolve any three.ws agent by Solana mint, agent ID, avatar ID, or slug — renders its interactive 3D avatar alongside its on-chain identity (collection, owner, agent wallet, Active/x402 status, Metaplex/Solscan/Magic Eden links).- [x402 Arbitrage](https://three.ws/arbitrage): Cross-provider price disparities surfaced live from the merged x402 facilitator catalog. Find the cheapest endpoint for any capability.- [x402 Providers](https://three.ws/providers): Quantified operator profiles for the x402 paid API catalog. Service counts, price bands, dominant categories, and the underlying listings.diff --git a/public/sitemap/index.html b/public/sitemap/index.htmlindex 81eec51d8..316cb651c 100644--- a/public/sitemap/index.html+++ b/public/sitemap/index.html@@ -65,7 +65,7 @@<main class="sm-wrap"><div class="sm-hero"><h1>Sitemap</h1>- <p>All 275 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>+ <p>All 276 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p><div class="sm-formats"><a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a><a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>@@ -77,7 +77,7 @@</div><div class="sm-filter"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>- <input id="sm-filter-input" type="search" placeholder="Filter 275 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />+ <input id="sm-filter-input" type="search" placeholder="Filter 276 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" /><kbd aria-hidden="true">/</kbd></div><p class="sm-filter-count" id="sm-filter-count" role="status" aria-live="polite"></p>@@ -452,7 +452,7 @@<section class="sm-section" id="crypto"><header>- <h2>Crypto<span class="sm-count" data-count>44</span></h2>+ <h2>Crypto<span class="sm-count" data-count>45</span></h2><p class="sm-section-desc">On-chain features: pay-per-call, token launches, vanity wallets.</p></header><ul class="sm-list">@@ -624,6 +624,13 @@<span class="sm-desc">Search and browse the x402 facilitator catalog. Filter by network, price, and extensions. Pay any service in one click.</span></a></li>+ <li>+ <a href="/ibm/x402-demo">+ <span class="sm-title">x402 Live Demo (IBM × three.ws)</span>+ <span class="sm-path">/ibm/x402-demo</span>+ <span class="sm-desc">A self-contained x402 micropayment demo: pay $0.001 USDC from your own wallet — MetaMask on Base or Phantom on Solana — to call a real three.ws data API. Watch the live HTTP 402 challenge, sign a gasless authorization, and see the on-chain settlement receipt. No backend, no account; built as the public face of the IBM × three.ws partnership.</span>+ </a>+ </li><li><a href="/lookup"><span class="sm-title">Agent Lookup</span>diff --git a/src/animation-retarget.js b/src/animation-retarget.jsindex 7fb5c060e..298d6d14a 100644--- a/src/animation-retarget.js+++ b/src/animation-retarget.js@@ -192,6 +192,56 @@ function rotateVectorTrack(values, c) {}}+// Rotation to apply to the Hips position (root-motion) track. The clip authors+// hip translation in the authoring rig's hips-parent frame, whose world rotation+// is identity (cz's armature has none). To preserve world motion on the target,+// rotate by the inverse of the target's hips-parent world rotation. When the+// caller can't supply that (a bare retargetClip call), fall back to the Hips+// bone correction — exact for any rig whose hips are upright at bind, i.e. every+// real humanoid. Returns null when no rotation is needed.+function hipPositionCorrection(hipsParentWorldQuat, corrections) {+ if (hipsParentWorldQuat) {+ const q = hipsParentWorldQuat.isQuaternion+ ? hipsParentWorldQuat.clone()+ : new Quaternion(+ hipsParentWorldQuat[0],+ hipsParentWorldQuat[1],+ hipsParentWorldQuat[2],+ hipsParentWorldQuat[3],+ );+ q.invert();+ return 1 - Math.abs(q.w) < BIND_EPSILON ? null : q;+ }+ return corrections.get('Hips') || null;+}++/**+ * World rotation of the target Hips' parent, measured *within the model* (i.e.+ * relative to `root`, so a placement rotation the viewer applies to the whole+ * avatar is excluded). Inverting it lets {@link retargetClip} re-express a clip's+ * authored hip translation in the target's hips-parent frame, so root motion+ * travels the same world direction on a Mixamo `+90°X` armature, an RPM rig, etc.+ * Requires the graph's local rotations to be at bind pose (true at attach time).+ *+ * @param {import('three').Object3D} root+ * @returns {import('three').Quaternion|null}+ */+export function hipsParentWorldQuat(root) {+ let hips = null;+ root.traverse((n) => {+ if (!hips && n.isBone && n.name && canonicalizeBoneName(n.name) === 'Hips') hips = n;+ });+ if (!hips) {+ root.traverse((n) => {+ if (!hips && n.name && canonicalizeBoneName(n.name) === 'Hips') hips = n;+ });+ }+ if (!hips || !hips.parent) return null;+ const q = new Quaternion();+ for (let n = hips.parent; n && n !== root; n = n.parent) q.premultiply(n.quaternion);+ return q;+}+/*** World-space rest height of the target's hips, used to scale root translation* onto a differently-sized rig. Returns 0 if it can't be determined (callers@@ -233,6 +283,7 @@ 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 hipsPosCorrection = hipPositionCorrection(opts.hipsParentWorldQuat, corrections);const total = clip.tracks.length;const dropped = [];const tracks = [];@@ -250,16 +301,21 @@ export function retargetClip(clip, canonicalToNode, opts = {}) {}const next = track.clone();next.name = `${nodeName}.${property}`;- // Bind correction: rotate the bone's rest convention onto the target rig- // so a clip authored for one rest pose doesn't flip a differently-rigged- // avatar (e.g. a Mixamo Hips baked at −90°X reading as "lying down").- const correction = corrections.get(canonical);- if (correction) {- if (property === 'quaternion') premultiplyQuaternionTrack(next.values, correction);- else if (property === 'position') rotateVectorTrack(next.values, correction);- }- if (hipScale !== 1 && canonical === 'Hips' && property === 'position') {- for (let i = 0; i < next.values.length; i++) next.values[i] *= hipScale;+ 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").+ const correction = corrections.get(canonical);+ if (correction) premultiplyQuaternionTrack(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+ // travels the same world direction on any rig, then scale for height.+ if (hipsPosCorrection) rotateVectorTrack(next.values, hipsPosCorrection);+ if (hipScale !== 1) {+ for (let i = 0; i < next.values.length; i++) next.values[i] *= hipScale;+ }}tracks.push(next);}@@ -296,7 +352,20 @@ export function retargetClipToRig(clip, rig, opts = {}) {hipScale = Math.min(5, Math.max(0.2, targetY / sourceY));}}- return retargetClip(clip, map, { hipScale, minCoverage: opts.minCoverage, targetRest });+ // Walk the hips' ancestor chain to the top so root motion is corrected for the+ // rig's axis convention (the rig is posed at origin, so within-model == world).+ let hipsParent = null;+ const hipsNode = rig.getNode?.('Hips');+ if (hipsNode?.parent) {+ hipsParent = new Quaternion();+ for (let n = hipsNode.parent; n; n = n.parent) hipsParent.premultiply(n.quaternion);+ }+ return retargetClip(clip, map, {+ hipScale,+ minCoverage: opts.minCoverage,+ targetRest,+ hipsParentWorldQuat: hipsParent,+ });}/**@@ -311,7 +380,8 @@ export function retargetClipToRig(clip, rig, opts = {}) {export function retargetClipToObject(clip, root, opts = {}) {const map = canonicalNodeMapFromObject(root);const targetRest = opts.targetRest || canonicalRestMapFromObject(root);- return retargetClip(clip, map, { ...opts, targetRest });+ const hipsParentWorld = opts.hipsParentWorldQuat || hipsParentWorldQuat(root);+ return retargetClip(clip, map, { ...opts, targetRest, hipsParentWorldQuat: hipsParentWorld });}/**diff --git a/src/irl.js b/src/irl.jsindex ec1a333f4..79093361d 100644--- a/src/irl.js+++ b/src/irl.js@@ -1279,6 +1279,23 @@ const NEARBY_RADIUS = 40; // metres// roster to 60 m, so this discovers nothing the user couldn't already stumble upon.const NEARBY_READ_RADIUS = 60; // metres — matches api/irl/pins.js Math.min(60, …)+// L4 — Approximate discovery. The origin we SEND to the nearby read. In precise+// mode it's the live fix; in approximate mode we snap to a ~25 m grid so our+// exact position never leaves the device while browsing. 25 m is the largest cell+// that still keeps every agent inside the 40 m display band returned by the 60 m+// read (worst-case snap offset ≈ 17.7 m; 40 + 17.7 < 60). Rendering + the+// ENTER/EXIT band always measure against the TRUE gpsState, so coarsening changes+// only WHICH pins come back, never where they draw.+function discoveryOrigin() {+ if (getDiscoveryPrecision() !== 'approximate') return { lat: gpsState.lat, lng: gpsState.lng };+ const latCell = 25 / 110540;+ const lngCell = 25 / ((111320 * Math.cos(gpsState.lat * Math.PI / 180)) || 1);+ return {+ lat: Math.round(gpsState.lat / latCell) * latCell,+ lng: Math.round(gpsState.lng / lngCell) * lngCell,+ };+}+// Honour the OS "reduce motion" setting for the spawn/despawn transitions below —// scale in/out for everyone else, instant for users who asked for less animation.function prefersReducedMotion() {@@ -2231,9 +2248,10 @@ async function loadNearbyPins() {// the wider read (NEARBY_READ_RADIUS = the 60 m cap) so an agent on the discovery// edge stays stably returned, then apply the asymmetric ENTER/EXIT band + despawn// debounce CLIENT-side (pinBandAction) so consumer GPS jitter can't pop it in and out.+ const _o = discoveryOrigin();try {const r = await fetch(- `/api/irl/pins?lat=${gpsState.lat}&lng=${gpsState.lng}&radius=${NEARBY_READ_RADIUS}`,+ `/api/irl/pins?lat=${_o.lat}&lng=${_o.lng}&radius=${NEARBY_READ_RADIUS}`,);if (!r.ok) { _nearbyError = true; updateNearbyBadge(); return; }const { pins } = await r.json();diff --git a/src/irl/privacy-center.js b/src/irl/privacy-center.jsindex dd1bf254c..2b1cdab98 100644--- a/src/irl/privacy-center.js+++ b/src/irl/privacy-center.js@@ -147,7 +147,7 @@ export function openPrivacyCenter({ getGhost, setGhost, onManagePins } = {}) {<h4>Discovery precision</h4><div class="irlpc-seg" role="group" aria-label="Discovery precision"><button type="button" data-prec="precise" class="${precision === 'precise' ? 'on' : ''}" aria-pressed="${precision === 'precise'}">Precise<small>exact spot</small></button>- <button type="button" data-prec="approximate" class="${precision === 'approximate' ? 'on' : ''}" aria-pressed="${precision === 'approximate'}">Approximate<small>~city block</small></button>+ <button type="button" data-prec="approximate" class="${precision === 'approximate' ? 'on' : ''}" aria-pressed="${precision === 'approximate'}">Approximate<small>~25 m area</small></button></div><div class="irlpc-note">Approximate keeps your exact position off our servers while you browse — nearby agents may resolve a little less precisely. Placement is always exactly where you choose.</div></div>diff --git a/src/viewer.js b/src/viewer.jsindex 83f4ff7e5..3a728edd1 100644--- a/src/viewer.js+++ b/src/viewer.js@@ -45,6 +45,7 @@ import { addLights, removeLights } from './viewer/lights.js';import { getCubeMapTexture } from './viewer/environment.js';import { takeScreenshot, captureScreenshot } from './viewer/screenshot.js';import { setClips, playAllClips } from './viewer/animation.js';+import { computeFramingExtent } from './viewer/framing.js';import { LightProbeGrid } from './light-probe-grid.js';import { AnimationManager } from './animation-manager.js';import { computeBoundsTree, disposeBoundsTree, acceleratedRaycast } from 'three-mesh-bvh';@@ -59,37 +60,6 @@ Mesh.prototype.raycast = acceleratedRaycast;Cache.enabled = true;-/**- * Vertical framing geometry for a humanoid bounding box.- *- * `full` (default) frames the whole body: the look-at sits at the vertical- * centre and the visible height is the full bounding box. `portrait` crops to- * roughly head-to-mid-thigh so the avatar fills a wide or short card instead of- * standing tiny-and-low in it — the read that works best for a small embedded- * thumbnail.- *- * Pure (no THREE dependency) so it is unit-testable and can be shared by both- * `setContent()` (initial framing) and `frameContent()` (re-framing on resize).- * Both must agree or a resize would jump the camera. For `full` the result is- * mathematically identical to the previous inline computation, so non-portrait- * embeds are byte-for-byte unchanged.- *- * @param {number} bodyHeight full bounding-box height in world units- * @param {number} topY world-y of the top of the head in the working frame- * @param {'full'|'portrait'} [mode]- * @returns {{ visH:number, baseY:number }} visible height + look-at y- */-export function computeFramingExtent(bodyHeight, topY, mode = 'full') {- if (mode === 'portrait') {- const PORTRAIT_FRAC = 0.62; // head → ~mid-thigh- const HEADROOM_FRAC = 0.04; // a little air above the crown- const visH = bodyHeight * PORTRAIT_FRAC;- const windowTop = topY + bodyHeight * HEADROOM_FRAC;- return { visH, baseY: windowTop - visH / 2 };- }- return { visH: bodyHeight, baseY: topY - bodyHeight / 2 };-}-/*** @class Viewer*@@ -896,6 +866,9 @@ export class Viewer {load(url, rootPath, assetMap, onProgress) {const baseURL = LoaderUtils.extractUrlBase(url);+ // Remember the source URL so the animation manager's fallen-pose guard can+ // report which avatar produced a broken retarget (passed to attach below).+ this._sourceUrl = url;// Load.return new Promise((resolve, reject) => {@@ -1032,7 +1005,7 @@ export class Viewer {});this.setClips(clips);- this.animationManager.attach(this.content);+ this.animationManager.attach(this.content, { avatarUrl: this._sourceUrl || '' });this._setupAnimationPanel();// _panelFrac() reads offsetHeight after _setupAnimationPanel hasdiff --git a/src/viewer/framing.js b/src/viewer/framing.jsnew file mode 100644index 000000000..b6915e7a9--- /dev/null+++ b/src/viewer/framing.js@@ -0,0 +1,31 @@+// Pure framing geometry for a humanoid bounding box — no THREE dependency, so+// it is unit-testable and shared by viewer.setContent (initial framing) and+// viewer.frameContent (re-framing on resize). Both must agree or a resize would+// jump the camera.++/**+ * Vertical framing for a humanoid bounding box.+ *+ * `full` (default) frames the whole body: the look-at sits at the vertical+ * centre and the visible height is the full bounding box. `portrait` crops to+ * roughly head-to-mid-thigh so the avatar fills a wide or short card instead of+ * standing tiny-and-low in it — the read that works best for a small embedded+ * thumbnail. For `full` the result is mathematically identical to the previous+ * inline computation (baseY === vertical centre), so non-portrait embeds are+ * byte-for-byte unchanged.+ *+ * @param {number} bodyHeight full bounding-box height in world units+ * @param {number} topY world-y of the top of the head in the working frame+ * @param {'full'|'portrait'} [mode]+ * @returns {{ visH:number, baseY:number }} visible height + look-at y+ */+export function computeFramingExtent(bodyHeight, topY, mode = 'full') {+ if (mode === 'portrait') {+ const PORTRAIT_FRAC = 0.62; // head → ~mid-thigh+ const HEADROOM_FRAC = 0.04; // a little air above the crown+ const visH = bodyHeight * PORTRAIT_FRAC;+ const windowTop = topY + bodyHeight * HEADROOM_FRAC;+ return { visH, baseY: windowTop - visH / 2 };+ }+ return { visH: bodyHeight, baseY: topY - bodyHeight / 2 };+}diff --git a/tests/animation-playonce.test.js b/tests/animation-playonce.test.jsnew file mode 100644index 000000000..34f4e0910--- /dev/null+++ b/tests/animation-playonce.test.js@@ -0,0 +1,127 @@+/**+ * AnimationManager.playOnce / freeze — unit tests.+ *+ * playOnce is the seamless one-shot path: a `loop:false` clip plays exactly once+ * then settles into idle via crossfade, instead of clamping and freezing on its+ * last frame (which reads as a hard snap on a looping thumbnail). freeze holds+ * the current pose and releases the active action so the render loop can idle —+ * the prefers-reduced-motion path.+ *+ * Builds a synthetic canonical rig + in-memory clips (no GLB, no fetch) so the+ * suite is fast and deterministic, mirroring animation-retarget.test.js.+ */++import { describe, it, expect } from 'vitest';+import {+ Bone,+ SkinnedMesh,+ Skeleton,+ BufferGeometry,+ QuaternionKeyframeTrack,+ VectorKeyframeTrack,+ AnimationClip,+ Object3D,+ LoopOnce,+ LoopRepeat,+} from 'three';+import { AnimationManager } from '../src/animation-manager.js';++// Eight canonical bones clears MIN_CANONICAL_BONES and gives the test clips+// full coverage so attach() builds real actions.+const RIG_BONES = ['Hips', 'Spine', 'Chest', 'Neck', 'Head', 'LeftArm', 'RightArm', 'LeftUpLeg'];++function makeRig(boneNames = RIG_BONES) {+ const root = new Object3D();+ const bones = boneNames.map((name) => {+ const b = new Bone();+ b.name = name;+ return b;+ });+ for (const b of bones) root.add(b);+ const mesh = new SkinnedMesh(new BufferGeometry());+ mesh.add(bones[0]);+ mesh.bind(new Skeleton(bones));+ root.add(mesh);+ return root;+}++function makeClip(name, duration = 1) {+ const q = new QuaternionKeyframeTrack('Hips.quaternion', [0, duration], [0, 0, 0, 1, 0, 0, 0, 1]);+ const spine = new QuaternionKeyframeTrack('Spine.quaternion', [0, duration], [0, 0, 0, 1, 0, 0, 0, 1]);+ const arm = new QuaternionKeyframeTrack('LeftArm.quaternion', [0, duration], [0, 0, 0, 1, 0, 0, 0, 1]);+ const pos = new VectorKeyframeTrack('Hips.position', [0, duration], [0, 1, 0, 0, 1, 0]);+ return new AnimationClip(name, duration, [q, spine, arm, pos]);+}++/** A manager pre-loaded with the named clips, attached to a fresh rig. */+function makeManager(names) {+ const am = new AnimationManager();+ for (const n of names) am.clips.set(n, makeClip(n));+ am.attach(makeRig());+ return am;+}++describe('AnimationManager.playOnce', () => {+ it('plays a one-shot as LoopOnce + clampWhenFinished and makes it current', async () => {+ const am = makeManager(['wave', 'idle']);+ await am.playOnce('wave', { settleTo: 'idle', fade: 0 });++ const action = am.actions.get('wave');+ expect(action).toBeTruthy();+ expect(am.currentName).toBe('wave');+ expect(am.currentAction).toBe(action);+ expect(action.loop).toBe(LoopOnce);+ expect(action.clampWhenFinished).toBe(true);+ expect(action.isRunning()).toBe(true);+ });++ it('settles into idle (a loop) once the one-shot finishes', async () => {+ const am = makeManager(['wave', 'idle']);+ await am.playOnce('wave', { settleTo: 'idle', fade: 0 });++ // Tick the mixer past the 1s clip so the 'finished' event fires.+ am.update(0.6);+ am.update(0.6);+ // crossfadeTo in the finished handler is async (ensureLoaded) — flush it.+ await new Promise((r) => setTimeout(r, 0));++ expect(am.currentName).toBe('idle');+ const idle = am.actions.get('idle');+ expect(am.currentAction).toBe(idle);+ expect(idle.loop).toBe(LoopRepeat);+ });++ it('falls back to the settle clip when the one-shot is unavailable on the rig', async () => {+ const am = makeManager(['idle']);+ await am.playOnce('does-not-exist', { settleTo: 'idle', fade: 0 });+ // Never leaves the avatar frozen in bind pose — settles to idle instead.+ expect(am.currentName).toBe('idle');+ expect(am.currentAction).toBe(am.actions.get('idle'));+ });++ it('does nothing (no throw) when neither the clip nor a settle clip exist', async () => {+ const am = makeManager(['idle']);+ await expect(am.playOnce('missing', { settleTo: null })).resolves.toBeUndefined();+ expect(am.currentName).toBeNull();+ });+});++describe('AnimationManager.freeze', () => {+ it('pauses the active action and releases it so the render loop can idle', async () => {+ const am = makeManager(['idle']);+ await am.crossfadeTo('idle', 0);+ const idle = am.actions.get('idle');+ expect(am.currentAction).toBe(idle);++ am.freeze();+ expect(idle.paused).toBe(true);+ expect(am.currentAction).toBeNull();+ expect(am.currentName).toBeNull();+ });++ it('is a no-op when nothing is playing', () => {+ const am = makeManager(['idle']);+ expect(() => am.freeze()).not.toThrow();+ expect(am.currentAction).toBeNull();+ });+});diff --git a/tests/animation-retarget.test.js b/tests/animation-retarget.test.jsindex 8ff4ae6d9..995e50d72 100644--- a/tests/animation-retarget.test.js+++ b/tests/animation-retarget.test.js@@ -26,6 +26,7 @@ import {import {canonicalNodeMapFromObject,canonicalRestMapFromObject,+ hipsParentWorldQuat,retargetClip,retargetClipToObject,scaleClipSpeed,@@ -229,6 +230,57 @@ describe('bind-rotation correction', () => {});});+describe('root-motion correction', () => {+ // A rig whose Hips sit under a tilted armature (the Mixamo +90°X pattern, or+ // any non-standard up-axis). Root motion authored in world-Y-up must be+ // re-expressed in this frame so the body still travels the right way.+ function makeRigWithTiltedArmature(tilt) {+ const root = new Object3D();+ const armature = new Object3D();+ armature.name = 'Armature';+ armature.quaternion.copy(tilt);+ root.add(armature);+ const bones = ['Hips', 'Spine', 'LeftArm', 'RightArm', 'Head'].map((n) => {+ const b = new Bone();+ b.name = n;+ return b;+ });+ armature.add(bones[0]);+ for (let i = 1; i < bones.length; i++) bones[0].add(bones[i]);+ const mesh = new SkinnedMesh(new BufferGeometry());+ mesh.bind(new Skeleton(bones));+ root.add(mesh);+ return root;+ }++ it('rotates the hip-position track by the inverse of the hips-parent world frame', () => {+ const clip = makeCanonicalClip(); // Hips.position keyframe (0,1,0)+ const tilt = new Quaternion().setFromAxisAngle({ x: 1, y: 0, z: 0 }, Math.PI / 2); // +90°X+ const rig = makeRigWithTiltedArmature(tilt);+ const map = canonicalNodeMapFromObject(rig);+ const targetRest = canonicalRestMapFromObject(rig);+ const hpq = hipsParentWorldQuat(rig);+ expect(hpq).not.toBeNull();+ const r = retargetClip(clip, map, { hipScale: 1, targetRest, hipsParentWorldQuat: hpq }).clip;+ const pos = r.tracks.find((t) => t.name.endsWith('.position'));+ // Parent is +90°X → position rotated by −90°X: (0,1,0) → (0,0,−1).+ expect(pos.values[0]).toBeCloseTo(0, 5);+ expect(pos.values[1]).toBeCloseTo(0, 5);+ expect(pos.values[2]).toBeCloseTo(-1, 5);+ });++ it('leaves the hip-position track untouched when the hips-parent frame is identity', () => {+ const clip = makeCanonicalClip();+ const rig = makeRigWithTiltedArmature(new Quaternion()); // identity armature+ const map = canonicalNodeMapFromObject(rig);+ const targetRest = canonicalRestMapFromObject(rig);+ const hpq = hipsParentWorldQuat(rig);+ const r = retargetClip(clip, map, { hipScale: 1, targetRest, hipsParentWorldQuat: hpq }).clip;+ const pos = r.tracks.find((t) => t.name.endsWith('.position'));+ expect(Array.from(pos.values)).toEqual([0, 1, 0, 0, 1.1, 0]);+ });+});+describe('retargetClipToObject', () => {it('retargets straight onto an Object3D graph', () => {const clip = makeCanonicalClip();diff --git a/tests/animation-upright-invariant.test.js b/tests/animation-upright-invariant.test.jsindex 3854a1051..cafee82ca 100644--- a/tests/animation-upright-invariant.test.js+++ b/tests/animation-upright-invariant.test.js@@ -49,6 +49,7 @@ import {MIN_COVERAGE,} from '../src/animation-retarget.js';import { FEATURED } from '../src/animation-presets.js';+import { measureHipsTiltDeg } from '../src/animation-manager.js';import { loadBoneGraph, hipsTiltAcrossClip } from './_helpers/glb-bone-graph.js';const __dirname = dirname(fileURLToPath(import.meta.url));@@ -301,23 +302,49 @@ describe('no-regression — cz.glb retarget is byte-for-byte the verbatim path',}});-// ── Runtime guard helper stays silent on healthy rigs ───────────────────────+// ── Runtime guard's pure measurement (the actual shipped code) ──────────────-// Mirror of the runtime guard's pure measurement in src/animation-manager.js:-// the at-rest (keyframe 0) Hips tilt, which is what the guard samples once per-// clip. Proves the guard's >45° threshold never fires on a healthy retarget.-describe('runtime guard is silent on healthy rigs (at-rest Hips tilt < 45°)', () => {+// measureHipsTiltDeg is the exact helper the runtime fallen-pose guard calls+// once per clip in src/animation-manager.js. Exercise it directly so what the+// guard decides on is what the corpus verifies. The guard's threshold is 45°.+const GUARD_THRESHOLD_DEG = 45;++// Retarget the way the manager does and measure with the real guard helper.+function guardTilt(root, clipName, { withFix = true } = {}) {+ const map = canonicalNodeMapFromObject(root);+ const targetRest = withFix ? canonicalRestMapFromObject(root) : new Map();+ const { clip } = retargetClip(CLIPS.get(clipName), map, { targetRest });+ return measureHipsTiltDeg(clip, root, map);+}++describe('runtime guard (measureHipsTiltDeg) is silent on healthy rigs', () => {for (const [label, file] of [['cz.glb', 'cz.glb'],['michelle.glb (post-fix)', 'michelle.glb'],]) {for (const clip of FEATURED) {- it(`${label} + ${clip}: at-rest tilt stays well under the 45° guard threshold`, () => {- const { root } = loadBoneGraph(avatar(file));- const scan = scanClip(root, clip);- expect(scan).not.toBeNull();- expect(scan.atKeyframe0).toBeLessThan(45);+ it(`${label} + ${clip}: at-rest tilt stays under the ${GUARD_THRESHOLD_DEG}° guard threshold`, () => {+ const tilt = guardTilt(loadBoneGraph(avatar(file)).root, clip);+ expect(tilt).not.toBeNull();+ expect(tilt).toBeLessThan(GUARD_THRESHOLD_DEG);});}}});++describe('runtime guard (measureHipsTiltDeg) catches a genuine fallen pose', () => {+ it('michelle + celebrate without the fix measures > 45° (the guard would fire)', () => {+ const tilt = guardTilt(loadBoneGraph(avatar('michelle.glb')).root, 'celebrate', {+ withFix: false,+ });+ expect(tilt).not.toBeNull();+ expect(tilt).toBeGreaterThan(GUARD_THRESHOLD_DEG);+ });++ it('returns null (can\'t assess, never a false alarm) when there is no clip', () => {+ const { root } = loadBoneGraph(avatar('cz.glb'));+ const map = canonicalNodeMapFromObject(root);+ expect(measureHipsTiltDeg(null, root, map)).toBeNull();+ expect(measureHipsTiltDeg(undefined, root, map)).toBeNull();+ });+});diff --git a/tests/irl-floor-anchor.test.js b/tests/irl-floor-anchor.test.jsnew file mode 100644index 000000000..795ffd21d--- /dev/null+++ b/tests/irl-floor-anchor.test.js@@ -0,0 +1,102 @@+// Pure floor-anchor math (src/irl/floor-anchor.js).+//+// The contract these tests pin is the WebXR write path: when you tap to place an+// agent on the floor, the anchored local pose must convert to a GPS pin that+// reloads where you tapped — for you and for every other viewer. A sign error+// here (the classic: storing +z as north instead of −z) ships silently and lands+// every saved anchor on the wrong side of the room. So we assert the projection+// round-trips through room-anchor's geoToLocal, the yaw extraction is right at+// every cardinal, and height/source ride through untouched. Pure math, no DOM /+// Three.js / clock — mirrors tests/irl-room-anchor.test.js.++import { describe, it, expect } from 'vitest';++import { yawDegFromQuat, anchorPoseToPin } from '../src/irl/floor-anchor.js';+import { geoToLocal } from '../src/irl/room-anchor.js';++const ORIGIN = { lat: 37.7749, lng: -122.4194 }; // arbitrary; math is origin-relative+const near = (a, b, eps = 1e-6) => Math.abs(a - b) <= eps;++// A yaw about world-Y by `deg` degrees, encoded as a quaternion [x,y,z,w].+// yawDegFromQuat reads the same clockwise-from-−Z convention savePin stores, so a+// quaternion built as a +Y rotation of θ must read back as θ.+const yawQuat = (deg) => {+ const half = (deg * Math.PI) / 180 / 2;+ return [0, Math.sin(half), 0, Math.cos(half)];+};++describe('yawDegFromQuat', () => {+ it('the identity quaternion is 0° yaw', () => {+ expect(yawDegFromQuat(0, 0, 0, 1)).toBe(0);+ });++ it('cardinal yaw quaternions read back as 90 / 180 / 270', () => {+ expect(near(yawDegFromQuat(...yawQuat(90)), 90)).toBe(true);+ expect(near(Math.abs(yawDegFromQuat(...yawQuat(180))), 180)).toBe(true); // ±180 are the same heading+ // 270° comes back as −90° in the raw atan2 range; the persist path normalises it.+ expect(near(yawDegFromQuat(...yawQuat(270)), -90)).toBe(true);+ });++ it('a wider sweep round-trips through anchorPoseToPin into [0,360)', () => {+ for (const deg of [0, 45, 90, 135, 180, 225, 270, 315, 359]) {+ const { heading } = anchorPoseToPin({+ originLat: ORIGIN.lat, originLng: ORIGIN.lng,+ x: 0, y: 0, z: 0, quat: yawQuat(deg),+ });+ expect(heading).toBeGreaterThanOrEqual(0);+ expect(heading).toBeLessThan(360);+ expect(near(heading, deg, 1)).toBe(true); // rounded to whole degrees+ }+ });+});++describe('anchorPoseToPin', () => {+ const QUAT = yawQuat(0);++ it('a pose +2 m east / +3 m north of the origin round-trips back to (2, 3)', () => {+ // Local frame: +X = east, world north = −Z, so 3 m north is z = −3.+ const pin = anchorPoseToPin({+ originLat: ORIGIN.lat, originLng: ORIGIN.lng,+ x: 2, y: 0, z: -3, quat: QUAT,+ });+ const back = geoToLocal(ORIGIN.lat, ORIGIN.lng, pin.lat, pin.lng);+ expect(near(back.east, 2, 1e-3)).toBe(true);+ expect(near(back.north, 3, 1e-3)).toBe(true);+ });++ it('the sign of z is north-negated (catches the +z mistake)', () => {+ // Walking the agent to +z (south) must DECREASE latitude, not increase it.+ const south = anchorPoseToPin({ originLat: ORIGIN.lat, originLng: ORIGIN.lng, x: 0, y: 0, z: 5, quat: QUAT });+ const north = anchorPoseToPin({ originLat: ORIGIN.lat, originLng: ORIGIN.lng, x: 0, y: 0, z: -5, quat: QUAT });+ expect(south.lat).toBeLessThan(ORIGIN.lat);+ expect(north.lat).toBeGreaterThan(ORIGIN.lat);+ // +x is east → longitude increases.+ const east = anchorPoseToPin({ originLat: ORIGIN.lat, originLng: ORIGIN.lng, x: 5, y: 0, z: 0, quat: QUAT });+ expect(east.lng).toBeGreaterThan(ORIGIN.lng);+ });++ it('heightM passes through unchanged (negative = below eye level)', () => {+ const below = anchorPoseToPin({ originLat: ORIGIN.lat, originLng: ORIGIN.lng, x: 0, y: -1.4, z: 0, quat: QUAT });+ expect(below.heightM).toBe(-1.4);+ const above = anchorPoseToPin({ originLat: ORIGIN.lat, originLng: ORIGIN.lng, x: 0, y: 0.6, z: 0, quat: QUAT });+ expect(above.heightM).toBe(0.6);+ });++ it('quat passes through untouched and source is webxr', () => {+ const q = yawQuat(47);+ const pin = anchorPoseToPin({ originLat: ORIGIN.lat, originLng: ORIGIN.lng, x: 1, y: 0, z: 1, quat: q });+ expect(pin.quat).toBe(q);+ expect(pin.source).toBe('webxr');+ });+});++describe('round-trip property: anchorPoseToPin then geoToLocal is identity', () => {+ it('survives within 1e-6 for assorted offsets', () => {+ for (const [x, z] of [[0, 0], [2, -3], [-4, 1], [12, 12], [-7.5, -2.25], [0.1, -0.1]]) {+ const pin = anchorPoseToPin({ originLat: ORIGIN.lat, originLng: ORIGIN.lng, x, y: 0, z, quat: yawQuat(0) });+ const back = geoToLocal(ORIGIN.lat, ORIGIN.lng, pin.lat, pin.lng);+ expect(near(back.east, x, 1e-6)).toBe(true); // east = +x+ expect(near(back.north, -z, 1e-6)).toBe(true); // north = −z+ }+ });+});diff --git a/tests/viewer-framing.test.js b/tests/viewer-framing.test.jsnew file mode 100644index 000000000..b0a254b80--- /dev/null+++ b/tests/viewer-framing.test.js@@ -0,0 +1,66 @@+/**+ * Viewer framing geometry — unit tests for computeFramingExtent.+ *+ * The pure helper decides the visible vertical extent + look-at height the+ * camera frames. `full` must stay byte-for-byte identical to the legacy inline+ * math (so every existing embed is unchanged); `portrait` crops to+ * head-to-mid-thigh so an avatar fills a wide/short card.+ */++import { describe, it, expect } from 'vitest';+import { computeFramingExtent } from '../src/viewer/framing.js';++describe('computeFramingExtent — full (default)', () => {+ it('is the legacy full-body framing: baseY at the vertical centre, full height', () => {+ // setContent works in recentered coords: crown at +H/2, so baseY must be 0.+ const H = 1.8;+ const { visH, baseY } = computeFramingExtent(H, H / 2, 'full');+ expect(visH).toBe(H);+ expect(baseY).toBeCloseTo(0, 12);+ });++ it('reduces to bbCenter.y when topY is the box max (frameContent coords)', () => {+ // frameContent passes topY = box.max.y; baseY must equal the box centre.+ const H = 2;+ const boxMaxY = 1.4; // centre = boxMaxY - H/2 = 0.4+ const { visH, baseY } = computeFramingExtent(H, boxMaxY, 'full');+ expect(visH).toBe(H);+ expect(baseY).toBeCloseTo(0.4, 12);+ });++ it('defaults to full when no mode is given', () => {+ const H = 1.7;+ expect(computeFramingExtent(H, H / 2)).toEqual(computeFramingExtent(H, H / 2, 'full'));+ });+});++describe('computeFramingExtent — portrait', () => {+ const H = 1.8;+ const top = H / 2; // recentered crown+ const { visH, baseY } = computeFramingExtent(H, top, 'portrait');++ it('shows a cropped slice of the body, not the whole height', () => {+ expect(visH).toBeLessThan(H);+ expect(visH).toBeGreaterThan(H * 0.4); // head-to-mid-thigh, not a tight headshot+ expect(visH).toBeCloseTo(H * 0.62, 6);+ });++ it('raises the look-at above the body centre so the head sits high in frame', () => {+ expect(baseY).toBeGreaterThan(0); // above centre (which is 0 for full)+ });++ it('keeps the crown inside the framed window (with a little headroom)', () => {+ // Visible window spans [baseY - visH/2, baseY + visH/2]; its top must sit+ // at or just above the crown so the head is never clipped.+ const windowTop = baseY + visH / 2;+ expect(windowTop).toBeGreaterThanOrEqual(top);+ expect(windowTop).toBeCloseTo(top + H * 0.04, 6); // exactly the headroom+ });++ it('scales linearly with body height', () => {+ const a = computeFramingExtent(2, 1, 'portrait');+ const b = computeFramingExtent(4, 2, 'portrait');+ expect(b.visH).toBeCloseTo(a.visH * 2, 9);+ expect(b.baseY).toBeCloseTo(a.baseY * 2, 9);+ });+});diff --git a/vercel.json b/vercel.jsonindex 2b05a4e6a..ae5df926d 100644--- a/vercel.json+++ b/vercel.json@@ -755,6 +755,10 @@"src": "/irl/?","dest": "/irl.html"},+ {+ "src": "/ibm/x402-demo",+ "dest": "/ibm/x402-demo.html"+ },{"src": "/communities/?","dest": "/communities.html"@@ -2014,6 +2018,10 @@"src": "/api/sniper/leaderboard","dest": "/api/sniper/leaderboard.js"},+ {+ "src": "/api/sniper/status",+ "dest": "/api/sniper/status.js"+ },{"src": "/api/trending","dest": "/api/trending.js"diff --git a/vite.config.js b/vite.config.jsindex e715d3f22..0d027e7ba 100644--- a/vite.config.js+++ b/vite.config.js@@ -1427,6 +1427,49 @@ support: resolve(__dirname, 'pages/support.html'),}},},+ {+ // The IBM × three.ws x402 demo (pages/ibm/x402-demo.html) is a hand-+ // authored, self-contained partner artifact — inline CSS+JS, self-hosted+ // fonts under pages/ibm/fonts/, absolute three.ws URLs. It ships to IBM to+ // host on a foreign origin under a strict CSP, so it must stay byte-for-byte+ // identical wherever it's served. We therefore copy it VERBATIM to dist/ibm/+ // instead of registering it as a Rollup input: a Vite input would minify the+ // HTML, hash the relative ./fonts/ URLs (so they no longer travel with the+ // file), and inject the site's analytics / error-reporter / three-guard+ // scripts via the transformIndexHtml plugins above — each of which diverges+ // the preview from the standalone file and pulls in origins the page's+ // `script-src 'self' three.ws` CSP forbids. The .md hosting guide is+ // source-only and excluded from the copy.+ name: 'copy-ibm-x402-demo',+ configureServer(server) {+ const dir = resolve(__dirname, 'pages/ibm');+ const MIME = { '.html': 'text/html; charset=utf-8', '.woff2': 'font/woff2' };+ server.middlewares.use((req, res, next) => {+ const path = (req.url || '').split('?')[0];+ let rel = null;+ if (path === '/ibm/x402-demo' || path === '/ibm/x402-demo.html')+ rel = 'x402-demo.html';+ else if (path.startsWith('/ibm/fonts/'))+ rel = 'fonts/' + path.slice('/ibm/fonts/'.length);+ if (!rel) return next();+ const file = resolve(dir, rel);+ // Path-traversal guard: never serve outside pages/ibm/.+ if (!file.startsWith(dir + '/') || !existsSync(file) || !statSync(file).isFile())+ return next();+ res.setHeader('Content-Type', MIME[extname(file)] || 'application/octet-stream');+ createReadStream(file).pipe(res);+ });+ },+ closeBundle() {+ const src = resolve(__dirname, 'pages/ibm');+ if (!existsSync(src)) return;+ // Ship the page + its fonts; the hosting guide stays in source.+ cpSync(src, resolve(__dirname, 'dist/ibm'), {+ recursive: true,+ filter: (s) => !s.endsWith('.md'),+ });+ },+ },{// Several static pages (dashboard, vanity-wallet, …) import ESM// directly from `/src/*.js`. Vite's dev server serves these from