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: walk control API, walk docs site, list controls, and Solana RPC fallback hardening
nirholas1b2028aa64e0
diff --git a/.gitignore b/.gitignoreindex 45e1a52e7..038281dac 100644--- a/.gitignore+++ b/.gitignore@@ -258,3 +258,5 @@ pages/ibm/test.html/bscwallets.jsonthree.ws-log-export-2026-06-20T06-40-10.jsonthree.ws-log-export-2026-06-20T11-29-59.json+three.ws-log-export-2026-06-21T06-35-55.json+three.ws-log-export-2026-06-21T06-36-48.jsondiff --git a/CHANGELOG.md b/CHANGELOG.mdindex d9b3112ac..6abb4c9ad 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,16 +14,19 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Authorize $THREE once, then pay with no wallet popups** — The $THREE page now lets you set a spending allowance: approve a cap once, and paid actions across the platform — forge, skills, names, cosmetics — debit it automatically without asking you to sign every time. It's non-custodial and built on Solana's native, audited Subscriptions & Allowances program: your tokens stay in your own wallet until a charge pulls them, never more than the cap you set, and you can let it expire or revoke it anytime. Set a cap, top it up, or leave it off and keep signing each payment — your choice. (`/three-token`) `[feature]`- **Clearer empty state on the $THREE live-trades feed** — Before the next trade lands, the live-trades panel on the $THREE token page now reads in plain language — 'Live trades will appear here' — with a short note on what it shows, and the technical detail tucked behind an info tooltip. Screen readers announce new trades as they stream in. (`/three-token`) `[improvement]`- **Discover and character feeds load faster under heavy traffic** — The Discover grid and the published-agents (Characters) feed now serve from the edge cache, so a surge of visitors is absorbed at the CDN instead of re-running a database scan on every request. Pages stay fast and consistent even during a rush, and a stale-while-revalidate window keeps them warm between refreshes. (`/discover`) `[improvement, infra]`+- **Discover and Marketplace now browse the same way** — Searching, filtering, and sorting agents now work identically on /discover and /marketplace. Both pages share one polished control bar — debounced search, filter chips, and sort — and your choices are saved in the page address, so a filtered view is shareable and the browser back button restores it. Loading, empty, and error states were unified too: a search that matches nothing shows a clear 'no results' panel with a one-click 'Clear filters', and a failed load offers a retry instead of a blank grid. (`/discover`) `[improvement]`- **Empty pages now guide you instead of going blank** — Across the dashboard and marketplace, anywhere a list can be empty now explains what belongs there, why it's useful, and the next step — instead of a bare 'No data' line. Your Agents, Avatars, Analytics, Brain, embed policies, the marketplace, and My Agents each greet a fresh account with a short plain-language intro and a clear button to create your first one (plus a 'What's an agent?' link). Filtered searches that return nothing now say so and offer to clear the filter. It's the same designed component everywhere, so the whole platform feels consistent and never abandoned. (`/dashboard`) `[improvement]`- **Every Forge quality tier now runs on free engines** — Forge's quality tiers — Draft, Standard, and High — all generate on zero-cost engines now: Draft and Standard on the fast free NVIDIA lane, and High on the higher-fidelity, fully textured free HuggingFace engine. Higher tiers buy you genuinely better geometry and textures, not a different bill behind the scenes. Photo-to-3D at any tier routes straight to a free engine too, so a generation never quietly falls back to a paid lane. The High tier stays a $THREE holder perk (or a one-off pay-per-use) — that's the price of premium quality, not a cost we're passing through. (`/forge`) `[improvement, feature]`- **Forge hardened for a traffic surge — faster loads, protected free lanes** — We scaled Forge for the influx of new users. The engine catalog and live health status now serve from the edge cache, so the page loads instantly even under heavy traffic instead of recomputing on every visit. We also added a platform-wide safety valve on paid generation: if demand ever spikes past the shared paid budget, the free engines (NVIDIA and Hugging Face) stay fully open and you get a clear 'try a free engine' message instead of a hard failure — your own bring-your-own-key engines are never affected. Net result: Forge stays fast and available as we grow, and free 3D generation never gets crowded out. (`/forge`) `[infra, improvement]`- **Forge scales further — duplicate generations collapse, free lane protected, prices shown up front** — More headroom for the influx. Forge now recognizes when the same prompt or photo set is already generating and quietly hands everyone the same result instead of paying to build it twice — so a viral prompt or a double-click no longer multiplies cost or wait. The free Hugging Face engine is now capped to a safe number of simultaneous jobs so a rush can't tie up the servers and stall everyone; over the cap, your generation cleanly falls back to another engine instead of hanging. The composer now shows the real price before you generate — 'Free' for Draft and Standard, the exact dollar amount (or 'Free, you hold $THREE') for High, and 'billed to your own key' for bring-your-own-key engines — so there are no surprises. The engine picker also gained a small legend explaining the badges at a glance — which engines are free, which use your own key, and which are busy or unavailable. And the 3D viewer now shows a loading shimmer instead of a dark void while your model paints in. (`/forge`) `[improvement, infra]`- **Forge stays calm under a crowd: live countdown, graceful high-demand handling, one-tap model retry** — Generating a 3D model now feels steadier when lots of people are forging at once. The progress meter shows a real "~Ns left" countdown instead of a static estimate, so you can see it moving. If the free engines are momentarily at capacity during a rush, you get a friendly "high demand" notice with a live retry countdown that re-arms itself the moment a slot frees up — your spot in line, not a dead-end error — and you can keep refining a model you already have while you wait. And if a finished model ever fails to paint because of a brief network blip, a new Retry button reloads it in place instead of forcing a download. Behind the scenes, generation success rate and latency are now tracked so we can catch slowdowns before they reach you. (`/forge`) `[improvement, fix]`- **forge_avatar — one call turns a prompt into a rigged, animation-ready avatar** — A new forge_avatar MCP tool collapses the old two-step flow (generate a mesh, then rig it) into a single call: describe a character in text — or pass reference images — and it generates the textured model, auto-rigs it with a humanoid skeleton, and returns an animation-ready GLB that drops straight into the pose studio and plays the idle/walk library. A built-in humanoid check runs first, so a non-character prompt (furniture, a vehicle, an animal) is turned away with no charge instead of wasting a paid rig. It bundles generation and rigging at their combined price ($0.45) with no hidden markup, and you are never charged if no rigged avatar is produced. (`/docs/mcp`) `[sdk, feature]`+- **Free 3D generation keeps working when the paid engines are down** — The text/image→3D forge has a free fallback that runs on public GPU Spaces so a generation never dead-ends when the paid engine is busy or out of capacity. Two of those Spaces had gone stale — one was taken offline and another was being called on the wrong endpoint — which meant the free lane could fail even when a working Space was available. The chain now targets only live Spaces with the correct settings, so 'type a prompt → get a model' keeps returning a result even when every paid lane is unavailable. `[fix]`- **Free 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]`- **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]`+- **Pay-per-call endpoints accept Solana USDC payments again** — Paying for any x402 endpoint with Solana USDC was failing the moment the wallet tried to build the payment — the platform's receiving address was being published with a stray invisible character, so a correctly-built payment got rejected as going to the wrong recipient. Payment addresses are now cleaned before they're ever advertised, so Solana USDC payments to paid endpoints go through and settle as expected. `[fix]`- **Payment hardening and a steadier holder leaderboard** — Two behind-the-scenes reliability and safety fixes. Agent payment invoices now verify that the wallet paying is actually linked to your account before an invoice is created, closing a gap that let bogus payment requests be generated against any agent. And the $THREE holder leaderboard, its share card, and the token stats panel no longer each kick off a full on-chain holder scan during a traffic spike — one scan now serves everyone and refreshes the shared snapshot, so the leaderboard stays fast and responsive under load. Nothing to do on your end. (`/leaderboard`) `[security, fix, infra]`- **Platform-wide hardening: payment integrity, security, and scale** — A broad reliability pass across the parts of three.ws that move real money and serve heavy traffic. On the money side: bundle purchases and agent payments are now verified on-chain before anything unlocks, each payment is credited exactly once, withdrawals can't be processed twice, and recurring subscriptions can't be double-billed. On the security side: a set of input-handling and link-safety fixes across pages, stronger protection for custodial keys at rest, and tighter checks on outbound agent payments so funds only ever move in the expected asset. On the scale side: the busiest directory, profile, and feed pages now ride a short cache and run far fewer database queries, so they stay fast as the community grows. Most of this is invisible by design — it's the plumbing that keeps the platform correct and quick under load. `[security, improvement, infra]`- **Profiles you can edit — and follow** — Your three.ws profile at three.ws/u/<your-username> is now a real social home. Edit it in place: add a bio, a profile picture and banner image, your location, and a website link — all from an Edit button on your own profile. You can now follow other creators and agents, and they can follow you; every profile shows live follower and following counts you can tap to browse the lists, with one-tap follow buttons throughout. And there's a new Feed at three.ws/feed that gathers the latest avatars, agents, and coin launches from everyone you follow, newest first. Find your profile and Feed links from your account page. (`/feed`) `[feature]`@@ -881,7 +884,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Chat** (`/chat`) — Talk to your agent. Voice, text, and tool-use in one interface.- **Marketplace** (`/marketplace`) — Buy access to agents, skills, and avatars from other creators.- **Pump.fun Stream** (`/pumpfun`) — Mint and trade pump.fun agent tokens on Solana. Live feed of every launch.-- **Solana Vanity Wallet** (`/vanity-wallet`) — Grind a Solana address with a custom prefix using your browser's GPU.+- **Solana Vanity Wallet** (`/vanity-wallet`) — Grind a Solana address with a custom prefix — entirely in your browser, across your CPU cores.- **On-chain agents on Solana and EVM** — Unified deployment stack — agents register on Ethereum, Base, Polygon, and Solana with passport pages, reputation, and attestations. `[feature]`- **Pump.fun launch and trading stack** — Token creation, bonding-curve swaps, KOL trade tracking, automated wallet monitoring, and a vanity address grinder for custom Solana prefixes. `[feature]`- **Solana Agent SDK** — Actions for token transfers, SPL swaps, balance queries, and stake attestations, with transaction builders and fee estimation. `[sdk]`diff --git a/api/_lib/env.js b/api/_lib/env.jsindex 16dd23179..b04b360ec 100644--- a/api/_lib/env.js+++ b/api/_lib/env.js@@ -16,6 +16,19 @@ function trimSlash(s) {return s ? s.replace(/\/$/, '') : s;}+// Blockchain addresses pasted into dashboards (Vercel/Helius/etc.) frequently+// carry a trailing newline or stray spaces. An untrimmed address breaks every+// spec-compliant x402 client the instant it does `new PublicKey(payTo)` —+// "Non-base58 character" — or silently routes funds via a malformed EVM+// checksum. Trim address-like env values at the source so no consumer ever+// emits whitespace into a 402 challenge. Returns undefined when blank so the+// `if (env.X402_PAY_TO_SOLANA)` guards downstream still skip cleanly.+function addr(value) {+ if (value == null) return value;+ const v = String(value).trim();+ return v || undefined;+}+// Canonical fallback origin — used when PUBLIC_APP_ORIGIN is unset, empty, or// not a parseable absolute URL.const DEFAULT_APP_ORIGIN = 'https://three.ws';@@ -437,20 +450,22 @@ export const env = {// Asset/mint addresses below keep their public-constant defaults; only the// money-routing receivers (payTo + feePayer) are required-by-config.get X402_PAY_TO_SOLANA() {- return opt('X402_PAY_TO_SOLANA', opt('X402_PAY_TO'));+ return addr(opt('X402_PAY_TO_SOLANA', opt('X402_PAY_TO')));},get X402_PAY_TO_BASE() {- return opt('X402_PAY_TO_BASE');+ return addr(opt('X402_PAY_TO_BASE'));},// USDC asset addresses per network.get X402_ASSET_MINT_SOLANA() {- return opt(- 'X402_ASSET_MINT_SOLANA',- opt('X402_ASSET_MINT', 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'),+ return addr(+ opt(+ 'X402_ASSET_MINT_SOLANA',+ opt('X402_ASSET_MINT', 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'),+ ),);},get X402_ASSET_ADDRESS_BASE() {- return opt('X402_ASSET_ADDRESS_BASE', '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913');+ return addr(opt('X402_ASSET_ADDRESS_BASE', '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913'));},// Price per /api/mcp call, in the asset's base units (USDC = 6 decimals; "1000" = 0.001 USDC).get X402_MAX_AMOUNT_REQUIRED() {@@ -511,7 +526,7 @@ export const env = {get X402_FEE_PAYER_SOLANA() {// No hardcoded default — see X402_PAY_TO_SOLANA. Without a fee payer the// Solana accept can't be co-signed, so it must come from config.- return opt('X402_FEE_PAYER_SOLANA');+ return addr(opt('X402_FEE_PAYER_SOLANA'));},// $THREE as a second Solana settlement asset, offered alongside USDC so// holders can pay any three.ws paid endpoint in the platform token — the@@ -578,13 +593,13 @@ export const env = {},// Native (non-bridged) USDC on Arbitrum One mainnet.get X402_ASSET_ADDRESS_ARBITRUM() {- return opt('X402_ASSET_ADDRESS_ARBITRUM', '0xaf88d065e77c8cC2239327C5EDb3A432268e5831');+ return addr(opt('X402_ASSET_ADDRESS_ARBITRUM', '0xaf88d065e77c8cC2239327C5EDb3A432268e5831'));},// Binance-Peg USD Coin (USDC) on BSC mainnet. Standard ERC-20; does NOT// implement EIP-3009 transferWithAuthorization, which is why BSC x402// payments use the contract-mediated "direct" scheme (see x402-bsc-direct.js).get X402_ASSET_ADDRESS_BSC() {- return opt('X402_ASSET_ADDRESS_BSC', '0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d');+ return addr(opt('X402_ASSET_ADDRESS_BSC', '0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d'));},// ThreeWSPayments x402 receiver contract on BSC. Client calls// pay(bytes32 ref) after approving USDC; the contract pulls pricePerCall@@ -593,7 +608,7 @@ export const env = {get X402_PAY_TO_BSC() {// No hardcoded default — see X402_PAY_TO_SOLANA. The ThreeWSPayments// receiver contract address must be set explicitly per deploy.- return opt('X402_PAY_TO_BSC');+ return addr(opt('X402_PAY_TO_BSC'));},// ── AWS Marketplace ──────────────────────────────────────────────────────// IAM credentials with marketplaceMetering:ResolveCustomer,diff --git a/api/_lib/migrations/20260621160000_walk_control.sql b/api/_lib/migrations/20260621160000_walk_control.sqlnew file mode 100644index 000000000..8f4d80c70--- /dev/null+++ b/api/_lib/migrations/20260621160000_walk_control.sql@@ -0,0 +1,85 @@+-- Walk programmatic-control sessions + command queue.+--+-- Powers the REST control surface (api/walk/control/[action].js) that lets an+-- external system — another agent, a CI bot, a webhook — drive a *running* walk+-- page: move the avatar to a world position, trigger a gesture, make it speak, or+-- swap the environment live.+--+-- Two principals, two credentials:+-- · The CONTROLLER creates a session (POST /session) and pushes commands. It+-- authenticates the create call as the avatar owner (cookie/bearer) and then+-- holds the returned `controlToken` (an opaque secret, stored hashed) to push+-- and to read state.+-- · The WALK CLIENT (src/walk.js, opened with ?control=<sessionId>&ck=<token>)+-- short-polls /session (or /poll) with the same controlToken to drain queued+-- commands and apply them to the real scene, and reports its live position+-- back so the controller's /state read reflects the actual avatar.+--+-- A command is enqueued once, delivered once: the poll claims undelivered rows+-- for the session in fifo order and stamps delivered_at, so a command is never+-- replayed across polls. Idempotency: a controller may pass a client-supplied+-- `dedup_key` per (session, kind) so a retried push collapses onto the same row+-- instead of enqueuing a duplicate move/say.+--+-- Sessions are ephemeral. `expires_at` bounds a session's life; a background+-- sweep (or a lazy delete on access) reclaims expired sessions and their+-- commands. Commands cascade-delete with their session.+--+-- Fully idempotent — safe to re-run. Mirrored into api/_lib/schema.sql.++-- ── walk_control_sessions — one row per live control session ─────────────────+create table if not exists walk_control_sessions (+ id uuid primary key default gen_random_uuid(),+ owner_id uuid not null references users(id) on delete cascade,+ avatar_id uuid references avatars(id) on delete set null,+ -- The controlToken handed to the controller, stored only as a SHA-256 hex+ -- digest. The plaintext is returned once at creation and never persisted.+ token_hash text not null,+ label text, -- optional human label for the session+ env_id text, -- requested initial environment+ -- Live avatar state, reported by the walk client on each poll. Null until the+ -- client first checks in. pos_x/pos_z are world metres; facing is radians.+ pos_x double precision,+ pos_z double precision,+ facing double precision,+ motion text, -- idle | walk | run (client-reported)+ current_env text, -- env the client actually has loaded+ -- Lifecycle timestamps.+ client_seen_at timestamptz, -- last time the walk client polled+ created_at timestamptz not null default now(),+ expires_at timestamptz not null+);++create index if not exists walk_control_sessions_owner+ on walk_control_sessions (owner_id, created_at desc);+create index if not exists walk_control_sessions_token+ on walk_control_sessions (token_hash);+create index if not exists walk_control_sessions_expires+ on walk_control_sessions (expires_at);++-- ── walk_control_commands — fifo command queue per session ───────────────────+-- kind ∈ move | gesture | say | env. `payload` carries the kind-specific args+-- ({x,z,speed} | {gesture} | {text,voice} | {env}). delivered_at is null until a+-- poll claims it; once stamped the command is never handed out again.+create table if not exists walk_control_commands (+ id bigserial primary key,+ session_id uuid not null references walk_control_sessions(id) on delete cascade,+ seq bigint not null, -- monotonic per-session ordering+ kind text not null check (kind in ('move','gesture','say','env')),+ payload jsonb not null default '{}'::jsonb,+ dedup_key text, -- optional controller-supplied idempotency key+ created_at timestamptz not null default now(),+ delivered_at timestamptz -- set when a poll claims the row+);++-- Drain order + "undelivered for this session" lookups.+create index if not exists walk_control_commands_drain+ on walk_control_commands (session_id, seq)+ where delivered_at is null;++-- Idempotent push: a retried controller call carrying the same (session, kind,+-- dedup_key) collapses onto the existing row rather than enqueuing a duplicate.+-- Partial unique index so commands without a dedup_key are unconstrained.+create unique index if not exists walk_control_commands_dedup+ on walk_control_commands (session_id, kind, dedup_key)+ where dedup_key is not null;diff --git a/api/_lib/schema.sql b/api/_lib/schema.sqlindex 40b33851a..c0f17a4ef 100644--- a/api/_lib/schema.sql+++ b/api/_lib/schema.sql@@ -1847,6 +1847,51 @@ create unique index if not exists walk_achievements_uniq);create index if not exists walk_achievements_user on walk_achievements (user_id) where user_id is not null;+-- ── walk programmatic-control sessions + command queue ───────────────────────+-- See api/_lib/migrations/20260621160000_walk_control.sql for the full rationale.+-- Mirrored here so a clean schema.sql apply provisions the walk control API.+-- Endpoint: api/walk/control/[action].js. The walk client opts in via+-- /walk?control=<sessionId>&ck=<controlToken>.+create table if not exists walk_control_sessions (+ id uuid primary key default gen_random_uuid(),+ owner_id uuid not null references users(id) on delete cascade,+ avatar_id uuid references avatars(id) on delete set null,+ token_hash text not null,+ label text,+ env_id text,+ pos_x double precision,+ pos_z double precision,+ facing double precision,+ motion text,+ current_env text,+ client_seen_at timestamptz,+ created_at timestamptz not null default now(),+ expires_at timestamptz not null+);+create index if not exists walk_control_sessions_owner+ on walk_control_sessions (owner_id, created_at desc);+create index if not exists walk_control_sessions_token+ on walk_control_sessions (token_hash);+create index if not exists walk_control_sessions_expires+ on walk_control_sessions (expires_at);++create table if not exists walk_control_commands (+ id bigserial primary key,+ session_id uuid not null references walk_control_sessions(id) on delete cascade,+ seq bigint not null,+ kind text not null check (kind in ('move','gesture','say','env')),+ payload jsonb not null default '{}'::jsonb,+ dedup_key text,+ created_at timestamptz not null default now(),+ delivered_at timestamptz+);+create index if not exists walk_control_commands_drain+ on walk_control_commands (session_id, seq)+ where delivered_at is null;+create unique index if not exists walk_control_commands_dedup+ on walk_control_commands (session_id, kind, dedup_key)+ where dedup_key is not null;+CREATE TABLE IF NOT EXISTS x_pending_reviews (id uuid NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,diff --git a/api/_lib/skill-license-onchain.js b/api/_lib/skill-license-onchain.jsindex e8903d3a7..b538769bd 100644--- a/api/_lib/skill-license-onchain.js+++ b/api/_lib/skill-license-onchain.js@@ -20,7 +20,6 @@import { createHash } from 'node:crypto';import {- Connection,Keypair,PublicKey,SystemProgram,@@ -32,6 +31,7 @@ import {import bs58 from 'bs58';import { env } from './env.js';+import { solanaConnection } from './solana/connection.js';/** Program id baked into the on-chain program's `declare_id!`. Override per* deployment with SKILL_LICENSE_PROGRAM_ID. */@@ -184,7 +184,7 @@ export async function verifyOnchainSkillLicense({connection,programId = SKILL_LICENSE_PROGRAM_ID,}) {- const conn = connection || new Connection(rpcForNetwork(network), 'confirmed');+ const conn = connection || solanaConnection({ url: rpcForNetwork(network), commitment: 'confirmed', network });const [license] = deriveSkillLicensePda(ownerWallet, agentMint, skill, programId);const [nftMint] = deriveSkillMintPda(ownerWallet, agentMint, skill, programId);const ownerTokenAccount = deriveAssociatedTokenAddress(ownerWallet, nftMint);@@ -333,7 +333,7 @@ export async function mintSkillLicenseOnchain({code: 'minter_unconfigured',});}- const conn = connection || new Connection(rpcForNetwork(network), 'confirmed');+ const conn = connection || solanaConnection({ url: rpcForNetwork(network), commitment: 'confirmed', network });const { instruction, accounts } = buildMintSkillLicenseIx({minter: minter.publicKey,diff --git a/api/_lib/solana/connection.js b/api/_lib/solana/connection.jsindex 89e693021..cb6adc47c 100644--- a/api/_lib/solana/connection.js+++ b/api/_lib/solana/connection.js@@ -246,7 +246,41 @@ export function makeRotatingFetch(endpoints) {lastErr = new Error(`solana rpc ${resp.status} @ ${maskUrl(url)}`);continue;}- return resp;+ // A healthy 2xx status is not a guarantee of a usable body. Under load+ // some providers answer a JSON-RPC POST with 200 + an empty payload or+ // 200 + an HTML interstitial/error page instead of a 5xx. web3.js then+ // runs that through its superstruct result schema and throws+ // `StructError: Expected the value to satisfy a union of type | type,+ // but received:` (the empty/garbage body) straight to the caller,+ // WITHOUT rotating, because a parse error carries no rotate-worthy HTTP+ // status. That single failure mode produced the recurring StructError+ // noise across getBalance / getLatestBlockhash / getSignaturesForAddress+ // / getBuyQuote. Detect the poison body here and fail over to the next+ // provider instead of handing web3.js something it cannot parse.+ const okBody = await resp.text();+ const firstChar = okBody.trimStart()[0];+ if (okBody.trim() === '' || firstChar === '<') {+ const alreadyCooling = isEndpointCooling(url);+ // Treat like a transient provider 5xx: short cooldown, not a long+ // quota park. The endpoint is up but momentarily returning garbage.+ const ms = markEndpointCooldown(url, 502, '');+ if (!alreadyCooling) {+ console.log(+ `[solana-rpc] ${maskUrl(url)} 200 but ${okBody.trim() === '' ? 'empty' : 'non-JSON'} body — cooling ${Math.round(ms / 60_000)}m, failing over`,+ );+ }+ lastErr = new Error(`solana rpc non-JSON-RPC body @ ${maskUrl(url)}`);+ continue;+ }+ // Body already consumed above; hand web3.js a fresh Response carrying+ // the same payload. Only content-type is preserved; copying+ // content-encoding/content-length would mislead the consumer since the+ // transport already decoded the body into `okBody`.+ return new Response(okBody, {+ status: resp.status,+ statusText: resp.statusText,+ headers: { 'content-type': resp.headers.get('content-type') || 'application/json' },+ });} catch (err) {// A thrown fetch is a transient network/DNS blip, not a quota signal —// cool only briefly so a healthy provider isn't parked for long.diff --git a/api/_lib/solana/rpc-fallback.js b/api/_lib/solana/rpc-fallback.jsindex 0614b3aec..fa19e1ce4 100644--- a/api/_lib/solana/rpc-fallback.js+++ b/api/_lib/solana/rpc-fallback.js@@ -58,7 +58,15 @@ function isRetryable(err) {msg.includes('ETIMEDOUT') ||msg.includes('ECONNREFUSED') ||msg.includes('ECONNRESET') ||- msg.includes('fetch failed')+ msg.includes('fetch failed') ||+ // A provider that returns 200 + an empty/garbage body makes web3.js throw a+ // `StructError: Expected the value to satisfy a union of …, but received:`+ // while parsing the response. makeRotatingFetch already catches this at the+ // transport layer, but a single-endpoint Connection (urls.length === 1, no+ // rotating fetch attached) surfaces it here — rotating/cooling is the right+ // response, not bubbling an opaque schema error to the caller.+ msg.includes('StructError') ||+ msg.includes('Expected the value to satisfy'));}diff --git a/api/_providers/huggingface.js b/api/_providers/huggingface.jsindex a15fb8dd9..a37b04913 100644--- a/api/_providers/huggingface.js+++ b/api/_providers/huggingface.js@@ -39,16 +39,22 @@ const HF_INFERENCE_TIMEOUT_MS = 280_000; // leave headroom for response framing// payload from the selfie photos. Add new Spaces as they come online; keep// the most reliable / highest-quality at the top.//-// Verified targets (2026-05):-// tencent/Hunyuan3D-2 — textured GLB via /generation_all-// tencent/Hunyuan3D-2.1 — successor; same /generation_all shape-// JeffreyXiang/TRELLIS — Microsoft TRELLIS, single image-// stabilityai/TripoSR — fast feed-forward, single image+// Verified targets (2026-06, probed live against each Space's Gradio /info):+// tencent/Hunyuan3D-2 — textured GLB via /generation_all (highest quality;+// flaky GPU/queue, recovers)+// tencent/Hunyuan3D-2.1 — successor; same /generation_all shape+// stabilityai/TripoSR — fast feed-forward via /generate; takes+// [image, mc_resolution] and returns [OBJ, GLB].+// Reliable terminal fallback — keep it last so the+// chain always has a Space that actually returns a GLB.+//+// JeffreyXiang/TRELLIS was removed: the Space host now 404s (taken down), so+// listing it only burned a failover hop. Re-add a working TRELLIS Space here (or+// via HF_RECONSTRUCT_SPACES) if one comes back online.const HF_FAILOVER_CHAIN = [- { space: 'tencent/Hunyuan3D-2.1', api: 'generation_all', builder: 'hunyuan' },{ space: 'tencent/Hunyuan3D-2', api: 'generation_all', builder: 'hunyuan' },- { space: 'JeffreyXiang/TRELLIS', api: 'image_to_3d', builder: 'single' },- { space: 'stabilityai/TripoSR', api: 'predict', builder: 'single' },+ { space: 'tencent/Hunyuan3D-2.1', api: 'generation_all', builder: 'hunyuan' },+ { space: 'stabilityai/TripoSR', api: 'generate', builder: 'triposr' },];function readEnv(name) {@@ -245,23 +251,38 @@ function resolveChain() {return {space,api: api || 'generation_all',- builder: api === 'image_to_3d' || api === 'predict' ? 'single' : 'hunyuan',+ builder: builderForApi(api),};});}const legacySpace = readEnv('HF_RECONSTRUCT_SPACE');if (legacySpace) {const api = readEnv('HF_RECONSTRUCT_API_NAME') || 'generation_all';- return [{ space: legacySpace, api, builder: api === 'generation_all' ? 'hunyuan' : 'single' }];+ return [{ space: legacySpace, api, builder: builderForApi(api) }];}return HF_FAILOVER_CHAIN;}+// Pick the payload builder for an env-supplied "owner/name[:api]" entry from its+// Gradio api_name. /generation_all is Hunyuan3D's 13-arg shape; /generate is+// TripoSR's [image, mc_resolution]; anything else (single-image endpoints) gets+// the bare one-file payload.+function builderForApi(api) {+ if (!api || api === 'generation_all') return 'hunyuan';+ if (api === 'generate') return 'triposr';+ return 'single';+}+// Per-Space payload builders. Map our normalized {photos, params} into the// argument list that Space's Gradio endpoint expects.const BUILDERS = {hunyuan: ({ photos, params }) => buildHunyuanPayload({ photos, params }),single: ({ photos }) => [toFileData(photos[0])],+ // stabilityai/TripoSR /generate: (image filepath, marching-cubes resolution+ // float) → [OBJ, GLB]. We pass the reference view straight through — the forge+ // image lane already supplies a clean subject view — and take the GLB output;+ // extractFirstGlbUrl skips the OBJ and returns the .glb.+ triposr: ({ photos, params }) => [toFileData(photos[0]), Number(params?.mc_resolution ?? 256)],};// Try one Space end-to-end: enqueue → consume SSE → extract GLB url.diff --git a/api/agent-wallet-bridge.js b/api/agent-wallet-bridge.jsindex 1abbc8323..058c9e17e 100644--- a/api/agent-wallet-bridge.js+++ b/api/agent-wallet-bridge.js@@ -79,11 +79,16 @@ let statusCache = null; // { at, payload }async function walletStatus() {if (statusCache && Date.now() - statusCache.at < 10_000) return statusCache.payload;const signer = await agentSigner();- const [{ Connection, PublicKey }, { getAssociatedTokenAddressSync }] = await Promise.all([+ const [{ PublicKey }, { getAssociatedTokenAddressSync }, { solanaConnection }] = await Promise.all([import('@solana/web3.js'),import('@solana/spl-token'),+ import('./_lib/solana/connection.js'),]);- const conn = new Connection(SOLANA_RPC_URL, 'confirmed');+ // Multi-endpoint failover: a quota-dead or garbage-returning primary is skipped+ // transparently instead of stalling this handler to the 30s Vercel ceiling+ // (the source of the "[agent-wallet-bridge] Task timed out" errors) or throwing+ // a StructError on a poison RPC body.+ const conn = solanaConnection({ url: SOLANA_RPC_URL, commitment: 'confirmed' });const owner = new PublicKey(signer.address);let sol = null;let usdc = 0;diff --git a/api/walk/control/[action].js b/api/walk/control/[action].jsnew file mode 100644index 000000000..7648fe616--- /dev/null+++ b/api/walk/control/[action].js@@ -0,0 +1,600 @@+// Walk programmatic-control API — drive a *running* /walk page from outside.+//+// An external system (another agent, a CI bot, a webhook) creates a control+// session bound to an avatar it owns, then pushes commands — move the avatar to+// a world position, trigger a gesture, make it speak, swap the environment. The+// open walk page (src/walk.js, entered with ?control=<sessionId>&ck=<token>)+// short-polls this endpoint, drains the queued commands, applies them to the+// real scene, and reports its live position back so the controller's /state read+// reflects the actual avatar.+//+// Routed via Vercel's [action] file param — one bundle, native bracket routing,+// no rewrite config:+//+// POST /api/walk/control/session create a session (avatar OWNER auth via+// cookie/bearer) → { sessionId, controlToken,+// controlUrl, expiresAt }+// POST /api/walk/control/move { sessionId, x, z, speed?, key? } enqueue+// POST /api/walk/control/gesture { sessionId, gesture, key? } enqueue+// POST /api/walk/control/say { sessionId, text, voice?, key? } enqueue+// POST /api/walk/control/env { sessionId, env, key? } enqueue+// GET /api/walk/control/session?sessionId=… walk client drains the queue+// GET /api/walk/control/poll?sessionId=… alias of the GET above+// GET /api/walk/control/state?sessionId=… live position/animation/env+//+// Two credentials. The CREATE call is authorized as the avatar owner (a signed-in+// session cookie or a Bearer access token / API key) — only the owner of an+// avatar may open a remote-control channel to it. Every other call carries the+// opaque `controlToken` (stored only as a SHA-256 hash) as `Authorization:+// Bearer <controlToken>` OR `?ck=<controlToken>` so the walk page — which loads+// it from the URL — can poll without a header.+//+// Delivery is exactly-once: a poll claims the session's undelivered commands in+// fifo order and stamps delivered_at in the same statement, so no command is ever+// replayed across polls. Idempotency: a controller may pass `key` per (session,+// kind) so a retried push collapses onto the same row instead of duplicating.+//+// Rate limits: a coarse per-IP flood guard (60/min) plus a precise per-session+// ceiling of 60 commands/min enforced against the command table itself.++import { z } from 'zod';+import { cors, method, readJson, error, json, wrap, rateLimited } from '../../_lib/http.js';+import { parse } from '../../_lib/validate.js';+import { limits, clientIp } from '../../_lib/rate-limit.js';+import { sql } from '../../_lib/db.js';+import { sha256, randomToken } from '../../_lib/crypto.js';+import {+ getSessionUser,+ extractBearer,+ authenticateBearer,+} from '../../_lib/auth.js';++export const maxDuration = 10;++// The avatar's gesture vocabulary — kept in lockstep with GESTURE_ORDER in+// src/walk-gestures.js (the client-side source of truth). Inlined here rather+// than imported so this serverless function never pulls the Three.js-backed+// gesture/animation modules into its bundle.+const GESTURE_ORDER = Object.freeze([+ 'wave', 'dance', 'sit', 'point', 'cheer', 'agree', 'disagree', 'talking',+]);++// How long a freshly-created control session stays drivable. Re-extended on each+// successful command push and on each walk-client poll, so an actively-used+// channel never expires mid-session; an abandoned one reclaims itself.+const SESSION_TTL_SEC = 60 * 60; // 1 hour++// Per-session command ceiling — the spec's "60 commands/min per session". Enforced+// against the command table (count of rows created in the trailing minute) so it+// holds across serverless instances without a Redis bucket.+const SESSION_COMMANDS_PER_MIN = 60;++// World is a disc of radius GROUND_RADIUS (12m) in src/walk.js; clamp move targets+// to just inside it so a command can't strand the avatar past the playable ground.+const WORLD_RADIUS = 11.5;++const GESTURES = new Set(GESTURE_ORDER);++// ── validation schemas ───────────────────────────────────────────────────────+const createSchema = z+ .object({+ avatarId: z.string().uuid().optional().nullable(),+ env: z.string().trim().min(1).max(64).optional().nullable(),+ label: z.string().trim().min(1).max(120).optional().nullable(),+ })+ .strict();++const sessionIdSchema = z.string().uuid();++const moveSchema = z+ .object({+ sessionId: sessionIdSchema,+ x: z.number().finite(),+ z: z.number().finite(),+ speed: z.number().finite().min(0.1).max(1).optional().nullable(),+ key: z.string().trim().min(1).max(80).optional().nullable(),+ })+ .strict();++const gestureSchema = z+ .object({+ sessionId: sessionIdSchema,+ gesture: z.string().trim().min(1).max(40),+ key: z.string().trim().min(1).max(80).optional().nullable(),+ })+ .strict();++const saySchema = z+ .object({+ sessionId: sessionIdSchema,+ text: z.string().trim().min(1).max(280),+ voice: z.boolean().optional().default(false),+ key: z.string().trim().min(1).max(80).optional().nullable(),+ })+ .strict();++const envSchema = z+ .object({+ sessionId: sessionIdSchema,+ env: z.string().trim().min(1).max(64),+ key: z.string().trim().min(1).max(80).optional().nullable(),+ })+ .strict();++// Live state reported by the walk client when it polls. All optional — a client+// that hasn't located the avatar yet polls without it.+const pollStateSchema = z+ .object({+ x: z.number().finite().optional().nullable(),+ z: z.number().finite().optional().nullable(),+ facing: z.number().finite().optional().nullable(),+ motion: z.enum(['idle', 'walk', 'run']).optional().nullable(),+ env: z.string().trim().max(64).optional().nullable(),+ })+ .strict();++// ── auth helpers ─────────────────────────────────────────────────────────────++// Resolve the signed-in / bearer user for the privileged CREATE call.+async function resolveOwner(req) {+ const bearer = extractBearer(req);+ if (bearer) {+ const user = await authenticateBearer(bearer);+ if (user?.userId) return user.userId;+ }+ const sessionUser = await getSessionUser(req);+ return sessionUser?.id || null;+}++// Pull the controlToken from `Authorization: Bearer …` (controllers) or the+// `?ck=` query param (the walk page, which only has the URL). Returns null if+// neither carries one.+function extractControlToken(req, url) {+ const bearer = extractBearer(req);+ if (bearer) return bearer;+ const ck = url.searchParams.get('ck');+ return ck ? ck.trim() : null;+}++// Load the session a controlToken authorizes, or null. Expired sessions never+// resolve — and are reaped lazily here so the table self-cleans on access.+async function sessionForToken(token) {+ if (!token) return null;+ const hash = await sha256(token);+ const rows = await sql`+ select id, owner_id, avatar_id, env_id, pos_x, pos_z, facing, motion,+ current_env, client_seen_at, created_at, expires_at+ from walk_control_sessions+ where token_hash = ${hash}+ limit 1+ `;+ const s = rows[0];+ if (!s) return null;+ if (new Date(s.expires_at) <= new Date()) {+ // Lazy reclaim of an expired channel; commands cascade-delete.+ await sql`delete from walk_control_sessions where id = ${s.id}`;+ return null;+ }+ return s;+}++// Bump a session's TTL whenever it is actively used (push or poll).+async function touchSession(sessionId) {+ await sql`+ update walk_control_sessions+ set expires_at = now() + ${`${SESSION_TTL_SEC} seconds`}::interval+ where id = ${sessionId}+ `;+}++// ── command enqueue ──────────────────────────────────────────────────────────++// Enqueue one command for a session, enforcing the per-session/min ceiling and+// the optional (session, kind, key) idempotency collapse. Returns the row.+async function enqueue(res, sessionId, kind, payload, dedupKey) {+ // Precise per-session rate limit: count rows created in the trailing minute.+ const [{ n }] = await sql`+ select count(*)::int as n+ from walk_control_commands+ where session_id = ${sessionId} and created_at > now() - interval '1 minute'+ `;+ if (n >= SESSION_COMMANDS_PER_MIN) {+ return rateLimited(+ res,+ { limit: SESSION_COMMANDS_PER_MIN, remaining: 0, reset: Date.now() + 60_000 },+ `session command rate limit (${SESSION_COMMANDS_PER_MIN}/min) exceeded`,+ );+ }++ // Idempotent push: a retried call with the same (session, kind, key) returns+ // the original row instead of enqueuing a duplicate. seq is monotonic per+ // session via a max()+1 in the same insert.+ const rows = dedupKey+ ? await sql`+ insert into walk_control_commands (session_id, seq, kind, payload, dedup_key)+ values (+ ${sessionId},+ coalesce((select max(seq) from walk_control_commands where session_id = ${sessionId}), 0) + 1,+ ${kind},+ ${JSON.stringify(payload)}::jsonb,+ ${dedupKey}+ )+ on conflict (session_id, kind, dedup_key) where dedup_key is not null+ do update set payload = excluded.payload+ returning id, seq, kind, created_at+ `+ : await sql`+ insert into walk_control_commands (session_id, seq, kind, payload)+ values (+ ${sessionId},+ coalesce((select max(seq) from walk_control_commands where session_id = ${sessionId}), 0) + 1,+ ${kind},+ ${JSON.stringify(payload)}::jsonb+ )+ returning id, seq, kind, created_at+ `;+ await touchSession(sessionId);+ const cmd = rows[0];+ return json(res, 202, {+ ok: true,+ command: { id: String(cmd.id), seq: Number(cmd.seq), kind: cmd.kind },+ });+}++// Resolve the controlToken-authorized session for a write/read, or write a 401.+// Returns the session row, or null (response already sent).+async function requireSession(req, res, url) {+ const token = extractControlToken(req, url);+ const session = await sessionForToken(token);+ if (!session) {+ error(res, 401, 'invalid_control_token', 'missing, invalid, or expired control token');+ return null;+ }+ return session;+}++// ── handlers ─────────────────────────────────────────────────────────────────++async function handleCreate(req, res) {+ const ownerId = await resolveOwner(req);+ if (!ownerId) {+ return error(res, 401, 'unauthorized', 'sign in or present a bearer token to open a control session');+ }++ const raw = await readJson(req).catch(() => ({}));+ const body = parse(createSchema, raw || {});++ // If an avatarId is supplied it must belong to the caller — a control channel+ // may only be opened against an avatar the owner controls.+ let avatarId = null;+ if (body.avatarId) {+ const rows = await sql`+ select id from avatars+ where id = ${body.avatarId} and owner_id = ${ownerId} and deleted_at is null+ limit 1+ `;+ if (!rows[0]) {+ return error(res, 403, 'forbidden', 'avatar not found or not owned by you');+ }+ avatarId = rows[0].id;+ }++ const controlToken = randomToken(32);+ const tokenHash = await sha256(controlToken);+ const rows = await sql`+ insert into walk_control_sessions (owner_id, avatar_id, token_hash, label, env_id, expires_at)+ values (+ ${ownerId}, ${avatarId}, ${tokenHash}, ${body.label || null}, ${body.env || null},+ now() + ${`${SESSION_TTL_SEC} seconds`}::interval+ )+ returning id, expires_at+ `;+ const session = rows[0];++ // The deep link the walk page opens to enter control mode. Relative so it+ // resolves against whatever host serves the API (prod or preview).+ const qs = new URLSearchParams({ control: session.id, ck: controlToken });+ if (avatarId) qs.set('avatar', avatarId);+ if (body.env) qs.set('env', body.env);+ const controlUrl = `/walk?${qs.toString()}`;++ return json(res, 201, {+ ok: true,+ sessionId: session.id,+ controlToken,+ controlUrl,+ expiresAt: session.expires_at,+ gestures: [...GESTURE_ORDER],+ });+}++async function handleMove(req, res, url) {+ const raw = await readJson(req);+ const body = parse(moveSchema, raw);+ const session = await requireSession(req, res, url);+ if (!session) return;+ if (body.sessionId !== session.id) {+ return error(res, 403, 'session_mismatch', 'control token does not authorize this session');+ }+ // Clamp the target to the playable disc so a command can't push the avatar+ // off the ground (the client re-clamps too, but reject obviously-bad input).+ let { x, z } = body;+ const r = Math.hypot(x, z);+ if (r > WORLD_RADIUS) {+ const k = WORLD_RADIUS / r;+ x *= k;+ z *= k;+ }+ return enqueue(res, session.id, 'move', { x, z, speed: body.speed ?? null }, body.key || null);+}++async function handleGesture(req, res, url) {+ const raw = await readJson(req);+ const body = parse(gestureSchema, raw);+ const session = await requireSession(req, res, url);+ if (!session) return;+ if (body.sessionId !== session.id) {+ return error(res, 403, 'session_mismatch', 'control token does not authorize this session');+ }+ const gesture = body.gesture.toLowerCase();+ if (!GESTURES.has(gesture)) {+ return error(res, 400, 'unknown_gesture', `gesture must be one of: ${[...GESTURE_ORDER].join(', ')}`, {+ gestures: [...GESTURE_ORDER],+ });+ }+ return enqueue(res, session.id, 'gesture', { gesture }, body.key || null);+}++async function handleSay(req, res, url) {+ const raw = await readJson(req);+ const body = parse(saySchema, raw);+ const session = await requireSession(req, res, url);+ if (!session) return;+ if (body.sessionId !== session.id) {+ return error(res, 403, 'session_mismatch', 'control token does not authorize this session');+ }+ return enqueue(res, session.id, 'say', { text: body.text, voice: !!body.voice }, body.key || null);+}++async function handleEnv(req, res, url) {+ const raw = await readJson(req);+ const body = parse(envSchema, raw);+ const session = await requireSession(req, res, url);+ if (!session) return;+ if (body.sessionId !== session.id) {+ return error(res, 403, 'session_mismatch', 'control token does not authorize this session');+ }+ return enqueue(res, session.id, 'env', { env: body.env }, body.key || null);+}++// GET /session (and its /poll alias): the walk client drains the queue. The same+// request may carry the client's live state in the query string (?x=&z=&…) so a+// single round-trip both reports position and pulls commands.+async function handlePoll(req, res, url) {+ const sessionId = url.searchParams.get('sessionId');+ if (!sessionId || !sessionIdSchema.safeParse(sessionId).success) {+ return error(res, 400, 'bad_request', 'sessionId query param (uuid) is required');+ }+ const session = await requireSession(req, res, url);+ if (!session) return;+ if (sessionId !== session.id) {+ return error(res, 403, 'session_mismatch', 'control token does not authorize this session');+ }++ // Optional live-state report folded into the poll.+ const stateRaw = {+ x: url.searchParams.has('x') ? Number(url.searchParams.get('x')) : undefined,+ z: url.searchParams.has('z') ? Number(url.searchParams.get('z')) : undefined,+ facing: url.searchParams.has('facing') ? Number(url.searchParams.get('facing')) : undefined,+ motion: url.searchParams.get('motion') || undefined,+ env: url.searchParams.get('cenv') || undefined,+ };+ const stateParsed = pollStateSchema.safeParse(stateRaw);+ const state = stateParsed.success ? stateParsed.data : {};++ // Claim every undelivered command for this session in fifo order, stamping+ // delivered_at in the same statement so they are never handed out twice.+ const commands = await sql`+ update walk_control_commands+ set delivered_at = now()+ where id in (+ select id from walk_control_commands+ where session_id = ${session.id} and delivered_at is null+ order by seq asc+ limit 50+ )+ returning id, seq, kind, payload+ `;++ // Record the client's check-in + any reported state, and extend the TTL.+ await sql`+ update walk_control_sessions+ set client_seen_at = now(),+ expires_at = now() + ${`${SESSION_TTL_SEC} seconds`}::interval,+ pos_x = coalesce(${state.x ?? null}, pos_x),+ pos_z = coalesce(${state.z ?? null}, pos_z),+ facing = coalesce(${state.facing ?? null}, facing),+ motion = coalesce(${state.motion ?? null}, motion),+ current_env = coalesce(${state.env ?? null}, current_env)+ where id = ${session.id}+ `;++ return json(+ res,+ 200,+ {+ ok: true,+ sessionId: session.id,+ commands: commands+ .sort((a, b) => Number(a.seq) - Number(b.seq))+ .map((c) => ({ id: String(c.id), seq: Number(c.seq), kind: c.kind, ...c.payload })),+ },+ { 'cache-control': 'no-store' },+ );+}++// GET /state: the controller reads the avatar's live position/animation/env, as+// last reported by the walk client.+async function handleState(req, res, url) {+ const sessionId = url.searchParams.get('sessionId');+ if (!sessionId || !sessionIdSchema.safeParse(sessionId).success) {+ return error(res, 400, 'bad_request', 'sessionId query param (uuid) is required');+ }+ const session = await requireSession(req, res, url);+ if (!session) return;+ if (sessionId !== session.id) {+ return error(res, 403, 'session_mismatch', 'control token does not authorize this session');+ }++ const [{ pending }] = await sql`+ select count(*)::int as pending+ from walk_control_commands+ where session_id = ${session.id} and delivered_at is null+ `;++ const connected =+ !!session.client_seen_at &&+ Date.now() - new Date(session.client_seen_at).getTime() < 10_000;++ return json(+ res,+ 200,+ {+ ok: true,+ sessionId: session.id,+ avatarId: session.avatar_id || null,+ connected,+ clientSeenAt: session.client_seen_at || null,+ expiresAt: session.expires_at,+ pendingCommands: pending,+ position: session.pos_x != null && session.pos_z != null+ ? { x: session.pos_x, z: session.pos_z }+ : null,+ facing: session.facing,+ motion: session.motion || null,+ env: session.current_env || session.env_id || null,+ },+ { 'cache-control': 'no-store' },+ );+}++// ── dispatch ─────────────────────────────────────────────────────────────────+const WRITE_ACTIONS = new Set(['move', 'gesture', 'say', 'env']);+const POLL_ACTIONS = new Set(['session', 'poll']);++export default wrap(async (req, res) => {+ // Controllers and the embedded walk page may call cross-origin, so open CORS.+ if (cors(req, res, { origins: '*', methods: 'GET,POST,OPTIONS' })) return;++ const url = new URL(req.url, 'http://x');+ const action = (req.query?.action || url.pathname.split('/').pop() || '').toLowerCase();++ // Coarse per-IP flood guard across every action (60/min).+ const ip = clientIp(req);+ const rl = await limits.irlInteractIp(ip);+ if (!rl.success) return rateLimited(res, rl, 'too many control requests from this IP');++ // CONTRACT — public, machine-readable description of the control surface so a+ // caller can discover routes, payload shapes, the gesture vocabulary, and the+ // auth model without out-of-band docs. GET only.+ if (action === 'contract') {+ if (!method(req, res, ['GET'])) return;+ return json(+ res,+ 200,+ {+ name: 'walk-control',+ description:+ 'Programmatically drive a running /walk avatar: create a session, push move/gesture/say/env commands, and read live state.',+ base: '/api/walk/control',+ auth: {+ create: 'avatar owner — session cookie OR Authorization: Bearer <accessToken|apiKey>',+ commands: 'control token — Authorization: Bearer <controlToken> OR ?ck=<controlToken>',+ },+ rateLimits: {+ perIp: '60 requests / minute',+ perSession: `${SESSION_COMMANDS_PER_MIN} commands / minute`,+ },+ sessionTtlSec: SESSION_TTL_SEC,+ gestures: [...GESTURE_ORDER],+ worldRadius: WORLD_RADIUS,+ endpoints: [+ {+ method: 'POST',+ path: '/session',+ auth: 'owner',+ body: { avatarId: 'uuid?', env: 'string?', label: 'string?' },+ returns: { sessionId: 'uuid', controlToken: 'string', controlUrl: 'string', expiresAt: 'iso8601' },+ },+ {+ method: 'POST',+ path: '/move',+ auth: 'control',+ body: { sessionId: 'uuid', x: 'number', z: 'number', speed: 'number(0.1-1)?', key: 'string?' },+ },+ {+ method: 'POST',+ path: '/gesture',+ auth: 'control',+ body: { sessionId: 'uuid', gesture: 'enum(gestures)', key: 'string?' },+ },+ {+ method: 'POST',+ path: '/say',+ auth: 'control',+ body: { sessionId: 'uuid', text: 'string(1-280)', voice: 'boolean?', key: 'string?' },+ },+ {+ method: 'POST',+ path: '/env',+ auth: 'control',+ body: { sessionId: 'uuid', env: 'string', key: 'string?' },+ },+ {+ method: 'GET',+ path: '/session?sessionId=… (alias: /poll)',+ auth: 'control',+ description: 'Walk client drains queued commands; may fold live state via ?x=&z=&facing=&motion=&cenv=.',+ returns: { commands: '[{ id, seq, kind, ...payload }]' },+ },+ {+ method: 'GET',+ path: '/state?sessionId=…',+ auth: 'control',+ returns: { connected: 'boolean', position: '{x,z}|null', facing: 'number|null', motion: 'string|null', env: 'string|null', pendingCommands: 'int' },+ },+ ],+ clientOptIn: '/walk?control=<sessionId>&ck=<controlToken>',+ },+ { 'cache-control': 'public, max-age=300' },+ );+ }++ // CREATE — privileged owner auth, POST only.+ if (action === 'session' && req.method === 'POST') {+ return handleCreate(req, res);+ }++ // WRITE commands — POST only, controlToken auth.+ if (WRITE_ACTIONS.has(action)) {+ if (!method(req, res, ['POST'])) return;+ if (action === 'move') return handleMove(req, res, url);+ if (action === 'gesture') return handleGesture(req, res, url);+ if (action === 'say') return handleSay(req, res, url);+ if (action === 'env') return handleEnv(req, res, url);+ }++ // POLL / drain — GET only, controlToken auth.+ if (POLL_ACTIONS.has(action)) {+ if (!method(req, res, ['GET'])) return;+ return handlePoll(req, res, url);+ }++ // STATE — GET only, controlToken auth.+ if (action === 'state') {+ if (!method(req, res, ['GET'])) return;+ return handleState(req, res, url);+ }++ return error(res, 404, 'not_found', `unknown control action "${action}"`);+});diff --git a/data/changelog.json b/data/changelog.jsonindex 89daad010..52101b66c 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,31 @@{"$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": "Discover and Marketplace now browse the same way",+ "summary": "Searching, filtering, and sorting agents now work identically on /discover and /marketplace. Both pages share one polished control bar — debounced search, filter chips, and sort — and your choices are saved in the page address, so a filtered view is shareable and the browser back button restores it. Loading, empty, and error states were unified too: a search that matches nothing shows a clear 'no results' panel with a one-click 'Clear filters', and a failed load offers a retry instead of a blank grid.",+ "tags": [+ "improvement"+ ],+ "link": "/discover"+ },+ {+ "date": "2026-06-21",+ "title": "Pay-per-call endpoints accept Solana USDC payments again",+ "summary": "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.",+ "tags": [+ "fix"+ ]+ },+ {+ "date": "2026-06-21",+ "title": "Free 3D generation keeps working when the paid engines are down",+ "summary": "The text/image→3D forge has a free fallback that runs on public GPU Spaces so a generation never dead-ends when the paid engine is busy or out of capacity. Two of those Spaces had gone stale — one was taken offline and another was being called on the wrong endpoint — which meant the free lane could fail even when a working Space was available. The chain now targets only live Spaces with the correct settings, so 'type a prompt → get a model' keeps returning a result even when every paid lane is unavailable.",+ "tags": [+ "fix"+ ]+ },{"date": "2026-06-21","title": "Your avatar now walks anywhere — new Walk hub, leaderboard, and creator analytics",diff --git a/pages/walk-embed.html b/pages/walk-embed.htmlindex ab92effa2..7dea7c580 100644--- a/pages/walk-embed.html+++ b/pages/walk-embed.html@@ -117,6 +117,47 @@<div id="walk-status">loading avatar…</div></div>+ <!--+ The postMessage contract (src/walk-embed-events.js) is the single+ source of truth for the host ↔ iframe protocol. We load it here+ explicitly — both so the runtime's transitive import is obvious to+ anyone reading this page, and so the public vocabulary (supported+ gestures, environments, control modes, protocol version) is readable+ from the embed window itself via `window.WALK_EMBED_PROTOCOL`. The+ interactive playground on /docs/walk-embed-api reads it to populate+ its command pickers, and it gives integrators a way to feature-detect+ what this build of the embed accepts. Constants only — no internal+ runtime state is ever exposed here.+ -->+ <script type="module">+ import {+ CHANNEL,+ PROTOCOL_VERSION,+ INBOUND,+ OUTBOUND,+ ENV_IDS,+ GESTURES,+ CONTROL_MODES,+ WORLD_RADIUS,+ } from '/src/walk-embed-events.js';+ window.WALK_EMBED_PROTOCOL = Object.freeze({+ channel: CHANNEL,+ version: PROTOCOL_VERSION,+ inbound: INBOUND,+ outbound: OUTBOUND,+ environments: ENV_IDS,+ gestures: GESTURES,+ controls: CONTROL_MODES,+ worldRadius: WORLD_RADIUS,+ });+ </script>++ <!--+ The walking-avatar runtime. It imports the same contract module and+ installs installEmbedBridge() against its live scene, so inbound+ commands drive the real avatar and outbound events fire from real+ lifecycle points.+ --><script type="module" src="/src/walk-embed.js"></script></body></html>diff --git a/public/changelog.json b/public/changelog.jsonindex c36abf858..20783e931 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-21T06:34:11.167Z",+ "generated_at": "2026-06-21T06:48:55.133Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -88,6 +88,16 @@"infra"]},+ {+ "date": "2026-06-21",+ "type": "update",+ "title": "Discover and Marketplace now browse the same way",+ "summary": "Searching, filtering, and sorting agents now work identically on /discover and /marketplace. Both pages share one polished control bar — debounced search, filter chips, and sort — and your choices are saved in the page address, so a filtered view is shareable and the browser back button restores it. Loading, empty, and error states were unified too: a search that matches nothing shows a clear 'no results' panel with a one-click 'Clear filters', and a failed load offers a retry instead of a blank grid.",+ "link": "/discover",+ "tags": [+ "improvement"+ ]+ },{"date": "2026-06-21","type": "update",@@ -153,6 +163,16 @@"feature"]},+ {+ "date": "2026-06-21",+ "type": "update",+ "title": "Free 3D generation keeps working when the paid engines are down",+ "summary": "The text/image→3D forge has a free fallback that runs on public GPU Spaces so a generation never dead-ends when the paid engine is busy or out of capacity. Two of those Spaces had gone stale — one was taken offline and another was being called on the wrong endpoint — which meant the free lane could fail even when a working Space was available. The chain now targets only live Spaces with the correct settings, so 'type a prompt → get a model' keeps returning a result even when every paid lane is unavailable.",+ "link": null,+ "tags": [+ "fix"+ ]+ },{"date": "2026-06-21","type": "update",@@ -199,6 +219,16 @@"improvement"]},+ {+ "date": "2026-06-21",+ "type": "update",+ "title": "Pay-per-call endpoints accept Solana USDC payments again",+ "summary": "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.",+ "link": null,+ "tags": [+ "fix"+ ]+ },{"date": "2026-06-21","type": "update",@@ -7664,7 +7694,7 @@"date": "2026-04-29","type": "launch","title": "Solana Vanity Wallet",- "summary": "Grind a Solana address with a custom prefix using your browser's GPU.",+ "summary": "Grind a Solana address with a custom prefix — entirely in your browser, across your CPU cores.","link": "/vanity-wallet","tags": ["launch"diff --git a/public/changelog.xml b/public/changelog.xmlindex 63d045466..786f1c274 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -70,6 +70,14 @@<category>improvement</category><description>The Discover grid and the published-agents (Characters) feed now serve from the edge cache, so a surge of visitors is absorbed at the CDN instead of re-running a database scan on every request. Pages stay fast and consistent even during a rush, and a stale-while-revalidate window keeps them warm between refreshes.</description></item>+ <item>+ <title>Discover and Marketplace now browse the same way</title>+ <link>https://three.ws/discover</link>+ <guid isPermaLink="false">2026-06-21:Discover and Marketplace now browse the same way</guid>+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>Searching, filtering, and sorting agents now work identically on /discover and /marketplace. Both pages share one polished control bar — debounced search, filter chips, and sort — and your choices are saved in the page address, so a filtered view is shareable and the browser back button restores it. Loading, empty, and error states were unified too: a search that matches nothing shows a clear 'no results' panel with a one-click 'Clear filters', and a failed load offers a retry instead of a blank grid.</description>+ </item><item><title>Empty pages now guide you instead of going blank</title><link>https://three.ws/dashboard</link>@@ -118,6 +126,14 @@<category>sdk</category><description>A new forge_avatar MCP tool collapses the old two-step flow (generate a mesh, then rig it) into a single call: describe a character in text — or pass reference images — and it generates the textured model, auto-rigs it with a humanoid skeleton, and returns an animation-ready GLB that drops straight into the pose studio and plays the idle/walk library. A built-in humanoid check runs first, so a non-character prompt (furniture, a vehicle, an animal) is turned away with no charge instead of wasting a paid rig. It bundles generation and rigging at their combined price ($0.45) with no hidden markup, and you are never charged if no rigged avatar is produced.</description></item>+ <item>+ <title>Free 3D generation keeps working when the paid engines are down</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-21:Free 3D generation keeps working when the paid engines are down</guid>+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>The text/image→3D forge has a free fallback that runs on public GPU Spaces so a generation never dead-ends when the paid engine is busy or out of capacity. Two of those Spaces had gone stale — one was taken offline and another was being called on the wrong endpoint — which meant the free lane could fail even when a working Space was available. The chain now targets only live Spaces with the correct settings, so 'type a prompt → get a model' keeps returning a result even when every paid lane is unavailable.</description>+ </item><item><title>Free photo → 3D is now a one-click engine in Forge</title><link>https://three.ws/forge</link>@@ -150,6 +166,14 @@<category>infra</category><description>The trending-tokens feed that powers the home card, communities, the token constellation, and the 3D visualizer is now resilient to upstream outages. If a market data provider goes down or rate-limits us, we transparently fall back to a second source; if both are briefly unavailable, the surfaces keep showing the last good data (clearly marked as a moment stale) instead of going blank. We also added a fast-fail circuit breaker so a slow provider can't drag the feed down during a traffic spike. Net effect: the live market views stay populated and snappy even when a data provider hiccups.</description></item>+ <item>+ <title>Pay-per-call endpoints accept Solana USDC payments again</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-21:Pay-per-call endpoints accept Solana USDC payments again</guid>+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>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.</description>+ </item><item><title>Payment hardening and a steadier holder leaderboard</title><link>https://three.ws/leaderboard</link>@@ -5956,7 +5980,7 @@<guid isPermaLink="false">2026-04-29:Solana Vanity Wallet</guid><pubDate>Wed, 29 Apr 2026 12:00:00 GMT</pubDate><category>launch</category>- <description>Grind a Solana address with a custom prefix using your browser's GPU.</description>+ <description>Grind a Solana address with a custom prefix — entirely in your browser, across your CPU cores.</description></item><item><title>On-chain agents on Solana and EVM</title>diff --git a/public/discover/discover.js b/public/discover/discover.jsindex 1fbcd55cf..4954be50d 100644--- a/public/discover/discover.js+++ b/public/discover/discover.js@@ -6,8 +6,19 @@* Clicking a card opens the on-chain token page on the source chain's* explorer; clicking the 3D preview (when present) loads the GLB in the* main viewer via /app#model=<url>.+ *+ * Controls (search · filter · source · sort) are driven by the shared+ * list-controls toolkit (src/shared/list-controls.js) so /discover and+ * /marketplace browse identically: same debounced search, same chip/sort+ * vocabulary, same URL-sync, same back/forward behaviour. Loading / empty /+ * error states use the shared state-kit so every browse surface reads as one+ * product. This file owns only the page-specific data flow (the /api/explore+ * fetch, the chain dropdown, card rendering, infinite scroll, embed modals).*/+import { createListControls } from '../../src/shared/list-controls.js';+import { skeletonHTML, emptyStateHTML, errorStateHTML } from '../../src/shared/state-kit.js';+const CHAINS = [{ id: 8453, name: 'Base' },{ id: 42161, name: 'Arbitrum One' },@@ -34,25 +45,16 @@ const CHAINS = [];const els = {- search: document.querySelector('[data-role="search"]'),- filters: document.querySelector('[data-role="filters"]'),- sources: document.querySelector('[data-role="sources"]'),+ listControls: document.querySelector('[data-role="list-controls"]'),chain: document.querySelector('[data-role="chain"]'),- sort: document.querySelector('[data-role="sort"]'),grid: document.querySelector('[data-role="grid"]'),stats: document.querySelector('[data-role="stats"]'),status: document.querySelector('[data-role="status"]'),loadMore: document.querySelector('[data-role="load-more"]'),sentinel: document.querySelector('[data-role="sentinel"]'),myAgentsChip: document.querySelector('[data-role="my-agents-chip"]'),- searchClear: document.querySelector('[data-role="search-clear"]'),};-function updateSearchClearVisibility() {- if (!els.searchClear) return;- els.searchClear.hidden = !els.search.value;-}-// Reveal "View my agents" chip + nav link when signed in.fetch('/api/auth/me', { credentials: 'include' }).then((r) => (r.ok ? r.json() : null))@@ -64,7 +66,8 @@ fetch('/api/auth/me', { credentials: 'include' })}).catch(() => {});-// Populate chain dropdown.+// Populate chain dropdown (page-specific — long dynamic option list, kept out of+// the shared toolkit which models fixed chip/sort vocabularies).for (const c of CHAINS) {const opt = document.createElement('option');opt.value = String(c.id);@@ -72,50 +75,50 @@ for (const c of CHAINS) {els.chain.appendChild(opt);}-// Hydrate initial state from URL so deep links from register-ui (?q=…) and-// browser back/forward restore the user's filters. The marketplace is a 3D-// showcase first — when no `only3d` param is present, default to 3D. Pass-// `only3d=0` (or click the "All agents" chip) to opt into the full firehose.-const initialParams = new URLSearchParams(location.search);-const hasAnyParam = initialParams.toString().length > 0;-const only3dParam = initialParams.get('only3d');-const initialFilter = only3dParam === '0' ? 'all' : '3d';-const initialChain = initialParams.get('chain') || '';-const initialQuery = initialParams.get('q') || '';-const initialSource = ['onchain', 'avatar', 'solana'].includes(initialParams.get('source'))- ? initialParams.get('source')- : 'all';-+// Page state. Search / filter / source / sort are owned by the shared+// list-controls toolkit; chain + pagination cursor live here.const state = {- filter: initialFilter, // 'all' | '3d' | 'x402'- source: initialSource, // 'all' | 'onchain' | 'avatar'- chainId: initialChain,- query: initialQuery,- sortBy: initialParams.get('sort') || 'newest', // 'newest' | 'x402' | 'alpha'+ filter: '3d', // 'all' | '3d' | 'x402'+ source: 'all', // 'all' | 'onchain' | 'avatar' | 'solana'+ chainId: '',+ query: '',+ sortBy: 'newest', // 'newest' | 'x402' | 'alpha'cursor: null,loading: false,};-// Reflect hydrated state in the controls.-if (initialQuery) els.search.value = initialQuery;+const initialParams = new URLSearchParams(location.search);+const hasAnyParam = initialParams.toString().length > 0;++// Pre-select the chain dropdown from the URL (falls back to All for an unknown id).+const initialChain = initialParams.get('chain') || '';if (initialChain) {- // Chain dropdown is populated above; pre-select if the option exists.const opt = els.chain.querySelector(`option[value="${CSS.escape(initialChain)}"]`);if (opt) els.chain.value = initialChain;- else state.chainId = ''; // unknown chain id — fall back to All}-if (initialFilter !== 'all') {- for (const b of els.filters.querySelectorAll('[data-filter]')) {- b.classList.toggle('active', b.dataset.filter === initialFilter);- }-}-if (els.sources && initialSource !== 'all') {- for (const b of els.sources.querySelectorAll('[data-source]')) {- b.classList.toggle('active', b.dataset.source === initialSource);- }++// Map /discover's legacy URL scheme (only3d / x402 / source / q / sort) onto the+// toolkit's state keys. Kept here so existing deep links from register-ui and+// shared bookmarks keep resolving, and the discover-rename test contract holds.+function hydrateFromUrl(params) {+ const only3d = params.get('only3d');+ const x402 = params.get('x402');+ let filter = 'all';+ if (only3d !== '0') filter = '3d'; // default: 3D-first showcase+ if (x402 === '1') filter = 'x402';+ if (only3d === '0' && x402 !== '1') filter = 'all';+ const source = ['onchain', 'avatar', 'solana'].includes(params.get('source'))+ ? params.get('source')+ : 'all';+ return {+ q: (params.get('q') || '').trim(),+ filter,+ source,+ sort: params.get('sort') || 'newest',+ };}-/** Sync state into URL via replaceState (no history spam). */+/** Write the toolkit/page state back to the URL in the legacy scheme. */function syncUrl() {const p = new URLSearchParams();if (state.filter === '3d') p.set('only3d', '1');@@ -132,74 +135,85 @@ function syncUrl() {}}-let searchDebounce;--els.filters.addEventListener('click', (e) => {- const btn = e.target.closest('[data-filter]');- if (!btn) return;- state.filter = btn.dataset.filter;- for (const b of els.filters.querySelectorAll('[data-filter]')) {- b.classList.toggle('active', b.dataset.filter === state.filter);- }- syncUrl();- resetAndLoad();-});--els.sources?.addEventListener('click', (e) => {- const btn = e.target.closest('[data-source]');- if (!btn) return;- state.source = btn.dataset.source;- for (const b of els.sources.querySelectorAll('[data-source]')) {- b.classList.toggle('active', b.dataset.source === state.source);- }- syncUrl();- resetAndLoad();-});--els.chain.addEventListener('change', () => {- state.chainId = els.chain.value;- syncUrl();- resetAndLoad();-});--els.search.addEventListener('input', () => {- updateSearchClearVisibility();- clearTimeout(searchDebounce);- searchDebounce = setTimeout(() => {- state.query = els.search.value.trim();+// Shared list-controls toolkit: debounced search, filter + source chip segments,+// sort dropdown. URL-sync is owned by this page (legacy scheme), so urlSync:false.+const controls = createListControls({+ mount: els.listControls,+ searchKey: 'q',+ searchPlaceholder: 'Search by name or description…',+ searchLabel: 'Search agents',+ urlSync: false,+ hydrate: hydrateFromUrl,+ defaults: { q: '', filter: 'all', source: 'all', sort: 'newest' },+ segments: [+ {+ key: 'filter',+ label: 'Agent type',+ options: [+ { value: 'all', label: 'All agents' },+ { value: '3d', label: '3D only' },+ { value: 'x402', label: 'x402' },+ ],+ },+ {+ key: 'source',+ label: 'Source',+ options: [+ { value: 'all', label: 'All sources' },+ { value: 'solana', label: 'Solana' },+ { value: 'onchain', label: 'EVM' },+ { value: 'avatar', label: 'Avatars' },+ ],+ },+ ],+ sortKey: 'sort',+ sortOptions: [+ { value: 'newest', label: 'Newest' },+ { value: 'x402', label: 'x402 first' },+ { value: 'alpha', label: 'A → Z' },+ ],+ onChange: (s, meta) => {+ state.filter = s.filter;+ state.source = s.source;+ state.query = s.q;+ state.sortBy = s.sort;+ // popstate may have changed the chain via the dropdown's own URL handling;+ // re-read it so back/forward restores chain too.+ if (meta.reason === 'popstate') {+ const ch = new URLSearchParams(location.search).get('chain') || '';+ els.chain.value = ch && els.chain.querySelector(`option[value="${CSS.escape(ch)}"]`) ? ch : '';+ state.chainId = els.chain.value;+ }syncUrl();resetAndLoad();- }, 250);+ },});-els.searchClear?.addEventListener('click', () => {- els.search.value = '';- state.query = '';- updateSearchClearVisibility();- syncUrl();- resetAndLoad();- els.search.focus();-});+// Move the page-specific chain selector into the toolbar's primary row so it+// sits inline with search + sort (one visual control bar).+const chainWrap = document.querySelector('[data-role="chain-wrap"]');+const primaryRow = els.listControls.querySelector('.tws-lc-row--primary');+if (chainWrap && primaryRow) primaryRow.appendChild(chainWrap);-els.sort?.addEventListener('change', () => {- state.sortBy = els.sort.value;+els.chain.addEventListener('change', () => {+ state.chainId = els.chain.value;syncUrl();resetAndLoad();});-// Reflect initial sort in dropdown-if (els.sort && state.sortBy !== 'newest') {- els.sort.value = state.sortBy;+// Seed page state from the toolkit's hydrated (URL-derived) values so the first+// load reflects deep links and the 3D-first default before any user interaction.+{+ const s = controls.getState();+ state.filter = s.filter;+ state.source = s.source;+ state.query = s.q;+ state.sortBy = s.sort;+ state.chainId = els.chain.value;}-// Initial visibility (covers ?q= deep links).-updateSearchClearVisibility();--// If we defaulted to 3D-only (no params on the URL), reflect that in the URL-// so the user can copy/share the canonical view.-if (!hasAnyParam) {- syncUrl();-}+// Canonicalise the URL on first load (covers the 3D-first default + ?q= deep links).+if (!hasAnyParam) syncUrl();els.loadMore.addEventListener('click', () => loadPage());@@ -256,26 +270,19 @@ els.grid.addEventListener('click', (e) => {}});+// Loading placeholders use the shared state-kit skeleton (same shimmer + token+// vocabulary as /marketplace) so both browse surfaces look identical while data+// streams in. A wrapper class keeps them removable as a group.function renderSkeletons(n) {- const frag = document.createDocumentFragment();- for (let i = 0; i < n; i++) {- const card = document.createElement('article');- card.className = 'explore-card explore-card--skel';- card.innerHTML = `- <div class="explore-card-thumb"></div>- <div class="explore-card-body">- <div class="explore-card-skel-name"> </div>- <div class="explore-card-skel-desc"> </div>- <div class="explore-card-skel-badges"> </div>- </div>- `;- frag.appendChild(card);- }- els.grid.appendChild(frag);+ const wrap = document.createElement('div');+ wrap.className = 'explore-skeletons';+ wrap.style.display = 'contents';+ wrap.innerHTML = skeletonHTML(n, 'card');+ els.grid.appendChild(wrap);}function clearSkeletons() {- for (const node of els.grid.querySelectorAll('.explore-card--skel')) node.remove();+ for (const node of els.grid.querySelectorAll('.explore-skeletons')) node.remove();}function resetAndLoad() {@@ -291,7 +298,9 @@ async function loadPage() {els.loadMore.hidden = true;if (!state.cursor) {els.status.textContent = '';+ els.status.hidden = true;} else {+ els.status.hidden = false;els.status.textContent = 'Loading more…';}@@ -343,64 +352,66 @@ async function loadPage() {// flicker as more cards stream in on paginated loads.if (isFirstPage && data.totals) renderStats(data.totals);- const visibleCards = els.grid.querySelectorAll('.explore-card:not(.explore-card--skel)').length;+ const visibleCards = els.grid.querySelectorAll('.explore-card').length;if (visibleCards === 0) {- const filtersActive = state.filter !== 'all' || !!state.chainId || !!state.query;+ const filtersActive =+ controls.isFiltered() || !!state.chainId || state.filter !== 'all';+ // Shared state-kit empty shell — identical look to /marketplace's+ // zero-results. The "Clear filters" CTA carries data-role="clear-filters"+ // so the existing delegated handler resets every control.els.status.innerHTML = filtersActive- ? `<div class="explore-empty">- No agents match these filters yet.- <button type="button" class="explore-clear-filters" data-role="clear-filters">Clear filters</button>- </div>`- : `<div class="explore-empty">- No agents indexed yet. Be the first —- <a href="/forge">forge a 3D model from a text prompt</a> and register it as an agent.- </div>`;+ ? emptyStateHTML({+ title: 'No agents match these filters',+ body: 'Try a broader search, a different chain, or clear everything to see the full directory.',+ actions: [{ label: 'Clear filters', id: 'clear-filters', primary: true }],+ }).replace('data-sk-action="clear-filters"', 'data-sk-action="clear-filters" data-role="clear-filters"')+ : emptyStateHTML({+ title: 'No agents indexed yet',+ body: 'Be the first — forge a 3D model from a text prompt and register it as an agent.',+ actions: [{ label: 'Forge a model', href: '/forge', primary: true }],+ });+ els.status.hidden = false;} else {els.status.textContent = '';+ els.status.hidden = true;}} catch (err) {clearSkeletons();- els.status.innerHTML = `<div class="explore-error" role="alert">- <span class="explore-error-msg">Couldn't load agents. Check your connection and try again.</span>- <button type="button" class="explore-retry" data-role="retry-load">Retry</button>- </div>`;+ // Shared state-kit error shell with a retry CTA (data-sk-retry).+ els.status.innerHTML = errorStateHTML({+ title: "Couldn't load agents",+ body: 'Check your connection and try again.',+ scope: 'discover',+ });+ els.status.hidden = false;} finally {state.loading = false;}}-// Delegated status-block clicks (the block is re-rendered each load).+// Delegated status-block clicks (the block is re-rendered each load). Matches+// both the state-kit hooks (data-sk-action / data-sk-retry) and the legacy+// data-role marker kept for backward-compatible selectors/tests.els.status.addEventListener('click', (e) => {- if (e.target.closest('[data-role="clear-filters"]')) {+ if (+ e.target.closest('[data-role="clear-filters"]') ||+ e.target.closest('[data-sk-action="clear-filters"]')+ ) {clearAllFilters();return;}- if (e.target.closest('[data-role="retry-load"]')) {+ if (e.target.closest('[data-sk-retry]')) {els.status.textContent = 'Loading…';loadPage();}});+// Resetting every control flows through the shared toolkit, which re-renders the+// chips, clears the search box, syncs the URL, and fires onChange → resetAndLoad.function clearAllFilters() {- state.filter = 'all';- state.source = 'all';- state.chainId = '';- state.query = '';- state.sortBy = 'newest';- els.search.value = '';els.chain.value = '';- if (els.sort) els.sort.value = 'newest';- updateSearchClearVisibility();- for (const b of els.filters.querySelectorAll('[data-filter]')) {- b.classList.toggle('active', b.dataset.filter === 'all');- }- if (els.sources) {- for (const b of els.sources.querySelectorAll('[data-source]')) {- b.classList.toggle('active', b.dataset.source === 'all');- }- }- syncUrl();- resetAndLoad();+ state.chainId = '';+ controls.reset();}function renderStats(totals) {@@ -875,4 +886,5 @@ function openAvatarEmbedModal({ avatarId, glbUrl, name }) {});}-loadPage();+// Initial load — render shared skeletons then fetch the first page.+resetAndLoad();diff --git a/public/discover/index.html b/public/discover/index.htmlindex 619088436..829636a29 100644--- a/public/discover/index.html+++ b/public/discover/index.html@@ -90,49 +90,18 @@</section><section class="explore-controls">- <div class="explore-search">- <input- type="search"- placeholder="Search by name or description…"- data-role="search"- aria-label="Search agents"- />- <button- type="button"- class="explore-search-clear"- data-role="search-clear"- aria-label="Clear search"- hidden- >- ×- </button>- </div>- <div class="explore-chips" data-role="filters">- <button class="explore-chip active" data-filter="all">All agents</button>- <button class="explore-chip" data-filter="3d">3D only</button>- <button class="explore-chip" data-filter="x402">x402</button>- </div>- <div class="explore-chips" data-role="sources">- <button class="explore-chip active" data-source="all">All sources</button>- <button class="explore-chip" data-source="solana">Solana</button>- <button class="explore-chip" data-source="onchain">EVM</button>- <button class="explore-chip" data-source="avatar">Avatars</button>- </div>- <div class="explore-controls-row">- <div class="explore-chain-select">- <label for="explore-chain">Chain:</label>- <select id="explore-chain" data-role="chain">+ <!-- Shared list-controls toolkit (search · filter chips · source chips · sort)+ mounts here. Built by discover.js via createListControls(). The chain+ selector below is page-specific (dynamic option list) and is appended+ into the toolbar's primary row at runtime. -->+ <div class="explore-toolbar" data-role="list-controls"></div>+ <div class="explore-chain-select" data-role="chain-wrap">+ <label for="explore-chain">Chain</label>+ <div class="explore-chain-select-control">+ <select id="explore-chain" data-role="chain" aria-label="Filter by chain"><option value="">All chains</option></select></div>- <div class="explore-sort-select">- <label for="explore-sort">Sort:</label>- <select id="explore-sort" data-role="sort">- <option value="newest">Newest</option>- <option value="x402">x402 first</option>- <option value="alpha">A → Z</option>- </select>- </div></div></section>diff --git a/public/docs/walk-embed-api.html b/public/docs/walk-embed-api.htmlnew file mode 100644index 000000000..7c1eae551--- /dev/null+++ b/public/docs/walk-embed-api.html@@ -0,0 +1,985 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />+ <title>Walk Embed API — three.ws</title>+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />+ <meta+ name="description"+ content="The bi-directional postMessage contract for the three.ws walking-avatar embed: outbound events, inbound commands, the JS SDK, security model, and copy-paste React, Vue, and vanilla examples."+ />+ <meta name="theme-color" content="#0a0a0a" />++ <meta property="og:type" content="article" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:title" content="three.ws — Walk Embed API" />+ <meta+ property="og:description"+ content="Drive a walking 3D avatar from any page. postMessage events, the ThreeWalkAvatar SDK, security, and React / Vue / vanilla examples."+ />+ <meta property="og:url" content="https://three.ws/docs/walk-embed-api" />+ <meta property="og:image" content="https://three.ws/og-image.png" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="twitter:title" content="Walk Embed API · three.ws" />+ <meta+ name="twitter:description"+ content="Drive a walking 3D avatar from any page. postMessage events, the ThreeWalkAvatar SDK, security, and React / Vue / vanilla examples."+ />+ <meta name="twitter:image" content="https://three.ws/og-image.png" />++ <link rel="canonical" href="https://three.ws/docs/walk-embed-api" />+ <link rel="shortcut icon" href="/favicon.ico" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/style.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/footer.css" />++ <style>+ .docs-main {+ max-width: 880px;+ margin: 0 auto;+ padding: var(--space-2xl) var(--space-lg) var(--space-2xl);+ line-height: var(--leading-normal);+ }+ .docs-main h1 {+ font-family: var(--font-display);+ font-weight: 300;+ font-size: var(--text-3xl);+ letter-spacing: -1px;+ margin: 0 0 var(--space-sm);+ }+ .docs-lede {+ color: var(--ink-dim);+ font-size: var(--text-base);+ max-width: 60ch;+ margin: 0 0 var(--space-xl);+ }+ .docs-main h2 {+ font-family: var(--font-display);+ font-weight: 400;+ font-size: var(--text-xl);+ margin: var(--space-2xl) 0 var(--space-sm);+ padding-bottom: var(--space-xs);+ border-bottom: 1px solid var(--stroke);+ scroll-margin-top: calc(var(--header-h) + var(--space-md));+ }+ .docs-main h3 {+ font-weight: 600;+ font-size: var(--text-lg);+ margin: var(--space-xl) 0 var(--space-sm);+ }+ .docs-main p,+ .docs-main li {+ color: var(--ink);+ }+ .docs-main ul,+ .docs-main ol {+ padding-left: var(--space-lg);+ }+ .docs-main li {+ margin: var(--space-2xs) 0;+ }+ .docs-main code {+ font-family: var(--font-mono);+ font-size: 0.9em;+ background: var(--surface-2);+ padding: 1px 6px;+ border-radius: var(--radius-sm);+ color: var(--ink-bright);+ }+ .docs-main a {+ color: var(--accent);+ text-decoration: none;+ border-bottom: 1px solid transparent;+ transition: border-color var(--duration-fast) var(--ease-standard);+ }+ .docs-main a:hover,+ .docs-main a:focus-visible {+ border-bottom-color: var(--accent);+ }++ .docs-toc {+ padding: var(--space-md);+ background: var(--surface-1);+ border: 1px solid var(--stroke);+ border-radius: var(--radius-lg);+ margin-bottom: var(--space-xl);+ }+ .docs-toc strong {+ color: var(--ink-bright);+ font-size: var(--text-sm);+ }+ .docs-toc ul {+ margin: var(--space-xs) 0 0;+ padding: 0;+ list-style: none;+ display: flex;+ flex-wrap: wrap;+ gap: var(--space-2xs) var(--space-md);+ }++ /* ── Tables ─────────────────────────────────────────────────── */+ .table-wrap {+ overflow-x: auto;+ border: 1px solid var(--stroke);+ border-radius: var(--radius-lg);+ margin: var(--space-md) 0;+ }+ table {+ width: 100%;+ border-collapse: collapse;+ font-size: var(--text-sm);+ min-width: 520px;+ }+ th,+ td {+ text-align: left;+ padding: var(--space-xs) var(--space-sm);+ border-bottom: 1px solid var(--stroke);+ vertical-align: top;+ }+ tr:last-child td {+ border-bottom: 0;+ }+ th {+ color: var(--ink-dim);+ font-weight: 600;+ background: var(--surface-1);+ position: sticky;+ top: 0;+ }+ td code {+ white-space: nowrap;+ }+ .dir {+ display: inline-block;+ font-family: var(--font-mono);+ font-size: var(--text-2xs);+ font-weight: 600;+ padding: 1px 7px;+ border-radius: var(--radius-pill);+ white-space: nowrap;+ }+ .dir.out {+ color: var(--success);+ background: color-mix(in srgb, var(--success) 14%, transparent);+ }+ .dir.in {+ color: var(--accent);+ background: var(--accent-soft);+ }++ /* ── Code blocks + copy ─────────────────────────────────────── */+ .code {+ position: relative;+ margin: var(--space-md) 0;+ }+ .code pre {+ background: var(--bg-1);+ border: 1px solid var(--stroke);+ border-radius: var(--radius-lg);+ padding: var(--space-md);+ padding-right: calc(var(--space-md) + 88px);+ overflow-x: auto;+ margin: 0;+ line-height: 1.6;+ }+ .code pre code {+ font-family: var(--font-mono);+ font-size: var(--text-sm);+ background: transparent;+ padding: 0;+ color: var(--ink);+ white-space: pre;+ }+ .copy-btn {+ position: absolute;+ top: var(--space-xs);+ right: var(--space-xs);+ font: inherit;+ font-size: var(--text-2xs);+ font-weight: 600;+ color: var(--ink-dim);+ background: var(--surface-2);+ border: 1px solid var(--stroke);+ border-radius: var(--radius-md);+ padding: var(--space-3xs) var(--space-xs);+ cursor: pointer;+ transition: color var(--duration-fast) var(--ease-standard),+ border-color var(--duration-fast) var(--ease-standard),+ background var(--duration-fast) var(--ease-standard);+ }+ .copy-btn:hover {+ color: var(--ink-bright);+ border-color: var(--stroke-strong);+ background: var(--surface-3);+ }+ .copy-btn:focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: 2px;+ }+ .copy-btn.copied {+ color: var(--success);+ border-color: color-mix(in srgb, var(--success) 50%, transparent);+ }++ /* ── Tabs (example languages) ───────────────────────────────── */+ .tabs {+ margin: var(--space-md) 0;+ }+ .tablist {+ display: flex;+ gap: var(--space-2xs);+ border-bottom: 1px solid var(--stroke);+ margin-bottom: var(--space-sm);+ }+ .tab {+ font: inherit;+ font-size: var(--text-sm);+ font-weight: 600;+ color: var(--ink-dim);+ background: none;+ border: 0;+ border-bottom: 2px solid transparent;+ padding: var(--space-xs) var(--space-sm);+ cursor: pointer;+ transition: color var(--duration-fast) var(--ease-standard);+ }+ .tab:hover {+ color: var(--ink);+ }+ .tab[aria-selected='true'] {+ color: var(--ink-bright);+ border-bottom-color: var(--accent);+ }+ .tab:focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: -2px;+ border-radius: var(--radius-sm);+ }+ .tabpanel[hidden] {+ display: none;+ }++ /* ── Callouts ───────────────────────────────────────────────── */+ .callout {+ border: 1px solid var(--stroke);+ border-left: 3px solid var(--accent);+ background: var(--surface-1);+ border-radius: var(--radius-md);+ padding: var(--space-sm) var(--space-md);+ margin: var(--space-md) 0;+ font-size: var(--text-sm);+ }+ .callout.warn {+ border-left-color: var(--warn);+ }+ .callout strong {+ color: var(--ink-bright);+ }++ /* ── Playground ─────────────────────────────────────────────── */+ .play {+ display: grid;+ grid-template-columns: minmax(0, 1fr) minmax(0, 1.1fr);+ gap: var(--space-md);+ margin: var(--space-md) 0;+ }+ .play-stage {+ border: 1px solid var(--stroke);+ border-radius: var(--radius-lg);+ overflow: hidden;+ background: var(--bg-1);+ aspect-ratio: 4 / 5;+ min-height: 320px;+ }+ .play-stage iframe {+ width: 100%;+ height: 100%;+ border: 0;+ display: block;+ }+ .play-controls {+ display: flex;+ flex-direction: column;+ gap: var(--space-sm);+ min-width: 0;+ }+ .ctrl-row {+ display: flex;+ flex-wrap: wrap;+ gap: var(--space-2xs);+ align-items: center;+ }+ .ctrl-row label {+ font-size: var(--text-xs);+ color: var(--ink-dim);+ min-width: 64px;+ }+ .btn {+ font: inherit;+ font-size: var(--text-sm);+ font-weight: 600;+ color: var(--ink-bright);+ background: var(--surface-2);+ border: 1px solid var(--stroke);+ border-radius: var(--radius-md);+ padding: var(--space-2xs) var(--space-sm);+ cursor: pointer;+ transition: background var(--duration-fast) var(--ease-standard),+ border-color var(--duration-fast) var(--ease-standard),+ transform var(--duration-instant) var(--ease-standard);+ }+ .btn:hover {+ background: var(--surface-3);+ border-color: var(--stroke-strong);+ }+ .btn:active {+ transform: translateY(1px);+ }+ .btn:focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: 2px;+ }+ .play select,+ .play input[type='text'] {+ font: inherit;+ font-size: var(--text-sm);+ color: var(--ink-bright);+ background: var(--bg-1);+ border: 1px solid var(--stroke);+ border-radius: var(--radius-md);+ padding: var(--space-2xs) var(--space-xs);+ }+ .play input[type='text'] {+ flex: 1;+ min-width: 120px;+ }+ .play-log {+ font-family: var(--font-mono);+ font-size: var(--text-2xs);+ line-height: 1.5;+ background: var(--bg-1);+ border: 1px solid var(--stroke);+ border-radius: var(--radius-md);+ padding: var(--space-xs);+ height: 150px;+ overflow-y: auto;+ color: var(--ink-dim);+ white-space: pre-wrap;+ word-break: break-word;+ }+ .play-log .ev-out {+ color: var(--success);+ }+ .play-log .ev-cmd {+ color: var(--accent);+ }+ .play-log .ev-err {+ color: var(--danger);+ }++ @media (max-width: 720px) {+ .play {+ grid-template-columns: 1fr;+ }+ .code pre {+ padding-right: var(--space-md);+ }+ .copy-btn {+ position: static;+ display: inline-block;+ margin-bottom: var(--space-2xs);+ }+ }++ .visually-hidden {+ position: absolute;+ width: 1px;+ height: 1px;+ padding: 0;+ margin: -1px;+ overflow: hidden;+ clip: rect(0, 0, 0, 0);+ white-space: nowrap;+ border: 0;+ }+ </style>+ </head>+ <body>+ <header>+ <div id="nav-container"></div>+ </header>+ <script src="/nav.js"></script>++ <main class="docs-main">+ <h1>Walk Embed API</h1>+ <p class="docs-lede">+ The walking-avatar embed is programmable. Drop the+ <a href="/walk-embed">/walk-embed</a> iframe on any page and drive it with a typed,+ bi-directional <code>postMessage</code> contract — or skip the wire format entirely+ and use the <code>ThreeWalkAvatar</code> SDK. This page is the full reference: every+ event, the security model, a live playground, and copy-paste examples.+ </p>++ <div class="docs-toc">+ <strong>On this page</strong>+ <ul>+ <li><a href="#quick-start">Quick start</a></li>+ <li><a href="#playground">Live playground</a></li>+ <li><a href="#outbound">Outbound events</a></li>+ <li><a href="#inbound">Inbound commands</a></li>+ <li><a href="#vocab">Vocabulary</a></li>+ <li><a href="#envelope">Envelope</a></li>+ <li><a href="#security">Security</a></li>+ <li><a href="#examples">Examples</a></li>+ </ul>+ </div>++ <h2 id="quick-start">Quick start</h2>+ <p>+ Render the iframe, then wrap it with the SDK to get a clean, promise-free command and+ event API:+ </p>+ <div class="code" data-code>+ <button class="copy-btn" type="button" aria-label="Copy code">Copy</button>+ <pre><code><iframe id="avatar" src="https://three.ws/walk-embed?env=studio"+ style="width:320px;height:400px;border:0"></iframe>++<script src="https://three.ws/walk-embed-sdk.js"></script>+<script>+ const a = ThreeWalkAvatar.embed('#avatar');+ a.on('ready', ({ avatarId, env }) => console.log('ready', avatarId, env));+ a.on('position', ({ x, z, heading }) => console.log(x, z, heading));+ a.goto(2, -1);+ a.gesture('wave');+ a.say('Hello from your site.');+</script></code></pre>+ </div>+ <div class="callout">+ <strong>No build step.</strong> The SDK is plain browser JS with zero dependencies.+ It works from a <code><script></code> tag, a bundler, or an ESM+ <code>import</code> of the URL.+ </div>++ <h2 id="playground">Live playground</h2>+ <p>+ A real <code>/walk-embed</code> iframe, driven through the SDK. Send commands and+ watch the event log update in real time — outbound events in green, the commands you+ send in blue, errors in red.+ </p>+ <div class="play">+ <div class="play-stage">+ <iframe+ id="pg-frame"+ src="/walk-embed?env=studio&controls=none&ground=true"+ title="Walk embed playground"+ allow="accelerometer; gyroscope"+ ></iframe>+ </div>+ <div class="play-controls">+ <div class="ctrl-row">+ <label for="pg-x">goto</label>+ <input type="text" id="pg-x" value="3" inputmode="decimal" aria-label="goto x" style="max-width:64px" />+ <input type="text" id="pg-z" value="-2" inputmode="decimal" aria-label="goto z" style="max-width:64px" />+ <button class="btn" type="button" id="pg-goto">Walk there</button>+ <button class="btn" type="button" id="pg-reset">Reset</button>+ </div>+ <div class="ctrl-row">+ <label for="pg-gesture">gesture</label>+ <select id="pg-gesture" aria-label="gesture"></select>+ <button class="btn" type="button" id="pg-play-gesture">Play</button>+ </div>+ <div class="ctrl-row">+ <label for="pg-env">env</label>+ <select id="pg-env" aria-label="environment"></select>+ </div>+ <div class="ctrl-row">+ <label for="pg-say">say</label>+ <input type="text" id="pg-say" value="Built on three.ws" aria-label="say text" />+ <button class="btn" type="button" id="pg-say-btn">Speak</button>+ </div>+ <div class="ctrl-row">+ <label for="pg-speed">speed</label>+ <input type="text" id="pg-speed" value="1.5" inputmode="decimal" aria-label="speed" style="max-width:64px" />+ <button class="btn" type="button" id="pg-speed-btn">Apply</button>+ <button class="btn" type="button" id="pg-clear-log">Clear log</button>+ </div>+ <div class="play-log" id="pg-log" role="log" aria-live="polite" aria-label="Event log">waiting for walk:ready…</div>+ </div>+ </div>++ <h2 id="outbound">Outbound events <span style="font-weight:400;color:var(--ink-dim);font-size:var(--text-md)">(iframe → host)</span></h2>+ <p>+ The embed emits these as you drive it and as the avatar lives its life. Subscribe with+ <code>avatar.on(name, cb)</code>; the callback receives the message object.+ </p>+ <div class="table-wrap">+ <table>+ <thead>+ <tr><th>Event</th><th>Dir</th><th>Payload</th><th>Fires when</th></tr>+ </thead>+ <tbody>+ <tr>+ <td><code>walk:ready</code></td>+ <td><span class="dir out">OUT</span></td>+ <td><code>{ avatarId, env }</code></td>+ <td>Avatar + animation clips finished loading. Re-sent in reply to <code>walk:ping</code>.</td>+ </tr>+ <tr>+ <td><code>walk:position</code></td>+ <td><span class="dir out">OUT</span></td>+ <td><code>{ x, z, heading }</code></td>+ <td>The avatar moves. Throttled to ≤ 10 Hz; <code>heading</code> is the facing yaw in radians.</td>+ </tr>+ <tr>+ <td><code>walk:gesture</code></td>+ <td><span class="dir out">OUT</span></td>+ <td><code>{ gesture }</code></td>+ <td>A gesture starts playing (echoes both one-shots and locomotion changes).</td>+ </tr>+ <tr>+ <td><code>walk:speak</code></td>+ <td><span class="dir out">OUT</span></td>+ <td><code>{ text, durationMs }</code></td>+ <td>The avatar starts speaking. <code>durationMs</code> is how long the bubble stays up.</td>+ </tr>+ <tr>+ <td><code>walk:env</code></td>+ <td><span class="dir out">OUT</span></td>+ <td><code>{ env }</code></td>+ <td>The environment changes.</td>+ </tr>+ <tr>+ <td><code>walk:avatarChanged</code></td>+ <td><span class="dir out">OUT</span></td>+ <td><code>{ avatarId }</code></td>+ <td>A live avatar swap finished loading.</td>+ </tr>+ <tr>+ <td><code>walk:error</code></td>+ <td><span class="dir out">OUT</span></td>+ <td><code>{ code, message }</code></td>+ <td>A command was rejected or a load failed. Never carries internal state.</td>+ </tr>+ </tbody>+ </table>+ </div>++ <h2 id="inbound">Inbound commands <span style="font-weight:400;color:var(--ink-dim);font-size:var(--text-md)">(host → iframe)</span></h2>+ <p>+ Send these to drive the avatar. With the SDK, each maps to a method; over raw+ <code>postMessage</code>, send the typed envelope (see+ <a href="#envelope">Envelope</a>). Every command is validated and clamped inside the+ iframe before it touches the avatar.+ </p>+ <div class="table-wrap">+ <table>+ <thead>+ <tr><th>Command</th><th>Dir</th><th>Payload</th><th>SDK method</th></tr>+ </thead>+ <tbody>+ <tr>+ <td><code>walk:goto</code></td>+ <td><span class="dir in">IN</span></td>+ <td><code>{ x, z }</code></td>+ <td><code>a.goto(x, z)</code> — walks to the point then stops (clamped to the ground disc).</td>+ </tr>+ <tr>+ <td><code>walk:gesture</code></td>+ <td><span class="dir in">IN</span></td>+ <td><code>{ gesture }</code></td>+ <td><code>a.gesture(name)</code></td>+ </tr>+ <tr>+ <td><code>walk:say</code></td>+ <td><span class="dir in">IN</span></td>+ <td><code>{ text, voice?, durationMs? }</code></td>+ <td><code>a.say(text, voice, durationMs)</code></td>+ </tr>+ <tr>+ <td><code>walk:env</code></td>+ <td><span class="dir in">IN</span></td>+ <td><code>{ env }</code></td>+ <td><code>a.setEnv(env)</code></td>+ </tr>+ <tr>+ <td><code>walk:avatar</code></td>+ <td><span class="dir in">IN</span></td>+ <td><code>{ avatarId }</code></td>+ <td><code>a.setAvatar(id)</code> — accepts an avatar id, a site path, or a GLB URL.</td>+ </tr>+ <tr>+ <td><code>walk:config</code></td>+ <td><span class="dir in">IN</span></td>+ <td><code>{ speed?, bg?, controls? }</code></td>+ <td><code>a.config({ … })</code></td>+ </tr>+ <tr>+ <td><code>walk:move</code></td>+ <td><span class="dir in">IN</span></td>+ <td><code>{ x, y, run? }</code></td>+ <td><code>a.move(x, y, run)</code> — held analog drive (−1…1 per axis).</td>+ </tr>+ <tr>+ <td><code>walk:reset</code></td>+ <td><span class="dir in">IN</span></td>+ <td><code>{}</code></td>+ <td><code>a.reset()</code> — recenter and stop all motion.</td>+ </tr>+ <tr>+ <td><code>walk:ping</code></td>+ <td><span class="dir in">IN</span></td>+ <td><code>{}</code></td>+ <td><code>a.ping()</code> — re-request <code>walk:ready</code> (the SDK fires this for you on attach).</td>+ </tr>+ </tbody>+ </table>+ </div>++ <h2 id="vocab">Vocabulary</h2>+ <p>The accepted values for the enumerated payload fields:</p>+ <ul>+ <li><strong>Gestures:</strong> <code>idle</code>, <code>walk</code>, <code>run</code>, <code>wave</code>, <code>jump</code>. <code>wave</code> and <code>jump</code> are one-shots that settle back to idle; the rest control locomotion.</li>+ <li><strong>Environments:</strong> <code>studio</code>, <code>void</code>, <code>beach</code>, <code>sunset</code>, <code>night</code>, <code>grid</code>.</li>+ <li><strong>Controls</strong> (<code>config.controls</code>): <code>joystick</code>, <code>keyboard</code>, <code>none</code>.</li>+ <li><strong>Speed</strong> (<code>config.speed</code>): a walk-speed multiplier, clamped to <code>0.3…3</code>.</li>+ <li><strong>Background</strong> (<code>config.bg</code>): <code>transparent</code>, a hex color, or an <code>rgb()/rgba()</code> string.</li>+ <li><strong>World bounds:</strong> <code>goto</code> targets are clamped to a radius of ~11.5 m (the ground disc).</li>+ </ul>+ <p>+ Feature-detect at runtime via <code>ThreeWalkAvatar.protocol</code> (the SDK) or+ <code>window.WALK_EMBED_PROTOCOL</code> (inside the embed window).+ </p>++ <h2 id="envelope">Envelope</h2>+ <p>+ Every message — both directions — is a plain object with a channel guard and version,+ so it can never be confused with another library's <code>postMessage</code> traffic:+ </p>+ <div class="code" data-code>+ <button class="copy-btn" type="button" aria-label="Copy code">Copy</button>+ <pre><code>{+ channel: 'three-walk', // namespace guard — ignore anything else+ v: 1, // protocol version+ type: 'walk:position', // event or command name+ id?: '<correlation id>', // echoed back on the result/error event+ ...payload // type-specific fields+}</code></pre>+ </div>+ <p>+ If you talk to the iframe directly (no SDK), post the envelope to+ <code>iframe.contentWindow</code> and read events off <code>window</code>:+ </p>+ <div class="code" data-code>+ <button class="copy-btn" type="button" aria-label="Copy code">Copy</button>+ <pre><code>const frame = document.getElementById('avatar');+// command+frame.contentWindow.postMessage(+ { channel: 'three-walk', v: 1, type: 'walk:goto', x: 2, z: -1 },+ 'https://three.ws'+);+// events+window.addEventListener('message', (e) => {+ if (e.source !== frame.contentWindow) return; // source check = auth+ if (!e.data || e.data.channel !== 'three-walk') return;+ if (e.data.type === 'walk:position') console.log(e.data.x, e.data.z);+});</code></pre>+ </div>++ <h2 id="security">Security</h2>+ <ul>+ <li>+ <strong>Source is the real authentication.</strong> The iframe only accepts+ commands whose source window is its own parent; the SDK only accepts events whose+ source is the iframe it wraps. Spoofed origins can't inject either way.+ </li>+ <li>+ <strong>Origin allow-listing is opt-in.</strong> The embed ships+ <code>frame-ancestors *</code> so it drops onto any site, so inbound is allow-any+ by default. Pin it with <code>?allowOrigins=https://your.site</code> (and+ <code>?targetOrigin=</code> to pin where events are posted) when you know the+ exact host.+ </li>+ <li>+ <strong>Nothing internal leaks.</strong> Outbound messages carry only the fields+ in the tables above — never session tokens, avatar source URLs, or scene state.+ A live avatar swap reports the <em>public</em> <code>avatarId</code> you gave it,+ not the resolved CDN URL.+ </li>+ <li>+ <strong>Everything inbound is validated.</strong> Numbers are clamped, strings+ are length-bounded, enums are checked, and <code>config.bg</code> is restricted to+ safe color forms. A bad command yields a <code>walk:error</code>, never a throw.+ </li>+ </ul>+ <div class="callout warn">+ <strong>Tip:</strong> if you embed user-generated avatar ids, still pass them through+ <code>a.setAvatar()</code> — the iframe resolves and loads them on the same origin so+ third-party hosts never need CORS exceptions.+ </div>++ <h2 id="examples">Examples</h2>+ <p>The same integration in three flavours. All three use the dependency-free SDK.</p>+ <div class="tabs" data-tabs>+ <div class="tablist" role="tablist" aria-label="Example language">+ <button class="tab" role="tab" id="tab-react" aria-controls="panel-react" aria-selected="true">React</button>+ <button class="tab" role="tab" id="tab-vue" aria-controls="panel-vue" aria-selected="false" tabindex="-1">Vue</button>+ <button class="tab" role="tab" id="tab-vanilla" aria-controls="panel-vanilla" aria-selected="false" tabindex="-1">Vanilla JS</button>+ </div>++ <div class="tabpanel" role="tabpanel" id="panel-react" aria-labelledby="tab-react">+ <div class="code" data-code>+ <button class="copy-btn" type="button" aria-label="Copy code">Copy</button>+ <pre><code>import { useEffect, useRef, useState } from 'react';++export function WalkAvatar({ avatarId, env = 'studio' }) {+ const frameRef = useRef(null);+ const [pos, setPos] = useState(null);++ useEffect(() => {+ // Load the SDK once.+ const SRC = 'https://three.ws/walk-embed-sdk.js';+ function attach() {+ const a = window.ThreeWalkAvatar.embed(frameRef.current);+ a.on('ready', () => a.gesture('wave'));+ a.on('position', setPos);+ frameRef.current._ctl = a;+ }+ if (window.ThreeWalkAvatar) attach();+ else {+ const s = document.createElement('script');+ s.src = SRC; s.onload = attach; document.head.appendChild(s);+ }+ return () => frameRef.current?._ctl?.destroy();+ }, []);++ return (+ <div>+ <iframe+ ref={frameRef}+ src={`https://three.ws/walk-embed?env=${env}${avatarId ? `&avatar=${avatarId}` : ''}`}+ style={{ width: 320, height: 400, border: 0 }}+ title="three.ws walking avatar"+ />+ {pos && <p>x {pos.x.toFixed(2)} · z {pos.z.toFixed(2)}</p>}+ </div>+ );+}</code></pre>+ </div>+ </div>++ <div class="tabpanel" role="tabpanel" id="panel-vue" aria-labelledby="tab-vue" hidden>+ <div class="code" data-code>+ <button class="copy-btn" type="button" aria-label="Copy code">Copy</button>+ <pre><code><script setup>+import { ref, onMounted, onBeforeUnmount } from 'vue';++const frame = ref(null);+const pos = ref(null);+let ctl = null;++function attach() {+ ctl = window.ThreeWalkAvatar.embed(frame.value);+ ctl.on('ready', () => ctl.setEnv('beach'));+ ctl.on('position', (p) => (pos.value = p));+}++onMounted(() => {+ if (window.ThreeWalkAvatar) return attach();+ const s = document.createElement('script');+ s.src = 'https://three.ws/walk-embed-sdk.js';+ s.onload = attach;+ document.head.appendChild(s);+});+onBeforeUnmount(() => ctl?.destroy());+</script>++<template>+ <iframe+ ref="frame"+ src="https://three.ws/walk-embed?env=studio"+ style="width:320px;height:400px;border:0"+ title="three.ws walking avatar"+ />+ <p v-if="pos">x {{ pos.x.toFixed(2) }} · z {{ pos.z.toFixed(2) }}</p>+</template></code></pre>+ </div>+ </div>++ <div class="tabpanel" role="tabpanel" id="panel-vanilla" aria-labelledby="tab-vanilla" hidden>+ <div class="code" data-code>+ <button class="copy-btn" type="button" aria-label="Copy code">Copy</button>+ <pre><code><iframe id="avatar" src="https://three.ws/walk-embed?env=studio"+ style="width:320px;height:400px;border:0"></iframe>++<script src="https://three.ws/walk-embed-sdk.js"></script>+<script>+ const a = ThreeWalkAvatar.embed('#avatar');++ a.on('ready', ({ avatarId, env }) => {+ console.log('ready:', avatarId, env);+ a.say('Welcome.', null, 4000);+ });+ a.on('position', ({ x, z, heading }) => {+ // throttled to 10 Hz+ });+ a.on('error', ({ code, message }) => console.warn(code, message));++ // Drive it.+ document.querySelector('#go').addEventListener('click', () => {+ a.goto(3, -2);+ a.gesture('wave');+ a.config({ speed: 1.5 });+ });+</script></code></pre>+ </div>+ </div>+ </div>+ </main>++ <!-- SDK first so the playground can call ThreeWalkAvatar.embed() synchronously. -->+ <script src="/walk-embed-sdk.js"></script>+ <script>+ (function () {+ 'use strict';++ // ── Copy buttons ─────────────────────────────────────────────+ document.querySelectorAll('.code[data-code]').forEach(function (block) {+ var btn = block.querySelector('.copy-btn');+ var pre = block.querySelector('pre code');+ if (!btn || !pre) return;+ btn.addEventListener('click', function () {+ var text = pre.textContent;+ var done = function () {+ btn.textContent = 'Copied';+ btn.classList.add('copied');+ setTimeout(function () {+ btn.textContent = 'Copy';+ btn.classList.remove('copied');+ }, 1400);+ };+ if (navigator.clipboard && navigator.clipboard.writeText) {+ navigator.clipboard.writeText(text).then(done, fallback);+ } else {+ fallback();+ }+ function fallback() {+ var ta = document.createElement('textarea');+ ta.value = text;+ ta.style.position = 'fixed';+ ta.style.opacity = '0';+ document.body.appendChild(ta);+ ta.select();+ try { document.execCommand('copy'); done(); } catch (e) {}+ document.body.removeChild(ta);+ }+ });+ });++ // ── Tabs ──────────────────────────────────────────────────────+ var tabsRoot = document.querySelector('.tabs[data-tabs]');+ if (tabsRoot) {+ var tabs = Array.prototype.slice.call(tabsRoot.querySelectorAll('.tab'));+ function select(tab) {+ tabs.forEach(function (t) {+ var on = t === tab;+ t.setAttribute('aria-selected', on ? 'true' : 'false');+ t.tabIndex = on ? 0 : -1;+ var panel = document.getElementById(t.getAttribute('aria-controls'));+ if (panel) panel.hidden = !on;+ });+ }+ tabs.forEach(function (tab, i) {+ tab.addEventListener('click', function () { select(tab); });+ tab.addEventListener('keydown', function (e) {+ var next;+ if (e.key === 'ArrowRight') next = tabs[(i + 1) % tabs.length];+ else if (e.key === 'ArrowLeft') next = tabs[(i - 1 + tabs.length) % tabs.length];+ if (next) { e.preventDefault(); next.focus(); select(next); }+ });+ });+ }++ // ── Live playground ───────────────────────────────────────────+ var frame = document.getElementById('pg-frame');+ var logEl = document.getElementById('pg-log');+ var protocol = (window.ThreeWalkAvatar && window.ThreeWalkAvatar.protocol) || {+ gestures: ['idle', 'walk', 'run', 'wave', 'jump'],+ environments: ['studio', 'void', 'beach', 'sunset', 'night', 'grid'],+ };++ function fillSelect(id, values) {+ var sel = document.getElementById(id);+ if (!sel) return;+ values.forEach(function (v) {+ var o = document.createElement('option');+ o.value = v; o.textContent = v;+ sel.appendChild(o);+ });+ }+ fillSelect('pg-gesture', protocol.gestures);+ fillSelect('pg-env', protocol.environments);++ function logLine(kind, text) {+ var line = document.createElement('div');+ line.className = kind;+ var stamp = new Date().toLocaleTimeString();+ line.textContent = stamp + ' ' + text;+ logEl.appendChild(line);+ // Keep the log bounded.+ while (logEl.childNodes.length > 80) logEl.removeChild(logEl.firstChild);+ logEl.scrollTop = logEl.scrollHeight;+ }++ if (!window.ThreeWalkAvatar) {+ logLine('ev-err', 'SDK not loaded — playground disabled');+ return;+ }++ var a = window.ThreeWalkAvatar.embed(frame);+ logEl.textContent = '';+ logLine('ev-cmd', 'embed() attached — pinging for walk:ready');++ a.on('ready', function (d) { logLine('ev-out', 'walk:ready avatar=' + (d.avatarId || '?') + ' env=' + (d.env || '?')); });+ a.on('position', function (d) {+ logLine('ev-out', 'walk:position x=' + Number(d.x).toFixed(2) + ' z=' + Number(d.z).toFixed(2) + ' h=' + Number(d.heading).toFixed(2));+ });+ a.on('gesture', function (d) { logLine('ev-out', 'walk:gesture ' + d.gesture); });+ a.on('speak', function (d) { logLine('ev-out', 'walk:speak "' + d.text + '" (' + d.durationMs + 'ms)'); });+ a.on('env', function (d) { logLine('ev-out', 'walk:env ' + d.env); });+ a.on('error', function (d) { logLine('ev-err', 'walk:error ' + d.code + ': ' + d.message); });++ function num(id) { return parseFloat(document.getElementById(id).value); }++ document.getElementById('pg-goto').addEventListener('click', function () {+ var x = num('pg-x'), z = num('pg-z');+ a.goto(x, z); logLine('ev-cmd', 'goto(' + x + ', ' + z + ')');+ });+ document.getElementById('pg-reset').addEventListener('click', function () {+ a.reset(); logLine('ev-cmd', 'reset()');+ });+ document.getElementById('pg-play-gesture').addEventListener('click', function () {+ var g = document.getElementById('pg-gesture').value;+ a.gesture(g); logLine('ev-cmd', "gesture('" + g + "')");+ });+ document.getElementById('pg-env').addEventListener('change', function (e) {+ a.setEnv(e.target.value); logLine('ev-cmd', "setEnv('" + e.target.value + "')");+ });+ document.getElementById('pg-say-btn').addEventListener('click', function () {+ var t = document.getElementById('pg-say').value;+ a.say(t); logLine('ev-cmd', "say('" + t + "')");+ });+ document.getElementById('pg-speed-btn').addEventListener('click', function () {+ var s = num('pg-speed');+ a.config({ speed: s }); logLine('ev-cmd', 'config({ speed: ' + s + ' })');+ });+ document.getElementById('pg-clear-log').addEventListener('click', function () {+ logEl.textContent = '';+ });+ })();+ </script>+ </body>+</html>diff --git a/public/docs/walk/analytics.html b/public/docs/walk/analytics.htmlnew file mode 100644index 000000000..3809860eb--- /dev/null+++ b/public/docs/walk/analytics.html@@ -0,0 +1,158 @@+<!doctype html>+<html lang="en">+ <head>+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />+ <title>Analytics — Walk docs — three.ws</title>+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />+ <meta name="description" content="Walk embed analytics: sessions, average duration, distance walked, unique embed origins, a daily time series, top hosts, and creator-defined conversion events fired with ThreeWalkAvatar.track." />+ <meta name="theme-color" content="#0a0a0a" />+ <link rel="canonical" href="https://three.ws/docs/walk/analytics" />+ <link rel="shortcut icon" href="/favicon.ico" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/style.css" />+ <link rel="stylesheet" href="/footer.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/docs/walk/docs.css" />+ </head>+ <body>+ <a class="wd-skip" href="#wd-main">Skip to content</a>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <div class="wd-shell">+ <button class="wd-side-toggle" type="button" aria-expanded="false" aria-controls="wd-side">+ <span>Documentation menu</span><span aria-hidden="true">☰</span>+ </button>+ <aside class="wd-side" id="wd-side" aria-label="Walk documentation">+ <h2>Walk docs</h2>+ <nav aria-label="Walk documentation pages">+ <a href="/docs/walk">Overview</a>+ <a href="/docs/walk/getting-started">Getting started</a>+ </nav>+ <h2>Use it</h2>+ <nav aria-label="Using Walk">+ <a href="/docs/walk/walk-page">The walk page</a>+ <a href="/docs/walk/companion-mode">Companion mode</a>+ <a href="/docs/walk/chrome-extension">Chrome extension</a>+ </nav>+ <h2>Build with it</h2>+ <nav aria-label="Building with Walk">+ <a href="/docs/walk/embed-iframe">Iframe embed</a>+ <a href="/docs/walk/embed-sdk">JavaScript SDK</a>+ <a href="/docs/walk/postmessage-events">postMessage events</a>+ <a href="/docs/walk/analytics" aria-current="page">Analytics</a>+ </nav>+ <h2>Reference</h2>+ <nav aria-label="Reference"><a href="/docs/walk/changelog">Changelog</a></nav>+ </aside>++ <main class="wd-main" id="wd-main">+ <p class="wd-crumbs"><a href="/docs">Docs</a> / <a href="/docs/walk">Walk</a> / Analytics</p>+ <h1>Analytics</h1>+ <p class="wd-lede">+ Every avatar you own has a private analytics dashboard at+ <a href="/walk-analytics">three.ws/walk-analytics</a> — sessions, distance,+ time, where it walked, and the conversion events you fire yourself. All figures+ come from real walk activity; nothing is sampled or estimated.+ </p>++ <h2>What's measured</h2>+ <div class="wd-table-wrap">+ <table class="wd-table">+ <thead><tr><th>Metric</th><th>Meaning</th></tr></thead>+ <tbody>+ <tr><td>Total sessions</td><td>Sessions counted across the selected window.</td></tr>+ <tr><td>Avg. duration</td><td>Total walk time ÷ total sessions.</td></tr>+ <tr><td>Total distance</td><td>Metres walked, summed from per-frame movement.</td></tr>+ <tr><td>Unique origins</td><td>Distinct host sites the avatar walked on.</td></tr>+ <tr><td>Time series</td><td>Per-day sessions, distance, and duration — gaps filled with zeroes for a continuous chart.</td></tr>+ <tr><td>Top origins</td><td>The top 10 embed hosts by session count.</td></tr>+ <tr><td>Events</td><td>Your conversion events with a count and conversion rate (events ÷ sessions).</td></tr>+ </tbody>+ </table>+ </div>++ <h2>How collection works</h2>+ <p>+ The walk runtime accumulates two running totals — horizontal distance and+ session wall-clock — and flushes a compact batch to <code>POST /api/walk/metrics</code>+ roughly every 60 seconds, plus once on page hide via+ <code>navigator.sendBeacon</code>. One batch becomes a single per-day rollup row,+ so an hour of walking is a handful of rows, not thousands.+ </p>+ <div class="wd-note">+ <span class="wd-icon" aria-hidden="true">✱</span>+ <span>The embed host (which site the avatar walked on) is derived server-side from the request's <code>Origin</code>/<code>Referer</code> header — never trusted from the request body. Your "unique origins" reflect where the avatar actually ran.</span>+ </div>++ <h2>Conversion events</h2>+ <p>+ Beyond automatic metrics, fire your own events to measure what matters — a+ subscribe, a purchase, a play. From a page running the walk runtime:+ </p>+ <div class="wd-code" data-lang="js" data-label="JavaScript">+ <pre><code>// name is trimmed and capped at 64 chars; value is an optional number.+window.ThreeWalkAvatar.track('subscribe', { value: 9 });+window.ThreeWalkAvatar.track('play');</code></pre>+ </div>+ <p>+ Each event posts immediately (events are sparse, unlike the batched metrics) and+ is attributed to the same avatar and walker as the surrounding session. The+ dashboard shows each event's count and its conversion rate against sessions.+ </p>++ <h2>Achievements</h2>+ <p>The runtime unlocks a fixed set of achievements, persisted once each:</p>+ <div class="wd-table-wrap">+ <table class="wd-table">+ <thead><tr><th>Code</th><th>Unlock</th></tr></thead>+ <tbody>+ <tr><td><code>distance_1km</code></td><td>1 km walked.</td></tr>+ <tr><td><code>distance_5km</code></td><td>5 km walked.</td></tr>+ <tr><td><code>sites_10</code></td><td>Walked on 10 different sites.</td></tr>+ <tr><td><code>all_environments</code></td><td>Walked in all six environments.</td></tr>+ </tbody>+ </table>+ </div>++ <h2>Access & privacy</h2>+ <ul>+ <li><strong>Owner-only.</strong> The dashboard API requires a signed-in session (or a bearer token with the <code>avatars:read</code> scope) and verifies you own the avatar — others get a 403.</li>+ <li><strong>Anonymous walkers count too.</strong> Signed-in walkers are attributed to their account; everyone else is keyed to a rotating anonymous id, so the leaderboard and your totals still include them.</li>+ <li><strong>No third-party tracking.</strong> Metrics flow only to the three.ws ingest; there is no external analytics provider in the pipeline.</li>+ </ul>++ <h2>The data shape</h2>+ <p>The ingest accepts this batch (all fields optional unless noted):</p>+ <div class="wd-code" data-lang="json" data-label="POST /api/walk/metrics">+ <pre><code>{+ "distanceMeters": 142.5,+ "durationSec": 96,+ "sessions": 1,+ "envId": "park",+ "avatarId": "your-avatar-uuid",+ "anonId": "anon-...", // required if not signed in+ "achievements": ["distance_1km"],+ "eventName": "subscribe", // for a conversion event+ "value": 9+}</code></pre>+ </div>++ <div class="wd-pagefoot">+ <a class="wd-edit" href="https://github.com/nirholas/three.ws/edit/main/public/docs/walk/analytics.html" rel="noopener"><span aria-hidden="true">✎</span> Edit this page on GitHub</a>+ <div class="wd-nextprev">+ <a href="/docs/walk/postmessage-events"><span>Previous</span>← postMessage events</a>+ <a href="/docs/walk/chrome-extension"><span>Next</span>Chrome extension →</a>+ </div>+ </div>+ </main>+ </div>++ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ <script src="/brand.js" defer></script>+ <script type="module" src="/docs/walk/docs.js"></script>+ </body>+</html>diff --git a/public/docs/walk/chrome-extension.html b/public/docs/walk/chrome-extension.htmlnew file mode 100644index 000000000..c771e99b0--- /dev/null+++ b/public/docs/walk/chrome-extension.html@@ -0,0 +1,163 @@+<!doctype html>+<html lang="en">+ <head>+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />+ <title>Chrome extension — Walk docs — three.ws</title>+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />+ <meta name="description" content="The three.ws Walk Avatar Chrome extension: walk your avatar on any site, configure appearance and per-site rules, and have pages read aloud with text-to-speech. Install, permissions, and settings." />+ <meta name="theme-color" content="#0a0a0a" />+ <link rel="canonical" href="https://three.ws/docs/walk/chrome-extension" />+ <link rel="shortcut icon" href="/favicon.ico" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/style.css" />+ <link rel="stylesheet" href="/footer.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/docs/walk/docs.css" />+ </head>+ <body>+ <a class="wd-skip" href="#wd-main">Skip to content</a>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <div class="wd-shell">+ <button class="wd-side-toggle" type="button" aria-expanded="false" aria-controls="wd-side">+ <span>Documentation menu</span><span aria-hidden="true">☰</span>+ </button>+ <aside class="wd-side" id="wd-side" aria-label="Walk documentation">+ <h2>Walk docs</h2>+ <nav aria-label="Walk documentation pages">+ <a href="/docs/walk">Overview</a>+ <a href="/docs/walk/getting-started">Getting started</a>+ </nav>+ <h2>Use it</h2>+ <nav aria-label="Using Walk">+ <a href="/docs/walk/walk-page">The walk page</a>+ <a href="/docs/walk/companion-mode">Companion mode</a>+ <a href="/docs/walk/chrome-extension" aria-current="page">Chrome extension</a>+ </nav>+ <h2>Build with it</h2>+ <nav aria-label="Building with Walk">+ <a href="/docs/walk/embed-iframe">Iframe embed</a>+ <a href="/docs/walk/embed-sdk">JavaScript SDK</a>+ <a href="/docs/walk/postmessage-events">postMessage events</a>+ <a href="/docs/walk/analytics">Analytics</a>+ </nav>+ <h2>Reference</h2>+ <nav aria-label="Reference"><a href="/docs/walk/changelog">Changelog</a></nav>+ </aside>++ <main class="wd-main" id="wd-main">+ <p class="wd-crumbs"><a href="/docs">Docs</a> / <a href="/docs/walk">Walk</a> / Chrome extension</p>+ <h1>Chrome extension</h1>+ <p class="wd-lede">+ The <strong>three.ws Walk Avatar</strong> extension (v1.0.0) puts a floating 3D+ avatar on any website you visit. It walks alongside you and can read page+ sections aloud — a living browsing companion. It only ever runs on tabs you+ explicitly enable.+ </p>++ <h2>What it does</h2>+ <ul>+ <li><strong>Mounts your avatar on any site.</strong> The avatar is the same transparent <code>/walk-embed</code> iframe, injected into the current tab when you toggle it on.</li>+ <li><strong>Reads pages aloud (optional).</strong> With narration enabled, it detects the main article, tracks what's in view, and speaks visible sections using text-to-speech.</li>+ <li><strong>Respects your rules.</strong> Per-site enabling plus an allowlist/blocklist, and it never auto-injects — it runs only where you ask.</li>+ </ul>++ <h2>Install</h2>+ <p>+ The extension is built from this repository and loaded unpacked. (It is prepared+ for the Chrome Web Store; a public listing is not yet available, so install it in+ developer mode.)+ </p>+ <div class="wd-code" data-lang="shell" data-label="Terminal">+ <pre><code>npm run build:extension</code></pre>+ </div>+ <ol>+ <li>Open <code>chrome://extensions</code>.</li>+ <li>Enable <strong>Developer mode</strong> (top-right).</li>+ <li>Click <strong>Load unpacked</strong>.</li>+ <li>Select <code>dist/extension/</code>.</li>+ </ol>+ <div class="wd-note">+ <span class="wd-icon" aria-hidden="true">✱</span>+ <span>Requires Chrome 109 or newer (Manifest V3). To package a store-ready zip, run <code>npm run build:extension:prod</code>, which emits <code>dist/extension-<version>.zip</code>.</span>+ </div>++ <h2>Permissions</h2>+ <p>The extension requests the minimum it needs and injects only on explicit user action.</p>+ <div class="wd-table-wrap">+ <table class="wd-table">+ <thead><tr><th>Permission</th><th>Why</th></tr></thead>+ <tbody>+ <tr><td><code>storage</code></td><td>Persist your chosen avatar, walk speed, position, site rules, and narration settings (synced across your Chrome devices).</td></tr>+ <tr><td><code>activeTab</code></td><td>Read the current tab's hostname to label "Enable on this site" and relay your toggle to that tab.</td></tr>+ <tr><td><code>tabs</code></td><td>Keep the avatar in sync as you navigate, evaluate your site rules, and relay live setting changes to mounted tabs.</td></tr>+ <tr><td><code>scripting</code></td><td>Inject the avatar into your active tab — only when you turn it on, never automatically.</td></tr>+ <tr><td><code>host_permissions</code> (<code><all_urls></code>)</td><td>Because you can enable the avatar on any site you visit. Injection still happens only on tabs you enable.</td></tr>+ <tr><td><code>host_permissions</code> (<code>three.ws</code>)</td><td>Fetch your avatars, featured avatars, and TTS voices, and serve the walking iframe.</td></tr>+ </tbody>+ </table>+ </div>++ <h2>The popup</h2>+ <p>Click the toolbar icon to open the popup:</p>+ <ul>+ <li><strong>Account</strong> — your handle and a sign-in / sign-out control.</li>+ <li><strong>Avatar picker</strong> — three tabs: <em>My Avatars</em> (signed in), <em>Featured</em>, and <em>Recent</em> (your last picks). Selecting one sets it as your walker.</li>+ <li><strong>Walk speed</strong> — a slider from 0.5× to 2.0×.</li>+ <li><strong>Enable on this site</strong> — a toggle that mounts/unmounts the avatar on the current tab, with the domain shown. It's disabled on restricted pages (<code>chrome://</code>, etc.).</li>+ <li><strong>All settings →</strong> — opens the full options page.</li>+ </ul>++ <h2>Settings (options page)</h2>+ <div class="wd-table-wrap">+ <table class="wd-table">+ <thead><tr><th>Setting</th><th>Options</th></tr></thead>+ <tbody>+ <tr><td>Default avatar</td><td>Choose from <em>My avatars</em> or <em>Featured</em>.</td></tr>+ <tr><td>Default position</td><td>Bottom right / left, top right / left, or follow cursor.</td></tr>+ <tr><td>Default size</td><td>Small, Medium, Large, or custom width × height.</td></tr>+ <tr><td>Walk speed</td><td>0.5× – 2.0×.</td></tr>+ <tr><td>Theme</td><td>Light, Dark, or Auto (samples the page background).</td></tr>+ <tr><td>Read page sections aloud</td><td>Narration on/off (off by default).</td></tr>+ <tr><td>Voice</td><td>Picked from the three.ws TTS voice list.</td></tr>+ <tr><td>Allowlist</td><td>Domains where the avatar may appear (when set, only these).</td></tr>+ <tr><td>Blocklist</td><td>Domains where it never appears (takes precedence).</td></tr>+ </tbody>+ </table>+ </div>++ <h2>Read-aloud narration</h2>+ <p>+ With narration on, the extension parses the page's main article (using a bundled+ Readability extractor), pulls out headings, paragraphs, list items, and+ blockquotes, and watches which section is in view. When a section becomes the+ focus it requests speech audio from the three.ws text-to-speech service and plays+ it, while telling the avatar to show a speech bubble and switch to an idle pose.+ You choose the voice, can mute mid-read, and narration honours+ <code>prefers-reduced-motion</code>. Authors can mark sections with+ <code>data-walk-narrate</code> (or skip them with <code>data-walk-narrate="skip"</code>).+ </p>+ <div class="wd-note">+ <span class="wd-icon" aria-hidden="true">✱</span>+ <span>Everything stays on your device except text-to-speech requests, which are sent to three.ws to synthesize audio. Your site rules and preferences are stored in Chrome's synced storage.</span>+ </div>++ <div class="wd-pagefoot">+ <a class="wd-edit" href="https://github.com/nirholas/three.ws/edit/main/public/docs/walk/chrome-extension.html" rel="noopener"><span aria-hidden="true">✎</span> Edit this page on GitHub</a>+ <div class="wd-nextprev">+ <a href="/docs/walk/companion-mode"><span>Previous</span>← Companion mode</a>+ <a href="/docs/walk/changelog"><span>Next</span>Changelog →</a>+ </div>+ </div>+ </main>+ </div>++ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ <script src="/brand.js" defer></script>+ <script type="module" src="/docs/walk/docs.js"></script>+ </body>+</html>diff --git a/public/docs/walk/companion-mode.html b/public/docs/walk/companion-mode.htmlnew file mode 100644index 000000000..5bb5ca05c--- /dev/null+++ b/public/docs/walk/companion-mode.html@@ -0,0 +1,115 @@+<!doctype html>+<html lang="en">+ <head>+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />+ <title>Companion mode — Walk docs — three.ws</title>+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />+ <meta name="description" content="Companion mode: a site-wide three.ws avatar that detaches from the page, walks around, and follows you between pages — with walk-aware page transitions and wave-goodbye / wave-hello." />+ <meta name="theme-color" content="#0a0a0a" />+ <link rel="canonical" href="https://three.ws/docs/walk/companion-mode" />+ <link rel="shortcut icon" href="/favicon.ico" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/style.css" />+ <link rel="stylesheet" href="/footer.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/docs/walk/docs.css" />+ </head>+ <body>+ <a class="wd-skip" href="#wd-main">Skip to content</a>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <div class="wd-shell">+ <button class="wd-side-toggle" type="button" aria-expanded="false" aria-controls="wd-side">+ <span>Documentation menu</span><span aria-hidden="true">☰</span>+ </button>+ <aside class="wd-side" id="wd-side" aria-label="Walk documentation">+ <h2>Walk docs</h2>+ <nav aria-label="Walk documentation pages">+ <a href="/docs/walk">Overview</a>+ <a href="/docs/walk/getting-started">Getting started</a>+ </nav>+ <h2>Use it</h2>+ <nav aria-label="Using Walk">+ <a href="/docs/walk/walk-page">The walk page</a>+ <a href="/docs/walk/companion-mode" aria-current="page">Companion mode</a>+ <a href="/docs/walk/chrome-extension">Chrome extension</a>+ </nav>+ <h2>Build with it</h2>+ <nav aria-label="Building with Walk">+ <a href="/docs/walk/embed-iframe">Iframe embed</a>+ <a href="/docs/walk/embed-sdk">JavaScript SDK</a>+ <a href="/docs/walk/postmessage-events">postMessage events</a>+ <a href="/docs/walk/analytics">Analytics</a>+ </nav>+ <h2>Reference</h2>+ <nav aria-label="Reference"><a href="/docs/walk/changelog">Changelog</a></nav>+ </aside>++ <main class="wd-main" id="wd-main">+ <p class="wd-crumbs"><a href="/docs">Docs</a> / <a href="/docs/walk">Walk</a> / Companion mode</p>+ <h1>Companion mode</h1>+ <p class="wd-lede">+ Companion mode is the site-wide walking avatar on three.ws. Turn it on and your+ avatar detaches from the page chrome, walks around the screen, and follows you+ as you move between pages — complete with walk-aware page transitions.+ </p>++ <h2>Turning it on</h2>+ <p>Three ways:</p>+ <ul>+ <li><strong>Nav button</strong> — the <strong>Walk</strong> control in the top navigation toggles the companion on and off. The preference is remembered across visits.</li>+ <li><strong>Query parameter</strong> — append <code>?walk=1</code> to any three.ws URL to force it on, or <code>?walk=0</code> to force it off.</li>+ <li><strong>Programmatically</strong> — the companion instance is available at <code>window.__walkCompanion</code> once enabled (this is the interface the navigation drives).</li>+ </ul>+ <div class="wd-code" data-lang="text" data-label="URL">+ <pre><code>https://three.ws/?walk=1</code></pre>+ </div>++ <h2>What it does</h2>+ <ul>+ <li><strong>Detaches and roams.</strong> Your avatar leaves the page layout and becomes a free 3D character you can watch walk around.</li>+ <li><strong>Follows you between pages.</strong> When you navigate, the companion persists — and walk-aware page transitions dress the jump to match where you're going.</li>+ <li><strong>Waves goodbye and hello.</strong> On a link click the avatar plays a wave and sets a one-shot flag the destination page reads to wave back when it loads.</li>+ <li><strong>Picks an avatar.</strong> The picker includes a "make your own" link straight to the <a href="/avatar-studio">avatar studio</a>.</li>+ </ul>++ <h2>How it's wired</h2>+ <p>+ Companion mode is the platform integration of the publishable walk SDK. The+ three.ws navigation injects the companion script only when the companion is+ enabled — a page that never turns it on pays nothing for it. Under the hood it+ loads the avatar's pre-baked animation manifest and the same rendering engine+ the <a href="/docs/walk/walk-page">walk page</a> and+ <a href="/docs/walk/embed-iframe">embeds</a> use.+ </p>+ <div class="wd-note">+ <span class="wd-icon" aria-hidden="true">✱</span>+ <span>Companion mode is a three.ws-site feature. To put a walking avatar on <em>your own</em> site, use the one-tag <a href="/docs/walk/embed-sdk">JavaScript SDK</a>; to walk your avatar on <em>every</em> site you visit, install the <a href="/docs/walk/chrome-extension">Chrome extension</a>.</span>+ </div>++ <h2>Accessibility & motion</h2>+ <p>+ The companion and its page transitions respect <code>prefers-reduced-motion</code>.+ The roaming avatar is decorative; all navigation and content remain fully usable+ with the companion off, which is the default state until you opt in.+ </p>++ <div class="wd-pagefoot">+ <a class="wd-edit" href="https://github.com/nirholas/three.ws/edit/main/public/docs/walk/companion-mode.html" rel="noopener"><span aria-hidden="true">✎</span> Edit this page on GitHub</a>+ <div class="wd-nextprev">+ <a href="/docs/walk/walk-page"><span>Previous</span>← The walk page</a>+ <a href="/docs/walk/chrome-extension"><span>Next</span>Chrome extension →</a>+ </div>+ </div>+ </main>+ </div>++ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ <script src="/brand.js" defer></script>+ <script type="module" src="/docs/walk/docs.js"></script>+ </body>+</html>diff --git a/public/docs/walk/docs.css b/public/docs/walk/docs.cssnew file mode 100644index 000000000..a04c59b92--- /dev/null+++ b/public/docs/walk/docs.css@@ -0,0 +1,328 @@+/* ============================================================================+ * Walk documentation hub — shared styles for /docs/walk/*+ * Token-only: every value resolves to a primitive in public/tokens.css+ * (loaded via /style.css). No hardcoded colours/spacing where a token exists.+ * ========================================================================= */++.wd-skip {+ position: absolute;+ left: var(--space-2);+ top: var(--space-2);+ transform: translateY(-200%);+ z-index: 100;+ background: var(--bg-1);+ color: var(--ink-bright);+ border: 1px solid var(--stroke-strong);+ border-radius: var(--radius-md);+ padding: var(--space-2) var(--space-4);+ font: var(--weight-medium) var(--text-md) / 1 var(--font-body);+ text-decoration: none;+ transition: transform var(--duration-fast) var(--ease-standard);+}+.wd-skip:focus { transform: translateY(0); }++.wd-shell {+ display: grid;+ grid-template-columns: 16rem minmax(0, 1fr);+ gap: var(--space-xl);+ max-width: 78rem;+ margin: 0 auto;+ padding: var(--space-lg) var(--space-md) var(--space-2xl);+}++/* ── Sidebar ────────────────────────────────────────────────────────────── */+.wd-side {+ position: sticky;+ top: calc(var(--header-h) + var(--space-2));+ align-self: start;+ max-height: calc(100vh - var(--header-h) - var(--space-4));+ overflow-y: auto;+ padding-right: var(--space-1);+}+.wd-side h2 {+ font: var(--weight-semibold) var(--text-2xs) / 1 var(--font-body);+ letter-spacing: 0.08em;+ text-transform: uppercase;+ color: var(--ink-faint);+ margin: var(--space-lg) 0 var(--space-2);+ padding: 0 var(--space-3);+}+.wd-side h2:first-child { margin-top: 0; }+.wd-side nav { display: flex; flex-direction: column; gap: var(--space-3xs); }+.wd-side a {+ display: flex;+ align-items: center;+ gap: var(--space-2);+ padding: var(--space-2) var(--space-3);+ border-radius: var(--radius-md);+ color: var(--ink-dim);+ text-decoration: none;+ font: var(--weight-medium) var(--text-md) / 1.2 var(--font-body);+ border: 1px solid transparent;+ transition: background var(--duration-fast) var(--ease-standard),+ color var(--duration-fast) var(--ease-standard);+}+.wd-side a:hover { background: var(--surface-1); color: var(--ink); }+.wd-side a[aria-current='page'] {+ background: var(--surface-2);+ color: var(--ink-bright);+ border-color: var(--stroke);+ font-weight: var(--weight-semibold);+}+.wd-side a:focus-visible {+ outline: var(--focus-ring-width) solid var(--focus-ring-color);+ outline-offset: var(--focus-ring-offset);+}++/* ── Article ────────────────────────────────────────────────────────────── */+.wd-main { min-width: 0; }+.wd-crumbs {+ font: var(--weight-medium) var(--text-sm) / 1 var(--font-body);+ color: var(--ink-faint);+ margin-bottom: var(--space-3);+}+.wd-crumbs a { color: var(--ink-dim); text-decoration: none; }+.wd-crumbs a:hover { color: var(--ink); text-decoration: underline; }++.wd-main h1 {+ font: var(--weight-bold) var(--text-2xl) / var(--leading-tight) var(--font-display);+ color: var(--ink-bright);+ letter-spacing: -0.02em;+ margin: 0 0 var(--space-3);+}+.wd-lede {+ font: var(--weight-regular) var(--text-lg) / var(--leading-normal) var(--font-body);+ color: var(--ink-dim);+ margin: 0 0 var(--space-xl);+ max-width: 46rem;+}+.wd-main h2 {+ font: var(--weight-semibold) var(--text-xl) / var(--leading-tight) var(--font-display);+ color: var(--ink-bright);+ letter-spacing: -0.01em;+ margin: var(--space-xl) 0 var(--space-3);+ scroll-margin-top: calc(var(--header-h) + var(--space-4));+}+.wd-main h3 {+ font: var(--weight-semibold) var(--text-lg) / var(--leading-tight) var(--font-display);+ color: var(--ink-bright);+ margin: var(--space-lg) 0 var(--space-2);+ scroll-margin-top: calc(var(--header-h) + var(--space-4));+}+.wd-main p, .wd-main li {+ font: var(--weight-regular) var(--text-base) / var(--leading-normal) var(--font-body);+ color: var(--ink);+ max-width: 46rem;+}+.wd-main p { margin: 0 0 var(--space-3); }+.wd-main ul, .wd-main ol { margin: 0 0 var(--space-3); padding-left: var(--space-lg); }+.wd-main li { margin: 0 0 var(--space-2); }+.wd-main a { color: var(--ink-bright); text-decoration: underline; text-underline-offset: 2px; }+.wd-main a:hover { color: var(--accent); }+.wd-main strong { color: var(--ink-bright); font-weight: var(--weight-semibold); }+.wd-main :is(p, li) code, .wd-main :is(p, li) kbd {+ font: var(--weight-medium) 0.85em var(--font-mono);+ background: var(--surface-2);+ border: 1px solid var(--stroke);+ border-radius: var(--radius-sm);+ padding: 0.1em 0.4em;+ color: var(--ink-bright);+}+.wd-main kbd {+ box-shadow: var(--shadow-1);+ white-space: nowrap;+}++/* ── Code blocks + copy button ──────────────────────────────────────────── */+.wd-code {+ position: relative;+ margin: 0 0 var(--space-lg);+ border: 1px solid var(--stroke);+ border-radius: var(--radius-lg);+ background: var(--bg-1);+ overflow: hidden;+}+.wd-code-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: var(--space-2);+ padding: var(--space-2) var(--space-3);+ border-bottom: 1px solid var(--stroke);+ background: var(--surface-1);+}+.wd-code-lang {+ font: var(--weight-semibold) var(--text-2xs) / 1 var(--font-mono);+ letter-spacing: 0.06em;+ text-transform: uppercase;+ color: var(--ink-faint);+}+.wd-copy {+ appearance: none;+ display: inline-flex;+ align-items: center;+ gap: var(--space-1);+ border: 1px solid var(--stroke);+ background: var(--surface-2);+ color: var(--ink-dim);+ font: var(--weight-medium) var(--text-2xs) / 1 var(--font-body);+ padding: var(--space-1) var(--space-2);+ border-radius: var(--radius-sm);+ cursor: pointer;+ transition: background var(--duration-fast) var(--ease-standard),+ color var(--duration-fast) var(--ease-standard);+}+.wd-copy:hover { background: var(--surface-3); color: var(--ink-bright); }+.wd-copy:focus-visible {+ outline: var(--focus-ring-width) solid var(--focus-ring-color);+ outline-offset: var(--focus-ring-offset);+}+.wd-copy[data-copied='true'] { color: var(--success); border-color: var(--success); }+.wd-code pre {+ margin: 0;+ padding: var(--space-3) var(--space-4);+ overflow-x: auto;+ font: var(--weight-regular) var(--text-md) / var(--leading-normal) var(--font-mono);+ color: var(--ink);+ tab-size: 2;+}+.wd-code pre code { background: none; border: 0; padding: 0; color: inherit; font: inherit; }+/* minimal token tints — applied by docs.js, no external highlighter */+.wd-code .t-key { color: var(--accent); }+.wd-code .t-str { color: var(--success); }+.wd-code .t-com { color: var(--ink-faint); font-style: italic; }+.wd-code .t-num { color: var(--warn); }++/* ── Callouts ───────────────────────────────────────────────────────────── */+.wd-note, .wd-warn {+ display: flex;+ gap: var(--space-2);+ border-radius: var(--radius-lg);+ padding: var(--space-3) var(--space-4);+ margin: 0 0 var(--space-lg);+ font: var(--weight-regular) var(--text-md) / var(--leading-normal) var(--font-body);+ max-width: 46rem;+}+.wd-note {+ background: var(--accent-soft);+ border: 1px solid var(--stroke-strong);+ color: var(--ink);+}+.wd-warn {+ background: rgba(var(--gold-rgb), 0.08);+ border: 1px solid rgba(var(--gold-rgb), 0.32);+ color: var(--ink);+}+.wd-note strong, .wd-warn strong { color: var(--ink-bright); }+.wd-icon { flex: 0 0 auto; line-height: 1.4; }++/* ── Tables ─────────────────────────────────────────────────────────────── */+.wd-table-wrap { overflow-x: auto; margin: 0 0 var(--space-lg); border-radius: var(--radius-lg); border: 1px solid var(--stroke); }+.wd-table { width: 100%; border-collapse: collapse; font: var(--weight-regular) var(--text-md) / var(--leading-normal) var(--font-body); }+.wd-table th, .wd-table td { text-align: left; padding: var(--space-2) var(--space-3); border-bottom: 1px solid var(--stroke); vertical-align: top; }+.wd-table thead th { background: var(--surface-1); color: var(--ink-bright); font-weight: var(--weight-semibold); font-size: var(--text-sm); position: sticky; top: 0; }+.wd-table tbody tr:last-child td { border-bottom: 0; }+.wd-table tbody tr:hover { background: var(--surface-1); }+.wd-table code { font: var(--weight-medium) 0.9em var(--font-mono); color: var(--ink-bright); white-space: nowrap; }+.wd-table td.wd-default { color: var(--ink-dim); }++/* ── Cards (overview grid) ──────────────────────────────────────────────── */+.wd-cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(15rem, 1fr)); gap: var(--space-3); margin: 0 0 var(--space-xl); }+.wd-card {+ display: block;+ padding: var(--space-4);+ border: 1px solid var(--stroke);+ border-radius: var(--radius-lg);+ background: var(--surface-glass);+ text-decoration: none;+ transition: transform var(--duration-fast) var(--ease-standard),+ border-color var(--duration-fast) var(--ease-standard),+ box-shadow var(--duration-base) var(--ease-standard);+}+.wd-card:hover { transform: translateY(-2px); border-color: var(--stroke-strong); box-shadow: var(--shadow-2); }+.wd-card:focus-visible { outline: var(--focus-ring-width) solid var(--focus-ring-color); outline-offset: var(--focus-ring-offset); }+.wd-card h3 { margin: 0 0 var(--space-1); font: var(--weight-semibold) var(--text-base) var(--font-display); color: var(--ink-bright); }+.wd-card p { margin: 0; font-size: var(--text-md); color: var(--ink-dim); }++/* ── Live demo frame ────────────────────────────────────────────────────── */+.wd-demo {+ margin: 0 0 var(--space-lg);+ border: 1px solid var(--stroke);+ border-radius: var(--radius-lg);+ overflow: hidden;+ background: var(--bg-1);+}+.wd-demo-head {+ display: flex; align-items: center; justify-content: space-between; gap: var(--space-2);+ padding: var(--space-2) var(--space-3);+ border-bottom: 1px solid var(--stroke);+ font: var(--weight-medium) var(--text-sm) / 1 var(--font-body);+ color: var(--ink-dim);+}+.wd-demo iframe { display: block; width: 100%; border: 0; background: transparent; }+.wd-demo-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--success); display: inline-block; margin-right: var(--space-1); }++/* ── Page footer / edit link ────────────────────────────────────────────── */+.wd-pagefoot {+ display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: var(--space-3);+ margin-top: var(--space-2xl);+ padding-top: var(--space-lg);+ border-top: 1px solid var(--stroke);+}+.wd-edit {+ display: inline-flex; align-items: center; gap: var(--space-1);+ font: var(--weight-medium) var(--text-md) / 1 var(--font-body);+ color: var(--ink-dim);+ text-decoration: none;+}+.wd-edit:hover { color: var(--ink-bright); text-decoration: underline; }+.wd-nextprev { display: flex; gap: var(--space-2); flex-wrap: wrap; }+.wd-nextprev a {+ display: inline-flex; flex-direction: column; gap: var(--space-3xs);+ padding: var(--space-2) var(--space-3);+ border: 1px solid var(--stroke);+ border-radius: var(--radius-md);+ text-decoration: none;+ color: var(--ink-bright);+ font: var(--weight-semibold) var(--text-md) / 1.2 var(--font-body);+ transition: border-color var(--duration-fast) var(--ease-standard), background var(--duration-fast) var(--ease-standard);+}+.wd-nextprev a:hover { border-color: var(--stroke-strong); background: var(--surface-1); }+.wd-nextprev a span { font: var(--weight-regular) var(--text-2xs) var(--font-body); color: var(--ink-faint); text-transform: uppercase; letter-spacing: 0.06em; }++/* ── Mobile sidebar toggle ──────────────────────────────────────────────── */+.wd-side-toggle { display: none; }++@media (max-width: 880px) {+ .wd-shell { grid-template-columns: 1fr; gap: var(--space-md); padding: var(--space-md); }+ .wd-side {+ position: static;+ max-height: none;+ border: 1px solid var(--stroke);+ border-radius: var(--radius-lg);+ background: var(--surface-1);+ padding: var(--space-2);+ margin-bottom: var(--space-2);+ }+ .wd-side[hidden] { display: none; }+ .wd-side-toggle {+ display: inline-flex; align-items: center; gap: var(--space-2);+ appearance: none;+ border: 1px solid var(--stroke);+ background: var(--surface-1);+ color: var(--ink-bright);+ font: var(--weight-semibold) var(--text-md) / 1 var(--font-body);+ padding: var(--space-2) var(--space-3);+ border-radius: var(--radius-md);+ cursor: pointer;+ margin-bottom: var(--space-2);+ width: 100%;+ justify-content: space-between;+ }+ .wd-side-toggle:focus-visible { outline: var(--focus-ring-width) solid var(--focus-ring-color); outline-offset: var(--focus-ring-offset); }+}++@media (max-width: 420px) {+ .wd-main h1 { font-size: var(--text-xl); }+ .wd-lede { font-size: var(--text-base); }+}diff --git a/public/docs/walk/docs.js b/public/docs/walk/docs.jsnew file mode 100644index 000000000..cea70eb0b--- /dev/null+++ b/public/docs/walk/docs.js@@ -0,0 +1,168 @@+// Walk documentation hub — shared client behaviour for /docs/walk/*+// ----------------------------------------------------------------------------+// Three small, dependency-free enhancements that every doc page opts into by+// loading this module:+// 1. Copy-to-clipboard buttons on code blocks (built from the raw text so the+// clipboard never picks up the highlight <span>s).+// 2. A minimal, safe syntax tint for fenced code (keywords / strings /+// comments / numbers) — no external highlighter, no CDN.+// 3. A responsive sidebar disclosure for narrow viewports.+//+// Everything degrades gracefully: with JS off, code blocks are still readable+// plain text and the sidebar is plain navigation.++(() => {+ 'use strict';++ // ── 1 + 2. Code blocks ──────────────────────────────────────────────────+ const KEYWORDS = new Set([+ 'const', 'let', 'var', 'function', 'return', 'if', 'else', 'for', 'while',+ 'new', 'await', 'async', 'import', 'export', 'from', 'class', 'extends',+ 'true', 'false', 'null', 'undefined', 'typeof', 'this', 'try', 'catch',+ 'window', 'document', 'script',+ ]);++ function escapeHtml(s) {+ return s.replace(/[&<>]/g, (c) => (c === '&' ? '&' : c === '<' ? '<' : '>'));+ }++ // Tokenise a single line for tinting. HTML/markup samples and shell are left+ // mostly alone (only strings + comments) to avoid mangling tags.+ function tintLine(line, mode) {+ const out = [];+ let i = 0;+ const push = (cls, text) => out.push(cls ? `<span class="${cls}">${escapeHtml(text)}</span>` : escapeHtml(text));+ while (i < line.length) {+ const rest = line.slice(i);+ // Line comment (// or #)+ if ((mode !== 'html') && (rest.startsWith('//') || (mode === 'shell' && rest.startsWith('#')))) {+ push('t-com', rest);+ break;+ }+ // HTML comment+ if (mode === 'html' && rest.startsWith('<!--')) {+ push('t-com', rest);+ break;+ }+ // String literals+ const q = rest[0];+ if (q === '"' || q === "'" || q === '`') {+ let j = 1;+ while (j < rest.length && rest[j] !== q) {+ if (rest[j] === '\\') j++;+ j++;+ }+ push('t-str', rest.slice(0, Math.min(j + 1, rest.length)));+ i += Math.min(j + 1, rest.length);+ continue;+ }+ // Identifiers / keywords (JS/JSON only)+ if ((mode === 'js' || mode === 'json') && /[A-Za-z_$]/.test(q)) {+ const m = rest.match(/^[A-Za-z0-9_$]+/);+ const word = m[0];+ push(KEYWORDS.has(word) ? 't-key' : null, word);+ i += word.length;+ continue;+ }+ // Numbers+ if (/[0-9]/.test(q) && (i === 0 || !/[A-Za-z0-9_]/.test(line[i - 1]))) {+ const m = rest.match(/^[0-9][0-9_.eE+-]*/);+ push('t-num', m[0]);+ i += m[0].length;+ continue;+ }+ push(null, q);+ i++;+ }+ return out.join('');+ }++ function enhanceCodeBlocks() {+ document.querySelectorAll('.wd-code').forEach((block) => {+ const pre = block.querySelector('pre');+ const code = pre && pre.querySelector('code');+ if (!pre || !code) return;+ const raw = code.textContent;+ const mode = block.dataset.lang || 'js';++ // Tint (skip 'text' / 'plain' blocks).+ if (mode !== 'text' && mode !== 'plain') {+ code.innerHTML = raw+ .split('\n')+ .map((l) => tintLine(l, mode))+ .join('\n');+ }++ // Build the head + copy button if not already present.+ if (!block.querySelector('.wd-code-head')) {+ const head = document.createElement('div');+ head.className = 'wd-code-head';+ const lang = document.createElement('span');+ lang.className = 'wd-code-lang';+ lang.textContent = block.dataset.label || mode;+ const btn = document.createElement('button');+ btn.type = 'button';+ btn.className = 'wd-copy';+ btn.textContent = 'Copy';+ btn.setAttribute('aria-label', 'Copy code to clipboard');+ btn.addEventListener('click', async () => {+ try {+ await navigator.clipboard.writeText(raw);+ } catch {+ // Fallback for non-secure contexts / older browsers.+ const ta = document.createElement('textarea');+ ta.value = raw;+ ta.style.position = 'fixed';+ ta.style.opacity = '0';+ document.body.appendChild(ta);+ ta.select();+ try { document.execCommand('copy'); } catch { /* nothing more we can do */ }+ ta.remove();+ }+ btn.textContent = 'Copied';+ btn.dataset.copied = 'true';+ setTimeout(() => {+ btn.textContent = 'Copy';+ btn.dataset.copied = 'false';+ }, 1600);+ });+ head.append(lang, btn);+ block.insertBefore(head, pre);+ }+ });+ }++ // ── 3. Responsive sidebar ───────────────────────────────────────────────+ function wireSidebar() {+ const toggle = document.querySelector('.wd-side-toggle');+ const side = document.getElementById('wd-side');+ if (!toggle || !side) return;+ const mq = window.matchMedia('(max-width: 880px)');+ const apply = () => {+ if (mq.matches) {+ side.hidden = true;+ toggle.setAttribute('aria-expanded', 'false');+ } else {+ side.hidden = false;+ }+ };+ toggle.addEventListener('click', () => {+ const open = side.hidden;+ side.hidden = !open;+ toggle.setAttribute('aria-expanded', String(open));+ });+ mq.addEventListener('change', apply);+ apply();+ }++ function init() {+ enhanceCodeBlocks();+ wireSidebar();+ }++ if (document.readyState === 'loading') {+ document.addEventListener('DOMContentLoaded', init);+ } else {+ init();+ }+})();diff --git a/public/docs/walk/embed-iframe.html b/public/docs/walk/embed-iframe.htmlnew file mode 100644index 000000000..d07607edb--- /dev/null+++ b/public/docs/walk/embed-iframe.html@@ -0,0 +1,149 @@+<!doctype html>+<html lang="en">+ <head>+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />+ <title>Iframe embed — Walk docs — three.ws</title>+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />+ <meta name="description" content="Embed a walking three.ws avatar with a plain iframe. Every /walk-embed query parameter — avatar, controls, env, autoplay, ground, orbit, bg — documented with a live preview." />+ <meta name="theme-color" content="#0a0a0a" />+ <link rel="canonical" href="https://three.ws/docs/walk/embed-iframe" />+ <link rel="shortcut icon" href="/favicon.ico" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/style.css" />+ <link rel="stylesheet" href="/footer.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/docs/walk/docs.css" />+ </head>+ <body>+ <a class="wd-skip" href="#wd-main">Skip to content</a>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <div class="wd-shell">+ <button class="wd-side-toggle" type="button" aria-expanded="false" aria-controls="wd-side">+ <span>Documentation menu</span><span aria-hidden="true">☰</span>+ </button>+ <aside class="wd-side" id="wd-side" aria-label="Walk documentation">+ <h2>Walk docs</h2>+ <nav aria-label="Walk documentation pages">+ <a href="/docs/walk">Overview</a>+ <a href="/docs/walk/getting-started">Getting started</a>+ </nav>+ <h2>Use it</h2>+ <nav aria-label="Using Walk">+ <a href="/docs/walk/walk-page">The walk page</a>+ <a href="/docs/walk/companion-mode">Companion mode</a>+ <a href="/docs/walk/chrome-extension">Chrome extension</a>+ </nav>+ <h2>Build with it</h2>+ <nav aria-label="Building with Walk">+ <a href="/docs/walk/embed-iframe" aria-current="page">Iframe embed</a>+ <a href="/docs/walk/embed-sdk">JavaScript SDK</a>+ <a href="/docs/walk/postmessage-events">postMessage events</a>+ <a href="/docs/walk/analytics">Analytics</a>+ </nav>+ <h2>Reference</h2>+ <nav aria-label="Reference"><a href="/docs/walk/changelog">Changelog</a></nav>+ </aside>++ <main class="wd-main" id="wd-main">+ <p class="wd-crumbs"><a href="/docs">Docs</a> / <a href="/docs/walk">Walk</a> / Iframe embed</p>+ <h1>Iframe embed</h1>+ <p class="wd-lede">+ <code>/walk-embed</code> is a chrome-less, transparent page that renders one+ avatar. It ships <code>frame-ancestors *</code>, so you can drop it into an+ <code><iframe></code> on any origin and configure everything through URL+ query parameters.+ </p>++ <h2>The minimal embed</h2>+ <div class="wd-code" data-lang="html" data-label="HTML">+ <pre><code><iframe+ src="https://three.ws/walk-embed?env=studio&autoplay=true&ground=false"+ width="240" height="340"+ style="border:0;background:transparent"+ allow="accelerometer; gyroscope; xr-spatial-tracking"+ title="three.ws walking avatar"></iframe></code></pre>+ </div>++ <div class="wd-demo">+ <div class="wd-demo-head"><span><span class="wd-demo-dot"></span>Live preview of the embed above</span><span>?env=studio&autoplay=true&ground=false</span></div>+ <iframe title="Live walking avatar embed" src="/walk-embed?env=studio&autoplay=true&ground=false&controls=none" height="320" loading="lazy" allow="accelerometer; gyroscope; xr-spatial-tracking"></iframe>+ </div>++ <div class="wd-note">+ <span class="wd-icon" aria-hidden="true">✱</span>+ <span>For a floating corner avatar that mounts itself and gives you a runtime API, use the one-tag <a href="/docs/walk/embed-sdk">JavaScript SDK</a> instead — it wraps this same iframe.</span>+ </div>++ <h2>Query parameters</h2>+ <div class="wd-table-wrap">+ <table class="wd-table">+ <thead><tr><th>Parameter</th><th>Values</th><th>Default</th><th>Description</th></tr></thead>+ <tbody>+ <tr><td><code>avatar</code></td><td>GLB / VRM URL, or avatar UUID</td><td class="wd-default">default avatar</td><td>The model to render. UUIDs are resolved through the avatar registry; URLs load directly.</td></tr>+ <tr><td><code>controls</code></td><td><code>joystick</code> · <code>keyboard</code> · <code>none</code></td><td class="wd-default"><code>joystick</code></td><td>Input method. <code>joystick</code> shows an on-screen stick, <code>keyboard</code> enables WASD/arrows, <code>none</code> disables input.</td></tr>+ <tr><td><code>env</code></td><td><code>studio</code> · <code>void</code> · <code>beach</code> · <code>sunset</code> · <code>night</code> · <code>grid</code></td><td class="wd-default"><code>studio</code></td><td>Scene preset — sets background, fog, ground, and lighting.</td></tr>+ <tr><td><code>autoplay</code></td><td><code>true</code> / <code>1</code></td><td class="wd-default">off</td><td>Start the avatar walking a slow circle so the embed is never static.</td></tr>+ <tr><td><code>ground</code></td><td><code>false</code> to hide</td><td class="wd-default">shown</td><td>The ground disc. Set <code>false</code> to float the avatar on the host background with only a soft shadow.</td></tr>+ <tr><td><code>orbit</code></td><td><code>false</code> to disable</td><td class="wd-default">enabled</td><td>Drag-to-orbit the camera. Disable for non-interactive, autoplay-only embeds.</td></tr>+ <tr><td><code>bg</code></td><td><code>transparent</code> or a hex colour</td><td class="wd-default"><code>transparent</code></td><td>Background fill. A hex value (e.g. <code>%23101820</code>) overrides the environment preset's clear colour.</td></tr>+ <tr><td><code>targetOrigin</code></td><td>an origin</td><td class="wd-default"><code>*</code></td><td>Restrict outbound <code>postMessage</code> events to a single origin.</td></tr>+ <tr><td><code>allowOrigins</code></td><td>comma-separated origins</td><td class="wd-default">allow any</td><td>Allow-list of origins permitted to send inbound commands.</td></tr>+ </tbody>+ </table>+ </div>+ <div class="wd-note">+ <span class="wd-icon" aria-hidden="true">✱</span>+ <span>In a URL, <code>#</code> in a hex colour must be encoded as <code>%23</code> — e.g. <code>?bg=%23101820</code>.</span>+ </div>++ <h2>Common recipes</h2>+ <h3>Floating, non-interactive avatar (no ground, no orbit)</h3>+ <div class="wd-code" data-lang="text" data-label="URL">+ <pre><code>/walk-embed?autoplay=true&ground=false&orbit=false&controls=none</code></pre>+ </div>+ <h3>Interactive avatar with a joystick on a beach</h3>+ <div class="wd-code" data-lang="text" data-label="URL">+ <pre><code>/walk-embed?env=beach&controls=joystick</code></pre>+ </div>+ <h3>Your own avatar with a solid backdrop</h3>+ <div class="wd-code" data-lang="text" data-label="URL">+ <pre><code>/walk-embed?avatar=YOUR-AVATAR-UUID&bg=%230b0f1a&ground=false</code></pre>+ </div>++ <h2>Driving it live</h2>+ <p>+ Once mounted you can change the avatar, environment, motion, and speech at runtime+ by posting messages to the iframe. The full message protocol — including the+ events the iframe emits back to you — is documented in+ <a href="/docs/walk/postmessage-events">postMessage events</a>.+ </p>+ <div class="wd-code" data-lang="js" data-label="JavaScript">+ <pre><code>const frame = document.querySelector('iframe');+// swap the avatar+frame.contentWindow.postMessage({ type: 'walk:setAvatar', id: 'NEW-UUID' }, '*');+// change the world+frame.contentWindow.postMessage({ type: 'walk:setEnv', env: 'night' }, '*');+// say something+frame.contentWindow.postMessage({ type: 'walk:narrate', text: 'Hello!' }, '*');</code></pre>+ </div>++ <div class="wd-pagefoot">+ <a class="wd-edit" href="https://github.com/nirholas/three.ws/edit/main/public/docs/walk/embed-iframe.html" rel="noopener"><span aria-hidden="true">✎</span> Edit this page on GitHub</a>+ <div class="wd-nextprev">+ <a href="/docs/walk/walk-page"><span>Previous</span>← The walk page</a>+ <a href="/docs/walk/embed-sdk"><span>Next</span>JavaScript SDK →</a>+ </div>+ </div>+ </main>+ </div>++ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ <script src="/brand.js" defer></script>+ <script type="module" src="/docs/walk/docs.js"></script>+ </body>+</html>diff --git a/public/docs/walk/embed-sdk.html b/public/docs/walk/embed-sdk.htmlnew file mode 100644index 000000000..c4b7fb00c--- /dev/null+++ b/public/docs/walk/embed-sdk.html@@ -0,0 +1,187 @@+<!doctype html>+<html lang="en">+ <head>+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />+ <title>JavaScript SDK — Walk docs — three.ws</title>+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />+ <meta name="description" content="The walk-embed-sdk.js host API. Mount a floating avatar with one script tag and control it at runtime through window.ThreeWalkAvatar: setAvatar, setEnv, setPosition, setSize, on/off events, and track." />+ <meta name="theme-color" content="#0a0a0a" />+ <link rel="canonical" href="https://three.ws/docs/walk/embed-sdk" />+ <link rel="shortcut icon" href="/favicon.ico" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/style.css" />+ <link rel="stylesheet" href="/footer.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/docs/walk/docs.css" />+ </head>+ <body>+ <a class="wd-skip" href="#wd-main">Skip to content</a>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <div class="wd-shell">+ <button class="wd-side-toggle" type="button" aria-expanded="false" aria-controls="wd-side">+ <span>Documentation menu</span><span aria-hidden="true">☰</span>+ </button>+ <aside class="wd-side" id="wd-side" aria-label="Walk documentation">+ <h2>Walk docs</h2>+ <nav aria-label="Walk documentation pages">+ <a href="/docs/walk">Overview</a>+ <a href="/docs/walk/getting-started">Getting started</a>+ </nav>+ <h2>Use it</h2>+ <nav aria-label="Using Walk">+ <a href="/docs/walk/walk-page">The walk page</a>+ <a href="/docs/walk/companion-mode">Companion mode</a>+ <a href="/docs/walk/chrome-extension">Chrome extension</a>+ </nav>+ <h2>Build with it</h2>+ <nav aria-label="Building with Walk">+ <a href="/docs/walk/embed-iframe">Iframe embed</a>+ <a href="/docs/walk/embed-sdk" aria-current="page">JavaScript SDK</a>+ <a href="/docs/walk/postmessage-events">postMessage events</a>+ <a href="/docs/walk/analytics">Analytics</a>+ </nav>+ <h2>Reference</h2>+ <nav aria-label="Reference"><a href="/docs/walk/changelog">Changelog</a></nav>+ </aside>++ <main class="wd-main" id="wd-main">+ <p class="wd-crumbs"><a href="/docs">Docs</a> / <a href="/docs/walk">Walk</a> / JavaScript SDK</p>+ <h1>JavaScript SDK</h1>+ <p class="wd-lede">+ <code>walk-embed-sdk.js</code> is a standalone, zero-dependency script. It reads+ <code>data-*</code> attributes off its own tag, injects a fixed-position+ transparent iframe, and exposes <code>window.ThreeWalkAvatar</code> for runtime+ control — plus it re-emits the iframe's <code>postMessage</code> events as+ document-level <code>CustomEvent</code>s so you never touch <code>postMessage</code>+ directly.+ </p>++ <h2>Install</h2>+ <p>One tag. It auto-mounts on DOM ready unless you set <code>data-auto="false"</code>.</p>+ <div class="wd-code" data-lang="html" data-label="HTML">+ <pre><code><script src="https://three.ws/walk-embed-sdk.js"+ data-avatar="YOUR-AVATAR-UUID"+ data-position="bottom-right"+ data-width="220"+ data-height="320"+ data-env="studio"></script></code></pre>+ </div>++ <h2>Script attributes</h2>+ <div class="wd-table-wrap">+ <table class="wd-table">+ <thead><tr><th>Attribute</th><th>Values</th><th>Default</th><th>Description</th></tr></thead>+ <tbody>+ <tr><td><code>data-avatar</code></td><td>avatar UUID / GLB URL</td><td class="wd-default">default avatar</td><td>The model to render.</td></tr>+ <tr><td><code>data-position</code></td><td><code>bottom-right</code> · <code>bottom-left</code> · <code>top-right</code> · <code>top-left</code></td><td class="wd-default"><code>bottom-right</code></td><td>Corner to anchor the floating avatar.</td></tr>+ <tr><td><code>data-width</code> / <code>data-height</code></td><td>pixels</td><td class="wd-default"><code>220</code> / <code>320</code></td><td>Iframe size.</td></tr>+ <tr><td><code>data-controls</code></td><td><code>none</code> · <code>joystick</code> · <code>keyboard</code></td><td class="wd-default"><code>none</code></td><td>Input method. With <code>none</code>, clicks pass through to your page.</td></tr>+ <tr><td><code>data-env</code></td><td>environment id</td><td class="wd-default"><code>studio</code></td><td>Scene preset.</td></tr>+ <tr><td><code>data-autoplay</code></td><td><code>true</code> / <code>false</code></td><td class="wd-default"><code>true</code></td><td>Auto-walk so the avatar is never static.</td></tr>+ <tr><td><code>data-ground</code></td><td><code>true</code> / <code>false</code></td><td class="wd-default"><code>false</code></td><td>Show the ground disc. Off by default for floating corner embeds.</td></tr>+ <tr><td><code>data-orbit</code></td><td><code>true</code> / <code>false</code></td><td class="wd-default"><code>false</code></td><td>Allow drag-to-orbit. Off by default for corner embeds.</td></tr>+ <tr><td><code>data-bg</code></td><td><code>transparent</code> / hex</td><td class="wd-default"><code>transparent</code></td><td>Background fill.</td></tr>+ <tr><td><code>data-z-index</code></td><td>integer</td><td class="wd-default"><code>2147483640</code></td><td>Stacking order of the floating container.</td></tr>+ <tr><td><code>data-auto</code></td><td><code>true</code> / <code>false</code></td><td class="wd-default"><code>true</code></td><td>Auto-mount on DOM ready. Set <code>false</code> to mount manually.</td></tr>+ </tbody>+ </table>+ </div>++ <h2>The <code>window.ThreeWalkAvatar</code> API</h2>+ <p>The SDK exposes this object once it loads. Every method below is real and shipped.</p>+ <div class="wd-table-wrap">+ <table class="wd-table">+ <thead><tr><th>Method</th><th>Description</th></tr></thead>+ <tbody>+ <tr><td><code>mount(target?)</code></td><td>Mount the floating iframe. Idempotent. <code>target</code> may be an element or selector; defaults to <code><body></code>. Returns the container element.</td></tr>+ <tr><td><code>unmount()</code></td><td>Remove the iframe and detach listeners.</td></tr>+ <tr><td><code>setAvatar(id)</code></td><td>Swap the avatar live (UUID or GLB URL).</td></tr>+ <tr><td><code>setEnv(env)</code></td><td>Change the environment preset.</td></tr>+ <tr><td><code>setMotion(motion)</code></td><td>Set motion: <code>'idle'</code>, <code>'walk'</code>, or <code>'run'</code>.</td></tr>+ <tr><td><code>setPosition(pos)</code></td><td>Re-anchor to a corner (<code>bottom-right</code> etc.).</td></tr>+ <tr><td><code>setSize(w, h)</code></td><td>Resize the floating container in pixels.</td></tr>+ <tr><td><code>resetPose()</code></td><td>Recenter the avatar and reset its facing.</td></tr>+ <tr><td><code>on(name, cb)</code></td><td>Subscribe to an event (see below).</td></tr>+ <tr><td><code>off(name, cb)</code></td><td>Remove a previously registered listener.</td></tr>+ <tr><td><code>getOptions()</code></td><td>Return a read-only snapshot of the current options.</td></tr>+ </tbody>+ </table>+ </div>++ <h2>Events</h2>+ <p>+ The SDK forwards the iframe's <code>postMessage</code> events two ways: as+ document-level <code>CustomEvent</code>s and through <code>on()/off()</code>.+ The forwarded names are <code>walk:ready</code>, <code>walk:position</code>,+ <code>walk:error</code>, and <code>walk:avatarChanged</code>.+ </p>+ <div class="wd-code" data-lang="js" data-label="JavaScript">+ <pre><code>// Either listen on the document…+document.addEventListener('walk:ready', (e) => {+ console.log('avatar loaded', e.detail);+});++// …or through the API.+ThreeWalkAvatar.on('walk:position', ({ x, z, motion }) => {+ console.log(`at ${x.toFixed(2)}, ${z.toFixed(2)} — ${motion}`);+});</code></pre>+ </div>++ <h2>Runtime control example</h2>+ <div class="wd-code" data-lang="js" data-label="JavaScript">+ <pre><code>const api = window.ThreeWalkAvatar;++api.setPosition('top-right');+api.setSize(180, 260);+api.setEnv('night');+api.setAvatar('NEW-AVATAR-UUID');+api.setMotion('run');</code></pre>+ </div>++ <h2>Conversion tracking</h2>+ <p>+ On the dedicated <a href="/walk">walk page</a> (and any surface that boots the+ full walk runtime), <code>window.ThreeWalkAvatar.track(name, opts?)</code> records+ a creator-defined conversion event against the current avatar. It posts+ immediately and powers the funnel in the+ <a href="/docs/walk/analytics">analytics dashboard</a>.+ </p>+ <div class="wd-code" data-lang="js" data-label="JavaScript">+ <pre><code>// name is capped at 64 chars; value is an optional number.+window.ThreeWalkAvatar.track('subscribe', { value: 9 });</code></pre>+ </div>+ <div class="wd-note">+ <span class="wd-icon" aria-hidden="true">✱</span>+ <span><code>track()</code> is provided by the full walk runtime. The lightweight floating-corner SDK focuses on mount and control; for conversion analytics, fire events from a page running the walk runtime.</span>+ </div>++ <h2>Manual mounting</h2>+ <div class="wd-code" data-lang="html" data-label="HTML">+ <pre><code><script src="https://three.ws/walk-embed-sdk.js"+ data-auto="false"></script>+<script>+ // mount into a specific container when you're ready+ ThreeWalkAvatar.mount('#avatar-slot');+</script></code></pre>+ </div>++ <div class="wd-pagefoot">+ <a class="wd-edit" href="https://github.com/nirholas/three.ws/edit/main/public/docs/walk/embed-sdk.html" rel="noopener"><span aria-hidden="true">✎</span> Edit this page on GitHub</a>+ <div class="wd-nextprev">+ <a href="/docs/walk/embed-iframe"><span>Previous</span>← Iframe embed</a>+ <a href="/docs/walk/postmessage-events"><span>Next</span>postMessage events →</a>+ </div>+ </div>+ </main>+ </div>++ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ <script src="/brand.js" defer></script>+ <script type="module" src="/docs/walk/docs.js"></script>+ </body>+</html>diff --git a/public/docs/walk/getting-started.html b/public/docs/walk/getting-started.htmlnew file mode 100644index 000000000..b1c1774cf--- /dev/null+++ b/public/docs/walk/getting-started.html@@ -0,0 +1,141 @@+<!doctype html>+<html lang="en">+ <head>+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />+ <title>Getting started — Walk docs — three.ws</title>+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />+ <meta name="description" content="Walk your first three.ws avatar in five minutes: try the walk page, drop a one-tag embed onto any site, or turn on the site-wide companion." />+ <meta name="theme-color" content="#0a0a0a" />+ <link rel="canonical" href="https://three.ws/docs/walk/getting-started" />+ <link rel="shortcut icon" href="/favicon.ico" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/style.css" />+ <link rel="stylesheet" href="/footer.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/docs/walk/docs.css" />+ </head>+ <body>+ <a class="wd-skip" href="#wd-main">Skip to content</a>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <div class="wd-shell">+ <button class="wd-side-toggle" type="button" aria-expanded="false" aria-controls="wd-side">+ <span>Documentation menu</span><span aria-hidden="true">☰</span>+ </button>+ <aside class="wd-side" id="wd-side" aria-label="Walk documentation">+ <h2>Walk docs</h2>+ <nav aria-label="Walk documentation pages">+ <a href="/docs/walk">Overview</a>+ <a href="/docs/walk/getting-started" aria-current="page">Getting started</a>+ </nav>+ <h2>Use it</h2>+ <nav aria-label="Using Walk">+ <a href="/docs/walk/walk-page">The walk page</a>+ <a href="/docs/walk/companion-mode">Companion mode</a>+ <a href="/docs/walk/chrome-extension">Chrome extension</a>+ </nav>+ <h2>Build with it</h2>+ <nav aria-label="Building with Walk">+ <a href="/docs/walk/embed-iframe">Iframe embed</a>+ <a href="/docs/walk/embed-sdk">JavaScript SDK</a>+ <a href="/docs/walk/postmessage-events">postMessage events</a>+ <a href="/docs/walk/analytics">Analytics</a>+ </nav>+ <h2>Reference</h2>+ <nav aria-label="Reference"><a href="/docs/walk/changelog">Changelog</a></nav>+ </aside>++ <main class="wd-main" id="wd-main">+ <p class="wd-crumbs"><a href="/docs">Docs</a> / <a href="/docs/walk">Walk</a> / Getting started</p>+ <h1>Walk your first avatar in five minutes</h1>+ <p class="wd-lede">+ Three ways in, fastest first. Try the live page, drop an avatar onto your own+ site with a single script tag, or turn on the companion that walks with you+ across three.ws.+ </p>++ <h2>1 · Try it live (zero setup)</h2>+ <p>+ Open <a href="/walk">three.ws/walk</a>. Move with <kbd>W</kbd> <kbd>A</kbd>+ <kbd>S</kbd> <kbd>D</kbd> or the arrow keys, hold <kbd>Shift</kbd> to run,+ press <kbd>Space</kbd> to jump, and tap a number key for a gesture. On a phone,+ use the on-screen joysticks. The full control reference lives on+ <a href="/docs/walk/walk-page">the walk page docs</a>.+ </p>+ <div class="wd-demo">+ <div class="wd-demo-head"><span><span class="wd-demo-dot"></span>Embedded preview</span><span>autoplay walk</span></div>+ <iframe title="Walking avatar preview" src="/walk-embed?controls=none&autoplay=true&ground=false&env=studio" height="300" loading="lazy" allow="accelerometer; gyroscope; xr-spatial-tracking"></iframe>+ </div>++ <h2>2 · Put an avatar on your own site (one tag)</h2>+ <p>+ The fastest integration is a single <code><script></code> tag. Drop this+ into the <code><body></code> of any page on any origin — no build step, no+ framework, no API key:+ </p>+ <div class="wd-code" data-lang="html" data-label="HTML">+ <pre><code><script src="https://three.ws/walk-embed-sdk.js"+ data-position="bottom-right"+ data-width="220"+ data-height="320"></script></code></pre>+ </div>+ <p>+ That injects a fixed-position, transparent iframe in the corner and starts a+ slow circular walk. To show a specific avatar, add its id:+ </p>+ <div class="wd-code" data-lang="html" data-label="HTML">+ <pre><code><script src="https://three.ws/walk-embed-sdk.js"+ data-avatar="YOUR-AVATAR-UUID"+ data-position="bottom-left"+ data-env="beach"></script></code></pre>+ </div>+ <div class="wd-note">+ <span class="wd-icon" aria-hidden="true">✱</span>+ <span>Omit <code>data-avatar</code> and the SDK falls back to the bundled default avatar — served same-origin, so it works in dev, preview, and production without any CORS setup.</span>+ </div>+ <p>+ Want full programmatic control instead of attributes? See the+ <a href="/docs/walk/embed-sdk">JavaScript SDK reference</a>. Prefer to manage+ the iframe yourself? See the <a href="/docs/walk/embed-iframe">iframe embed+ guide</a>.+ </p>++ <h2>3 · Walk across three.ws (companion mode)</h2>+ <p>+ On three.ws itself, the <strong>Walk</strong> button in the top navigation+ detaches your avatar from the page and lets it stroll around — and it follows+ you as you navigate between pages. You can also force it on with a query+ parameter on any three.ws URL:+ </p>+ <div class="wd-code" data-lang="text" data-label="URL">+ <pre><code>https://three.ws/?walk=1</code></pre>+ </div>+ <p>Read more in <a href="/docs/walk/companion-mode">Companion mode</a>.</p>++ <h2>Next steps</h2>+ <ul>+ <li><a href="/docs/walk/walk-page">The walk page</a> — every control, camera, environment, gesture, and AR.</li>+ <li><a href="/docs/walk/embed-sdk">JavaScript SDK</a> — drive the avatar at runtime: <code>setAvatar</code>, <code>setEnv</code>, <code>setPosition</code>, events.</li>+ <li><a href="/docs/walk/analytics">Analytics</a> — measure sessions, distance, and conversions per avatar.</li>+ <li><a href="/docs/walk/chrome-extension">Chrome extension</a> — your avatar on every website you visit.</li>+ </ul>++ <div class="wd-pagefoot">+ <a class="wd-edit" href="https://github.com/nirholas/three.ws/edit/main/public/docs/walk/getting-started.html" rel="noopener"><span aria-hidden="true">✎</span> Edit this page on GitHub</a>+ <div class="wd-nextprev">+ <a href="/docs/walk"><span>Previous</span>← Overview</a>+ <a href="/docs/walk/walk-page"><span>Next</span>The walk page →</a>+ </div>+ </div>+ </main>+ </div>++ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ <script src="/brand.js" defer></script>+ <script type="module" src="/docs/walk/docs.js"></script>+ </body>+</html>diff --git a/public/docs/walk/index.html b/public/docs/walk/index.htmlnew file mode 100644index 000000000..c9057db36--- /dev/null+++ b/public/docs/walk/index.html@@ -0,0 +1,151 @@+<!doctype html>+<html lang="en">+ <head>+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />+ <title>Walk avatar docs — three.ws</title>+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />+ <meta name="description" content="Developer and user documentation for the three.ws walking-avatar system: the /walk page, iframe embeds, the JavaScript SDK, the postMessage event contract, companion mode, analytics, and the Chrome extension." />+ <meta name="theme-color" content="#0a0a0a" />+ <link rel="canonical" href="https://three.ws/docs/walk" />+ <link rel="shortcut icon" href="/favicon.ico" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/style.css" />+ <link rel="stylesheet" href="/footer.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/docs/walk/docs.css" />+ </head>+ <body>+ <a class="wd-skip" href="#wd-main">Skip to content</a>+ <header>+ <div id="nav-container"></div>+ </header>+ <script src="/nav.js"></script>++ <div class="wd-shell">+ <button class="wd-side-toggle" type="button" aria-expanded="false" aria-controls="wd-side">+ <span>Documentation menu</span>+ <span aria-hidden="true">☰</span>+ </button>++ <aside class="wd-side" id="wd-side" aria-label="Walk documentation">+ <h2>Walk docs</h2>+ <nav aria-label="Walk documentation pages">+ <a href="/docs/walk" aria-current="page">Overview</a>+ <a href="/docs/walk/getting-started">Getting started</a>+ </nav>+ <h2>Use it</h2>+ <nav aria-label="Using Walk">+ <a href="/docs/walk/walk-page">The walk page</a>+ <a href="/docs/walk/companion-mode">Companion mode</a>+ <a href="/docs/walk/chrome-extension">Chrome extension</a>+ </nav>+ <h2>Build with it</h2>+ <nav aria-label="Building with Walk">+ <a href="/docs/walk/embed-iframe">Iframe embed</a>+ <a href="/docs/walk/embed-sdk">JavaScript SDK</a>+ <a href="/docs/walk/postmessage-events">postMessage events</a>+ <a href="/docs/walk/analytics">Analytics</a>+ </nav>+ <h2>Reference</h2>+ <nav aria-label="Reference">+ <a href="/docs/walk/changelog">Changelog</a>+ </nav>+ </aside>++ <main class="wd-main" id="wd-main">+ <p class="wd-crumbs"><a href="/docs">Docs</a> / Walk</p>+ <h1>Walk avatar documentation</h1>+ <p class="wd-lede">+ Walk turns a three.ws avatar into a real 3D character that moves through the+ web — on the dedicated walk page, as a floating companion on any page, as a+ one-tag embed on your own site, or as a Chrome extension that strolls across+ every tab. This hub documents everything the system actually ships today.+ </p>++ <div class="wd-demo">+ <div class="wd-demo-head"><span><span class="wd-demo-dot"></span>Live embed — a real avatar, rendered now</span><span>/walk-embed</span></div>+ <iframe+ title="Live walking avatar embed"+ src="/walk-embed?controls=none&autoplay=true&ground=false&env=studio"+ height="320"+ loading="lazy"+ allow="accelerometer; gyroscope; xr-spatial-tracking"+ ></iframe>+ </div>++ <h2>Start here</h2>+ <div class="wd-cards">+ <a class="wd-card" href="/docs/walk/getting-started">+ <h3>Getting started →</h3>+ <p>Walk your first avatar in five minutes — page, embed, or companion.</p>+ </a>+ <a class="wd-card" href="/docs/walk/walk-page">+ <h3>The walk page →</h3>+ <p>Controls, four camera modes, six environments, gestures, multiplayer, and AR.</p>+ </a>+ <a class="wd-card" href="/docs/walk/embed-iframe">+ <h3>Iframe embed →</h3>+ <p>Every <code>/walk-embed</code> query parameter, with a live preview to copy.</p>+ </a>+ <a class="wd-card" href="/docs/walk/embed-sdk">+ <h3>JavaScript SDK →</h3>+ <p>The <code>window.ThreeWalkAvatar</code> host API: mount, control, listen.</p>+ </a>+ <a class="wd-card" href="/docs/walk/postmessage-events">+ <h3>postMessage events →</h3>+ <p>The full bi-directional contract between a host page and the iframe.</p>+ </a>+ <a class="wd-card" href="/docs/walk/companion-mode">+ <h3>Companion mode →</h3>+ <p>A site-wide avatar that walks with you between three.ws pages.</p>+ </a>+ <a class="wd-card" href="/docs/walk/analytics">+ <h3>Analytics →</h3>+ <p>Sessions, distance, top origins, and conversion events per avatar.</p>+ </a>+ <a class="wd-card" href="/docs/walk/chrome-extension">+ <h3>Chrome extension →</h3>+ <p>Your avatar on every site, with optional read-aloud narration.</p>+ </a>+ </div>++ <h2>What "Walk" is made of</h2>+ <p>The system is four surfaces over one rendering engine:</p>+ <ul>+ <li><strong>The walk page</strong> (<code>/walk</code>) — the full experience: WASD/touch movement, four camera modes, six worlds, gestures, live multiplayer presence, AR camera passthrough, and a global distance leaderboard.</li>+ <li><strong>The embed</strong> (<code>/walk-embed</code>) — a chrome-less, transparent iframe that renders a single avatar. Configured entirely by URL query parameters and driven live over <code>postMessage</code>.</li>+ <li><strong>The SDK</strong> (<code>/walk-embed-sdk.js</code>) — a zero-dependency script tag that mounts the embed as a floating corner avatar and exposes <code>window.ThreeWalkAvatar</code> for runtime control and event listening.</li>+ <li><strong>Companion mode & the extension</strong> — the same avatar following you across three.ws pages, or across every website via the Chrome extension.</li>+ </ul>++ <div class="wd-note">+ <span class="wd-icon" aria-hidden="true">✱</span>+ <span>Every example on these pages is taken from the shipped source. There are no placeholders and no "coming soon" sections — if it is documented here, it works today.</span>+ </div>++ <h2>Conventions</h2>+ <ul>+ <li>URLs are shown relative to <code>https://three.ws</code>. From a third-party page, prefix the origin (e.g. <code>https://three.ws/walk-embed</code>).</li>+ <li>Code blocks have a <strong>Copy</strong> button. The copied text is the raw source, never the on-screen syntax tint.</li>+ <li>Every page has an <strong>Edit this page</strong> link to its file in the canonical GitHub repository.</li>+ </ul>++ <div class="wd-pagefoot">+ <a class="wd-edit" href="https://github.com/nirholas/three.ws/edit/main/public/docs/walk/index.html" rel="noopener">+ <span aria-hidden="true">✎</span> Edit this page on GitHub+ </a>+ <div class="wd-nextprev">+ <a href="/docs/walk/getting-started"><span>Next</span>Getting started →</a>+ </div>+ </div>+ </main>+ </div>++ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ <script src="/brand.js" defer></script>+ <script type="module" src="/docs/walk/docs.js"></script>+ </body>+</html>diff --git a/public/docs/walk/postmessage-events.html b/public/docs/walk/postmessage-events.htmlnew file mode 100644index 000000000..87648d70c--- /dev/null+++ b/public/docs/walk/postmessage-events.html@@ -0,0 +1,188 @@+<!doctype html>+<html lang="en">+ <head>+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />+ <title>postMessage events — Walk docs — three.ws</title>+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />+ <meta name="description" content="The bi-directional postMessage contract between a host page and the three.ws walk-embed iframe: the channelled envelope, inbound commands, outbound events, the handshake, and origin handling." />+ <meta name="theme-color" content="#0a0a0a" />+ <link rel="canonical" href="https://three.ws/docs/walk/postmessage-events" />+ <link rel="shortcut icon" href="/favicon.ico" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/style.css" />+ <link rel="stylesheet" href="/footer.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/docs/walk/docs.css" />+ </head>+ <body>+ <a class="wd-skip" href="#wd-main">Skip to content</a>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <div class="wd-shell">+ <button class="wd-side-toggle" type="button" aria-expanded="false" aria-controls="wd-side">+ <span>Documentation menu</span><span aria-hidden="true">☰</span>+ </button>+ <aside class="wd-side" id="wd-side" aria-label="Walk documentation">+ <h2>Walk docs</h2>+ <nav aria-label="Walk documentation pages">+ <a href="/docs/walk">Overview</a>+ <a href="/docs/walk/getting-started">Getting started</a>+ </nav>+ <h2>Use it</h2>+ <nav aria-label="Using Walk">+ <a href="/docs/walk/walk-page">The walk page</a>+ <a href="/docs/walk/companion-mode">Companion mode</a>+ <a href="/docs/walk/chrome-extension">Chrome extension</a>+ </nav>+ <h2>Build with it</h2>+ <nav aria-label="Building with Walk">+ <a href="/docs/walk/embed-iframe">Iframe embed</a>+ <a href="/docs/walk/embed-sdk">JavaScript SDK</a>+ <a href="/docs/walk/postmessage-events" aria-current="page">postMessage events</a>+ <a href="/docs/walk/analytics">Analytics</a>+ </nav>+ <h2>Reference</h2>+ <nav aria-label="Reference"><a href="/docs/walk/changelog">Changelog</a></nav>+ </aside>++ <main class="wd-main" id="wd-main">+ <p class="wd-crumbs"><a href="/docs">Docs</a> / <a href="/docs/walk">Walk</a> / postMessage events</p>+ <h1>postMessage events</h1>+ <p class="wd-lede">+ The host page and the <code>/walk-embed</code> iframe talk over+ <code>window.postMessage</code>. This is the wire contract: the message+ envelope, the commands you send in, the events the iframe sends back, and how+ origins are handled.+ </p>++ <h2>The envelope</h2>+ <p>Every message is a plain object on the <code>three-walk</code> channel at protocol version <code>1</code>:</p>+ <div class="wd-code" data-lang="js" data-label="JavaScript">+ <pre><code>{+ channel: 'three-walk', // namespace guard — ignore anything else+ v: 1, // protocol version+ type: 'walk:moved', // see commands / events below+ id: '<correlation id>', // optional; echoed on a command's result+ // ...type-specific payload+}</code></pre>+ </div>+ <div class="wd-note">+ <span class="wd-icon" aria-hidden="true">✱</span>+ <span>The legacy flat shape — a bare <code>{ type: 'walk:*' }</code> with no <code>channel</code>/<code>v</code> — is still accepted inbound for backward compatibility with embeds shipped before this contract existed. New integrations should use the channelled envelope.</span>+ </div>++ <h2>Handshake</h2>+ <ul>+ <li>iframe → host: <code>walk:loaded</code> fires once, when the avatar is ready.</li>+ <li>host → iframe: <code>walk:ping</code> (optional) makes the iframe re-emit <code>walk:loaded</code>.</li>+ </ul>+ <p>If you mount the iframe after it has already loaded, send <code>walk:ping</code> instead of racing the initial <code>walk:loaded</code>.</p>++ <h2>Inbound commands (host → iframe)</h2>+ <div class="wd-table-wrap">+ <table class="wd-table">+ <thead><tr><th>type</th><th>payload</th><th>Effect</th></tr></thead>+ <tbody>+ <tr><td><code>walk:ping</code></td><td>—</td><td>Re-emit <code>walk:loaded</code>.</td></tr>+ <tr><td><code>walk:move</code></td><td><code>{ x, y, run? }</code> or <code>{ dir, meters? }</code></td><td>Analog vector (each axis −1…1) or a discrete step (<code>dir</code>: <code>forward</code>/<code>back</code>/<code>left</code>/<code>right</code>, <code>meters</code> 0…12).</td></tr>+ <tr><td><code>walk:gesture</code></td><td><code>{ gesture }</code></td><td>Play <code>idle</code>, <code>walk</code>, <code>run</code>, <code>wave</code>, or <code>jump</code>.</td></tr>+ <tr><td><code>walk:say</code></td><td><code>{ text, durationMs? }</code></td><td>Show a speech bubble. Text is capped at 280 chars; duration clamps to 800–20000 ms.</td></tr>+ <tr><td><code>walk:setEnvironment</code></td><td><code>{ env }</code></td><td>Switch world: <code>studio</code>, <code>void</code>, <code>beach</code>, <code>sunset</code>, <code>night</code>, or <code>grid</code>.</td></tr>+ <tr><td><code>walk:setAvatar</code></td><td><code>{ id }</code></td><td>Swap the avatar (UUID or GLB/VRM URL, ≤2048 chars).</td></tr>+ <tr><td><code>walk:config</code></td><td><code>{ speed? }</code></td><td>Set walk speed multiplier; clamps to 0.3–3.</td></tr>+ <tr><td><code>walk:reset</code></td><td>—</td><td>Recenter the avatar and reset its pose.</td></tr>+ </tbody>+ </table>+ </div>+ <h3>Legacy command aliases (still accepted)</h3>+ <div class="wd-table-wrap">+ <table class="wd-table">+ <thead><tr><th>Legacy type</th><th>Canonical</th></tr></thead>+ <tbody>+ <tr><td><code>walk:setEnv</code></td><td><code>walk:setEnvironment</code></td></tr>+ <tr><td><code>walk:setMotion</code></td><td><code>walk:gesture</code></td></tr>+ <tr><td><code>walk:narrate</code></td><td><code>walk:say</code></td></tr>+ <tr><td><code>walk:resetPose</code></td><td><code>walk:reset</code></td></tr>+ </tbody>+ </table>+ </div>++ <h2>Outbound events (iframe → host)</h2>+ <div class="wd-table-wrap">+ <table class="wd-table">+ <thead><tr><th>type</th><th>payload</th><th>When</th></tr></thead>+ <tbody>+ <tr><td><code>walk:loaded</code></td><td><code>{ avatar }</code></td><td>Once, when the avatar is ready.</td></tr>+ <tr><td><code>walk:moved</code></td><td><code>{ x, z, yaw, motion }</code></td><td>As the avatar moves (also emitted as legacy <code>walk:position</code>).</td></tr>+ <tr><td><code>walk:spoke</code></td><td><code>{ text }</code></td><td>After a <code>walk:say</code> command renders.</td></tr>+ <tr><td><code>walk:gestured</code></td><td><code>{ gesture }</code></td><td>After a gesture plays.</td></tr>+ <tr><td><code>walk:environment</code></td><td><code>{ env }</code></td><td>After the environment changes.</td></tr>+ <tr><td><code>walk:avatarChanged</code></td><td><code>{ id }</code></td><td>After an avatar swap succeeds.</td></tr>+ <tr><td><code>walk:error</code></td><td><code>{ error, code? }</code></td><td>On a load or command failure.</td></tr>+ </tbody>+ </table>+ </div>++ <h2>Origin & security</h2>+ <p>+ The embed is designed to run on <em>any</em> origin (it ships+ <code>frame-ancestors *</code>), so the host's origin cannot be allow-listed in+ advance. The real authentication is the message <strong>source</strong>: the+ iframe only accepts messages from its own parent window, and the host SDK only+ accepts messages from the iframe it mounted. As a belt-and-suspenders filter,+ a security-conscious integrator can pass an explicit+ <code>allowOrigins</code> list to the embed when the exact origin is known.+ </p>+ <div class="wd-warn">+ <span class="wd-icon" aria-hidden="true">▲</span>+ <span>When you listen for events on the host side, always verify <code>event.source === iframe.contentWindow</code> before trusting a message, and check <code>data.channel === 'three-walk'</code> (or that the bare <code>type</code> is a known <code>walk:*</code> event).</span>+ </div>++ <h2>End-to-end example</h2>+ <div class="wd-code" data-lang="js" data-label="JavaScript">+ <pre><code>const frame = document.querySelector('iframe');++// Listen for events from the iframe.+window.addEventListener('message', (e) => {+ if (e.source !== frame.contentWindow) return; // source check+ const msg = e.data;+ if (!msg || msg.channel !== 'three-walk') return; // channel guard+ if (msg.type === 'walk:loaded') {+ // Avatar ready — start driving it.+ frame.contentWindow.postMessage(+ { channel: 'three-walk', v: 1, type: 'walk:setEnvironment', env: 'night' }, '*');+ frame.contentWindow.postMessage(+ { channel: 'three-walk', v: 1, type: 'walk:say', text: 'Welcome!' }, '*');+ }+ if (msg.type === 'walk:moved') {+ console.log('moved', msg.x, msg.z, msg.yaw, msg.motion);+ }+});++// If the frame may already be loaded, nudge it to re-announce.+frame.contentWindow.postMessage({ channel: 'three-walk', v: 1, type: 'walk:ping' }, '*');</code></pre>+ </div>+ <div class="wd-note">+ <span class="wd-icon" aria-hidden="true">✱</span>+ <span>Using the <a href="/docs/walk/embed-sdk">JavaScript SDK</a>? It does the source check, channel guard, and event forwarding for you — just call <code>ThreeWalkAvatar.on('walk:ready', …)</code>.</span>+ </div>++ <div class="wd-pagefoot">+ <a class="wd-edit" href="https://github.com/nirholas/three.ws/edit/main/public/docs/walk/postmessage-events.html" rel="noopener"><span aria-hidden="true">✎</span> Edit this page on GitHub</a>+ <div class="wd-nextprev">+ <a href="/docs/walk/embed-sdk"><span>Previous</span>← JavaScript SDK</a>+ <a href="/docs/walk/analytics"><span>Next</span>Analytics →</a>+ </div>+ </div>+ </main>+ </div>++ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ <script src="/brand.js" defer></script>+ <script type="module" src="/docs/walk/docs.js"></script>+ </body>+</html>diff --git a/public/docs/walk/walk-page.html b/public/docs/walk/walk-page.htmlnew file mode 100644index 000000000..b4cad18de--- /dev/null+++ b/public/docs/walk/walk-page.html@@ -0,0 +1,219 @@+<!doctype html>+<html lang="en">+ <head>+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />+ <title>The walk page — Walk docs — three.ws</title>+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />+ <meta name="description" content="The three.ws walk page: keyboard and touch controls, four camera modes, six environments, eight gestures, live multiplayer presence, AR camera passthrough, and the URL parameters it reads." />+ <meta name="theme-color" content="#0a0a0a" />+ <link rel="canonical" href="https://three.ws/docs/walk/walk-page" />+ <link rel="shortcut icon" href="/favicon.ico" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/style.css" />+ <link rel="stylesheet" href="/footer.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/docs/walk/docs.css" />+ </head>+ <body>+ <a class="wd-skip" href="#wd-main">Skip to content</a>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <div class="wd-shell">+ <button class="wd-side-toggle" type="button" aria-expanded="false" aria-controls="wd-side">+ <span>Documentation menu</span><span aria-hidden="true">☰</span>+ </button>+ <aside class="wd-side" id="wd-side" aria-label="Walk documentation">+ <h2>Walk docs</h2>+ <nav aria-label="Walk documentation pages">+ <a href="/docs/walk">Overview</a>+ <a href="/docs/walk/getting-started">Getting started</a>+ </nav>+ <h2>Use it</h2>+ <nav aria-label="Using Walk">+ <a href="/docs/walk/walk-page" aria-current="page">The walk page</a>+ <a href="/docs/walk/companion-mode">Companion mode</a>+ <a href="/docs/walk/chrome-extension">Chrome extension</a>+ </nav>+ <h2>Build with it</h2>+ <nav aria-label="Building with Walk">+ <a href="/docs/walk/embed-iframe">Iframe embed</a>+ <a href="/docs/walk/embed-sdk">JavaScript SDK</a>+ <a href="/docs/walk/postmessage-events">postMessage events</a>+ <a href="/docs/walk/analytics">Analytics</a>+ </nav>+ <h2>Reference</h2>+ <nav aria-label="Reference"><a href="/docs/walk/changelog">Changelog</a></nav>+ </aside>++ <main class="wd-main" id="wd-main">+ <p class="wd-crumbs"><a href="/docs">Docs</a> / <a href="/docs/walk">Walk</a> / The walk page</p>+ <h1>The walk page</h1>+ <p class="wd-lede">+ <a href="/walk">three.ws/walk</a> is the full experience: move an avatar through+ six 3D worlds, switch between four camera modes, fire gestures, see other+ walkers live, and step into AR. This page documents the controls exactly as+ they ship.+ </p>++ <h2>Keyboard & pointer controls</h2>+ <p>On desktop, the avatar is driven with the keyboard; the mouse orbits the camera.</p>+ <div class="wd-table-wrap">+ <table class="wd-table">+ <thead><tr><th>Key</th><th>Action</th></tr></thead>+ <tbody>+ <tr><td><kbd>W</kbd> / <kbd>↑</kbd></td><td>Move forward</td></tr>+ <tr><td><kbd>S</kbd> / <kbd>↓</kbd></td><td>Move backward</td></tr>+ <tr><td><kbd>A</kbd> / <kbd>←</kbd></td><td>Strafe left</td></tr>+ <tr><td><kbd>D</kbd> / <kbd>→</kbd></td><td>Strafe right</td></tr>+ <tr><td><kbd>Shift</kbd> (hold)</td><td>Run</td></tr>+ <tr><td><kbd>Space</kbd></td><td>Jump</td></tr>+ <tr><td><kbd>Q</kbd> / <kbd>E</kbd></td><td>Snap-turn 45° left / right</td></tr>+ <tr><td><kbd>C</kbd></td><td>Cycle camera mode</td></tr>+ <tr><td><kbd>V</kbd></td><td>Cycle environment</td></tr>+ <tr><td><kbd>G</kbd> (hold)</td><td>Open the gesture wheel</td></tr>+ <tr><td><kbd>1</kbd>–<kbd>8</kbd></td><td>Play a gesture directly</td></tr>+ <tr><td><kbd>T</kbd> / <kbd>Enter</kbd></td><td>Focus chat</td></tr>+ <tr><td><kbd>P</kbd></td><td>Screenshot</td></tr>+ <tr><td><kbd>R</kbd></td><td>Toggle GIF recording</td></tr>+ <tr><td><kbd>M</kbd></td><td>Toggle minimap</td></tr>+ <tr><td><kbd>Z</kbd></td><td>Hide UI (Zen mode)</td></tr>+ <tr><td><kbd>H</kbd> / <kbd>?</kbd></td><td>Toggle the help overlay</td></tr>+ <tr><td>Mouse drag</td><td>Orbit the camera</td></tr>+ <tr><td>Scroll / pinch</td><td>Zoom in / out</td></tr>+ <tr><td><kbd>Esc</kbd></td><td>Close overlay / release pointer lock</td></tr>+ </tbody>+ </table>+ </div>+ <div class="wd-note">+ <span class="wd-icon" aria-hidden="true">✱</span>+ <span>On touch devices the page shows dual on-screen sticks — the left stick moves the avatar, the right stick orbits the camera — plus jump, camera, and gesture buttons. Hold the gesture button to open the radial wheel.</span>+ </div>++ <h2>Camera modes</h2>+ <p>Press <kbd>C</kbd> (or tap the camera button) to cycle through four modes. Your choice persists across sessions.</p>+ <div class="wd-table-wrap">+ <table class="wd-table">+ <thead><tr><th>Mode</th><th>Label</th><th>Behaviour</th></tr></thead>+ <tbody>+ <tr><td><code>follow</code></td><td>Follow</td><td>Default third-person camera that trails the avatar.</td></tr>+ <tr><td><code>cinematic</code></td><td>Cinematic</td><td>Auto-orbiting camera that periodically cuts to a new angle.</td></tr>+ <tr><td><code>firstperson</code></td><td>First Person</td><td>Sees through the avatar's eyes; the body is hidden.</td></tr>+ <tr><td><code>topdown</code></td><td>Top Down</td><td>Overhead view of the avatar and surrounding world.</td></tr>+ </tbody>+ </table>+ </div>++ <h2>Environments</h2>+ <p>Six worlds, each with its own terrain, sky, and lighting. Cycle with <kbd>V</kbd>, or land directly in one with the <code>?env=</code> URL parameter.</p>+ <div class="wd-table-wrap">+ <table class="wd-table">+ <thead><tr><th>id</th><th>Name</th><th>Setting</th></tr></thead>+ <tbody>+ <tr><td><code>park</code></td><td>Park</td><td>Rolling green with shade trees, benches, and lamp posts. <em>(default)</em></td></tr>+ <tr><td><code>beach</code></td><td>Beach</td><td>Bright sand, palms, parasols, and a turquoise sea.</td></tr>+ <tr><td><code>gallery</code></td><td>Gallery</td><td>White-walled exhibition space with pedestals and hung art.</td></tr>+ <tr><td><code>cyberpunk</code></td><td>Cyberpunk</td><td>Neon towers and holo signs over a rain-dark street.</td></tr>+ <tr><td><code>office</code></td><td>Office</td><td>The three.ws virtual office — desks, plants, brand wall.</td></tr>+ <tr><td><code>void</code></td><td>Void</td><td>A minimal grid plane under a soft gradient — pure focus.</td></tr>+ </tbody>+ </table>+ </div>+ <div class="wd-code" data-lang="text" data-label="URL">+ <pre><code>https://three.ws/walk?env=cyberpunk</code></pre>+ </div>++ <h2>Gestures</h2>+ <p>+ Eight gestures play on top of (or instead of) walking. Hold <kbd>G</kbd> for the+ radial wheel, or press a number key. Upper-body gestures layer over locomotion+ so the avatar keeps walking; full-body gestures take over until they finish.+ </p>+ <div class="wd-table-wrap">+ <table class="wd-table">+ <thead><tr><th>#</th><th>Gesture</th><th>Layer</th></tr></thead>+ <tbody>+ <tr><td>1</td><td><code>wave</code></td><td>Upper body (keeps walking)</td></tr>+ <tr><td>2</td><td><code>dance</code></td><td>Full body</td></tr>+ <tr><td>3</td><td><code>sit</code></td><td>Full body</td></tr>+ <tr><td>4</td><td><code>point</code></td><td>Upper body (keeps walking)</td></tr>+ <tr><td>5</td><td><code>cheer</code></td><td>Upper body (keeps walking)</td></tr>+ <tr><td>6</td><td><code>agree</code></td><td>Upper body (keeps walking)</td></tr>+ <tr><td>7</td><td><code>disagree</code></td><td>Upper body (keeps walking)</td></tr>+ <tr><td>8</td><td><code>talking</code></td><td>Full body</td></tr>+ </tbody>+ </table>+ </div>++ <h2>Multiplayer presence</h2>+ <p>+ The walk page connects to a real-time presence server, so when others are in the+ same world you see them move, gesture, and chat live. Each remote walker's+ position, facing, motion, name, colour, and avatar are synchronised continuously.+ The status pill shows <strong>online</strong>, <strong>connecting</strong>,+ <strong>solo</strong>, or <strong>offline</strong>, and a player list names+ everyone present.+ </p>+ <p>+ Walkers are grouped into shared rooms by the <code>?coin</code> community they+ arrive with — pass a Solana mint and a friendly name to put a community in one+ room together:+ </p>+ <div class="wd-code" data-lang="text" data-label="URL">+ <pre><code>https://three.ws/walk?coin=<mint>&coinName=<name>&coinSymbol=<ticker></code></pre>+ </div>+ <div class="wd-note">+ <span class="wd-icon" aria-hidden="true">✱</span>+ <span>If the presence server is unreachable the page still works perfectly — it simply runs solo. Multiplayer is an enhancement, never a requirement.</span>+ </div>++ <h2>AR camera passthrough</h2>+ <p>+ On a phone, the AR button drops the avatar into your real surroundings. It+ streams the rear camera as the backdrop, hides the procedural terrain, keeps a+ shadow-catcher under the avatar's feet, freezes the camera in world space, and+ continuously samples the live video to match the avatar's lighting to your room.+ </p>+ <div class="wd-warn">+ <span class="wd-icon" aria-hidden="true">▲</span>+ <span>AR uses the device camera (<code>getUserMedia</code>) for passthrough — it is not WebXR spatial AR, so there is no plane detection or world anchoring. It requires a browser with camera access and falls back gracefully with a clear message where the camera API is unavailable.</span>+ </div>++ <h2>URL parameters the page reads</h2>+ <p>Append these to <code>/walk</code> to deep-link into a configuration.</p>+ <div class="wd-table-wrap">+ <table class="wd-table">+ <thead><tr><th>Parameter</th><th>Value</th><th>Effect</th></tr></thead>+ <tbody>+ <tr><td><code>avatar</code></td><td>avatar UUID</td><td>Load a registered avatar by id.</td></tr>+ <tr><td><code>avatarUrl</code></td><td>GLB / VRM URL</td><td>Load a model directly by URL.</td></tr>+ <tr><td><code>name</code></td><td>string (≤24 chars)</td><td>Pre-fill the player name.</td></tr>+ <tr><td><code>env</code></td><td>environment id</td><td>Start in a specific world.</td></tr>+ <tr><td><code>coin</code></td><td>Solana mint</td><td>Join that community's shared room.</td></tr>+ <tr><td><code>coinName</code></td><td>string (≤48)</td><td>Display name for the community.</td></tr>+ <tr><td><code>coinSymbol</code></td><td>string (≤16)</td><td>Ticker for the community.</td></tr>+ <tr><td><code>coinImage</code></td><td>image URL (≤1024)</td><td>Community logo.</td></tr>+ <tr><td><code>agent</code></td><td>agent id</td><td>The three.ws agent this walker embodies.</td></tr>+ <tr><td><code>ui</code></td><td><code>hidden</code> / <code>off</code></td><td>Hide the UI on load (Zen mode).</td></tr>+ </tbody>+ </table>+ </div>++ <div class="wd-pagefoot">+ <a class="wd-edit" href="https://github.com/nirholas/three.ws/edit/main/public/docs/walk/walk-page.html" rel="noopener"><span aria-hidden="true">✎</span> Edit this page on GitHub</a>+ <div class="wd-nextprev">+ <a href="/docs/walk/getting-started"><span>Previous</span>← Getting started</a>+ <a href="/docs/walk/embed-iframe"><span>Next</span>Iframe embed →</a>+ </div>+ </div>+ </main>+ </div>++ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ <script src="/brand.js" defer></script>+ <script type="module" src="/docs/walk/docs.js"></script>+ </body>+</html>diff --git a/public/error-reporter.js b/public/error-reporter.jsindex 9f83ca0f3..6505270e2 100644--- a/public/error-reporter.js+++ b/public/error-reporter.js@@ -75,7 +75,16 @@// "history.pushState is undefined" inside wallet browsers) — analytics// degrading on an exotic UA is not actionable.const IGNORED_THIRD_PARTY_CODE =- /ajax\.googleapis\.com\/ajax\/libs\/model-viewer\/|\/_vercel\/(insights|speed-insights)\/script/;+ /ajax\.googleapis\.com\/ajax\/libs\/model-viewer\/|\/_vercel\/(insights|speed-insights)\/script|\/ingest\/static\/|\.i\.posthog\.com\//;+ // WalletConnect's sign-client (loaded from esm.sh) raises an unhandled rejection+ // — "No matching key. session topic doesn't exist: <hex>" — when a relay event+ // arrives for a session the client has already torn down (the user disconnected,+ // the pairing expired, or a duplicate event replays). It is a benign internal+ // race in the SDK's own event queue, not a three.ws fault and not fixable from+ // app code; the wallet connection still works. Identify it by the SDK in the+ // stack or the distinctive message so it stops flooding [client-error].+ const IGNORED_WALLETCONNECT =+ /@walletconnect\/|\bNo matching key\b|session topic doesn't exist|Record was recently deleted/i;// Expiring signed URLs embedded in user-generated feed data: GitHub// private-user-images, S3/GCS presigned links, and anything carrying a// short-lived JWT/signature. The token lapses on a timer, so the asset 404s@@ -202,6 +211,13 @@) {return true;}+ // WalletConnect's internal session-key race (matched on message or stack).+ if (+ IGNORED_WALLETCONNECT.test(report.message || '') ||+ IGNORED_WALLETCONNECT.test(report.stack || '')+ ) {+ return true;+ }// Dev-tooling rejections (Vite HMR / Fast Refresh) — never a product fault.if (IGNORED_DEV_TOOLING.test(report.source || '') ||diff --git a/public/features.json b/public/features.jsonindex ff1f38723..89a44dfcd 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-21T06:34:11.153Z",+ "generated_at": "2026-06-21T06:48:55.119Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",@@ -809,7 +809,7 @@{"path": "/vanity-wallet","title": "Solana Vanity Wallet",- "description": "Grind a Solana address with a custom prefix using your browser's GPU.",+ "description": "Grind a Solana address with a custom prefix — entirely in your browser, across your CPU cores.","added": "2026-04-29","auth": null,"indexable": true,diff --git a/public/llms-full.txt b/public/llms-full.txtindex 8e4dedd2d..e21cbeeb6 100644--- a/public/llms-full.txt+++ b/public/llms-full.txt@@ -494,7 +494,7 @@ Build DCA and subscription strategies that trade on-chain on your behalf.URL: https://three.ws/vanity-wallet-Grind a Solana address with a custom prefix using your browser's GPU.+Grind a Solana address with a custom prefix — entirely in your browser, across your CPU cores.### Verify a Vanity Receiptdiff --git a/public/llms.txt b/public/llms.txtindex b364649e6..f447a2383 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -101,7 +101,7 @@ On-chain features: pay-per-call, token launches, vanity wallets.- [Watchlist](https://three.ws/watchlist): Your privately-stored watchlist of pump.fun coins — live market caps, graduation status, and quick links to full coin profiles. No account required; stored in your browser.- [Pump Dashboard](https://three.ws/pump-dashboard): Pump.fun trading desk: watchlists, scanner, quotes, portfolio, and live charts.- [Strategy Lab](https://three.ws/strategy-lab): Build DCA and subscription strategies that trade on-chain on your behalf.-- [Solana Vanity Wallet](https://three.ws/vanity-wallet): Grind a Solana address with a custom prefix using your browser's GPU.+- [Solana Vanity Wallet](https://three.ws/vanity-wallet): Grind a Solana address with a custom prefix — entirely in your browser, across your CPU cores.- [Verify a Vanity Receipt](https://three.ws/vanity/verify): Independently verify a three.ws provably-fair vanity wallet receipt — entirely in your browser. Prove the key was generated fresh under a committed seed and the operator never kept a copy.- [Proof-of-Grind Gallery](https://three.ws/vanity/gallery): A public gallery and leaderboard of the rarest Solana vanity addresses ground on three.ws — each provably-fair, verified, and shareable. Appraise any address to see its honest rarity tier and grind cost.- [Grind-Bounty Market](https://three.ws/vanity/bounties): A decentralized x402 bounty market for hard Solana vanity addresses — escrow a USDC bounty and a fleet of independent workers grinds it in parallel. The first verified match wins, but the found key is sealed to you so the worker never sees your wallet. Earn USDC by grinding open bounties.diff --git a/public/sitemap/index.html b/public/sitemap/index.htmlindex 4fb74ba23..078b53f91 100644--- a/public/sitemap/index.html+++ b/public/sitemap/index.html@@ -670,7 +670,7 @@<a href="/vanity-wallet"><span class="sm-title">Solana Vanity Wallet</span><span class="sm-path">/vanity-wallet</span>- <span class="sm-desc">Grind a Solana address with a custom prefix using your browser's GPU.</span>+ <span class="sm-desc">Grind a Solana address with a custom prefix — entirely in your browser, across your CPU cores.</span></a></li><li>diff --git a/public/style.css b/public/style.cssindex 4bb66c93b..8d245d2bc 100644--- a/public/style.css+++ b/public/style.css@@ -2485,73 +2485,9 @@ body.deploy-page {background: rgba(255, 255, 255, 0.05);}-/* Skeleton cards (loading state) */-.explore-card--skel {- background: rgba(255, 255, 255, 0.02);- pointer-events: none;-}-.explore-card--skel .explore-card-thumb,-.explore-card--skel .explore-card-skel-name,-.explore-card--skel .explore-card-skel-desc,-.explore-card--skel .explore-card-skel-badges {- background: linear-gradient(- 90deg,- rgba(255, 255, 255, 0.04) 0%,- rgba(255, 255, 255, 0.08) 50%,- rgba(255, 255, 255, 0.04) 100%- );- background-size: 200% 100%;- animation: explore-shimmer 1.4s linear infinite;- color: transparent;- border-radius: var(--radius-sm);-}-.explore-card--skel .explore-card-thumb {- aspect-ratio: 1 / 1;- border-radius: 0;-}-.explore-card--skel .explore-card-skel-name {- height: 14px;- width: 65%;- margin: 14px 16px 0;-}-.explore-card--skel .explore-card-skel-desc {- height: 28px;- width: 90%;- margin: 10px 16px 0;-}-.explore-card--skel .explore-card-skel-badges {- height: 18px;- width: 55%;- margin: 8px 16px 0;-}-.explore-skel-img {- aspect-ratio: 1 / 1;- background: linear-gradient(- 110deg,- rgba(255, 255, 255, 0.03) 30%,- rgba(255, 255, 255, 0.07) 50%,- rgba(255, 255, 255, 0.03) 70%- );- background-size: 200% 100%;- animation: explore-shimmer 1.4s ease-in-out infinite;-}-.explore-skel-line {- height: 10px;- margin: var(--space-sm) var(--space-md);- background: rgba(255, 255, 255, 0.05);- border-radius: var(--radius-sm);-}-.explore-skel-line--short {- width: 60%;-}-@keyframes explore-shimmer {- 0% {- background-position: 200% 0;- }- 100% {- background-position: -200% 0;- }-}+/* Loading skeletons are provided by the shared state-kit (.tws-sk-*); /discover+ renders them via skeletonHTML() so it matches /marketplace exactly. The old+ bespoke .explore-card--skel shimmer was removed when the toolkit was adopted. *//* Featured (no-query) header */.explore-featured-head {@@ -8051,143 +7987,66 @@ textarea.erc8004-code {.explore-controls {display: flex;- gap: var(--space-md);- align-items: center;- flex-wrap: wrap;+ flex-direction: column;+ gap: var(--space-sm);+ align-items: stretch;margin: var(--space-xl) 0 var(--space-lg);padding: var(--space-md);- background: rgba(255, 255, 255, 0.02);- border: 1px solid rgba(255, 255, 255, 0.06);+ background: var(--surface-1);+ border: 1px solid var(--stroke);border-radius: var(--radius-md);}-.explore-search {- flex: 1 1 260px;- position: relative;-}-.explore-search input {+/* The shared list-controls toolbar fills the panel; its rows wrap naturally. */+.explore-controls .tws-lc {width: 100%;- padding: 10px 36px 10px 14px;- background: rgba(0, 0, 0, 0.4);- border: 1px solid rgba(255, 255, 255, 0.08);- border-radius: var(--radius-sm);- color: #fff;- font: inherit;- font-size: 14px;-}-.explore-search input:focus {- outline: none;- border-color: rgba(255, 255, 255, 0.35);- background: rgba(0, 0, 0, 0.6);-}-/* Hide native WebKit clear; we render our own. */-.explore-search input[type='search']::-webkit-search-cancel-button {- -webkit-appearance: none;- appearance: none;-}-.explore-search-clear {- position: absolute;- top: 50%;- right: 8px;- transform: translateY(-50%);- width: 22px;- height: 22px;- display: grid;- place-items: center;- border: 0;- border-radius: 50%;- background: rgba(255, 255, 255, 0.1);- color: rgba(255, 255, 255, 0.7);- font-size: 16px;- line-height: 1;- cursor: pointer;- transition:- background 0.15s ease,- color 0.15s ease;}-.explore-search-clear:hover,-.explore-search-clear:focus-visible {- background: rgba(255, 255, 255, 0.15);- color: #fff;- outline: none;-}-.explore-chips {- display: flex;- gap: 6px;-}-.explore-chip {- padding: 8px 14px;- background: transparent;- border: 1px solid rgba(255, 255, 255, 0.12);- border-radius: var(--radius-sm);- color: rgba(255, 255, 255, 0.6);- font: inherit;- font-size: 13px;- font-weight: 500;- cursor: pointer;- transition: all 0.15s;-}-.explore-chip:hover {- border-color: rgba(255, 255, 255, 0.25);- color: #fff;+/* Page-specific chain selector, relocated into the toolbar's primary row at+ runtime so it sits inline with search + sort. Mirror the toolkit's select. */+.explore-chain-select {+ display: inline-flex;+ align-items: center;+ gap: var(--space-xs);+ color: var(--ink-dim);+ font-size: var(--text-md);+ flex-shrink: 0;}-.explore-chip.active {- background: rgba(255, 255, 255, 0.1);- border-color: rgba(255, 255, 255, 0.4);- color: #fff;+.explore-chain-select label {+ color: var(--ink-dim);}-.explore-chain-select {- display: flex;+.explore-chain-select-control {+ position: relative;+ display: inline-flex;align-items: center;- gap: 8px;- color: rgba(255, 255, 255, 0.55);- font-size: 13px;}-.explore-chain-select select,-.explore-sort-select select {+.explore-chain-select select {appearance: none;-webkit-appearance: none;- padding: 8px 30px 8px 10px;+ padding: 8px 30px 8px 11px;background-color: var(--surface-2);background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='8' viewBox='0 0 12 8' fill='none'%3E%3Cpath d='M1 1.5L6 6.5L11 1.5' stroke='%23888888' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E");background-repeat: no-repeat;background-position: right 10px center;border: 1px solid var(--stroke-strong);- border-radius: var(--radius-control);- color: #fff;- font: inherit;- font-size: 13px;+ border-radius: var(--radius-md);+ color: var(--ink);+ font: var(--weight-medium) var(--text-md) / 1 var(--font-body);cursor: pointer;transition:- background-color 0.15s,- border-color 0.15s;+ background-color var(--duration-fast) var(--ease-standard),+ border-color var(--duration-fast) var(--ease-standard);}--.explore-chain-select select:hover,-.explore-sort-select select:hover {+.explore-chain-select select:hover {background-color: var(--surface-3);- border-color: rgba(255, 255, 255, 0.28);-}--.explore-chain-select select:focus-visible,-.explore-sort-select select:focus-visible {- outline: 2px solid var(--accent);- outline-offset: 2px;+ border-color: var(--stroke-strong);}--.explore-chain-select select option,-.explore-sort-select select option {- background-color: #111111;- color: #e6e6e6;+.explore-chain-select select:focus-visible {+ outline: var(--focus-ring-width) solid var(--focus-ring-color);+ outline-offset: var(--focus-ring-offset);}--.explore-sort-select {- display: flex;- align-items: center;- gap: 8px;- color: rgba(255, 255, 255, 0.55);- font-size: 13px;+.explore-chain-select select option {+ background-color: var(--bg-1);+ color: var(--ink);}-.explore-sentinel {height: 1px;width: 100%;@@ -8527,67 +8386,48 @@ textarea.erc8004-code {font-size: 14px;}- /* Stack the toolbar; every control spans the row and is easy to tap. */+ /* Stack the toolbar; every control spans the row and is easy to tap. The+ shared list-controls toolkit (.tws-lc-*) handles its own row wrapping; we+ tighten the panel padding and make the page-specific chain select full+ width + comfortably tappable on phones. */.explore-controls {- flex-direction: column;- align-items: stretch;- gap: var(--space-sm);padding: var(--space-sm);}- .explore-search {- flex: 1 1 auto;- width: 100%;- }- .explore-search input {- /* >=16px stops iOS Safari from zooming the page on focus. */+ /* >=16px font stops iOS Safari from zooming the page on input/select focus. */+ .explore-controls .tws-lc-search input,+ .explore-chain-select select {font-size: 16px;- padding: 11px 40px 11px 14px;- }-- /* Chip rows wrap into clean bands — for 3-4 chips this reads better than a- scroll rail and carries zero overflow risk. */- .explore-chips {- flex-wrap: wrap;- gap: 8px;- max-width: 100%;}- .explore-chip {- flex: 0 0 auto;+ .explore-controls .tws-lc-search input {min-height: 44px;+ }+ .explore-controls .tws-lc-chip {+ min-height: 38px;display: inline-flex;align-items: center;- white-space: nowrap;}-- /* Chain + Sort selects stack, each on its own full-width row, fully tappable. */- .explore-controls-row {- flex-direction: column;- align-items: stretch;- gap: var(--space-sm);- width: 100%;- }- .explore-chain-select,- .explore-sort-select {+ .explore-chain-select {display: flex;width: 100%;min-width: 0;align-items: center;gap: 10px;}- .explore-chain-select label,- .explore-sort-select label {+ .explore-chain-select label {flex: 0 0 auto;min-width: 44px;}- .explore-chain-select select,- .explore-sort-select select {+ .explore-chain-select-control {+ flex: 1 1 auto;+ min-width: 0;+ }+ .explore-chain-select select {flex: 1 1 auto;width: 100%;/* Without min-width:0 a <select> keeps the intrinsic width of its widestoption (long chain names), forcing the row past the viewport. */min-width: 0;min-height: 44px;- font-size: 16px;}/* One comfortable column on phones; the desktop 260px track woulddiff --git a/public/walk-embed-sdk.js b/public/walk-embed-sdk.jsindex 0305a2af4..6d2992243 100644--- a/public/walk-embed-sdk.js+++ b/public/walk-embed-sdk.js@@ -1,23 +1,27 @@-// walk-embed-sdk.js — one-tag walking-avatar embed for any website.+// walk-embed-sdk.js — host-side wrapper for the three.ws walking-avatar embed.//-// Usage:-// <script src="https://three.ws/walk-embed-sdk.js"-// data-avatar="<uuid>"-// data-position="bottom-right"-// data-width="220"-// data-height="320"-// data-env="studio"></script>+// Two ways to use it://-// The script:-// 1. Reads `data-*` attributes off its own <script> tag.-// 2. Injects a fixed-position <iframe> pointing at /walk-embed?... so the-// avatar appears as a floating 3D character on the host page.-// 3. Exposes `window.ThreeWalkAvatar` with mount / unmount / setAvatar /-// setSize / setPosition / on / off methods.-// 4. Re-emits postMessage events from the iframe as document-level-// CustomEvents (`walk:ready`, `walk:position`, `walk:error`,-// `walk:avatarChanged`) so host code can listen without knowing about-// postMessage at all.+// 1) One-tag floating avatar (auto-mount). Drop a <script> with data-* attrs and+// the SDK injects a fixed-position <iframe> for you:+//+// <script src="https://three.ws/walk-embed-sdk.js"+// data-avatar="<id>" data-position="bottom-right"+// data-width="220" data-height="320" data-env="studio"></script>+//+// 2) Programmatic control of any iframe you already rendered (React/Vue/vanilla):+//+// const a = ThreeWalkAvatar.embed('#avatar'); // or an HTMLIFrameElement+// a.on('ready', ({ avatarId, env }) => …);+// a.on('position', ({ x, z, heading }) => …);+// a.goto(2, -1); a.gesture('wave'); a.say('hi', 'aria');+// a.setEnv('beach'); a.setAvatar('<id>'); a.config({ speed: 1.5 });+// a.off('position', fn); a.destroy();+//+// Both paths speak the same typed postMessage contract as the iframe runtime+// (src/walk-embed-events.js): a `{ channel:'three-walk', v:1, type, …payload }`+// envelope. Outbound events: ready · position · gesture · speak · env · error.+// Inbound commands: goto · gesture · say · env · avatar · config · move · reset.//// Standalone — no runtime deps. Safe to embed on any origin; the iframe page// ships `content-security-policy: frame-ancestors *`.@@ -25,6 +29,32 @@(function () {'use strict';+ // ── Wire contract (mirror of src/walk-embed-events.js) ────────────────────+ // Kept in lock-step with the module by hand because this file ships as a+ // plain <script> to third-party pages and can't import the ESM contract.+ var CHANNEL = 'three-walk';+ var PROTOCOL_VERSION = 1;+ // Public outbound event names (what hosts subscribe to).+ var OUT = {+ ready: 'walk:ready',+ position: 'walk:position',+ gesture: 'walk:gesture',+ speak: 'walk:speak',+ env: 'walk:env',+ avatarChanged: 'walk:avatarChanged',+ error: 'walk:error',+ };+ var OUT_NAMES = Object.keys(OUT);+ var ENV_IDS = ['studio', 'void', 'beach', 'sunset', 'night', 'grid'];+ var GESTURE_IDS = ['idle', 'walk', 'run', 'wave', 'jump'];+ var CONTROL_MODES = ['joystick', 'keyboard', 'none'];++ function envelope(type, payload) {+ var msg = { channel: CHANNEL, v: PROTOCOL_VERSION, type: type };+ if (payload) for (var k in payload) if (Object.prototype.hasOwnProperty.call(payload, k)) msg[k] = payload[k];+ return msg;+ }+// ── Locate self ───────────────────────────────────────────────────────// document.currentScript only works while the script is initially// executing; once we go async we need a stable handle.@@ -200,16 +230,159 @@state.container = null;}+ // ── Programmatic controller: ThreeWalkAvatar.embed(iframeOrSelector) ──────+ // Wraps an existing <iframe> (one the host rendered, or one mount() made) in+ // the full typed command/event API. Each controller is independent — you can+ // drive several embeds on one page. Listeners are scoped to the controller,+ // not the document, so they never collide with the auto-mount CustomEvents.+ function resolveIframe(target) {+ if (!target) return null;+ if (typeof target === 'string') {+ var el = document.querySelector(target);+ return el && el.tagName === 'IFRAME' ? el : null;+ }+ if (target.tagName === 'IFRAME') return target;+ // A wrapper element — find the iframe inside it (covers mount()'s container).+ if (target.querySelector) return target.querySelector('iframe');+ return null;+ }++ // Derive the origin we post commands to from the iframe's own src, so a+ // security-conscious controller never targets '*'. Falls back to the SDK's+ // own origin (same domain that served this script) when src is relative.+ function originForIframe(iframe) {+ try {+ var u = new URL(iframe.getAttribute('src') || iframe.src, location.href);+ return u.origin;+ } catch (e) {+ return EMBED_ORIGIN;+ }+ }++ function embed(target) {+ var iframe = resolveIframe(target);+ if (!iframe) {+ throw new Error('ThreeWalkAvatar.embed(): no <iframe> found for ' + target);+ }+ var origin = originForIframe(iframe);+ var listeners = {}; // event-name → [cb]+ var ready = null; // last { avatarId, env } from walk:ready+ var destroyed = false;++ function fire(name, detail) {+ var arr = listeners[name];+ if (arr) for (var i = 0; i < arr.slice().length; i++) {+ try { arr[i](detail); } catch (e) {}+ }+ }++ function onMessage(e) {+ if (destroyed) return;+ // Source check is the real authentication: only this iframe's window.+ if (e.source !== iframe.contentWindow) return;+ var msg = e.data;+ if (!msg || typeof msg !== 'object') return;+ // Accept the typed envelope or the flat legacy shape.+ if (msg.channel != null && msg.channel !== CHANNEL) return;+ var type = msg.type;+ if (typeof type !== 'string' || type.indexOf('walk:') !== 0) return;+ if (type === OUT.ready) ready = { avatarId: msg.avatarId, env: msg.env };+ // Re-key to the short event name (ready/position/…); pass payload only.+ for (var name in OUT) {+ if (OUT[name] === type) { fire(name, msg); break; }+ }+ }+ window.addEventListener('message', onMessage);++ function send(type, payload) {+ if (destroyed || !iframe.contentWindow) return ctl;+ try { iframe.contentWindow.postMessage(envelope(type, payload), origin); } catch (e) {}+ return ctl;+ }++ var ctl = {+ iframe: iframe,+ // Lifecycle / events --------------------------------------------------+ on: function (name, cb) {+ (listeners[name] = listeners[name] || []).push(cb);+ // If we already saw ready, replay it to a late 'ready' subscriber.+ if (name === 'ready' && ready) { try { cb(ready); } catch (e) {} }+ return ctl;+ },+ off: function (name, cb) {+ var arr = listeners[name];+ if (!arr) return ctl;+ if (!cb) { listeners[name] = []; return ctl; }+ var i = arr.indexOf(cb);+ if (i >= 0) arr.splice(i, 1);+ return ctl;+ },+ // Re-request the ready handshake (useful if you attached after load).+ ping: function () { return send('walk:ping'); },+ isReady: function () { return !!ready; },+ getReady: function () { return ready ? Object.assign({}, ready) : null; },+ // Commands ------------------------------------------------------------+ goto: function (x, z) { return send('walk:goto', { x: Number(x) || 0, z: Number(z) || 0 }); },+ move: function (x, y, run) {+ return send('walk:move', { x: Number(x) || 0, y: Number(y) || 0, run: !!run });+ },+ gesture: function (g) { return send('walk:gesture', { gesture: g }); },+ say: function (text, voice, durationMs) {+ return send('walk:say', { text: String(text == null ? '' : text), voice: voice, durationMs: durationMs });+ },+ setEnv: function (env) { return send('walk:env', { env: env }); },+ setAvatar: function (avatarId) { return send('walk:avatar', { avatarId: avatarId }); },+ config: function (opts) { return send('walk:config', opts || {}); },+ reset: function () { return send('walk:reset'); },+ // Teardown ------------------------------------------------------------+ destroy: function () {+ if (destroyed) return;+ destroyed = true;+ window.removeEventListener('message', onMessage);+ listeners = {};+ },+ };++ // Kick the handshake in case the iframe finished loading before we+ // attached our message listener (mounting an already-loaded iframe).+ ctl.ping();+ return ctl;+ }+// ── Public API ────────────────────────────────────────────────────────var API = {+ // Programmatic controller (preferred for app integrations).+ embed: embed,+ // Vocabulary — lets hosts feature-detect / build pickers.+ protocol: Object.freeze({+ channel: CHANNEL,+ version: PROTOCOL_VERSION,+ outboundEvents: OUT_NAMES.slice(),+ environments: ENV_IDS.slice(),+ gestures: GESTURE_IDS.slice(),+ controls: CONTROL_MODES.slice(),+ }),+ // One-tag floating-avatar API (auto-mount path).mount: mount,unmount: unmount,setAvatar: function (id) {state.options.avatar = id || '';- postToFrame({ type: 'walk:setAvatar', id: id });+ postToFrame(envelope('walk:avatar', { avatarId: id }));},setMotion: function (motion) {- postToFrame({ type: 'walk:setMotion', motion: motion });+ postToFrame(envelope('walk:gesture', { gesture: motion }));+ },+ gesture: function (g) {+ postToFrame(envelope('walk:gesture', { gesture: g }));+ },+ goto: function (x, z) {+ postToFrame(envelope('walk:goto', { x: Number(x) || 0, z: Number(z) || 0 }));+ },+ say: function (text, voice, durationMs) {+ postToFrame(envelope('walk:say', { text: String(text == null ? '' : text), voice: voice, durationMs: durationMs }));+ },+ config: function (opts) {+ postToFrame(envelope('walk:config', opts || {}));},setSize: function (w, h) {state.options.width = w;@@ -224,11 +397,11 @@if (state.container) setPositionStyles(state.container, pos);},resetPose: function () {- postToFrame({ type: 'walk:resetPose' });+ postToFrame(envelope('walk:reset'));},setEnv: function (env) {state.options.env = env || 'studio';- postToFrame({ type: 'walk:setEnv', env: env });+ postToFrame(envelope('walk:env', { env: env }));},on: function (name, cb) {(state.listeners[name] = state.listeners[name] || []).push(cb);@@ -251,10 +424,22 @@}// ── Auto-mount ────────────────────────────────────────────────────────- // Default behavior: if the script tag has any data-* attributes, we- // auto-mount on DOM ready. Hosts that want explicit control can add- // `data-auto="false"` and call `ThreeWalkAvatar.mount(...)` themselves.- var autoMount = attr('data-auto', 'true') !== 'false';+ // Default behavior: if the script tag carries any of the embed's data-*+ // attributes, auto-mount a floating avatar on DOM ready. A bare+ // `<script src=…>` (e.g. a page that only wants the embed() controller for an+ // iframe it rendered itself) mounts nothing. `data-auto="false"` opts out+ // explicitly even when data-* attributes are present.+ function hasEmbedDataAttr() {+ if (!SCRIPT) return false;+ var keys = ['data-avatar', 'data-position', 'data-width', 'data-height',+ 'data-controls', 'data-env', 'data-autoplay', 'data-ground', 'data-orbit',+ 'data-bg', 'data-z-index'];+ for (var i = 0; i < keys.length; i++) {+ if (SCRIPT.getAttribute(keys[i]) != null) return true;+ }+ return false;+ }+ var autoMount = attr('data-auto', null) === 'true' || (attr('data-auto', null) !== 'false' && hasEmbedDataAttr());if (autoMount) {if (document.readyState === 'loading') {document.addEventListener('DOMContentLoaded', function () { mount(); });diff --git a/scripts/x402-test-solana.mjs b/scripts/x402-test-solana.mjsindex 7f9167a78..95e5dfb82 100644--- a/scripts/x402-test-solana.mjs+++ b/scripts/x402-test-solana.mjs@@ -86,11 +86,17 @@ function pickSolanaRequirement(envelope) {);}+// Server-supplied addresses can carry trailing whitespace/newlines from+// dashboard-pasted env vars; `new PublicKey()` rejects them as "Non-base58+// character". A robust client trims before decoding rather than trusting the+// challenge to be clean (the server is also fixed at api/_lib/env.js).+const cleanKey = (s) => String(s ?? '').trim();+async function buildAndSignTransferTx({ kp, connection, requirement }) {const payer = kp.publicKey;- const mint = new PublicKey(requirement.asset);- const payTo = new PublicKey(requirement.payTo);- const feePayer = new PublicKey(requirement.extra.feePayer);+ const mint = new PublicKey(cleanKey(requirement.asset));+ const payTo = new PublicKey(cleanKey(requirement.payTo));+ const feePayer = new PublicKey(cleanKey(requirement.extra.feePayer));const amount = BigInt(requirement.amount);const mintInfo = await getMint(connection, mint);@@ -150,7 +156,17 @@ async function runOne(endpoint, kp, connection) {return { name: endpoint.name, ok: false, status: probe.status };}const envelope = await probe.json();- const requirement = pickSolanaRequirement(envelope);+ const rawRequirement = pickSolanaRequirement(envelope);+ // Normalize address fields up front so the signed tx and the echoed+ // `accepted` requirement agree — a server with a whitespace-tainted payTo+ // env would otherwise make the facilitator compute a different expected+ // recipient than the one we transfer to (recipient_mismatch).+ const requirement = rawRequirement && {+ ...rawRequirement,+ asset: cleanKey(rawRequirement.asset),+ payTo: cleanKey(rawRequirement.payTo),+ extra: { ...rawRequirement.extra, feePayer: cleanKey(rawRequirement.extra?.feePayer) },+ };if (!requirement) {console.log(` ✗ envelope has no Solana accepts entry`);return { name: endpoint.name, ok: false, note: 'no solana accept' };diff --git a/src/marketplace.js b/src/marketplace.jsindex 02ec1a6f5..e6620c712 100644--- a/src/marketplace.js+++ b/src/marketplace.js@@ -23,6 +23,7 @@ import { walletChipHTML, walletChipEl, wireWalletChips } from './shared/agent-waimport { seeInWorldHref, hasCustomAvatar } from './shared/agent-3d.js';import { coinChipHTML } from './shared/agent-coin.js';import { skeletonHTML, emptyStateHTML, errorStateHTML, ensureStateKitStyles } from './shared/state-kit.js';+import { debounce, syncStateToUrl } from './shared/list-controls.js';import { log } from './shared/log.js';import { track, trackError, ANALYTICS_EVENTS } from './analytics.js';ensureStateKitStyles();@@ -218,24 +219,27 @@ function readRoute() {// and page refresh both restore the same view. Uses replaceState by default// to avoid flooding history with every keystroke; pass push=true when the// change is user-meaningful (filter chip click, sort change).+// URL params owned by the discovery list view, with the default value that+// drops the param from the URL (canonical short links). Shared with /discover's+// scheme conceptually via the same syncStateToUrl helper from the list-controls+// toolkit, so both surfaces write querystrings the same way.+const LIST_URL_DEFAULTS = { tab: '', q: '', sort: 'recommended', pricing: 'all' };+function syncFilterToUrl({ push = false } = {}) {if (!location.pathname.startsWith('/marketplace')) return;// Only sync from the discovery list view — detail / tools / mine views// own their own URLs and we shouldn't trample them.- const path = location.pathname;- if (path !== '/marketplace') return;- const url = new URL(location.href);- const set = (key, val) => {- if (val) url.searchParams.set(key, val);- else url.searchParams.delete(key);- };- set('tab', LIST_FILTER_TABS.has(state.filter) ? state.filter : null);- set('q', state.q || null);- set('sort', state.sort && state.sort !== 'recommended' ? state.sort : null);- set('pricing', state.priceFilter && state.priceFilter !== 'all' ? state.priceFilter : null);- if (url.href === location.href) return;- if (push) history.pushState({}, '', url);- else history.replaceState({}, '', url);+ if (location.pathname !== '/marketplace') return;+ syncStateToUrl(+ {+ tab: LIST_FILTER_TABS.has(state.filter) ? state.filter : '',+ q: state.q || '',+ sort: state.sort || 'recommended',+ pricing: state.priceFilter || 'all',+ },+ LIST_URL_DEFAULTS,+ { push },+ );}function navTo(path, replace = false) {@@ -5693,28 +5697,34 @@ async function toggleBookmark() {function bindEvents() {bindEmptyStateActions();- let searchTimer;- els.search.addEventListener('input', (e) => {- clearTimeout(searchTimer);- searchTimer = setTimeout(() => {- state.q = e.target.value.trim();- syncFilterToUrl();- // Engagement: search intent. Debounced above, so this fires once per- // settled query — never per keystroke. Length only, never the query text.- track(ANALYTICS_EVENTS.MARKETPLACE_SEARCHED, {- query_len: state.q.length,- filters: { filter: state.filter, sort: state.sort },- });- // All three feeds (agents, avatars, onchain) accept ?q= on the server.- // If we only re-fetch agents on search, the grid keeps stale avatar +- // onchain cards from the previous query — and the empty state never- // fires when the query genuinely matches nothing.- state.publicAvatarsLoaded = false;- state.onchainLoaded = false;- loadList(true);- loadPublicAvatars();- loadOnchainAgents(true);- }, 200);+ // Shared 200ms debounce from the list-controls toolkit — same timing and+ // trailing-edge behaviour as /discover so search feels identical on both.+ const runSearch = debounce((value) => {+ state.q = value.trim();+ syncFilterToUrl();+ // Engagement: search intent. Debounced above, so this fires once per+ // settled query — never per keystroke. Length only, never the query text.+ track(ANALYTICS_EVENTS.MARKETPLACE_SEARCHED, {+ query_len: state.q.length,+ filters: { filter: state.filter, sort: state.sort },+ });+ // All three feeds (agents, avatars, onchain) accept ?q= on the server.+ // If we only re-fetch agents on search, the grid keeps stale avatar ++ // onchain cards from the previous query — and the empty state never+ // fires when the query genuinely matches nothing.+ state.publicAvatarsLoaded = false;+ state.onchainLoaded = false;+ loadList(true);+ loadPublicAvatars();+ loadOnchainAgents(true);+ }, 200);+ els.search.addEventListener('input', (e) => runSearch(e.target.value));+ // Enter flushes the pending search immediately.+ els.search.addEventListener('keydown', (e) => {+ if (e.key === 'Enter') {+ e.preventDefault();+ runSearch.flush(els.search.value);+ }});els.sortSel.addEventListener('change', (e) => {state.sort = e.target.value;diff --git a/src/shared/list-controls.js b/src/shared/list-controls.jsnew file mode 100644index 000000000..475817c6b--- /dev/null+++ b/src/shared/list-controls.js@@ -0,0 +1,574 @@+/**+ * Shared list/grid controls toolkit — E03.+ *+ * One data-source-agnostic toolbar for every browse surface (/discover,+ * /marketplace, …): a debounced search input, a sort <select>, filter chip+ * segments, and a results count, all URL-synced so views are shareable and the+ * browser back/forward button restores them.+ *+ * The toolkit owns the CHROME (controls + their state + URL plumbing). It does+ * NOT fetch — the caller passes an `onChange(state, meta)` callback and runs+ * whatever real API it already uses. Loading / empty / error rendering is+ * delegated to the shared state-kit so every surface reads as one product.+ *+ * Two ways to use it:+ *+ * 1. Controller (full adoption — /discover):+ * const lc = createListControls({+ * mount: el, segments: [...], sortOptions: [...],+ * searchPlaceholder: '…', onChange: (s) => loadPage(s),+ * });+ * The controller renders the bar, wires events + debounce, syncs the URL,+ * and calls onChange whenever the user changes anything (and once on init+ * after hydrating from the URL).+ *+ * 2. Helpers (incremental adoption — surfaces with bespoke markup):+ * import { debounce, syncStateToUrl, readStateFromUrl } from './list-controls.js';+ * Pure functions a page can drop into its existing wiring without ceding+ * control of its DOM.+ *+ * CSS: ensureListControlsStyles() injects the stylesheet once (idempotent),+ * mirroring the state-kit pattern. The bar reuses the canonical design tokens+ * — never a parallel palette.+ */++import { ensureStateKitStyles } from './state-kit.js';++const STYLE_ID = 'tws-list-controls-styles';++function esc(s) {+ return String(s == null ? '' : s).replace(+ /[&<>"']/g,+ (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],+ );+}++/**+ * CSS.escape with a safe fallback for environments that don't expose it (older+ * runtimes, some test harnesses). Segment keys are author-controlled simple+ * identifiers, so the fallback only needs to neutralise selector metacharacters.+ */+function cssEscape(s) {+ const str = String(s == null ? '' : s);+ if (typeof CSS !== 'undefined' && typeof CSS.escape === 'function') return CSS.escape(str);+ return str.replace(/[^a-zA-Z0-9_-]/g, '\\$&');+}++// ── Pure helpers (incremental-adoption surface) ─────────────────────────────++/**+ * Trailing-edge debounce. Returns a wrapped fn plus a `.cancel()` to drop any+ * pending call (e.g. on teardown or an explicit clear).+ * @param {Function} fn+ * @param {number} [wait=200]+ */+export function debounce(fn, wait = 200) {+ let t;+ const wrapped = (...args) => {+ clearTimeout(t);+ t = setTimeout(() => fn(...args), wait);+ };+ wrapped.cancel = () => clearTimeout(t);+ wrapped.flush = (...args) => {+ clearTimeout(t);+ fn(...args);+ };+ return wrapped;+}++/**+ * Read a list-view state object from the current URL's querystring.+ * Only keys present in `defaults` are read; anything else is ignored so a page+ * never picks up stray params. Values are coerced to the type of their default.+ *+ * @param {Record<string, string|null>} defaults e.g. { q:'', sort:'newest', chain:'' }+ * @param {URLSearchParams} [params]+ * @returns {Record<string, string>}+ */+export function readStateFromUrl(defaults, params = new URLSearchParams(location.search)) {+ const out = {};+ for (const key of Object.keys(defaults)) {+ const v = params.get(key);+ out[key] = v == null ? defaults[key] : v;+ }+ return out;+}++/**+ * Reflect a state object into the URL. Keys whose value equals the matching+ * `defaults` entry are dropped (canonical short URLs). Uses replaceState by+ * default to avoid history spam on each keystroke; pass push:true for+ * user-meaningful changes (chip click, sort change) so back/forward step+ * through them.+ *+ * @param {Record<string, string>} stateObj+ * @param {Record<string, string|null>} defaults+ * @param {{ push?: boolean }} [opts]+ */+export function syncStateToUrl(stateObj, defaults, { push = false } = {}) {+ const url = new URL(location.href);+ for (const key of Object.keys(defaults)) {+ const val = stateObj[key];+ if (val == null || val === '' || val === defaults[key]) url.searchParams.delete(key);+ else url.searchParams.set(key, String(val));+ }+ if (url.href === location.href) return;+ if (push) history.pushState({}, '', url);+ else history.replaceState({}, '', url);+}++// ── CSS injection ───────────────────────────────────────────────────────────++/** Inject the list-controls stylesheet once. Idempotent and SSR-safe. */+export function ensureListControlsStyles() {+ if (typeof document === 'undefined') return;+ ensureStateKitStyles(); // controls live alongside state-kit empty/error blocks+ if (document.getElementById(STYLE_ID)) return;+ const style = document.createElement('style');+ style.id = STYLE_ID;+ style.textContent = LIST_CONTROLS_CSS;+ (document.head || document.documentElement).appendChild(style);+}++// ── Controller ──────────────────────────────────────────────────────────────++/**+ * @typedef {Object} Segment+ * @property {string} key state key this segment writes to (e.g. 'filter', 'source')+ * @property {string} [label] optional group label (visually hidden, used for aria-label)+ * @property {Array<{value:string,label:string}>} options+ *+ * @typedef {Object} ListControlsConfig+ * @property {Element} mount container the bar renders into+ * @property {string} [searchKey='q'] state key the search input writes to+ * @property {string} [searchPlaceholder]+ * @property {string} [searchLabel='Search']+ * @property {Array<{value:string,label:string}>} [sortOptions]+ * @property {string} [sortKey='sort']+ * @property {Segment[]} [segments]+ * @property {Record<string,string>} [defaults] default value per state key+ * @property {number} [debounceMs=200]+ * @property {boolean} [urlSync=true] when false the toolkit never touches the+ * URL — the caller owns it (e.g. a page with a legacy/custom query scheme).+ * Hydration from the URL still happens via `hydrate`.+ * @property {(params:URLSearchParams, defaults:Record<string,string>) => Record<string,string>} [hydrate]+ * custom reader for the initial state (defaults to readStateFromUrl).+ * @property {(state:Record<string,string>, meta:{reason:string}) => void} onChange+ */++/**+ * Build and wire a list-controls bar. Returns a handle exposing the live state,+ * imperative setters, and a teardown.+ * @param {ListControlsConfig} config+ */+export function createListControls(config) {+ ensureListControlsStyles();++ const {+ mount,+ searchKey = 'q',+ searchPlaceholder = 'Search…',+ searchLabel = 'Search',+ sortOptions = [],+ sortKey = 'sort',+ segments = [],+ debounceMs = 200,+ urlSync = true,+ hydrate,+ onChange,+ } = config;++ if (!mount) throw new Error('createListControls: mount element is required');++ // Assemble the full default map: search + sort + every segment's first option.+ const defaults = { [searchKey]: '', ...(config.defaults || {}) };+ if (sortOptions.length && !(sortKey in defaults)) defaults[sortKey] = sortOptions[0].value;+ for (const seg of segments) {+ if (!(seg.key in defaults)) defaults[seg.key] = seg.options[0]?.value ?? '';+ }++ // Hydrate from URL so deep links + back/forward restore filters. A page with+ // a custom/legacy query scheme supplies its own reader via `hydrate`.+ const readState = (params) =>+ hydrate ? hydrate(params, defaults) : readStateFromUrl(defaults, params);+ const state = readState(new URLSearchParams(location.search));++ mount.classList.add('tws-lc');+ mount.innerHTML = buildBarHTML({+ state,+ searchKey,+ searchPlaceholder,+ searchLabel,+ sortOptions,+ sortKey,+ segments,+ });++ const $ = (sel) => mount.querySelector(sel);+ const searchInput = $('[data-lc="search"]');+ const searchClear = $('[data-lc="search-clear"]');+ const sortSelect = $('[data-lc="sort"]');+ const countEl = $('[data-lc="count"]');++ const emit = (reason, push) => {+ if (urlSync) syncStateToUrl(state, defaults, { push });+ onChange?.({ ...state }, { reason });+ };++ // ── Search (debounced) ──+ const runSearch = debounce(() => {+ const next = searchInput.value.trim();+ if (next === state[searchKey]) return;+ state[searchKey] = next;+ emit('search', false);+ }, debounceMs);++ if (searchInput) {+ searchInput.addEventListener('input', () => {+ updateClearVisibility();+ runSearch();+ });+ // Enter flushes immediately (don't make the user wait out the debounce).+ searchInput.addEventListener('keydown', (e) => {+ if (e.key === 'Enter') {+ e.preventDefault();+ runSearch.flush();+ }+ });+ }+ searchClear?.addEventListener('click', () => {+ searchInput.value = '';+ state[searchKey] = '';+ updateClearVisibility();+ runSearch.cancel();+ emit('search-clear', true);+ searchInput.focus();+ });++ // ── Sort ──+ sortSelect?.addEventListener('change', () => {+ state[sortKey] = sortSelect.value;+ emit('sort', true);+ });++ // ── Segment chips (delegated, survives nothing — bar is built once) ──+ mount.addEventListener('click', (e) => {+ const chip = e.target.closest('[data-lc-seg]');+ if (!chip) return;+ const key = chip.dataset.lcSeg;+ const value = chip.dataset.lcValue;+ if (state[key] === value) return;+ state[key] = value;+ for (const c of mount.querySelectorAll(`[data-lc-seg="${cssEscape(key)}"]`)) {+ const active = c.dataset.lcValue === value;+ c.classList.toggle('active', active);+ c.setAttribute('aria-pressed', active ? 'true' : 'false');+ }+ emit('segment', true);+ });++ // ── Keyboard arrow nav within a chip group ──+ mount.addEventListener('keydown', (e) => {+ if (e.key !== 'ArrowRight' && e.key !== 'ArrowLeft') return;+ const chip = e.target.closest('[data-lc-seg]');+ if (!chip) return;+ const group = chip.closest('[data-lc-seg-group]');+ if (!group) return;+ const chips = [...group.querySelectorAll('[data-lc-seg]')];+ const i = chips.indexOf(chip);+ const next = e.key === 'ArrowRight' ? chips[i + 1] : chips[i - 1];+ if (next) {+ e.preventDefault();+ next.focus();+ }+ });++ function updateClearVisibility() {+ if (searchClear) searchClear.hidden = !searchInput.value;+ }+ updateClearVisibility();++ // Restore on popstate so back/forward re-hydrate the bar + re-run onChange.+ const onPop = () => {+ const restored = readState(new URLSearchParams(location.search));+ Object.assign(state, restored);+ syncControlsToState();+ onChange?.({ ...state }, { reason: 'popstate' });+ };+ window.addEventListener('popstate', onPop);++ function syncControlsToState() {+ if (searchInput) searchInput.value = state[searchKey] || '';+ updateClearVisibility();+ if (sortSelect) sortSelect.value = state[sortKey] ?? sortSelect.value;+ for (const seg of segments) {+ for (const c of mount.querySelectorAll(`[data-lc-seg="${cssEscape(seg.key)}"]`)) {+ const active = c.dataset.lcValue === state[seg.key];+ c.classList.toggle('active', active);+ c.setAttribute('aria-pressed', active ? 'true' : 'false');+ }+ }+ }+ syncControlsToState();++ return {+ /** Current state snapshot (copy). */+ getState: () => ({ ...state }),+ /** True when any control differs from its default (drives "clear filters"). */+ isFiltered: () => Object.keys(defaults).some((k) => state[k] !== defaults[k]),+ /** Programmatically reset every control to its default and re-emit. */+ reset: () => {+ Object.assign(state, defaults);+ runSearch.cancel();+ syncControlsToState();+ emit('reset', true);+ },+ /** Set the visible results count (or hide it with null/''). */+ setCount: (text) => {+ if (!countEl) return;+ countEl.textContent = text || '';+ countEl.hidden = !text;+ },+ /** Fire onChange once after wiring (callers that don't want an init call skip this). */+ emitInitial: () => onChange?.({ ...state }, { reason: 'init' }),+ destroy: () => {+ runSearch.cancel();+ window.removeEventListener('popstate', onPop);+ },+ };+}++// ── Bar markup ───────────────────────────────────────────────────────────────++function buildBarHTML({ state, searchKey, searchPlaceholder, searchLabel, sortOptions, sortKey, segments }) {+ const searchVal = esc(state[searchKey] || '');+ const searchHTML = `+ <div class="tws-lc-search">+ <svg class="tws-lc-search-icon" width="15" height="15" viewBox="0 0 16 16" fill="none" aria-hidden="true">+ <circle cx="7" cy="7" r="5" stroke="currentColor" stroke-width="1.5"/>+ <path d="M11 11l3 3" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>+ </svg>+ <input type="search" data-lc="search" value="${searchVal}"+ placeholder="${esc(searchPlaceholder)}" aria-label="${esc(searchLabel)}"+ autocomplete="off" spellcheck="false" />+ <button type="button" class="tws-lc-search-clear" data-lc="search-clear"+ aria-label="Clear search"${searchVal ? '' : ' hidden'}>+ <svg width="12" height="12" viewBox="0 0 12 12" fill="none" aria-hidden="true">+ <path d="M2 2l8 8M10 2l-8 8" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/>+ </svg>+ </button>+ </div>`;++ const segmentsHTML = segments+ .map((seg) => {+ const active = state[seg.key];+ const chips = seg.options+ .map((o) => {+ const on = o.value === active;+ return `<button type="button" class="tws-lc-chip${on ? ' active' : ''}"+ data-lc-seg="${esc(seg.key)}" data-lc-value="${esc(o.value)}"+ aria-pressed="${on ? 'true' : 'false'}">${esc(o.label)}</button>`;+ })+ .join('');+ return `<div class="tws-lc-chips" role="group"${seg.label ? ` aria-label="${esc(seg.label)}"` : ''} data-lc-seg-group>${chips}</div>`;+ })+ .join('');++ const sortHTML = sortOptions.length+ ? `<div class="tws-lc-sort">+ <label class="tws-lc-sort-label" for="tws-lc-sort-${esc(sortKey)}">Sort</label>+ <div class="tws-lc-select">+ <select id="tws-lc-sort-${esc(sortKey)}" data-lc="sort" aria-label="Sort results">+ ${sortOptions+ .map(+ (o) =>+ `<option value="${esc(o.value)}"${o.value === state[sortKey] ? ' selected' : ''}>${esc(o.label)}</option>`,+ )+ .join('')}+ </select>+ <svg class="tws-lc-select-caret" width="11" height="7" viewBox="0 0 12 8" fill="none" aria-hidden="true">+ <path d="M1 1.5L6 6.5L11 1.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>+ </svg>+ </div>+ </div>`+ : '';++ return `+ <div class="tws-lc-row tws-lc-row--primary">+ ${searchHTML}+ ${sortHTML}+ </div>+ ${segmentsHTML ? `<div class="tws-lc-row tws-lc-row--segments">${segmentsHTML}</div>` : ''}+ <div class="tws-lc-count" data-lc="count" role="status" aria-live="polite" hidden></div>`;+}++// ── CSS ───────────────────────────────────────────────────────────────────────++const LIST_CONTROLS_CSS = `+/* ═══════════════════════════════════════════════════════════════════════════+ three.ws list-controls — shared search / sort / filter toolbar (E03)+ Source: src/shared/list-controls.js · Namespace: tws-lc-*+ Token-driven only; no parallel palette.+ ═══════════════════════════════════════════════════════════════════════════ */++.tws-lc {+ display: flex;+ flex-direction: column;+ gap: var(--space-sm, 0.618rem);+}+.tws-lc-row {+ display: flex;+ align-items: center;+ gap: var(--space-sm, 0.618rem);+ flex-wrap: wrap;+}+.tws-lc-row--segments { gap: var(--space-md, 1rem); }++/* ── Search ── */+.tws-lc-search {+ position: relative;+ flex: 1 1 260px;+ min-width: 0;+ display: flex;+ align-items: center;+}+.tws-lc-search-icon {+ position: absolute;+ left: 12px;+ color: var(--ink-dim, #888);+ pointer-events: none;+}+.tws-lc-search input {+ width: 100%;+ padding: 9px 34px 9px 34px;+ background: var(--surface-1, rgba(255,255,255,0.03));+ border: 1px solid var(--stroke, rgba(255,255,255,0.08));+ border-radius: var(--radius-md, 10px);+ color: var(--ink, #e8e8e8);+ font: var(--weight-medium, 500) var(--text-md, 13px)/1.2 var(--font-body, system-ui, sans-serif);+ transition: border-color var(--duration-fast, 140ms) var(--ease-standard, ease),+ background var(--duration-fast, 140ms) var(--ease-standard, ease);+}+.tws-lc-search input::placeholder { color: var(--ink-faint, rgba(255,255,255,0.45)); }+.tws-lc-search input:hover { border-color: var(--stroke-strong, rgba(255,255,255,0.14)); }+.tws-lc-search input:focus-visible,+.tws-lc-search input:focus {+ outline: none;+ border-color: var(--accent, #fff);+ background: var(--surface-2, rgba(255,255,255,0.05));+}+.tws-lc-search input[type='search']::-webkit-search-cancel-button {+ -webkit-appearance: none;+ appearance: none;+}+.tws-lc-search-clear {+ position: absolute;+ right: 7px;+ width: 22px;+ height: 22px;+ display: grid;+ place-items: center;+ border: 0;+ border-radius: var(--radius-pill, 999px);+ background: var(--surface-3, rgba(255,255,255,0.08));+ color: var(--ink-dim, #888);+ cursor: pointer;+ transition: background var(--duration-fast, 140ms) var(--ease-standard, ease),+ color var(--duration-fast, 140ms) var(--ease-standard, ease);+}+.tws-lc-search-clear:hover { background: var(--surface-3, rgba(255,255,255,0.12)); color: var(--ink, #e8e8e8); }+.tws-lc-search-clear:focus-visible {+ outline: var(--focus-ring-width, 2px) solid var(--focus-ring-color, #fff);+ outline-offset: var(--focus-ring-offset, 2px);+}++/* ── Chips / segments ── */+.tws-lc-chips {+ display: inline-flex;+ gap: var(--space-2xs, 0.236rem);+ flex-wrap: wrap;+}+.tws-lc-chip {+ padding: 7px 13px;+ background: transparent;+ border: 1px solid var(--stroke-strong, rgba(255,255,255,0.14));+ border-radius: var(--radius-sm, 6px);+ color: var(--ink-dim, #888);+ font: var(--weight-medium, 500) var(--text-md, 13px)/1 var(--font-body, system-ui, sans-serif);+ cursor: pointer;+ white-space: nowrap;+ transition: border-color var(--duration-fast, 140ms) var(--ease-standard, ease),+ color var(--duration-fast, 140ms) var(--ease-standard, ease),+ background var(--duration-fast, 140ms) var(--ease-standard, ease);+}+.tws-lc-chip:hover { border-color: var(--stroke-strong, rgba(255,255,255,0.28)); color: var(--ink, #e8e8e8); }+.tws-lc-chip.active {+ background: var(--surface-3, rgba(255,255,255,0.10));+ border-color: var(--accent, rgba(255,255,255,0.4));+ color: var(--ink-bright, #fff);+}+.tws-lc-chip:focus-visible {+ outline: var(--focus-ring-width, 2px) solid var(--focus-ring-color, #fff);+ outline-offset: var(--focus-ring-offset, 2px);+}++/* ── Sort select ── */+.tws-lc-sort {+ display: inline-flex;+ align-items: center;+ gap: var(--space-xs, 0.382rem);+ color: var(--ink-dim, #888);+ font-size: var(--text-md, 13px);+ flex-shrink: 0;+}+.tws-lc-sort-label { color: var(--ink-dim, #888); }+.tws-lc-select { position: relative; display: inline-flex; align-items: center; }+.tws-lc-select select {+ appearance: none;+ -webkit-appearance: none;+ padding: 8px 30px 8px 11px;+ background: var(--surface-2, rgba(255,255,255,0.05));+ border: 1px solid var(--stroke-strong, rgba(255,255,255,0.14));+ border-radius: var(--radius-md, 10px);+ color: var(--ink, #e8e8e8);+ font: var(--weight-medium, 500) var(--text-md, 13px)/1 var(--font-body, system-ui, sans-serif);+ cursor: pointer;+ transition: background var(--duration-fast, 140ms) var(--ease-standard, ease),+ border-color var(--duration-fast, 140ms) var(--ease-standard, ease);+}+.tws-lc-select select:hover { background: var(--surface-3, rgba(255,255,255,0.08)); border-color: var(--stroke-strong, rgba(255,255,255,0.28)); }+.tws-lc-select select:focus-visible {+ outline: var(--focus-ring-width, 2px) solid var(--focus-ring-color, #fff);+ outline-offset: var(--focus-ring-offset, 2px);+}+.tws-lc-select select option { background: var(--bg-1, #1a1a1a); color: var(--ink, #e6e6e6); }+.tws-lc-select-caret {+ position: absolute;+ right: 10px;+ color: var(--ink-dim, #888);+ pointer-events: none;+}++/* ── Result count ── */+.tws-lc-count {+ font-size: var(--text-sm, 12px);+ color: var(--ink-dim, #888);+ font-variant-numeric: tabular-nums;+}++@media (max-width: 600px) {+ .tws-lc-row--primary { flex-direction: column; align-items: stretch; }+ .tws-lc-sort { justify-content: space-between; }+ .tws-lc-select select { flex: 1; }+}+`;++if (typeof window !== 'undefined') {+ window.twsListControls = {+ createListControls,+ debounce,+ readStateFromUrl,+ syncStateToUrl,+ ensureListControlsStyles,+ };+}diff --git a/src/walk-embed-events.js b/src/walk-embed-events.jsindex f98d137b3..b53cff6d6 100644--- a/src/walk-embed-events.js+++ b/src/walk-embed-events.js@@ -10,7 +10,7 @@// {// channel: 'three-walk', // namespace guard — ignore anything else// v: 1, // protocol version-// type: 'walk:moved', // see INBOUND / OUTBOUND below+// type: 'walk:position', // see INBOUND / OUTBOUND below// id?: '<correlation id>', // echoes a command id on its result event// ...payload // type-specific fields// }@@ -18,70 +18,95 @@// accepted on the inbound side for backward compatibility with embeds shipped// before this module existed — see isWalkMessage().//+// ── Public contract (task 48) ──────────────────────────────────────────────+// Outbound (iframe → host):+// walk:ready { avatarId, env }+// walk:position { x, z, heading } (10 Hz while moving)+// walk:gesture { gesture } (when a gesture plays)+// walk:speak { text, durationMs } (when the avatar speaks)+// walk:env { env } (environment changed)+// walk:error { code, message }+// Inbound (host → iframe):+// walk:goto { x, z }+// walk:gesture { gesture }+// walk:say { text, voice }+// walk:env { env }+// walk:avatar { avatarId }+// walk:config { speed?, bg?, controls? }+//// ── Handshake ──────────────────────────────────────────────────────────────-// iframe → host : walk:loaded (once, when the avatar is ready)-// host → iframe: walk:ping (optional) → iframe replies walk:loaded again+// iframe → host : walk:ready (once, when the avatar is loaded)+// host → iframe: walk:ping (optional) → iframe replies walk:ready again// A host that mounts the iframe after it has already loaded can fire walk:ping-// to re-trigger the ready event instead of racing the initial walk:loaded.+// to re-trigger the ready event instead of racing the initial walk:ready.export const CHANNEL = 'three-walk';export const PROTOCOL_VERSION = 1;-// Commands a host sends INTO the iframe.+// Commands a host sends INTO the iframe. Canonical names are the task-48 public+// contract; legacy names (walk:setEnvironment, walk:setAvatar, walk:setMotion,+// walk:narrate, walk:move…) are accepted as aliases — see INBOUND_ALIASES.export const INBOUND = Object.freeze({PING: 'walk:ping',+ GOTO: 'walk:goto', // { x, z } — walk to a world position then stopMOVE: 'walk:move', // { x, y, run? } analog vector, OR { dir, meters? } discreteGESTURE: 'walk:gesture', // { gesture: 'wave' | 'jump' | 'idle' | 'walk' | 'run' }- SAY: 'walk:say', // { text, durationMs? }- SET_ENVIRONMENT: 'walk:setEnvironment', // { env }- SET_AVATAR: 'walk:setAvatar', // { id }- SET_CONFIG: 'walk:config', // { speed? }+ SAY: 'walk:say', // { text, voice?, durationMs? }+ SET_ENVIRONMENT: 'walk:env', // { env }+ SET_AVATAR: 'walk:avatar', // { avatarId } (legacy: { id })+ SET_CONFIG: 'walk:config', // { speed?, bg?, controls? }RESET: 'walk:reset',});-// Events the iframe emits OUT to the host.+// Events the iframe emits OUT to the host. Canonical names match the task-48+// contract; legacy names hosts may already listen for are emitted alongside+// (see legacyOutbound() and the embed runtime's emit()).export const OUTBOUND = Object.freeze({- LOADED: 'walk:loaded', // { avatar }- MOVED: 'walk:moved', // { x, z, yaw, motion }- SPOKE: 'walk:spoke', // { text }- GESTURE: 'walk:gestured', // { gesture }- ENVIRONMENT: 'walk:environment', // { env }- AVATAR_CHANGED: 'walk:avatarChanged', // { id }- ERROR: 'walk:error', // { error, code? }+ READY: 'walk:ready', // { avatarId, env }+ POSITION: 'walk:position', // { x, z, heading }+ GESTURE: 'walk:gesture', // { gesture }+ SPEAK: 'walk:speak', // { text, durationMs }+ ENVIRONMENT: 'walk:env', // { env }+ AVATAR_CHANGED: 'walk:avatarChanged', // { avatarId }+ ERROR: 'walk:error', // { code, message }});-// ── Legacy aliases ───────────────────────────────────────────────────────────-// Older embeds spoke walk:ready / walk:position / walk:narrate / walk:setEnv /-// walk:setMotion. We accept those names on input and (for the two outbound ones-// hosts may already listen for) also emit them, so no existing integration-// breaks when this contract lands.+// ── Aliases ──────────────────────────────────────────────────────────────────+// Older embeds spoke walk:setEnvironment / walk:setAvatar / walk:setMotion /+// walk:narrate / walk:resetPose. We accept those names on input so no existing+// integration breaks when this contract lands.const INBOUND_ALIASES = Object.freeze({+ 'walk:setEnvironment': INBOUND.SET_ENVIRONMENT,'walk:setEnv': INBOUND.SET_ENVIRONMENT,+ 'walk:setAvatar': INBOUND.SET_AVATAR,'walk:setMotion': INBOUND.GESTURE,'walk:narrate': INBOUND.SAY,'walk:resetPose': INBOUND.RESET,});const ALL_INBOUND = new Set([...Object.values(INBOUND), ...Object.keys(INBOUND_ALIASES)]);-const ALL_OUTBOUND = new Set(Object.values(OUTBOUND));-const ALL_TYPES = new Set([...ALL_INBOUND, ...ALL_OUTBOUND, 'walk:ready', 'walk:position', 'walk:narrateEnd']);+const ALL_OUTBOUND = new Set([...Object.values(OUTBOUND), 'walk:loaded', 'walk:moved', 'walk:environment', 'walk:gestured', 'walk:spoke']);+const ALL_TYPES = new Set([...ALL_INBOUND, ...ALL_OUTBOUND]);// ── Origin allow-listing ─────────────────────────────────────────────────────// The walk embed is designed to be dropped onto ANY origin (it ships// `frame-ancestors *`), so the host page's origin can be anything. We therefore-// cannot allow-list the host. What we DO validate is the message *source*: the-// iframe only accepts messages whose source window is its own parent, and the-// host SDK only accepts messages whose source is the iframe it mounted. That-// source check (done by the caller) is the real authentication; the optional+// default to allow-any on inbound. What we ALWAYS validate (in the runtime) is+// the message *source*: the iframe only accepts messages whose source window is+// its own parent, and the host SDK only accepts messages whose source is the+// iframe it mounted. That source check is the real authentication; the optional// `allowedOrigins` list below is a belt-and-suspenders filter a security--// conscious integrator can opt into when they know the embed's exact origin.+// conscious integrator can opt into when they know the host's exact origin.export function makeOriginAllowList(origins) {if (!origins || origins === '*') return () => true;- const set = new Set((Array.isArray(origins) ? origins : [origins]).map(normalizeOrigin));+ const list = (Array.isArray(origins) ? origins : [origins]).map(normalizeOrigin).filter(Boolean);+ if (!list.length) return () => true;+ const set = new Set(list);return (origin) => origin === 'null' /* sandboxed/file iframe */ || set.has(normalizeOrigin(origin));}function normalizeOrigin(o) {+ if (o === '*' || o == null) return '';try {return new URL(o).origin;} catch {@@ -101,25 +126,35 @@ export function makeMessage(type, payload = {}, { id } = {}) {export function isWalkMessage(data) {if (!data || typeof data !== 'object') return false;if (data.channel === CHANNEL) return typeof data.type === 'string';- // Legacy: any object whose `type` is a known walk event.+ // Legacy / flat: any object whose `type` is a known walk event.return typeof data.type === 'string' && ALL_TYPES.has(data.type);}-// Normalize an inbound command to its canonical type, resolving legacy aliases.+// Normalize an inbound command to its canonical type, resolving aliases.export function canonicalInboundType(type) {if (INBOUND_ALIASES[type]) return INBOUND_ALIASES[type];return ALL_INBOUND.has(type) ? type : null;}+// ── Vocabulary (exported so the SDK + docs stay in sync with the runtime) ─────+export const ENV_IDS = Object.freeze(['studio', 'void', 'beach', 'sunset', 'night', 'grid']);+export const GESTURES = Object.freeze(['idle', 'walk', 'run', 'wave', 'jump']);+export const DIRECTIONS = Object.freeze(['forward', 'back', 'left', 'right']);+export const CONTROL_MODES = Object.freeze(['joystick', 'keyboard', 'none']);+export const SAY_MAX = 280;+// World bound the avatar can be sent to. Mirrors GROUND_RADIUS in walk-embed.js+// (12m) minus a small margin so a goto target never lands off the ground disc.+export const WORLD_RADIUS = 11.5;++const ENV_SET = new Set(ENV_IDS);+const GESTURE_SET = new Set(GESTURES);+const DIRECTION_SET = new Set(DIRECTIONS);+const CONTROL_SET = new Set(CONTROL_MODES);+// ── Inbound command validation (runs inside the iframe) ──────────────────────// Returns { type, payload } on success or { error } describing the rejection.// Trusts nothing: clamps numbers, bounds strings, rejects unknown shapes. This// is the boundary between the untrusted host page and the embed's runtime.-const ENV_IDS = new Set(['studio', 'void', 'beach', 'sunset', 'night', 'grid']);-const GESTURES = new Set(['idle', 'walk', 'run', 'wave', 'jump']);-const DIRECTIONS = new Set(['forward', 'back', 'left', 'right']);-const SAY_MAX = 280;-export function validateInbound(raw) {const type = canonicalInboundType(raw?.type);if (!type) return { error: `unknown command: ${raw?.type}` };@@ -130,10 +165,16 @@ export function validateInbound(raw) {case INBOUND.RESET:return { type, id, payload: {} };+ case INBOUND.GOTO: {+ const x = clampWorld(num(raw.x, 0));+ const z = clampWorld(num(raw.z, 0));+ return { type, id, payload: { x, z } };+ }+case INBOUND.MOVE: {// Two accepted shapes: analog { x, y, run } or discrete { dir, meters }.if (typeof raw.dir === 'string') {- if (!DIRECTIONS.has(raw.dir)) return { error: `move.dir must be one of ${[...DIRECTIONS].join('/')}` };+ if (!DIRECTION_SET.has(raw.dir)) return { error: `move.dir must be one of ${DIRECTIONS.join('/')}` };const meters = clamp(num(raw.meters, 1), 0, 12);return { type, id, payload: { dir: raw.dir, meters } };}@@ -145,34 +186,41 @@ export function validateInbound(raw) {case INBOUND.GESTURE: {const g = raw.gesture ?? raw.motion; // legacy walk:setMotion used `motion`- if (!GESTURES.has(g)) return { error: `gesture must be one of ${[...GESTURES].join('/')}` };+ if (!GESTURE_SET.has(g)) return { error: `gesture must be one of ${GESTURES.join('/')}` };return { type, id, payload: { gesture: g } };}case INBOUND.SAY: {const text = typeof raw.text === 'string' ? raw.text.slice(0, SAY_MAX) : '';if (!text.trim()) return { error: 'say.text required' };+ const voice = typeof raw.voice === 'string' ? raw.voice.slice(0, 64) : undefined;const durationMs = raw.durationMs == null ? undefined : clamp(num(raw.durationMs, 0), 800, 20000);- return { type, id, payload: { text, durationMs } };+ return { type, id, payload: { text, voice, durationMs } };}case INBOUND.SET_ENVIRONMENT: {const e = String(raw.env || '').toLowerCase();- if (!ENV_IDS.has(e)) return { error: `env must be one of ${[...ENV_IDS].join('/')}` };+ if (!ENV_SET.has(e)) return { error: `env must be one of ${ENV_IDS.join('/')}` };return { type, id, payload: { env: e } };}case INBOUND.SET_AVATAR: {- const avatarId = typeof raw.id === 'string' ? raw.id : (typeof raw.avatar === 'string' ? raw.avatar : '');- // `id` here is the avatar id, which doubles as the correlation id slot —- // keep them separate: avatar id can be a URL/uuid, correlation id is short.- if (!avatarId || avatarId.length > 2048) return { error: 'setAvatar.id required' };- return { type, id: undefined, payload: { id: avatarId } };+ const avatarId = typeof raw.avatarId === 'string'+ ? raw.avatarId+ : (typeof raw.id === 'string' ? raw.id : (typeof raw.avatar === 'string' ? raw.avatar : ''));+ if (!avatarId || avatarId.length > 2048) return { error: 'avatar.avatarId required' };+ return { type, id: undefined, payload: { avatarId } };}case INBOUND.SET_CONFIG: {const payload = {};if (raw.speed != null) payload.speed = clamp(num(raw.speed, 1), 0.3, 3);+ if (raw.bg != null) payload.bg = sanitizeBg(raw.bg);+ if (raw.controls != null) {+ const c = String(raw.controls).toLowerCase();+ if (!CONTROL_SET.has(c)) return { error: `config.controls must be one of ${CONTROL_MODES.join('/')}` };+ payload.controls = c;+ }return { type, id, payload };}@@ -181,6 +229,21 @@ export function validateInbound(raw) {}}+// Only allow CSS hex colors, a small set of safe keywords, or rgb()/rgba() —+// never arbitrary strings (defends against url()/expression injection into a+// host-controlled style value).+function sanitizeBg(v) {+ const s = String(v).trim().slice(0, 32);+ if (s.toLowerCase() === 'transparent') return 'transparent';+ if (/^#[0-9a-fA-F]{3}([0-9a-fA-F]{3})?$/.test(s)) return s;+ if (/^rgba?\(\s*[\d.]+\s*,\s*[\d.]+\s*,\s*[\d.]+\s*(,\s*[\d.]+\s*)?\)$/.test(s)) return s;+ return 'transparent';+}++function clampWorld(n) {+ const r = WORLD_RADIUS;+ return clamp(n, -r, r);+}function num(v, fallback) {const n = typeof v === 'number' ? v : Number(v);return Number.isFinite(n) ? n : fallback;@@ -188,3 +251,98 @@ function num(v, fallback) {function clamp(n, lo, hi) {return Math.min(hi, Math.max(lo, n));}++// ── Embed-side bridge ─────────────────────────────────────────────────────────+// Wires the public postMessage contract to the real walk-embed runtime+// (src/walk-embed.js) without coupling the two modules at import time. The+// runtime publishes a small imperative handle on `window.__walkEmbed`; this+// bridge consumes it. Loaded by pages/walk-embed.html.+//+// `runtime` is the handle the embed exposes:+// {+// goto(x, z), gesture(g), say(text, voice, durationMs), setEnv(env),+// setAvatar(avatarId), config({speed, bg, controls}), reset(),+// getReady() -> { avatarId, env } | null+// }+// plus `runtime.on(event, cb)` for outbound lifecycle hooks the bridge re-emits+// as typed walk:* messages. The bridge owns ALL host-facing postMessage: origin+// validation, the typed envelope, and never leaking internal state.+export function installEmbedBridge(runtime, {+ win = typeof window !== 'undefined' ? window : null,+ allowedOrigins = '*',+ targetOrigin = '*',+} = {}) {+ if (!win) return () => {};+ const parentWin = win.parent && win.parent !== win ? win.parent : null;+ const originAllowed = makeOriginAllowList(allowedOrigins);++ function post(type, payload, opts) {+ if (!parentWin) return;+ try { parentWin.postMessage(makeMessage(type, payload, opts), targetOrigin); } catch {}+ }++ // Outbound: re-emit the runtime's real lifecycle events as typed messages.+ runtime.on?.(OUTBOUND.READY, (d) => post(OUTBOUND.READY, { avatarId: d.avatarId, env: d.env }));+ runtime.on?.(OUTBOUND.POSITION, (d) => post(OUTBOUND.POSITION, { x: d.x, z: d.z, heading: d.heading }));+ runtime.on?.(OUTBOUND.GESTURE, (d) => post(OUTBOUND.GESTURE, { gesture: d.gesture }));+ runtime.on?.(OUTBOUND.SPEAK, (d) => post(OUTBOUND.SPEAK, { text: d.text, durationMs: d.durationMs }));+ runtime.on?.(OUTBOUND.ENVIRONMENT, (d) => post(OUTBOUND.ENVIRONMENT, { env: d.env }));+ runtime.on?.(OUTBOUND.AVATAR_CHANGED, (d) => post(OUTBOUND.AVATAR_CHANGED, { avatarId: d.avatarId }));+ runtime.on?.(OUTBOUND.ERROR, (d) => post(OUTBOUND.ERROR, { code: d.code || 'error', message: d.message }));++ // Inbound: validate, then apply to the real avatar/controls.+ function onMessage(e) {+ // Source check is the real authentication: only accept from our parent.+ if (parentWin && e.source !== parentWin) return;+ if (!originAllowed(e.origin)) return;+ const data = e.data;+ if (!isWalkMessage(data)) return;++ const result = validateInbound(data);+ if (result.error) {+ post(OUTBOUND.ERROR, { code: 'bad_command', message: result.error }, { id: typeof data.id === 'string' ? data.id.slice(0, 64) : undefined });+ return;+ }+ const { type, id, payload } = result;+ try {+ switch (type) {+ case INBOUND.PING: {+ const ready = runtime.getReady?.();+ if (ready) post(OUTBOUND.READY, { avatarId: ready.avatarId, env: ready.env }, { id });+ break;+ }+ case INBOUND.GOTO:+ runtime.goto?.(payload.x, payload.z);+ break;+ case INBOUND.MOVE:+ runtime.move?.(payload);+ break;+ case INBOUND.GESTURE:+ runtime.gesture?.(payload.gesture);+ break;+ case INBOUND.SAY:+ runtime.say?.(payload.text, payload.voice, payload.durationMs);+ break;+ case INBOUND.SET_ENVIRONMENT:+ runtime.setEnv?.(payload.env);+ break;+ case INBOUND.SET_AVATAR:+ runtime.setAvatar?.(payload.avatarId);+ break;+ case INBOUND.SET_CONFIG:+ runtime.config?.(payload);+ break;+ case INBOUND.RESET:+ runtime.reset?.();+ break;+ default:+ break;+ }+ } catch (err) {+ post(OUTBOUND.ERROR, { code: 'command_failed', message: String(err?.message || err) }, { id });+ }+ }++ win.addEventListener('message', onMessage);+ return () => win.removeEventListener('message', onMessage);+}diff --git a/src/walk-embed.js b/src/walk-embed.jsindex 633d60e78..9a703361f 100644--- a/src/walk-embed.js+++ b/src/walk-embed.js@@ -40,14 +40,8 @@ import { getMeshoptDecoder } from './viewer/internal.js';import { AnimationManager } from './animation-manager.js';import { log } from './shared/log.js';import {- CHANNEL,- PROTOCOL_VERSION,- INBOUND,OUTBOUND,- makeMessage,- makeOriginAllowList,- isWalkMessage,- validateInbound,+ installEmbedBridge,} from './walk-embed-events.js';const AVATAR_URL_DEFAULT = '/avatars/default.glb';@@ -61,6 +55,14 @@ const SHOW_GROUND = params.get('ground') !== 'false';const ORBIT_ENABLED = params.get('orbit') !== 'false';const ENV_PARAM = (params.get('env') || 'studio').toLowerCase();+// Live-tracked state surfaced to the host via the typed contract. `currentAvatarId`+// is the public identifier hosts gave us (?avatar=<id|url>) or 'default'; never a+// resolved internal R2/CDN URL with credentials. `currentEnv` and `isReady` back+// the walk:ready handshake + walk:ping replies.+let currentAvatarId = params.get('avatar') || 'default';+let currentEnv = ENV_PARAM;+let isReady = false;+// Real, self-contained scene presets. Each preset retints the clear color,// fog, ground disc, and the hemisphere/sun lights — no external HDRIs to// fetch, so the embed stays a single iframe with no extra requests. An@@ -141,36 +143,25 @@ function setStatus(text, { error = false, sticky = false } = {}) {}}-// ── postMessage bridge to host page ──────────────────────────────────────-// The host frame learns about embed lifecycle + avatar position via the typed-// walk-embed-events contract (src/walk-embed-events.js). We post to window.parent-// only when it's a different window (i.e. we're actually inside an iframe).-// Direct page loads still work — they just don't emit messages.-//-// `?targetOrigin=` lets a security-conscious host pin the exact origin we post-// to; default '*' keeps the embed droppable on any site (it ships-// frame-ancestors *). The inbound source check below is the real authentication.-const INSIDE_IFRAME = window.parent && window.parent !== window;-const TARGET_ORIGIN = params.get('targetOrigin') || '*';-const isOriginAllowed = makeOriginAllowList(params.get('allowOrigins')?.split(',').map((s) => s.trim()).filter(Boolean) || '*');--// Emit a typed outbound event. `legacy` (optional) is the pre-contract message-// shape we still emit alongside the new one so integrations written against-// walk:ready / walk:position keep receiving events during the transition.-function emit(type, payload = {}, legacy = null) {- if (!INSIDE_IFRAME) return;- try {- window.parent.postMessage(makeMessage(type, payload), TARGET_ORIGIN);- if (legacy) window.parent.postMessage(legacy, TARGET_ORIGIN);- } catch {}+// ── Outbound event bus → installEmbedBridge (src/walk-embed-events.js) ──────+// The runtime never touches postMessage itself. It fires typed lifecycle events+// on this tiny in-process bus; the embed bridge (installed from+// pages/walk-embed.html) subscribes via runtime.on() and is the single place+// that validates origins, shapes the envelope, and posts to window.parent. This+// keeps the wire contract in one module and guarantees no internal state leaks+// out by accident — only the fields the bridge forwards ever cross the boundary.+const _listeners = new Map();+function busOn(event, cb) {+ if (!_listeners.has(event)) _listeners.set(event, new Set());+ _listeners.get(event).add(cb);+ return () => _listeners.get(event)?.delete(cb);}--// Post a raw, pre-shaped message to the host frame. Used for the embed's-// imperative ack/error replies (walk:avatarChanged, walk:error) that aren't part-// of the typed lifecycle contract; emit() is preferred for ready/position/move.-function postToHost(message) {- if (!INSIDE_IFRAME) return;- try { window.parent.postMessage(message, TARGET_ORIGIN); } catch {}+function emit(type, payload = {}) {+ const set = _listeners.get(type);+ if (!set) return;+ for (const cb of set) {+ try { cb(payload); } catch {}+ }}// ── Renderer / scene ──────────────────────────────────────────────────────@@ -327,9 +318,14 @@ const input = {// Scripted discrete move ({ dir, meters }) — walks a fixed distance then stops.// `remaining` counts down in metres each frame; `vx/vy` is the unit heading.scripted: { remaining: 0, vx: 0, vy: 0, run: false },+ // Seek target from `walk:goto` — drive toward a world (x,z) then stop within+ // GOTO_ARRIVE_EPSILON. Cleared by any live input or a new command.+ seek: { active: false, x: 0, z: 0, run: false },_speedMultiplier: 1.0,};+const GOTO_ARRIVE_EPSILON = 0.18; // metres — close enough to "arrived"+// Map a discrete direction to a camera-relative input vector. forward/back use// the y axis (joystick up = forward), left/right the x axis — same convention// readMoveInput already resolves against the camera heading.@@ -464,7 +460,8 @@ async function loadAvatar() {}setStatus('walk it');- emit(OUTBOUND.LOADED, { avatar: avatarUrl }, { type: 'walk:ready', avatar: avatarUrl });+ isReady = true;+ emit(OUTBOUND.READY, { avatarId: currentAvatarId, env: currentEnv });}// ── Resize ────────────────────────────────────────────────────────────────@@ -485,14 +482,47 @@ const moveForward = new Vector3();const moveRight = new Vector3();const upY = new Vector3(0, 1, 0);+// A human grabbing the controls (or a fresh command) cancels every form of+// programmatic drive so they never fight for the avatar.+function cancelProgrammatic() {+ input.scripted.remaining = 0;+ input.cmd.active = false;+ input.seek.active = false;+}+function readMoveInput(dt) {// Live input always wins and cancels any programmatic drive so a human can// grab control mid-script.- if (input.joy.active) { input.scripted.remaining = 0; input.cmd.active = false; return { ix: input.joy.x, iy: input.joy.y, run: false }; }+ if (input.joy.active) { cancelProgrammatic(); return { ix: input.joy.x, iy: input.joy.y, run: false }; }if (CONTROLS !== 'none') {const ix = input.keys.right - input.keys.left;const iy = input.keys.forward - input.keys.back;- if (ix || iy) { input.scripted.remaining = 0; input.cmd.active = false; return { ix, iy, run: input.keys.run }; }+ if (ix || iy) { cancelProgrammatic(); return { ix, iy, run: input.keys.run }; }+ }+ // Seek to a world (x,z) from walk:goto. Steer in world space, then express+ // the world heading in the camera-relative basis the loop consumes so the+ // avatar walks straight to the point regardless of camera orbit.+ if (input.seek.active && avatar) {+ const dx = input.seek.x - avatarRig.position.x;+ const dz = input.seek.z - avatarRig.position.z;+ const dist = Math.hypot(dx, dz);+ if (dist <= GOTO_ARRIVE_EPSILON) {+ input.seek.active = false;+ return { ix: 0, iy: 0 };+ }+ moveForward.copy(camLookCurrent).sub(camera.position);+ moveForward.y = 0;+ if (moveForward.lengthSq() < 1e-6) moveForward.set(0, 0, -1);+ else moveForward.normalize();+ moveRight.crossVectors(moveForward, upY).normalize();+ const ndx = dx / dist, ndz = dz / dist;+ // Decompose the world unit heading onto the camera basis: iy along+ // forward, ix along right.+ const iy = moveForward.x * ndx + moveForward.z * ndz;+ const ix = moveRight.x * ndx + moveRight.z * ndz;+ // Ease the final stretch so we settle instead of overshooting.+ const gain = Math.min(1, dist / 0.6);+ return { ix: ix * gain, iy: iy * gain, run: input.seek.run };}// Scripted discrete move: walk a fixed distance then stop. Decrement by the// per-frame distance the loop will actually travel (speed × dt) so `meters`@@ -519,7 +549,13 @@ function readMoveInput(dt) {let lastBroadcastX = 0;let lastBroadcastZ = 0;+let lastBroadcastAt = 0;const BROADCAST_EPSILON = 0.02; // metres — skip duplicate post messages+const BROADCAST_INTERVAL_MS = 100; // walk:position fires at ≤10 Hz per the contract++function round3(n) {+ return Math.round(n * 1000) / 1000;+}function tick() {clock.update();@@ -598,21 +634,22 @@ function tick() {animationManager.update(dt);+ const now = performance.now();if (- avatar && (+ avatar &&+ now - lastBroadcastAt >= BROADCAST_INTERVAL_MS && (Math.abs(avatarRig.position.x - lastBroadcastX) > BROADCAST_EPSILON ||Math.abs(avatarRig.position.z - lastBroadcastZ) > BROADCAST_EPSILON)) {+ lastBroadcastAt = now;lastBroadcastX = avatarRig.position.x;lastBroadcastZ = avatarRig.position.z;- const pos = {- x: avatarRig.position.x,- z: avatarRig.position.z,- yaw: avatarYaw,- motion: currentMotion,- };- emit(OUTBOUND.MOVED, pos, { type: 'walk:position', ...pos });+ emit(OUTBOUND.POSITION, {+ x: round3(avatarRig.position.x),+ z: round3(avatarRig.position.z),+ heading: round3(avatarYaw),+ });}renderer.render(scene, camera);@@ -625,56 +662,163 @@ function lerpAngle(a, b, t) {return a + diff * t;}-// ── Host commands ─────────────────────────────────────────────────────────-// Hosts can drive the embed via window.postMessage. Supported commands:-// { type: 'walk:setAvatar', id } — swap avatar live-// { type: 'walk:setMotion', motion } — 'idle' | 'walk' | 'run' (autoplay)-// { type: 'walk:resetPose' } — recenter avatar on the ground-window.addEventListener('message', async (e) => {- const msg = e.data;- if (!msg || typeof msg !== 'object') return;- if (msg.type === 'walk:setAvatar' && msg.id) {+// ── Imperative runtime handle (consumed by installEmbedBridge) ─────────────+// Every method receives values the bridge has already validated, clamped, and+// bounded against the walk-embed-events contract — so the runtime trusts them+// and just applies them to the real avatar/controls. The bridge is the only+// thing that talks postMessage; the runtime only knows about its scene.+const runtime = {+ on: busOn,+ getReady() {+ return isReady ? { avatarId: currentAvatarId, env: currentEnv } : null;+ },+ // Walk to a world (x, z) then stop. Steered each frame in readMoveInput.+ goto(x, z) {+ cancelProgrammatic();+ const dist = Math.hypot(x - avatarRig.position.x, z - avatarRig.position.z);+ input.seek.active = true;+ input.seek.x = x;+ input.seek.z = z;+ input.seek.run = dist > 4; // jog to far targets, walk to near ones+ input.autoplay.active = false;+ },+ // Held analog vector / discrete nudge from walk:move.+ move(payload) {+ cancelProgrammatic();+ input.autoplay.active = false;+ if (typeof payload.dir === 'string') {+ const v = DIR_VECTORS[payload.dir];+ if (!v) return;+ input.scripted.vx = v.vx;+ input.scripted.vy = v.vy;+ input.scripted.run = false;+ input.scripted.remaining = payload.meters;+ } else {+ input.cmd.x = payload.x;+ input.cmd.y = payload.y;+ input.cmd.run = !!payload.run;+ input.cmd.active = Math.hypot(payload.x, payload.y) > 0.01;+ }+ },+ // One-shot gestures (wave/jump) play over locomotion then settle to idle.+ // Locomotion gestures (idle/walk/run) drive the autoplay loop the same way+ // the legacy walk:setMotion command did.+ gesture(g) {+ if (g === 'wave' || g === 'jump') {+ const clip = GESTURE_CLIPS[g];+ if (clip && animationManager.supportsCanonicalClips?.() !== false) {+ animationManager.playOnce(clip, { settleTo: CLIP_IDLE, fade: 0.18 });+ }+ emit(OUTBOUND.GESTURE, { gesture: g });+ return;+ }+ if (g === 'walk' || g === 'run') {+ input.autoplay.active = true;+ input.autoplay.t = 0;+ } else if (g === 'idle') {+ input.autoplay.active = false;+ input.cmd.active = false;+ input.seek.active = false;+ input.scripted.remaining = 0;+ }+ emit(OUTBOUND.GESTURE, { gesture: g });+ },+ // Show a speech bubble; `voice` is forwarded to the host echo as a hint (the+ // embed renders text, the host owns any TTS). durationMs sets the auto-hide.+ say(text, voice, durationMs) {+ const ms = showSpeechBubble(text, durationMs);+ emit(OUTBOUND.SPEAK, { text, voice, durationMs: ms });+ },+ setEnv(env) {+ applyEnvironment(env);+ currentEnv = env;+ emit(OUTBOUND.ENVIRONMENT, { env });+ },+ async setAvatar(avatarId) {try {+ const url = /^https?:\/\//i.test(avatarId) || avatarId.startsWith('/')+ ? avatarId+ : `/api/avatars/${encodeURIComponent(avatarId)}/glb`;const loader = await getAvatarLoader();- const gltf = await loader.loadAsync(`/api/avatars/${encodeURIComponent(msg.id)}/glb`);+ const gltf = await loader.loadAsync(url);if (avatar) avatarRig.remove(avatar);avatar = gltf.scene;- avatar.traverse((n) => { if (n.isMesh) n.castShadow = true; });+ avatar.traverse((n) => {+ if (n.isMesh) {+ n.castShadow = true;+ if (n.material && 'envMapIntensity' in n.material) n.material.envMapIntensity = 0.85;+ }+ });const box = new Box3().setFromObject(avatar);avatar.position.y -= box.min.y;avatarRig.add(avatar);+ const height = Math.max(0.5, box.max.y - box.min.y);+ CAM_OFFSET.set(0, height * 1.05, height * 1.95);+ CAM_LOOK_OFFSET.set(0, height * 0.6, 0);+ applyCameraImmediate();animationManager.attach(avatar);await animationManager.crossfadeTo(CLIP_IDLE, 0.0);currentMotion = 'idle';- postToHost({ type: 'walk:avatarChanged', id: msg.id });+ currentAvatarId = avatarId;+ emit(OUTBOUND.AVATAR_CHANGED, { avatarId });} catch (err) {- postToHost({ type: 'walk:error', error: String(err?.message || err) });+ emit(OUTBOUND.ERROR, { code: 'avatar_load_failed', message: String(err?.message || err) });}- } else if (msg.type === 'walk:setMotion') {- if (msg.motion === 'walk' || msg.motion === 'run') {- input.autoplay.active = true;- input.autoplay.t = 0;- } else if (msg.motion === 'idle') {- input.autoplay.active = false;- }- } else if (msg.type === 'walk:resetPose') {+ },+ config({ speed, bg, controls } = {}) {+ if (typeof speed === 'number') input._speedMultiplier = speed;+ if (typeof bg === 'string') applyBackground(bg);+ if (typeof controls === 'string') applyControls(controls);+ },+ reset() {+ cancelProgrammatic();+ input.autoplay.active = false;avatarRig.position.set(0, 0, 0);avatarYaw = 0;avatarRig.quaternion.setFromAxisAngle(upY, 0);- applyCameraImmediate();- } else if (msg.type === 'walk:narrate' && typeof msg.text === 'string') {- // Show a DOM speech bubble above the avatar for the narration text.- showSpeechBubble(msg.text);- } else if (msg.type === 'walk:narrateEnd') {hideSpeechBubble();- } else if (msg.type === 'walk:config') {- if (typeof msg.speed === 'number') {- // Walk speed multiplier — applied to input magnitude each frame- input._speedMultiplier = Math.max(0.3, Math.min(3, msg.speed));- }- } else if (msg.type === 'walk:setEnv' && typeof msg.env === 'string') {- applyEnvironment(msg.env.toLowerCase());+ applyCameraImmediate();+ },+};++// Expose the handle so installEmbedBridge (and integration tests) can drive the+// runtime without importing it. Public methods only — no scene internals.+window.__walkEmbed = runtime;++// Apply a runtime background override (walk:config { bg }). 'transparent' lets+// the host page show through; a hex/rgb paints a solid clear color.+function applyBackground(bg) {+ if (!bg || bg === 'transparent') {+ renderer.setClearColor(0x000000, 0);+ document.body.style.background = 'transparent';+ stage.style.background = 'transparent';+ return;+ }+ try {+ renderer.setClearColor(new Color(bg), 1);+ document.body.style.background = bg;+ stage.style.background = bg;+ } catch {}+}++// Swap control scheme at runtime (walk:config { controls }). Only toggles the+// joystick visibility + clears live key/joy state; keyboard listeners stay+// installed and simply go unused when controls are 'none'.+function applyControls(mode) {+ stage.dataset.controls = mode;+ if (mode === 'none') {+ input.keys.forward = input.keys.back = input.keys.left = input.keys.right = 0;+ input.keys.run = false;+ input.joy.x = input.joy.y = 0;+ input.joy.active = false;}+}++// Install the postMessage bridge — origin allow-list and target origin come+// from the embed URL so a security-conscious host can pin them.+installEmbedBridge(runtime, {+ allowedOrigins: params.get('allowOrigins')?.split(',').map((s) => s.trim()).filter(Boolean) || '*',+ targetOrigin: params.get('targetOrigin') || '*',});// ── Speech bubble (DOM overlay) ───────────────────────────────────────────@@ -743,15 +887,17 @@ function ensureBubble() {return bubbleEl;}-function showSpeechBubble(text) {+// Returns the resolved visible duration (ms) so the host's walk:speak echo can+// report exactly how long the bubble will stay up.+function showSpeechBubble(text, durationMs) {clearTimeout(bubbleHideTimer);ensureBubble();bubbleTextEl.textContent = text.slice(0, 280);bubbleEl.style.opacity = '1';- // Fallback auto-hide keyed to estimated reading time, in case walk:narrateEnd- // never arrives (e.g. audio blocked by the host's autoplay policy).- const ms = Math.max(2500, text.length * 55);+ // Explicit durationMs wins; otherwise estimate from reading time.+ const ms = durationMs && durationMs > 0 ? durationMs : Math.max(2500, text.length * 55);bubbleHideTimer = setTimeout(hideSpeechBubble, ms);+ return ms;}function hideSpeechBubble() {@@ -770,6 +916,6 @@ loadAvatar()statusEl.classList.add('is-error');statusEl.classList.remove('is-hidden');}- postToHost({ type: 'walk:error', error: String(err?.message || err) });+ emit(OUTBOUND.ERROR, { code: 'avatar_load_failed', message: String(err?.message || err) });requestAnimationFrame(tick);});diff --git a/src/walk.js b/src/walk.jsindex 23a8f0250..82581d10c 100644--- a/src/walk.js+++ b/src/walk.js@@ -4450,3 +4450,140 @@ if (import.meta.env?.DEV) {if (localStorage.getItem(ZEN_STORAGE_KEY) === '1') setZen(true);} catch {}})();++// ── Programmatic control mode (REST) ─────────────────────────────────────────+// When the page is opened as /walk?control=<sessionId>&ck=<controlToken>, an+// external system (another agent, a CI bot, a webhook) is driving this avatar+// over the control API (api/walk/control/[action].js). We short-poll the+// session every second, fold our live position into the same request, and apply+// each drained command to the real scene:+//+// move → set the existing waypointTarget; the locomotion pipeline walks+// (and faces, and animates) the avatar there, exactly as a minimap+// click does.+// gesture → gestures.play(name) — the same call the wheel / quick keys use.+// say → a speech bubble above the avatar + the talking overlay, with+// optional browser TTS when the command requested voice.+// env → applyEnvironment(name) — a live, faded environment swap.+//+// Commands are delivered exactly once by the server, so we simply apply what each+// poll returns. The poll cadence backs off on transient failures so a blip never+// turns into a request storm, and stops cleanly if the session 401s (expired or+// revoked) — there is nothing left to drive.+(() => {+ const params = new URLSearchParams(location.search);+ const sessionId = (params.get('control') || '').trim();+ const controlToken = (params.get('ck') || '').trim();+ if (!sessionId || !controlToken) return;++ const POLL_MS = 1000;+ const MAX_BACKOFF_MS = 15000;+ let backoff = POLL_MS;+ let stopped = false;+ let inFlight = false;++ function speakControl(text, withVoice) {+ showSpeechBubbleFor('local', text);+ triggerTalking(text);+ net?.sendChat(text);+ if (withVoice && typeof window.speechSynthesis !== 'undefined') {+ try {+ const u = new SpeechSynthesisUtterance(text.slice(0, 280));+ u.rate = 1;+ u.pitch = 1;+ window.speechSynthesis.cancel();+ window.speechSynthesis.speak(u);+ } catch {+ /* synthesis unavailable — the bubble already conveyed the line */+ }+ }+ }++ function applyControlCommand(cmd) {+ switch (cmd.kind) {+ case 'move': {+ if (Number.isFinite(cmd.x) && Number.isFinite(cmd.z)) {+ // Clamp to just inside the playable disc, mirroring the server.+ let { x, z } = cmd;+ const r = Math.hypot(x, z);+ if (r > GROUND_RADIUS - 0.5) {+ const k = (GROUND_RADIUS - 0.5) / r;+ x *= k;+ z *= k;+ }+ waypointTarget = { x, z };+ setStatus('Remote control: walking to target');+ }+ break;+ }+ case 'gesture': {+ if (cmd.gesture) {+ gestures?.play(cmd.gesture);+ setStatus(`Remote control: ${cmd.gesture}`);+ }+ break;+ }+ case 'say': {+ if (cmd.text) speakControl(String(cmd.text), !!cmd.voice);+ break;+ }+ case 'env': {+ if (cmd.env && cmd.env !== currentEnvName) {+ applyEnvironment(cmd.env);+ setStatus(`Remote control: environment → ${cmd.env}`);+ }+ break;+ }+ default:+ break;+ }+ }++ async function pollOnce() {+ if (stopped || inFlight) return;+ inFlight = true;+ // Fold our live state into the poll so the controller's /state read reflects+ // the real avatar without a second request.+ const q = new URLSearchParams({ sessionId, ck: controlToken });+ if (avatar) {+ q.set('x', avatarRig.position.x.toFixed(3));+ q.set('z', avatarRig.position.z.toFixed(3));+ q.set('facing', avatarYaw.toFixed(3));+ q.set('motion', currentMotion);+ q.set('cenv', currentEnvName);+ }+ try {+ const res = await fetch(`/api/walk/control/session?${q.toString()}`, {+ headers: { accept: 'application/json' },+ cache: 'no-store',+ });+ if (res.status === 401 || res.status === 403) {+ // Session expired or revoked — nothing left to drive.+ stopped = true;+ setStatus('Remote-control session ended', { sticky: false });+ return;+ }+ if (res.ok) {+ const data = await res.json();+ for (const cmd of data.commands || []) applyControlCommand(cmd);+ backoff = POLL_MS; // healthy round-trip resets the cadence+ } else {+ backoff = Math.min(MAX_BACKOFF_MS, backoff * 2);+ }+ } catch {+ // Offline / transient — back off and retry.+ backoff = Math.min(MAX_BACKOFF_MS, backoff * 2);+ } finally {+ inFlight = false;+ if (!stopped) setTimeout(pollOnce, backoff);+ }+ }++ window.addEventListener('beforeunload', () => {+ stopped = true;+ });++ setStatus('Remote control active — awaiting commands', { sticky: false });+ // First poll after a short delay so the avatar/scene have a frame to settle.+ setTimeout(pollOnce, 600);+})();diff --git a/tests/api/solana-rpc-endpoints.test.js b/tests/api/solana-rpc-endpoints.test.jsindex b06a20838..135d79017 100644--- a/tests/api/solana-rpc-endpoints.test.js+++ b/tests/api/solana-rpc-endpoints.test.js@@ -8,8 +8,12 @@// un-throttled fallback so failover never depends on the aggressively// rate-limited public mainnet-beta endpoint alone.-import { describe, it, expect, beforeEach, afterEach } from 'vitest';-import { solanaRpcEndpoints, shouldRotate } from '../../api/_lib/solana/connection.js';+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import {+ solanaRpcEndpoints,+ shouldRotate,+ makeRotatingFetch,+} from '../../api/_lib/solana/connection.js';const KEYS = ['HELIUS_API_KEY',@@ -120,3 +124,62 @@ describe('shouldRotate', () => {}});});++// Regression guard for the recurring StructError storm: a provider answered a+// JSON-RPC POST with HTTP 200 but an empty or HTML body, which web3.js then ran+// through its superstruct result schema and threw+// `StructError: Expected the value to satisfy a union of … but received:` to the+// caller WITHOUT rotating (a parse error carries no rotate-worthy HTTP status).+// makeRotatingFetch now detects the poison body and fails over to the next lane.+describe('makeRotatingFetch poison-body failover', () => {+ const json = '{"jsonrpc":"2.0","result":{"value":1},"id":1}';+ let realFetch;+ beforeEach(() => {+ realFetch = global.fetch;+ });+ afterEach(() => {+ global.fetch = realFetch;+ vi.restoreAllMocks();+ });++ function mockResponses(map) {+ global.fetch = vi.fn(async (url) => {+ const r = map[url];+ if (!r) throw new Error(`unexpected fetch ${url}`);+ return new Response(r.body, { status: r.status ?? 200, headers: { 'content-type': 'application/json' } });+ });+ }++ it('fails over a 200-but-empty body to the next endpoint and returns its JSON', async () => {+ vi.spyOn(console, 'log').mockImplementation(() => {});+ const a = 'https://poison-empty.example/sol';+ const b = 'https://healthy.example/sol';+ mockResponses({ [a]: { body: '' }, [b]: { body: json } });+ const fetchImpl = makeRotatingFetch([a, b]);+ const resp = await fetchImpl(a, { method: 'POST', body: '{}' });+ expect(resp.status).toBe(200);+ expect(await resp.text()).toBe(json);+ });++ it('fails over a 200-but-HTML body (provider interstitial) to the next endpoint', async () => {+ vi.spyOn(console, 'log').mockImplementation(() => {});+ const a = 'https://poison-html.example/sol';+ const b = 'https://healthy.example/sol';+ mockResponses({ [a]: { body: '<!DOCTYPE html><html>503</html>' }, [b]: { body: json } });+ const fetchImpl = makeRotatingFetch([a, b]);+ const resp = await fetchImpl(a, { method: 'POST', body: '{}' });+ expect(await resp.text()).toBe(json);+ });++ it('passes a valid JSON-RPC error body straight through (does not rotate)', async () => {+ const errBody = '{"jsonrpc":"2.0","error":{"code":-32601,"message":"Method not found"},"id":1}';+ const a = 'https://rpc.example/sol';+ const fetchImpl = makeRotatingFetch([a, 'https://unused.example/sol']);+ global.fetch = vi.fn(async (url) => {+ if (url !== a) throw new Error('should not have rotated');+ return new Response(errBody, { status: 200, headers: { 'content-type': 'application/json' } });+ });+ const resp = await fetchImpl(a, { method: 'POST', body: '{}' });+ expect(await resp.text()).toBe(errBody);+ });+});diff --git a/tests/discover-rename.test.js b/tests/discover-rename.test.jsindex 9877ad811..e42e2007c 100644--- a/tests/discover-rename.test.js+++ b/tests/discover-rename.test.js@@ -35,10 +35,14 @@ describe('discover page — cross-links and new features', () => {});it('/discover JS hydrates filter state from URL on load', () => {+ // Controls are driven by the shared list-controls toolkit; URL hydration+ // runs through hydrateFromUrl(params) (q / only3d / x402 / source / sort)+ // plus the page-specific chain read. The behaviour contract — deep links+ // and back/forward restore every filter — is preserved.expect(discoverJs).toContain('new URLSearchParams(location.search)');- expect(discoverJs).toContain("initialParams.get('q')");+ expect(discoverJs).toContain("params.get('q')");expect(discoverJs).toContain("initialParams.get('chain')");- expect(discoverJs).toContain("initialParams.get('only3d')");+ expect(discoverJs).toContain("params.get('only3d')");});it('/discover JS has a clear-all-filters function', () => {@@ -46,8 +50,13 @@ describe('discover page — cross-links and new features', () => {expect(discoverJs).toContain('data-role="clear-filters"');});- it('/discover has a search clear button in HTML', () => {- expect(discoverHtml).toContain('data-role="search-clear"');+ it('/discover renders a search input with a clear control via the shared toolkit', () => {+ // The search box + its clear button are now produced by the shared+ // list-controls toolkit (mounted into [data-role="list-controls"]), which+ // renders a data-lc="search" input and a data-lc="search-clear" button.+ expect(discoverHtml).toContain('data-role="list-controls"');+ expect(discoverJs).toContain('createListControls');+ expect(discoverJs).toContain("searchLabel: 'Search agents'");});it('/discover JS stats are only set on first page (not on paginated loads)', () => {diff --git a/tests/list-controls.test.js b/tests/list-controls.test.jsnew file mode 100644index 000000000..f0257e98e--- /dev/null+++ b/tests/list-controls.test.js@@ -0,0 +1,211 @@+// @vitest-environment jsdom+//+// Shared list-controls toolkit (E03) — the unified search / sort / filter /+// URL-sync layer adopted on /discover and /marketplace. These tests lock the+// contract both surfaces rely on: pure URL helpers round-trip state, and the+// controller renders accessible controls, debounces search, syncs the URL, and+// re-emits on back/forward.++import { describe, it, expect, beforeEach, vi } from 'vitest';+import {+ debounce,+ readStateFromUrl,+ syncStateToUrl,+ createListControls,+} from '../src/shared/list-controls.js';++describe('list-controls — pure helpers', () => {+ beforeEach(() => {+ history.replaceState({}, '', '/');+ });++ it('debounce fires once on the trailing edge', async () => {+ vi.useFakeTimers();+ const spy = vi.fn();+ const d = debounce(spy, 200);+ d('a');+ d('b');+ d('c');+ expect(spy).not.toHaveBeenCalled();+ vi.advanceTimersByTime(200);+ expect(spy).toHaveBeenCalledTimes(1);+ expect(spy).toHaveBeenCalledWith('c');+ vi.useRealTimers();+ });++ it('debounce.flush runs immediately and cancel drops the pending call', () => {+ vi.useFakeTimers();+ const spy = vi.fn();+ const d = debounce(spy, 200);+ d('x');+ d.flush('y');+ expect(spy).toHaveBeenCalledWith('y');+ d('z');+ d.cancel();+ vi.advanceTimersByTime(500);+ expect(spy).toHaveBeenCalledTimes(1);+ vi.useRealTimers();+ });++ it('readStateFromUrl only reads declared keys and falls back to defaults', () => {+ history.replaceState({}, '', '/?q=robot&sort=alpha&stray=nope');+ const s = readStateFromUrl({ q: '', sort: 'newest', chain: '' });+ expect(s).toEqual({ q: 'robot', sort: 'alpha', chain: '' });+ expect(s.stray).toBeUndefined();+ });++ it('syncStateToUrl drops keys equal to their default (canonical short URLs)', () => {+ history.replaceState({}, '', '/');+ syncStateToUrl({ q: 'robot', sort: 'newest', chain: '8453' }, { q: '', sort: 'newest', chain: '' });+ const p = new URLSearchParams(location.search);+ expect(p.get('q')).toBe('robot');+ expect(p.get('chain')).toBe('8453');+ expect(p.has('sort')).toBe(false); // equals default → dropped+ });++ it('readStateFromUrl + syncStateToUrl round-trip', () => {+ const defaults = { q: '', sort: 'newest', filter: 'all' };+ history.replaceState({}, '', '/');+ syncStateToUrl({ q: 'agent', sort: 'alpha', filter: '3d' }, defaults);+ expect(readStateFromUrl(defaults)).toEqual({ q: 'agent', sort: 'alpha', filter: '3d' });+ });+});++describe('list-controls — controller', () => {+ let mount;+ beforeEach(() => {+ history.replaceState({}, '', '/');+ document.body.innerHTML = '<div id="mount"></div>';+ mount = document.getElementById('mount');+ });++ function build(onChange = () => {}) {+ return createListControls({+ mount,+ searchKey: 'q',+ searchPlaceholder: 'Search…',+ searchLabel: 'Search agents',+ defaults: { q: '', filter: 'all', sort: 'newest' },+ segments: [+ {+ key: 'filter',+ label: 'Type',+ options: [+ { value: 'all', label: 'All' },+ { value: '3d', label: '3D' },+ ],+ },+ ],+ sortKey: 'sort',+ sortOptions: [+ { value: 'newest', label: 'Newest' },+ { value: 'alpha', label: 'A → Z' },+ ],+ debounceMs: 200,+ onChange,+ });+ }++ it('renders an accessible search input, chip group, and sort select', () => {+ build();+ const input = mount.querySelector('[data-lc="search"]');+ expect(input).toBeTruthy();+ expect(input.getAttribute('type')).toBe('search');+ expect(input.getAttribute('aria-label')).toBe('Search agents');+ const group = mount.querySelector('[data-lc-seg-group]');+ expect(group.getAttribute('role')).toBe('group');+ const chips = mount.querySelectorAll('[data-lc-seg="filter"]');+ expect(chips.length).toBe(2);+ expect(chips[0].getAttribute('aria-pressed')).toBe('true');+ const sort = mount.querySelector('[data-lc="sort"]');+ expect(sort.getAttribute('aria-label')).toBe('Sort results');+ });++ it('hydrates controls from the URL on init', () => {+ history.replaceState({}, '', '/?q=robot&filter=3d&sort=alpha');+ const lc = build();+ expect(mount.querySelector('[data-lc="search"]').value).toBe('robot');+ expect(mount.querySelector('[data-lc="sort"]').value).toBe('alpha');+ const active = mount.querySelector('[data-lc-seg="filter"].active');+ expect(active.dataset.lcValue).toBe('3d');+ expect(lc.getState()).toMatchObject({ q: 'robot', filter: '3d', sort: 'alpha' });+ expect(lc.isFiltered()).toBe(true);+ });++ it('chip click updates state, toggles active class, and pushes to the URL', () => {+ const onChange = vi.fn();+ build(onChange);+ const chip3d = mount.querySelector('[data-lc-seg="filter"][data-lc-value="3d"]');+ chip3d.click();+ expect(chip3d.classList.contains('active')).toBe(true);+ expect(chip3d.getAttribute('aria-pressed')).toBe('true');+ expect(new URLSearchParams(location.search).get('filter')).toBe('3d');+ expect(onChange).toHaveBeenCalledWith(+ expect.objectContaining({ filter: '3d' }),+ expect.objectContaining({ reason: 'segment' }),+ );+ });++ it('debounces search input then emits once and syncs the URL', () => {+ vi.useFakeTimers();+ const onChange = vi.fn();+ build(onChange);+ const input = mount.querySelector('[data-lc="search"]');+ input.value = 'rob';+ input.dispatchEvent(new Event('input'));+ input.value = 'robot';+ input.dispatchEvent(new Event('input'));+ expect(onChange).not.toHaveBeenCalled();+ vi.advanceTimersByTime(200);+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(onChange).toHaveBeenCalledWith(+ expect.objectContaining({ q: 'robot' }),+ expect.objectContaining({ reason: 'search' }),+ );+ expect(new URLSearchParams(location.search).get('q')).toBe('robot');+ vi.useRealTimers();+ });++ it('search clear button resets the query and refocuses the input', () => {+ history.replaceState({}, '', '/?q=robot');+ const onChange = vi.fn();+ build(onChange);+ const clear = mount.querySelector('[data-lc="search-clear"]');+ expect(clear.hidden).toBe(false);+ clear.click();+ expect(mount.querySelector('[data-lc="search"]').value).toBe('');+ expect(new URLSearchParams(location.search).has('q')).toBe(false);+ expect(onChange).toHaveBeenCalledWith(+ expect.objectContaining({ q: '' }),+ expect.objectContaining({ reason: 'search-clear' }),+ );+ });++ it('reset() returns every control to its default', () => {+ history.replaceState({}, '', '/?q=robot&filter=3d&sort=alpha');+ const onChange = vi.fn();+ const lc = build(onChange);+ lc.reset();+ expect(lc.getState()).toEqual({ q: '', filter: 'all', sort: 'newest' });+ expect(lc.isFiltered()).toBe(false);+ expect(mount.querySelector('[data-lc="search"]').value).toBe('');+ expect(location.search).toBe('');+ });++ it('urlSync:false leaves the URL untouched (page owns the scheme)', () => {+ const onChange = vi.fn();+ createListControls({+ mount,+ searchKey: 'q',+ urlSync: false,+ defaults: { q: '', filter: 'all' },+ segments: [+ { key: 'filter', options: [{ value: 'all', label: 'All' }, { value: '3d', label: '3D' }] },+ ],+ onChange,+ });+ mount.querySelector('[data-lc-seg="filter"][data-lc-value="3d"]').click();+ expect(location.search).toBe(''); // toolkit did NOT write the URL+ expect(onChange).toHaveBeenCalled();+ });+});diff --git a/vite.config.js b/vite.config.jsindex 1bdf477d8..3840be172 100644--- a/vite.config.js+++ b/vite.config.js@@ -1402,6 +1402,33 @@ support: resolve(__dirname, 'pages/support.html'),},},},+ {+ // Vercel Speed Insights — real-user Core Web Vitals (LCP/INP/CLS/TTFB)+ // for every page, collected from actual visitors and surfaced in the+ // Vercel dashboard. This is the "measure, don't guess" complement to the+ // first-party error reporter above: it tells us which pages are slow for+ // real users under load instead of inferring it from synthetic audits.+ //+ // Injected ONLY on Vercel builds (process.env.VERCEL is set there). The+ // script is served by the platform at /_vercel/speed-insights/script.js+ // once Speed Insights is enabled for the project; off-Vercel (the+ // push-only mirror, local dev) it would 404, so we never emit it there.+ // Zero ingestion code by design — the platform owns collection + storage.+ name: 'vercel-speed-insights',+ transformIndexHtml: {+ order: 'pre',+ handler() {+ if (!process.env.VERCEL) return [];+ return [+ {+ tag: 'script',+ attrs: { defer: true, src: '/_vercel/speed-insights/script.js' },+ injectTo: 'head',+ },+ ];+ },+ },+ },{// Native View Transitions for internal nav. Chrome/Safari ship it,// Firefox falls back to a normal location change (no UX regression).diff --git a/x402-payment-modal/CHANGELOG.md b/x402-payment-modal/CHANGELOG.mdindex bd1b7e985..0765dff7d 100644--- a/x402-payment-modal/CHANGELOG.md+++ b/x402-payment-modal/CHANGELOG.md@@ -15,6 +15,23 @@ Hardening pass for scale and a UX/accessibility overhaul.program (legacy vs Token-2022) and derives ATAs, the idempotent-create, and`transferChecked` against the right one.+### Added — wallets++- **Multi-wallet detection.** Solana now detects Phantom, Solflare, Backpack,+ Glow, and Coinbase Wallet (was Phantom-only); EVM uses **EIP-6963** multi-+ provider discovery (falling back to `window.ethereum[.providers]`) so a user+ with several wallets isn't stuck with whichever won the injection race. The+ connect screen lists every detected wallet; auto-connect only fires when+ exactly one is present.++### Added — developer experience++- **First-class React export** — `import { X402Button, useX402 } from+ '@three-ws/x402-payment-modal/react'`. `useX402()` exposes a+ `{ pay, status, result, error, reset, isPaying }` state machine; both are+ SSR-safe (the browser-only core is dynamically imported on first use). `react`+ is an optional peer dependency.+### Added — reliability & scale- **RPC failover** — `prepareSolanaCheckout` / `handleCheckout` accept `rpcUrls`diff --git a/x402-payment-modal/package.json b/x402-payment-modal/package.jsonindex a460efb6f..524c4ff6b 100644--- a/x402-payment-modal/package.json+++ b/x402-payment-modal/package.json@@ -32,6 +32,11 @@"import": "./server/vercel.js","default": "./server/vercel.js"},+ "./react": {+ "types": "./react/index.d.ts",+ "import": "./react/index.js",+ "default": "./react/index.js"+ },"./package.json": "./package.json"},"files": [@@ -39,6 +44,7 @@"dist","types","server",+ "react","examples","docs","README.md",@@ -87,7 +93,8 @@},"peerDependencies": {"@solana/web3.js": "^1.95.0",- "@solana/spl-token": "^0.4.0"+ "@solana/spl-token": "^0.4.0",+ "react": ">=17"},"peerDependenciesMeta": {"@solana/web3.js": {@@ -95,6 +102,9 @@},"@solana/spl-token": {"optional": true+ },+ "react": {+ "optional": true}},"devDependencies": {diff --git a/x402-payment-modal/react/index.d.ts b/x402-payment-modal/react/index.d.tsnew file mode 100644index 000000000..a6397ecbb--- /dev/null+++ b/x402-payment-modal/react/index.d.ts@@ -0,0 +1,39 @@+import type { ComponentPropsWithoutRef, ReactNode } from 'react';+import type { PayOptions, PayResult, X402Config } from '@three-ws/x402-payment-modal';++export type X402Status = 'idle' | 'paying' | 'done' | 'error';++export interface UseX402Return {+ /** Open the modal and run the 402 → sign → settle flow. Resolves to the result, or `undefined` if the user cancelled. */+ pay: (opts?: Partial<PayOptions>) => Promise<PayResult | undefined>;+ status: X402Status;+ result: PayResult | null;+ error: Error | null;+ reset: () => void;+ isPaying: boolean;+}++/** Payment hook with a small state machine. `defaults` are merged under every `pay()` call. */+export function useX402(defaults?: Partial<PayOptions>): UseX402Return;++/** Configure the modal before the first payment (resolves once applied). */+export function configure(opts?: X402Config): Promise<Required<X402Config>>;++export interface X402ButtonProps extends Omit<ComponentPropsWithoutRef<'button'>, 'onError' | 'children'> {+ endpoint: string;+ method?: string;+ body?: unknown;+ merchant?: string;+ action?: string;+ caps?: PayOptions['caps'];+ headers?: Record<string, string>;+ autoConnect?: boolean;+ label?: string;+ onResult?: (result: PayResult) => void;+ onError?: (error: Error) => void;+ children?: ReactNode;+}++/** Drop-in pay button. */+export function X402Button(props: X402ButtonProps): JSX.Element;+export default X402Button;diff --git a/x402-payment-modal/react/index.js b/x402-payment-modal/react/index.jsnew file mode 100644index 000000000..a1d69e852--- /dev/null+++ b/x402-payment-modal/react/index.js@@ -0,0 +1,112 @@+// @three-ws/x402-payment-modal/react — first-class React bindings.+//+// import { X402Button, useX402 } from '@three-ws/x402-payment-modal/react';+//+// The core package is a browser-only ES module (it renders a modal and talks to+// a wallet), so it is dynamically imported on first use — nothing from it runs+// during render or on the server, keeping this SSR-safe. `react` is an optional+// peer dependency; this file uses `createElement` so it needs no JSX build step.++import { createElement, useCallback, useRef, useState } from 'react';++let _modPromise;+function loadCore() {+ if (!_modPromise) _modPromise = import('@three-ws/x402-payment-modal');+ return _modPromise;+}++/**+ * Configure the modal (checkout origin, theme, branding, …) before the first+ * payment. Resolves once the core module has loaded and applied the config.+ */+export function configure(opts) {+ return loadCore().then((m) => m.configure(opts));+}++/**+ * Headless-ish payment hook with a small state machine.+ * @param {object} [defaults] PayOptions merged under every pay() call.+ * @returns {{ pay: Function, status: string, result: any, error: Error|null, reset: Function, isPaying: boolean }}+ */+export function useX402(defaults = {}) {+ const [status, setStatus] = useState('idle'); // idle | paying | done | error+ const [result, setResult] = useState(null);+ const [error, setError] = useState(null);+ const inflight = useRef(false);+ // Keep the latest defaults without making pay() identity churn every render.+ const defaultsRef = useRef(defaults);+ defaultsRef.current = defaults;++ const pay = useCallback(async (opts = {}) => {+ if (inflight.current) return undefined;+ inflight.current = true;+ setStatus('paying');+ setError(null);+ setResult(null);+ try {+ const m = await loadCore();+ const res = await m.pay({ ...defaultsRef.current, ...opts });+ setResult(res);+ setStatus('done');+ return res;+ } catch (err) {+ // User dismissed the modal — not an error; return to idle quietly.+ if (err && err.code === 'cancelled') {+ setStatus('idle');+ return undefined;+ }+ setError(err);+ setStatus('error');+ throw err;+ } finally {+ inflight.current = false;+ }+ }, []);++ const reset = useCallback(() => {+ setStatus('idle');+ setResult(null);+ setError(null);+ }, []);++ return { pay, status, result, error, reset, isPaying: status === 'paying' };+}++/**+ * Drop-in pay button. Passes its payment props to `pay()`; calls `onResult` on+ * success and `onError` on failure (cancellation is silent).+ */+export function X402Button({+ endpoint,+ method,+ body,+ merchant,+ action,+ caps,+ headers,+ autoConnect,+ label = 'Pay',+ onResult,+ onError,+ children,+ ...rest+}) {+ const { pay, isPaying } = useX402();++ const handleClick = useCallback(async () => {+ try {+ const res = await pay({ endpoint, method, body, merchant, action, caps, headers, autoConnect });+ if (res) onResult?.(res);+ } catch (err) {+ onError?.(err);+ }+ }, [pay, endpoint, method, body, merchant, action, caps, headers, autoConnect, onResult, onError]);++ return createElement(+ 'button',+ { type: 'button', onClick: handleClick, disabled: isPaying, 'aria-busy': isPaying, ...rest },+ isPaying ? 'Processing…' : (children ?? label),+ );+}++export default X402Button;diff --git a/x402-payment-modal/src/index.js b/x402-payment-modal/src/index.jsindex 92d50217c..860a24c6b 100644--- a/x402-payment-modal/src/index.js+++ b/x402-payment-modal/src/index.js@@ -26,8 +26,9 @@// action: 'Summarize',// });//-// The modal handles wallet connect (Phantom for Solana, window.ethereum for-// Base/EVM USDC via EIP-3009), drives the 402 → sign → retry flow, optional+// The modal handles wallet connect (Phantom/Solflare/Backpack/… for Solana,+// EIP-6963 browser wallets for Base/EVM USDC via EIP-3009), drives the+// 402 → sign → retry flow, optional// SIWX (Sign-In-With-X) re-entry, client-side spending caps, and shows the// result. Vanilla JS, no bundler required.//@@ -920,6 +921,65 @@ const STEP_LABELS = {verify: "Payment couldn't be completed",};+// ──────────────────────────────────────────────────── wallet discovery ────+// Detect every injected Solana wallet, not just Phantom — Solflare/Backpack/Glow+// users were dead-ended before. They share Phantom's connect/signTransaction/+// signMessage shape, so each drops straight into runSolana. Returns+// [{ kind:'solana', name, provider, icon }] in preference order.+function discoverSolanaWallets() {+ if (typeof window === 'undefined') return [];+ const out = [];+ const seen = new Set();+ const add = (name, provider, icon) => {+ if (!provider || typeof provider.signTransaction !== 'function' || seen.has(provider)) return;+ seen.add(provider);+ out.push({ kind: 'solana', name, provider, icon: icon || ICONS.wallet });+ };+ add('Phantom', window.phantom?.solana || (window.solana?.isPhantom ? window.solana : null), ICONS.phantom);+ add('Solflare', window.solflare?.isSolflare ? window.solflare : null, ICONS.wallet);+ add('Backpack', window.backpack?.isBackpack ? window.backpack : null, ICONS.wallet);+ add('Glow', window.glowSolana || window.glow || null, ICONS.wallet);+ add('Coinbase Wallet', window.coinbaseSolana || null, ICONS.wallet);+ // A standards-compliant injected provider that isn't one of the above.+ if (window.solana && !window.solana.isPhantom) add(window.solana.isSolflare ? 'Solflare' : 'Solana wallet', window.solana, ICONS.wallet);+ return out;+}++// EIP-6963 multi-provider discovery so a user with several EVM wallets isn't+// stuck with whoever won the window.ethereum race. Wallets that implement 6963+// re-announce synchronously on request; we fall back to legacy window.ethereum+// (and its .providers[] array) when none do.+function discoverEvmWallets() {+ if (typeof window === 'undefined' || typeof window.dispatchEvent !== 'function') return [];+ const out = [];+ const seen = new Set();+ const add = (name, provider, icon) => {+ if (!provider || seen.has(provider)) return;+ seen.add(provider);+ out.push({ kind: 'evm', name: name || 'Browser wallet', provider, icon: icon || ICONS.wallet });+ };+ const announced = [];+ const onAnnounce = (e) => { if (e?.detail) announced.push(e.detail); };+ window.addEventListener('eip6963:announceProvider', onAnnounce);+ try { window.dispatchEvent(new Event('eip6963:requestProvider')); } catch { /* ignore */ }+ window.removeEventListener('eip6963:announceProvider', onAnnounce);+ for (const d of announced) add(d.info?.name, d.provider, d.info?.icon);+ if (!out.length) {+ const eth = window.ethereum;+ const label = (p) => (p?.isMetaMask ? 'MetaMask' : p?.isCoinbaseWallet ? 'Coinbase Wallet' : 'Browser wallet');+ if (Array.isArray(eth?.providers)) for (const p of eth.providers) add(label(p), p);+ else if (eth) add(label(eth), eth);+ }+ return out;+}++// A wallet's icon is either an inline SVG string (our ICONS) or a data:/https+// URL (EIP-6963 / Wallet-Standard supply these) — render accordingly.+function walletIconHtml(icon) {+ if (icon && /^(data:|https?:)/.test(icon)) return `<img src="${escapeHtml(icon)}" alt="" />`;+ return icon || ICONS.wallet;+}+function injectStyles() {if (document.getElementById(STYLE_ID)) return;const el = document.createElement('style');@@ -1082,8 +1142,13 @@ class CheckoutModal {}renderConnect() {- const phantomDetected = typeof window !== 'undefined' && (window.solana?.isPhantom || window.phantom?.solana);- const evmDetected = typeof window !== 'undefined' && window.ethereum;+ // Detect ALL injected wallets, not just Phantom/window.ethereum.+ const solanaWallets = discoverSolanaWallets();+ const evmWallets = discoverEvmWallets();+ this._solWallets = solanaWallets;+ this._evmWallets = evmWallets;+ const phantomDetected = solanaWallets.length > 0;+ const evmDetected = evmWallets.length > 0;const solanaList = listSolanaAccepts(this.challenge);// Keep a valid selection: honour the buyer's prior pick if it's still on// offer, otherwise fall back to the default (USDC-first).@@ -1114,10 +1179,12 @@ class CheckoutModal {// fallback, which needs to explain itself. One-shot via autoConnectTried.if (this.opts.autoConnect && !this.autoConnectTried && !this.siwxFallbackNotice) {this.autoConnectTried = true;- const solanaViable = !!(solanaAccept && phantomDetected);- const evmViable = !!(evmAccept && evmDetected);- if (solanaViable && !evmViable) { this.runSolana(solanaAccept); return; }- if (evmViable && !solanaViable) { this.runEvm(evmAccept); return; }+ // Only auto-connect when there's exactly one wallet to choose — otherwise+ // the buyer must pick which one.+ const solanaViable = solanaAccept && solanaWallets.length === 1;+ const evmViable = evmAccept && evmWallets.length === 1;+ if (solanaViable && !evmViable) { this.runSolana(solanaAccept, solanaWallets[0].provider); return; }+ if (evmViable && !solanaViable) { this.runEvm(evmAccept, evmWallets[0].provider); return; }}// When the merchant offers more than one Solana token (e.g. USDC and@@ -1143,22 +1210,42 @@ class CheckoutModal {const solMeta = solanaList.length > 1? `${networkLabel(solanaAccept.network, solanaAccept)} · ${solInfo.symbol}`: networkLabel(solanaAccept.network, solanaAccept);- buttons.push(`- <button class="x402-wallet-btn" data-wallet="phantom" ${phantomDetected ? '' : 'disabled'}>- <div class="x402-wallet-icon">${ICONS.phantom}</div>- <span class="x402-wallet-name">${phantomDetected ? 'Phantom' : 'Phantom (not detected)'}</span>- <span class="x402-wallet-meta" data-sol-meta>${escapeHtml(solMeta)}</span>- </button>- `);+ if (solanaWallets.length) {+ solanaWallets.forEach((w, i) => buttons.push(`+ <button class="x402-wallet-btn" data-wallet-kind="solana" data-wallet-idx="${i}">+ <div class="x402-wallet-icon">${walletIconHtml(w.icon)}</div>+ <span class="x402-wallet-name">${escapeHtml(w.name)}</span>+ <span class="x402-wallet-meta"${i === 0 ? ' data-sol-meta' : ''}>${escapeHtml(solMeta)}</span>+ </button>+ `));+ } else {+ buttons.push(`+ <button class="x402-wallet-btn" disabled>+ <div class="x402-wallet-icon">${ICONS.phantom}</div>+ <span class="x402-wallet-name">No Solana wallet detected</span>+ <span class="x402-wallet-meta">${escapeHtml(solMeta)}</span>+ </button>+ `);+ }}if (evmAccept) {- buttons.push(`- <button class="x402-wallet-btn" data-wallet="evm" ${evmDetected ? '' : 'disabled'}>- <div class="x402-wallet-icon">${ICONS.wallet}</div>- <span class="x402-wallet-name">${evmDetected ? 'Browser wallet' : 'No EVM wallet detected'}</span>- <span class="x402-wallet-meta">${networkLabel(evmAccept.network, evmAccept)}</span>- </button>- `);+ if (evmWallets.length) {+ evmWallets.forEach((w, i) => buttons.push(`+ <button class="x402-wallet-btn" data-wallet-kind="evm" data-wallet-idx="${i}">+ <div class="x402-wallet-icon">${walletIconHtml(w.icon)}</div>+ <span class="x402-wallet-name">${escapeHtml(w.name)}</span>+ <span class="x402-wallet-meta">${escapeHtml(networkLabel(evmAccept.network, evmAccept))}</span>+ </button>+ `));+ } else {+ buttons.push(`+ <button class="x402-wallet-btn" disabled>+ <div class="x402-wallet-icon">${ICONS.wallet}</div>+ <span class="x402-wallet-name">No EVM wallet detected</span>+ <span class="x402-wallet-meta">${escapeHtml(networkLabel(evmAccept.network, evmAccept))}</span>+ </button>+ `);+ }}// When nothing is installed, don't dead-end — point users to a wallet.const installHelp = (!phantomDetected && !evmDetected)@@ -1184,13 +1271,14 @@ class CheckoutModal {`;requestAnimationFrame(() => this.focusFirst());const onClick = (e) => {- const btn = e.target.closest('[data-wallet]');+ const btn = e.target.closest('[data-wallet-kind]');if (!btn || btn.disabled) return;- const wallet = btn.dataset.wallet;- if (wallet === 'phantom') this.runSolana(this.solanaAccept);- else if (wallet === 'evm') this.runEvm(evmAccept);+ const kind = btn.dataset.walletKind;+ const idx = Number(btn.dataset.walletIdx);+ if (kind === 'solana') this.runSolana(this.solanaAccept, this._solWallets[idx]?.provider);+ else if (kind === 'evm') this.runEvm(evmAccept, this._evmWallets[idx]?.provider);};- this.bodyEl.querySelectorAll('[data-wallet]').forEach((b) => b.addEventListener('click', onClick));+ this.bodyEl.querySelectorAll('[data-wallet-kind]').forEach((b) => b.addEventListener('click', onClick));// Token chooser — switch the active Solana token in place: update the// headline price and the Phantom button's token label without a re-render@@ -1366,13 +1454,14 @@ class CheckoutModal {}}- async runSolana(accept) {+ async runSolana(accept, providerArg) {this.accept = accept;this.setPrice(accept);- this.renderProgress('connect', { text: 'Opening Phantom…' });+ const provider = providerArg || window.phantom?.solana || window.solana;+ const walletName = provider?.isPhantom ? 'Phantom' : (this._solWallets?.find((w) => w.provider === provider)?.name || 'wallet');+ this.renderProgress('connect', { text: `Opening ${walletName}…` });try {- const provider = window.phantom?.solana || window.solana;- if (!provider) throw new Error('Phantom wallet not detected');+ if (!provider) throw new Error('No Solana wallet detected');const conn = await provider.connect();const payerAddress = (conn?.publicKey || provider.publicKey)?.toString();if (!payerAddress) throw new Error('Phantom did not return a public key');@@ -1421,12 +1510,12 @@ class CheckoutModal {}}- async runEvm(accept) {+ async runEvm(accept, providerArg) {this.accept = accept;this.setPrice(accept);this.renderProgress('connect', { text: 'Opening browser wallet…' });try {- const eth = window.ethereum;+ const eth = providerArg || window.ethereum;if (!eth) throw new Error('No EVM wallet detected');const accounts = await eth.request({ method: 'eth_requestAccounts' });const payerAddress = accounts?.[0];