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: feature tour curriculum, walk sessions, and x402 checkout updates
nirholas31f003c1873c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 93b2ae412..2a1ff89a1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,8 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr## 2026-06-21+- **Docs · Walk Avatar** (`/docs/walk`) — 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.+- **Feed** (`/feed`) — Recent activity from the people and agents you follow on three.ws.- **Walk** (`/walk`) — Your 3D avatar walks anywhere on the web. Live demos across six environments, a Chrome extension, one-tag embeds, and a global distance leaderboard.- **Walk Leaderboard** (`/walk-leaderboard`) — Global leaderboard for the walking avatar — distance walked, sites visited, and time, ranked daily, weekly, and all-time.- **$THREE buyback commitment is now public and verifiable on the token page** — The $THREE page now leads with the protocol's buyback commitment — the fixed share of all platform revenue routed into buying $THREE on the open market and sending it to the treasury — shown as revenue earned, dollars committed, dollars deployed on-chain, and how much of the commitment has been kept. Every individual buyback is listed with a one-click Solscan receipt, so the promise is provable, not just stated. No burn: supply is never destroyed. (`/three-token`) `[feature]`@@ -35,6 +37,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Smoother landing page on hover** — The homepage's parallax hero and 3D stack-card glow used to read the page layout on every pointer move, which could make the cursor feel sticky on the first page new visitors see. Those effects now batch their work to one frame at a time, so hover and tilt stay buttery on any device. (`/`) `[improvement]`- **Solana is now the default payment network** — Solana is now the default everywhere you pick a chain — the dashboard's Default payment network setting, x402 merchant settlement, and the monetization payout wallet all default to Solana for every user, with Solana listed first. Base and Polygon remain available if you prefer an EVM chain. (`/dashboard`) `[improvement]`- **The $THREE page now spells out why to hold — four real utility pillars** — The $THREE page leads with a clear "Why hold $THREE" section: revenue buybacks (a fixed, live share of platform revenue buys $THREE on the open market), holder rewards (every paid action reflects $THREE back to holders pro-rata), hold-to-access (discounts, higher quotas, and pro perks), and real usage (deploying agents, forging avatars, and trading the marketplace all run on $THREE). Each pillar maps to a mechanism that actually exists on the platform, and the buyback figure is wired to the live commitment. The page's market data also now rides a shared cache, so it stays fast and reliable under heavy traffic. (`/three-token`) `[feature, improvement]`+- **The guided tour, now yours to steer** — The 3D guided tour got a major upgrade. Pick how deep to go: a new “Quick highlights” track samples the best of every chapter in a few minutes, or take the full feature-by-feature walk. A new tour map (open it from the ☰ button or press C) lists every chapter and stop, marks where you are, and lets you search and jump anywhere instantly. You can now change the narrator's voice and set the playback speed (0.75×–1.5×) on the fly, and the tour remembers your spot, voice, and pace across sessions — come back later and pick up right where you left off. (`/tour`) `[feature, improvement]`- **Walk with any agent, and leave a trail** — Every agent profile now has a “Walk with this agent” action and a live preview that renders that specific agent walking — the walk embed can now load any agent’s avatar by id. And the walking avatar leaves an aesthetic trail behind it (footprints, a glow, or a fading line, your pick) both in the full walk scene and the site-wide companion. (`/walk`) `[feature, improvement]`- **Your avatar now walks anywhere — new Walk hub, leaderboard, and creator analytics** — There's a dedicated home for the walking avatar at /walk with live demos across six environments, an embeddable one-tag widget, and a Chrome-extension CTA. A new global leaderboard ranks walkers by distance, sites visited, and time (daily / weekly / all-time), and creators who embed an avatar get a private analytics dashboard — sessions, average duration, distance, top embed origins, and custom conversion events. Page-to-page navigation also gained themed, motion-aware transitions. (`/walk`) `[feature]`diff --git a/api/_lib/migrations/20260621170000_walk_session.sql b/api/_lib/migrations/20260621170000_walk_session.sqlnew file mode 100644index 000000000..2915c52c0--- /dev/null+++ b/api/_lib/migrations/20260621170000_walk_session.sql@@ -0,0 +1,34 @@+-- Walk session persistence — resume-where-you-left-off for the /walk runtime.+--+-- One row per signed-in user holds the last snapshot of their walk state so+-- returning to /walk (on any device) resumes from where they left off instead of+-- starting over. Anonymous walkers persist the same shape to localStorage in the+-- browser; only authenticated users sync here, which is what gives cross-device+-- continuity (walk on a laptop, reopen on a phone, same state restored).+--+-- The snapshot is a single jsonb document rather than a wide column set: the walk+-- client owns the shape (avatar id, environment, camera mode, position/heading,+-- trail style, recent gestures, companion prefs, multiplayer room) and it evolves+-- with the runtime, so a schema-less document avoids a migration per new field.+-- The server still validates the document with zod (api/walk/session.js) before+-- it is written, so a malformed/hostile client can't store arbitrary blobs.+--+-- One row per user (PK = user_id), upserted on every save (last-write-wins).+-- updated_at drives the "< 7 days old" freshness gate the client applies on+-- restore, and lets a future sweep reclaim long-abandoned rows.+--+-- Idempotent — safe to re-run.++create table if not exists walk_sessions (+ user_id uuid primary key references users(id) on delete cascade,+ -- The full client-owned snapshot. Validated by api/walk/session.js before+ -- write; never trusted as-is on read beyond shape.+ state jsonb not null default '{}'::jsonb,+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now()+);++-- Freshness / sweep ordering: the most recently touched sessions first, and a+-- cheap predicate for a background reclaim of rows older than the restore window.+create index if not exists walk_sessions_updated_at+ on walk_sessions (updated_at desc);diff --git a/api/walk/session.js b/api/walk/session.jsnew file mode 100644index 000000000..25ff4ef06--- /dev/null+++ b/api/walk/session.js@@ -0,0 +1,131 @@+// /api/walk/session — resume-where-you-left-off persistence for the /walk runtime.+//+// GET → load the signed-in user's last walk snapshot, or 204 when none exists.+// PUT → save (upsert) the snapshot. Last-write-wins per user.+//+// This is the cross-device sync half of walk session persistence: the walk client+// (src/walk-session.js) debounce-saves the live state and restores it on load.+// Anonymous walkers persist the same shape to localStorage; only authenticated+// users reach this endpoint, which is what gives continuity across browsers+// (walk on a laptop, reopen on a phone, same state restored).+//+// Identity: a session cookie or bearer token resolves the user server-side. No+// user → 401, so an unauthenticated client cleanly falls back to localStorage.+//+// The snapshot is a single client-owned document validated with zod here before+// it is written, so the row never stores arbitrary blobs. The document shape is+// kept in lockstep with src/walk-session.js.++import { z } from 'zod';+import { cors, method, readJson, json, error, 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 { getSessionUser, extractBearer, authenticateBearer } from '../_lib/auth.js';++export const maxDuration = 10;++const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++// The walk snapshot. Every field is optional so a partial save (e.g. only a+// camera-mode change) is valid; the client always sends what it currently holds.+// Bounds are deliberately tight — this is small UI state, never a payload.+const stateSchema = z+ .object({+ // Selected avatar (a real avatar UUID) or null for the default avatar.+ avatarId: z.string().regex(UUID_RE).nullable().optional(),+ avatarUrl: z.string().max(2048).nullable().optional(),+ // Environment scene name (manifest `name`, e.g. "park").+ envId: z.string().trim().max(64).nullable().optional(),+ // Camera mode — one of the walk runtime's modes.+ cameraMode: z.enum(['follow', 'cinematic', 'firstperson', 'topdown']).nullable().optional(),+ // Last known world position (metres) + facing (radians).+ position: z+ .object({+ x: z.number().finite(),+ y: z.number().finite(),+ z: z.number().finite(),+ })+ .nullable()+ .optional(),+ heading: z.number().finite().nullable().optional(),+ // Path-trail style (off | footprints | glow | line).+ trailStyle: z.string().trim().max(32).nullable().optional(),+ // Most-recent-first list of gesture names used, surfaced for quick re-use.+ recentGestures: z.array(z.string().trim().max(48)).max(5).optional(),+ // Companion preferences mirrored from the in-page companion controls.+ companion: z+ .object({+ size: z.number().finite().min(0.1).max(10).optional(),+ walkSpeed: z.number().finite().min(0).max(20).optional(),+ })+ .strict()+ .nullable()+ .optional(),+ // Multiplayer room code, when the session is in a room.+ roomCode: z.string().trim().max(64).nullable().optional(),+ // Client-stamped capture time (epoch ms) — informational; the server's+ // updated_at is authoritative for the freshness gate.+ savedAt: z.number().finite().nonnegative().optional(),+ })+ .strict();++const putSchema = z.object({ state: stateSchema }).strict();++async function resolveUserId(req) {+ try {+ const bearer = extractBearer(req);+ const user = bearer ? await authenticateBearer(bearer) : await getSessionUser(req);+ return user?.userId || user?.id || user?.sub || null;+ } catch {+ return null;+ }+}++export default wrap(async (req, res) => {+ // Same-origin only — this is per-user state behind a session cookie. Echo the+ // app origin and allow credentials so the cookie rides along on the fetch.+ if (cors(req, res, { methods: 'GET,PUT,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET', 'PUT'])) return;++ const ip = clientIp(req);+ const rl = await limits.prefsWrite(ip);+ if (!rl.success) return rateLimited(res, rl, 'too many walk-session writes');++ const userId = await resolveUserId(req);+ if (!userId) {+ // No identity → the client persists to localStorage instead. A clear 401+ // (not a 200 with empty state) lets it distinguish "not signed in" from+ // "signed in, nothing saved yet".+ return error(res, 401, 'unauthenticated', 'sign in to sync your walk across devices');+ }++ if (req.method === 'GET') {+ const rows = await sql`+ select state, updated_at+ from walk_sessions+ where user_id = ${userId}+ limit 1+ `;+ if (!rows[0]) return json(res, 204, {});+ return json(res, 200, {+ state: rows[0].state || {},+ updatedAt: rows[0].updated_at,+ });+ }++ // PUT — upsert the snapshot (last-write-wins).+ const raw = await readJson(req);+ const { state } = parse(putSchema, raw);++ const [row] = await sql`+ insert into walk_sessions (user_id, state, created_at, updated_at)+ values (${userId}, ${JSON.stringify(state)}::jsonb, now(), now())+ on conflict (user_id) do update set+ state = excluded.state,+ updated_at = now()+ returning updated_at+ `;++ return json(res, 200, { ok: true, updatedAt: row.updated_at });+});diff --git a/api/x402-checkout.js b/api/x402-checkout.jsindex 5193f4d2b..8b935cc64 100644--- a/api/x402-checkout.js+++ b/api/x402-checkout.js@@ -80,6 +80,22 @@ async function getMintDecimals(conn, rpc, mint) {return info.decimals;}+// Build a PublicKey from a (schema-trimmed) address, converting web3.js's raw+// "Non-base58 character" / "Invalid public key" throw into a structured 400.+// Without this, a malformed address in the posted `accept` surfaces as an opaque+// 500 — the exact failure that took down USDC checkout when a stray newline rode+// in on the challenge's payTo.+function toPubkey(value, field) {+ try {+ return new PublicKey(value);+ } catch {+ const err = new Error(`${field} is not a valid Solana address`);+ err.status = 400;+ err.code = 'invalid_address';+ throw err;+ }+}+async function getRecentBlockhash(conn, rpc) {const hit = blockhashCache.get(rpc);if (hit && Date.now() - hit.at < BLOCKHASH_TTL_MS) return hit.blockhash;@@ -88,18 +104,26 @@ async function getRecentBlockhash(conn, rpc) {return blockhash;}-const acceptSchema = z.object({+// Solana addresses arrive inside the 402 challenge's `accept` entry, which is+// built from operator-configured env (X402_PAY_TO_SOLANA / X402_FEE_PAYER_SOLANA).+// Those values are pasted into dashboards and routinely carry a trailing newline+// or stray spaces. `.trim()` here means a whitespace-tainted challenge still+// yields a working transaction instead of 500'ing on `new PublicKey()` — the+// same defensive posture as env.js's addr(). Length is checked post-trim.+const solanaAddress = z.string().trim().min(32).max(44);++export const acceptSchema = z.object({scheme: z.literal('exact'),- network: z.string().min(1).max(80),+ network: z.string().trim().min(1).max(80),amount: z.string().regex(/^\d+$/),- asset: z.string().min(32).max(44),- payTo: z.string().min(32).max(44),+ asset: solanaAddress,+ payTo: solanaAddress,maxTimeoutSeconds: z.number().int().positive().optional(),extra: z.object({name: z.string().optional(),decimals: z.number().int().nonnegative().optional(),- feePayer: z.string().min(32).max(44),+ feePayer: solanaAddress,}).passthrough(),});@@ -112,13 +136,13 @@ const acceptSchema = z.object({// sweeping a buyer: ≤ 100 tokens and ≤ 50× the payment per recipient.const TIP_ABS_MAX = 100_000_000n; // 100 USDC in 6-decimal atomicsconst tipSchema = z.object({- to: z.string().min(32).max(44),+ to: z.string().trim().min(32).max(44),amount: z.string().regex(/^\d+$/),});-const prepareSchema = z.object({+export const prepareSchema = z.object({accept: acceptSchema,- buyer: z.string().min(32).max(44),+ buyer: solanaAddress,tips: z.array(tipSchema).max(2).optional(),});@@ -188,10 +212,10 @@ async function handlePrepare(req, res) {const rpc = rpcFor(accept.network);const conn = solanaConnection({ url: rpc, commitment: 'confirmed' });- const mint = new PublicKey(accept.asset);- const payTo = new PublicKey(accept.payTo);- const feePayer = new PublicKey(accept.extra.feePayer);- const buyerPubkey = new PublicKey(buyer);+ const mint = toPubkey(accept.asset, 'asset');+ const payTo = toPubkey(accept.payTo, 'payTo');+ const feePayer = toPubkey(accept.extra.feePayer, 'feePayer');+ const buyerPubkey = toPubkey(buyer, 'buyer');const amount = BigInt(accept.amount);const senderAta = getAssociatedTokenAddressSync(diff --git a/data/changelog.json b/data/changelog.jsonindex d8f6322a9..cafcd7934 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,16 @@{"$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": "The guided tour, now yours to steer",+ "summary": "The 3D guided tour got a major upgrade. Pick how deep to go: a new “Quick highlights” track samples the best of every chapter in a few minutes, or take the full feature-by-feature walk. A new tour map (open it from the ☰ button or press C) lists every chapter and stop, marks where you are, and lets you search and jump anywhere instantly. You can now change the narrator's voice and set the playback speed (0.75×–1.5×) on the fly, and the tour remembers your spot, voice, and pace across sessions — come back later and pick up right where you left off.",+ "tags": [+ "feature",+ "improvement"+ ],+ "link": "/tour"+ },{"date": "2026-06-21","title": "Walk with any agent, and leave a trail",diff --git a/data/pages.json b/data/pages.jsonindex 152aefb42..5c0284d2c 100644--- a/data/pages.json+++ b/data/pages.json@@ -149,6 +149,14 @@"priority": 0.8,"changefreq": "weekly","added": "2026-06-21"+ },+ {+ "path": "/feed",+ "title": "Feed",+ "description": "Recent activity from the people and agents you follow on three.ws.",+ "priority": 0.6,+ "changefreq": "daily",+ "added": "2026-06-21"}]},@@ -1036,6 +1044,14 @@"changefreq": "weekly","added": "2026-04-27"},+ {+ "path": "/docs/walk",+ "title": "Docs · Walk Avatar",+ "description": "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.",+ "priority": 0.7,+ "changefreq": "monthly",+ "added": "2026-06-21"+ },{"path": "/docs/start-here","title": "Docs · Start Here",diff --git a/pages/features.html b/pages/features.htmlindex c9ace2cd2..ce91ba1f3 100644--- a/pages/features.html+++ b/pages/features.html@@ -70,6 +70,273 @@<meta property="og:image:alt" content="Features — three.ws"><meta name="twitter:site" content="@trythreews"><script type="module" src="/model-viewer-meshopt.js"></script>++ <style>+ /* ── Walking-avatar inline demo ─────────────────────────────────────+ Scoped to the features page. Mirrors the design tokens used by the+ animation showcase (.feat-anim-*) so the section reads as part of the+ same family: same accent indigo, same card radii, same spacing rhythm. */+ .feat-walk-demo {+ padding: var(--space-2xl) var(--space-2xl);+ background: linear-gradient(180deg, rgba(99, 102, 241, 0.05) 0%, transparent 100%);+ border-top: 1px solid rgba(255, 255, 255, 0.06);+ border-bottom: 1px solid rgba(255, 255, 255, 0.06);+ }++ .feat-walk-demo-inner {+ max-width: 1100px;+ margin: 0 auto;+ display: grid;+ grid-template-columns: 1fr 360px;+ gap: 48px;+ align-items: center;+ }++ .feat-walk-demo-copy {+ min-width: 0;+ }++ .feat-walk-demo-title {+ font-size: clamp(1.5rem, 2.6vw, 2rem);+ font-weight: 800;+ line-height: 1.15;+ color: var(--color-text, #f9fafb);+ margin: 6px 0 10px;+ }++ .feat-walk-demo-tagline {+ font-size: clamp(1rem, 1.6vw, 1.15rem);+ font-weight: 600;+ color: #c7d2fe;+ margin: 0 0 14px;+ }++ .feat-walk-demo-desc {+ font-size: 14px;+ color: rgba(255, 255, 255, 0.55);+ line-height: 1.65;+ margin: 0 0 22px;+ max-width: 480px;+ }++ .feat-walk-demo-bullets {+ list-style: none;+ margin: 0 0 26px;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: 12px;+ }++ .feat-walk-demo-bullet {+ display: flex;+ align-items: center;+ gap: 12px;+ font-size: 14px;+ color: rgba(255, 255, 255, 0.78);+ }++ .feat-walk-demo-bullet svg {+ flex: 0 0 auto;+ color: #818cf8;+ }++ .feat-walk-demo-cta {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ }++ /* ── Iframe stage ── */+ .feat-walk-demo-stage {+ position: relative;+ width: 100%;+ max-width: 360px;+ aspect-ratio: 360 / 480;+ margin-inline: auto;+ border-radius: 20px;+ overflow: hidden;+ background: rgba(255, 255, 255, 0.03);+ border: 1px solid rgba(255, 255, 255, 0.08);+ box-shadow: 0 24px 60px -28px rgba(99, 102, 241, 0.55);+ }++ .feat-walk-demo-iframe {+ position: absolute;+ inset: 0;+ width: 100%;+ height: 100%;+ border: 0;+ display: block;+ background: transparent;+ }++ /* Loading skeleton shown until the iframe reports ready (walk:ready). */+ .feat-walk-demo-skeleton {+ position: absolute;+ inset: 0;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: 14px;+ color: rgba(255, 255, 255, 0.5);+ font-size: 12px;+ letter-spacing: 0.06em;+ text-transform: uppercase;+ background:+ radial-gradient(120% 80% at 50% 18%, rgba(99, 102, 241, 0.16), transparent 70%),+ rgba(12, 13, 18, 0.6);+ transition: opacity 0.4s ease;+ pointer-events: none;+ }++ .feat-walk-demo-stage[data-ready='true'] .feat-walk-demo-skeleton {+ opacity: 0;+ }++ .feat-walk-demo-spinner {+ width: 28px;+ height: 28px;+ border-radius: 50%;+ border: 2px solid rgba(255, 255, 255, 0.15);+ border-top-color: #818cf8;+ animation: feat-walk-spin 0.8s linear infinite;+ }++ @keyframes feat-walk-spin {+ to {+ transform: rotate(360deg);+ }+ }++ .feat-walk-demo-hint {+ position: absolute;+ left: 50%;+ bottom: 12px;+ transform: translateX(-50%);+ font-size: 11px;+ font-weight: 600;+ letter-spacing: 0.08em;+ text-transform: uppercase;+ color: rgba(255, 255, 255, 0.55);+ background: rgba(0, 0, 0, 0.45);+ backdrop-filter: blur(8px);+ -webkit-backdrop-filter: blur(8px);+ padding: 5px 12px;+ border-radius: 20px;+ border: 1px solid rgba(255, 255, 255, 0.1);+ pointer-events: none;+ opacity: 0;+ transition: opacity 0.4s ease;+ }++ .feat-walk-demo-stage[data-ready='true'] .feat-walk-demo-hint {+ opacity: 1;+ }++ /* ── Sub-cards row ── */+ .feat-walk-demo-cards {+ max-width: 1100px;+ margin: 32px auto 0;+ display: grid;+ grid-template-columns: repeat(3, 1fr);+ gap: 16px;+ }++ .feat-walk-demo-card {+ display: flex;+ flex-direction: column;+ gap: 6px;+ padding: 18px 18px 20px;+ border-radius: 16px;+ background: rgba(255, 255, 255, 0.03);+ border: 1px solid rgba(255, 255, 255, 0.08);+ color: inherit;+ text-decoration: none;+ cursor: pointer;+ transition:+ background 0.18s ease,+ border-color 0.18s ease,+ transform 0.18s ease;+ text-align: left;+ font-family: inherit;+ }++ .feat-walk-demo-card:hover,+ .feat-walk-demo-card:focus-visible {+ background: rgba(99, 102, 241, 0.1);+ border-color: rgba(99, 102, 241, 0.45);+ transform: translateY(-2px);+ }++ .feat-walk-demo-card:active {+ transform: translateY(0);+ }++ .feat-walk-demo-card-icon {+ color: #818cf8;+ }++ .feat-walk-demo-card-title {+ font-size: 14px;+ font-weight: 700;+ color: var(--color-text, #f9fafb);+ }++ .feat-walk-demo-card-sub {+ font-size: 12.5px;+ color: rgba(255, 255, 255, 0.5);+ line-height: 1.5;+ }++ .feat-walk-demo-card-status {+ margin-top: 4px;+ font-size: 11px;+ font-weight: 600;+ letter-spacing: 0.04em;+ color: #818cf8;+ }++ .feat-walk-demo-card-status--copied {+ color: #4ade80;+ }++ @media screen and (max-width: 900px) {+ .feat-walk-demo-inner {+ grid-template-columns: 1fr;+ gap: 32px;+ }+ .feat-walk-demo-stage {+ order: -1;+ max-width: 320px;+ }+ }++ @media screen and (max-width: 680px) {+ .feat-walk-demo-cards {+ grid-template-columns: 1fr;+ }+ }++ @media screen and (max-width: 480px) {+ .feat-walk-demo {+ padding: var(--space-xl) var(--space-md);+ }+ .feat-walk-demo-stage {+ max-width: min(100%, 300px);+ }+ }++ @media (prefers-reduced-motion: reduce) {+ .feat-walk-demo-spinner {+ animation-duration: 2s;+ }+ .feat-walk-demo-card {+ transition: none;+ }+ }+ </style></head><body class="features-page"><a href="#main-content" class="skip-link">Skip to main content</a>@@ -212,6 +479,18 @@</div></section>+ <!-- ════════════════════════════════════+ WALKING AVATAR — live inline demo+ Rendered by the demoType registry below+ (demoType: "walking-avatar-inline").+ ════════════════════════════════════ -->+ <section+ class="feat-walk-demo"+ id="walking-avatar"+ aria-labelledby="walk-demo-title"+ data-feature-demo="walking-avatar-inline"+ ></section>+<!-- ════════════════════════════════════CORE — works today, no crypto════════════════════════════════════ -->@@ -1402,6 +1681,209 @@viewer.setAttribute('reveal', 'auto');}})();++ // ── Feature demo registry ───────────────────────────────────────+ // Data-driven inline demos. Each entry's `demoType` maps to a+ // renderer in DEMO_RENDERERS; sections opt in with+ // data-feature-demo="<demoType>". Adding a new interactive feature+ // demo = one FEATURES entry + one renderer, nothing else to wire.+ (function () {+ const FEATURES = [+ {+ id: 'walking-avatar',+ title: 'Walking Avatars',+ tagline: 'Your avatar walks. Anywhere on the web.',+ description:+ 'Embed a fully animated, voice-capable, walking 3D avatar on any page — or browse the web with your own avatar as your guide via our Chrome extension.',+ demoType: 'walking-avatar-inline',+ bullets: ['Walk anywhere', 'Voice chat', 'Chrome extension'],+ ctaLabel: 'Try Walking',+ ctaHref: '/walk',+ },+ ];++ // Small inline icon set (16px, currentColor) so the bullets and+ // sub-cards stay dependency-free and theme-aware.+ const ICONS = {+ check:+ '<svg viewBox="0 0 16 16" width="16" height="16" fill="none" aria-hidden="true"><path d="M3 8.5l3 3 7-7.5" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></svg>',+ walk:+ '<svg viewBox="0 0 20 20" width="18" height="18" fill="none" aria-hidden="true"><circle cx="11" cy="3.5" r="1.6" stroke="currentColor" stroke-width="1.4"/><path d="M10.5 7l-2.2 3.2L6 12.5M10.5 7l2.2 1.4 1.8 2.6M10.5 7v4.5l-2 5M10.5 11.5l1.8 5" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></svg>',+ puzzle:+ '<svg viewBox="0 0 20 20" width="18" height="18" fill="none" aria-hidden="true"><path d="M8 3.5a1.5 1.5 0 113 0V5h2.5a1 1 0 011 1V8h1.5a1.5 1.5 0 110 3H15v2.5a1 1 0 01-1 1H11.5V16a1.5 1.5 0 11-3 0v-1.5H6a1 1 0 01-1-1V11H3.5a1.5 1.5 0 110-3H5V6a1 1 0 011-1h2V3.5z" stroke="currentColor" stroke-width="1.3" stroke-linejoin="round"/></svg>',+ code:+ '<svg viewBox="0 0 20 20" width="18" height="18" fill="none" aria-hidden="true"><path d="M7 6l-3.5 4L7 14M13 6l3.5 4L13 14M11 4l-2 12" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></svg>',+ };++ const EMBED_SNIPPET =+ '<iframe src="https://three.ws/walk-embed?controls=joystick" width="360" height="480" style="border:0;border-radius:20px" allow="accelerometer; gyroscope" title="Walking avatar"></iframe>';++ function escapeHtml(s) {+ return String(s).replace(/[&<>"']/g, (c) => ({+ '&': '&',+ '<': '<',+ '>': '>',+ '"': '"',+ "'": ''',+ })[c]);+ }++ // Renderer for demoType "walking-avatar-inline". Builds the copy+ // column + a lazy-loaded /walk-embed iframe, plus three sub-cards.+ // The iframe src is only assigned once the section scrolls near the+ // viewport (IntersectionObserver), so the embed's Three.js scene and+ // avatar GLB never download for visitors who don't reach it.+ function renderWalkingAvatarInline(host, feature) {+ const bullets = feature.bullets+ .map(+ (b) =>+ `<li class="feat-walk-demo-bullet">${ICONS.check}<span>${escapeHtml(b)}</span></li>`,+ )+ .join('');++ host.classList.add('scroll-reveal');+ host.innerHTML = `+ <div class="feat-walk-demo-inner">+ <div class="feat-walk-demo-copy">+ <p class="feat-eyebrow">Walking avatars</p>+ <h2 id="walk-demo-title" class="feat-walk-demo-title">${escapeHtml(feature.title)}</h2>+ <p class="feat-walk-demo-tagline">${escapeHtml(feature.tagline)}</p>+ <p class="feat-walk-demo-desc">${escapeHtml(feature.description)}</p>+ <ul class="feat-walk-demo-bullets">${bullets}</ul>+ <a href="${escapeHtml(feature.ctaHref)}" class="btn-primary feat-walk-demo-cta">+ ${escapeHtml(feature.ctaLabel)} <span class="btn-arrow">→</span>+ </a>+ </div>+ <div class="feat-walk-demo-stage" data-ready="false">+ <div class="feat-walk-demo-skeleton" aria-hidden="true">+ <span class="feat-walk-demo-spinner"></span>+ <span>Loading avatar…</span>+ </div>+ <span class="feat-walk-demo-hint" aria-hidden="true">Drag to look · joystick to walk</span>+ </div>+ </div>+ <div class="feat-walk-demo-cards">+ <a class="feat-walk-demo-card" href="/walk">+ <span class="feat-walk-demo-card-icon">${ICONS.walk}</span>+ <span class="feat-walk-demo-card-title">Open the Walk page</span>+ <span class="feat-walk-demo-card-sub">Full-screen avatar with six environments and a distance leaderboard.</span>+ </a>+ <a class="feat-walk-demo-card" href="/docs/walk/chrome-extension">+ <span class="feat-walk-demo-card-icon">${ICONS.puzzle}</span>+ <span class="feat-walk-demo-card-title">Chrome extension</span>+ <span class="feat-walk-demo-card-sub">Browse any site with your avatar walking alongside you as a guide.</span>+ </a>+ <button type="button" class="feat-walk-demo-card" data-copy-embed aria-label="Copy the walking-avatar embed snippet">+ <span class="feat-walk-demo-card-icon">${ICONS.code}</span>+ <span class="feat-walk-demo-card-title">Copy embed snippet</span>+ <span class="feat-walk-demo-card-sub">One iframe tag drops a walking avatar onto any page.</span>+ <span class="feat-walk-demo-card-status" data-copy-status>Copy <iframe> →</span>+ </button>+ </div>+ `;++ const stageEl = host.querySelector('.feat-walk-demo-stage');++ // Lazy-load the embed iframe only when the demo nears the viewport.+ let loaded = false;+ function loadEmbed() {+ if (loaded) return;+ loaded = true;+ const iframe = document.createElement('iframe');+ iframe.className = 'feat-walk-demo-iframe';+ // controls=joystick + autoplay → the avatar strolls on its own+ // until a visitor grabs the joystick; bg=transparent lets the+ // card's gradient show through (see /walk-embed param contract).+ iframe.src = '/walk-embed?controls=joystick&autoplay=true&bg=transparent&env=studio';+ iframe.title = 'Live walking 3D avatar demo';+ iframe.loading = 'lazy';+ iframe.setAttribute('allow', 'accelerometer; gyroscope');+ iframe.setAttribute('referrerpolicy', 'no-referrer-when-downgrade');+ stageEl.insertBefore(iframe, stageEl.firstChild);+ }++ if ('IntersectionObserver' in window) {+ const obs = new IntersectionObserver(+ (entries) => {+ if (entries[0].isIntersecting) {+ loadEmbed();+ obs.disconnect();+ }+ },+ { rootMargin: '200px 0px' },+ );+ obs.observe(stageEl);+ } else {+ loadEmbed();+ }++ // The embed posts `{ source:'walk-embed', type:'walk:ready' }`+ // once its scene + avatar are live (src/walk-embed-events.js).+ // Flip the stage to ready state to fade out the skeleton and+ // reveal the controls hint. Fallback timer covers the rare case+ // where the message is missed (e.g. blocked postMessage).+ let readyFallback = 0;+ function markReady() {+ stageEl.dataset.ready = 'true';+ clearTimeout(readyFallback);+ }+ window.addEventListener('message', (e) => {+ const d = e.data;+ if (d && d.source === 'walk-embed' && d.type === 'walk:ready') markReady();+ });+ readyFallback = setTimeout(markReady, 9000);++ // Embed-snippet copy button.+ const copyBtn = host.querySelector('[data-copy-embed]');+ const copyStatus = host.querySelector('[data-copy-status]');+ if (copyBtn && copyStatus) {+ copyBtn.addEventListener('click', () => {+ navigator.clipboard+ .writeText(EMBED_SNIPPET)+ .then(() => {+ copyStatus.textContent = 'Copied!';+ copyStatus.classList.add('feat-walk-demo-card-status--copied');+ setTimeout(() => {+ copyStatus.innerHTML = 'Copy <iframe> →';+ copyStatus.classList.remove('feat-walk-demo-card-status--copied');+ }, 2000);+ })+ .catch(() => {+ copyStatus.textContent = 'Copy failed — select manually';+ });+ });+ }++ // Join the page's scroll-reveal choreography for the new section.+ if ('IntersectionObserver' in window) {+ const revealObs = new IntersectionObserver(+ (entries) => {+ entries.forEach((entry) => {+ if (entry.isIntersecting) {+ entry.target.classList.add('revealed');+ revealObs.unobserve(entry.target);+ }+ });+ },+ { threshold: 0.1, rootMargin: '0px 0px -40px 0px' },+ );+ revealObs.observe(host);+ } else {+ host.classList.add('revealed');+ }+ }++ const DEMO_RENDERERS = {+ 'walking-avatar-inline': renderWalkingAvatarInline,+ };++ document.querySelectorAll('[data-feature-demo]').forEach((host) => {+ const type = host.dataset.featureDemo;+ const renderer = DEMO_RENDERERS[type];+ const feature = FEATURES.find((f) => f.demoType === type);+ if (renderer && feature) renderer(host, feature);+ });+ })();</script></body></html>diff --git a/pages/tour.html b/pages/tour.htmlindex 6088010ae..a42a8ee53 100644--- a/pages/tour.html+++ b/pages/tour.html@@ -160,6 +160,79 @@outline: 2px solid var(--accent);outline-offset: 3px;}+ /* Track picker */+ .tour-tracks {+ display: flex;+ gap: 14px;+ justify-content: center;+ flex-wrap: wrap;+ margin-top: 6px;+ }+ .tour-track {+ display: flex;+ align-items: center;+ gap: 14px;+ text-align: left;+ appearance: none;+ cursor: pointer;+ width: 300px;+ max-width: 100%;+ padding: 16px 18px;+ border-radius: 16px;+ border: 1px solid rgba(255, 255, 255, 0.12);+ background: rgba(255, 255, 255, 0.04);+ color: #eef1f6;+ transition: border-color 0.18s ease, background 0.18s ease, transform 0.12s ease;+ }+ .tour-track:hover {+ border-color: rgba(122, 162, 255, 0.45);+ background: rgba(122, 162, 255, 0.07);+ transform: translateY(-2px);+ }+ .tour-track:active {+ transform: translateY(0) scale(0.99);+ }+ .tour-track:focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: 3px;+ }+ .tour-track--primary {+ border-color: transparent;+ background: linear-gradient(120deg, rgba(122, 162, 255, 0.22), rgba(157, 123, 255, 0.22));+ box-shadow: 0 12px 34px rgba(122, 162, 255, 0.22);+ }+ .tour-track--primary:hover {+ background: linear-gradient(120deg, rgba(122, 162, 255, 0.3), rgba(157, 123, 255, 0.3));+ }+ .tour-track__icon {+ flex: 0 0 auto;+ width: 42px;+ height: 42px;+ border-radius: 12px;+ display: grid;+ place-items: center;+ font-size: 20px;+ background: rgba(0, 0, 0, 0.22);+ }+ .tour-track__body {+ flex: 1;+ display: flex;+ flex-direction: column;+ gap: 3px;+ }+ .tour-track__title {+ font-weight: 700;+ font-size: 15.5px;+ }+ .tour-track__meta {+ font-size: 12.5px;+ color: #9aa3b6;+ }+ .tour-track__go {+ flex: 0 0 auto;+ color: var(--accent);+ font-size: 13px;+ }.tour-resume {display: none;margin-top: 16px;@@ -327,8 +400,25 @@out loud with a chat bubble over its head. It covers the whole platform, onthe real live site, and you set the pace.</p>- <div class="tour-cta-row">- <button class="tour-btn tour-btn--primary" id="tour-start">▶ Start the guided tour</button>+ <div class="tour-tracks" id="tour-tracks">+ <button class="tour-track tour-track--primary" data-track="quick" id="tour-start-quick">+ <span class="tour-track__icon">⚡</span>+ <span class="tour-track__body">+ <span class="tour-track__title">Quick highlights</span>+ <span class="tour-track__meta" id="track-quick-meta">the best of every chapter</span>+ </span>+ <span class="tour-track__go">▶</span>+ </button>+ <button class="tour-track" data-track="full" id="tour-start-full">+ <span class="tour-track__icon">🗺️</span>+ <span class="tour-track__body">+ <span class="tour-track__title">Full tour</span>+ <span class="tour-track__meta" id="track-full-meta">every feature, chapter by chapter</span>+ </span>+ <span class="tour-track__go">▶</span>+ </button>+ </div>+ <div class="tour-cta-row" style="margin-top:18px"><a class="tour-btn" href="#how">How it works</a></div><p class="tour-resume" id="tour-resume">@@ -391,42 +481,78 @@};const STATE_KEY = 'tws:tour:state';+ const RESUME_KEY = 'tws:tour:resume';- function startTour() {+ function startTour(track) {// The engine boots on the first stop's page via ?tour=start.+ const q = track === 'quick' ? '?tour=start&track=quick' : '?tour=start';fetch('/tour/curriculum.json', { cache: 'force-cache' }).then((r) => r.json()).then((c) => {const first = (c.stops && c.stops[0] && c.stops[0].path) || '/';- location.href = first + '?tour=start';+ location.href = first + q;}).catch(() => {- location.href = '/?tour=start';+ location.href = '/' + q;});}- document.getElementById('tour-start').addEventListener('click', startTour);- document.getElementById('tour-start-2').addEventListener('click', startTour);+ document.getElementById('tour-start-quick').addEventListener('click', () => startTour('quick'));+ document.getElementById('tour-start-full').addEventListener('click', () => startTour('full'));+ document.getElementById('tour-start-2').addEventListener('click', () => startTour('quick'));- // Resume affordance when a tour is already in progress this session.- try {- const raw = sessionStorage.getItem(STATE_KEY);- const st = raw ? JSON.parse(raw) : null;- if (st && st.active) {- const resume = document.getElementById('tour-resume');- resume.style.display = 'block';- document.getElementById('tour-resume-link').addEventListener('click', (e) => {- e.preventDefault();- fetch('/tour/curriculum.json', { cache: 'force-cache' })- .then((r) => r.json())- .then((c) => {- const stop = (c.stops && c.stops[st.index || 0]) || c.stops[0];- location.href = (stop ? stop.path : '/') + '?tour=1';- })- .catch(() => (location.href = '/?tour=1'));- });+ // Resume affordance: an in-progress tour this session (sessionStorage)+ // takes priority; otherwise a durable cross-session bookmark+ // (localStorage) lets a returning visitor pick up where they left off.+ function readJSON(store, key) {+ try {+ const raw = store.getItem(key);+ return raw ? JSON.parse(raw) : null;+ } catch (_) {+ return null;+ }+ }+ (function setupResume() {+ const live = readJSON(sessionStorage, STATE_KEY);+ const saved = readJSON(localStorage, RESUME_KEY);+ const inProgress = live && live.active;+ const bookmarked = saved && !saved.completed && (saved.index || 0) > 0;+ if (!inProgress && !bookmarked) return;+ const src = inProgress ? live : saved;+ const resume = document.getElementById('tour-resume');+ resume.style.display = 'block';+ if (!inProgress) {+ resume.firstChild.textContent = 'Welcome back — your tour is bookmarked. ';}- } catch (_) {}+ document.getElementById('tour-resume-link').addEventListener('click', (e) => {+ e.preventDefault();+ const param = inProgress ? '?tour=1' : '?tour=1';+ fetch('/tour/curriculum.json', { cache: 'force-cache' })+ .then((r) => r.json())+ .then((c) => {+ const stop = (c.stops && c.stops[src.index || 0]) || c.stops[0];+ // Re-seed the live session from the durable bookmark before navigating.+ if (!inProgress && src) {+ try {+ sessionStorage.setItem(+ STATE_KEY,+ JSON.stringify({+ active: true,+ index: src.index || 0,+ track: src.track || 'full',+ voice: src.voice || 'nova',+ speed: src.speed || 1,+ paused: false,+ muted: false,+ }),+ );+ } catch (_) {}+ }+ location.href = (stop ? stop.path : '/') + param;+ })+ .catch(() => (location.href = '/' + param));+ });+ })();// Populate stats + chapter cards from the live curriculum.fetch('/tour/curriculum.json', { cache: 'force-cache' })@@ -436,6 +562,18 @@document.getElementById('stat-minutes').textContent = '~' + (c.estimatedMinutes || 30);document.getElementById('stat-chapters').textContent = (c.sections || []).length || 6;+ // Fill the track-picker cards from the curriculum's track metadata.+ const tracks = {};+ (c.tracks || []).forEach((t) => (tracks[t.id] = t));+ if (tracks.quick) {+ document.getElementById('track-quick-meta').textContent =+ tracks.quick.stopCount + ' picks · ~' + tracks.quick.estimatedMinutes + ' min';+ }+ if (tracks.full) {+ document.getElementById('track-full-meta').textContent =+ tracks.full.stopCount + ' features · ~' + tracks.full.estimatedMinutes + ' min';+ }+const counts = {};(c.stops || []).forEach((s) => (counts[s.section] = (counts[s.section] || 0) + 1));const host = document.getElementById('tour-chapters');diff --git a/public/changelog.json b/public/changelog.jsonindex ec41efa48..ea8e5668b 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,11 +1,31 @@{- "generated_at": "2026-06-21T07:22:29.113Z",+ "generated_at": "2026-06-21T07:29:27.432Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws","url": "https://three.ws"},"entries": [+ {+ "date": "2026-06-21",+ "type": "launch",+ "title": "Docs · Walk Avatar",+ "summary": "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.",+ "link": "/docs/walk",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-06-21",+ "type": "launch",+ "title": "Feed",+ "summary": "Recent activity from the people and agents you follow on three.ws.",+ "link": "/feed",+ "tags": [+ "launch"+ ]+ },{"date": "2026-06-21","type": "launch",@@ -316,6 +336,17 @@"improvement"]},+ {+ "date": "2026-06-21",+ "type": "update",+ "title": "The guided tour, now yours to steer",+ "summary": "The 3D guided tour got a major upgrade. Pick how deep to go: a new “Quick highlights” track samples the best of every chapter in a few minutes, or take the full feature-by-feature walk. A new tour map (open it from the ☰ button or press C) lists every chapter and stop, marks where you are, and lets you search and jump anywhere instantly. You can now change the narrator's voice and set the playback speed (0.75×–1.5×) on the fly, and the tour remembers your spot, voice, and pace across sessions — come back later and pick up right where you left off.",+ "link": "/tour",+ "tags": [+ "feature",+ "improvement"+ ]+ },{"date": "2026-06-21","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 6f11399cf..acff8cd9e 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -6,6 +6,22 @@<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/><description>What's new on three.ws — features, improvements, and releases, newest first.</description><language>en</language>+ <item>+ <title>Docs · Walk Avatar</title>+ <link>https://three.ws/docs/walk</link>+ <guid isPermaLink="false">2026-06-21:Docs · Walk Avatar</guid>+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>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.</description>+ </item>+ <item>+ <title>Feed</title>+ <link>https://three.ws/feed</link>+ <guid isPermaLink="false">2026-06-21:Feed</guid>+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Recent activity from the people and agents you follow on three.ws.</description>+ </item><item><title>Walk</title><link>https://three.ws/walk</link>@@ -238,6 +254,14 @@<category>feature</category><description>The $THREE page leads with a clear "Why hold $THREE" section: revenue buybacks (a fixed, live share of platform revenue buys $THREE on the open market), holder rewards (every paid action reflects $THREE back to holders pro-rata), hold-to-access (discounts, higher quotas, and pro perks), and real usage (deploying agents, forging avatars, and trading the marketplace all run on $THREE). Each pillar maps to a mechanism that actually exists on the platform, and the buyback figure is wired to the live commitment. The page's market data also now rides a shared cache, so it stays fast and reliable under heavy traffic.</description></item>+ <item>+ <title>The guided tour, now yours to steer</title>+ <link>https://three.ws/tour</link>+ <guid isPermaLink="false">2026-06-21:The guided tour, now yours to steer</guid>+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>The 3D guided tour got a major upgrade. Pick how deep to go: a new “Quick highlights” track samples the best of every chapter in a few minutes, or take the full feature-by-feature walk. A new tour map (open it from the ☰ button or press C) lists every chapter and stop, marks where you are, and lets you search and jump anywhere instantly. You can now change the narrator's voice and set the playback speed (0.75×–1.5×) on the fly, and the tour remembers your spot, voice, and pace across sessions — come back later and pick up right where you left off.</description>+ </item><item><title>Walk with any agent, and leave a trail</title><link>https://three.ws/walk</link>diff --git a/public/features.json b/public/features.jsonindex 5d8dccae9..32c00d06a 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-21T07:22:29.085Z",+ "generated_at": "2026-06-21T07:29:27.407Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",@@ -184,6 +184,16 @@"indexable": true,"tags": [],"showcase": false+ },+ {+ "path": "/feed",+ "title": "Feed",+ "description": "Recent activity from the people and agents you follow on three.ws.",+ "added": "2026-06-21",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false}]},@@ -1257,6 +1267,16 @@"tags": [],"showcase": false},+ {+ "path": "/docs/walk",+ "title": "Docs · Walk Avatar",+ "description": "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.",+ "added": "2026-06-21",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },{"path": "/docs/start-here","title": "Docs · Start Here",diff --git a/public/llms-full.txt b/public/llms-full.txtindex e21cbeeb6..c99fecd19 100644--- a/public/llms-full.txt+++ b/public/llms-full.txt@@ -115,6 +115,12 @@ URL: https://three.ws/walkYour 3D avatar walks anywhere on the web. Live demos across six environments, a Chrome extension, one-tag embeds, and a global distance leaderboard.+### Feed++URL: https://three.ws/feed++Recent activity from the people and agents you follow on three.ws.+## BuildCreate and customize an agent.@@ -772,6 +778,12 @@ URL: https://three.ws/docsFull documentation: SDKs, API reference, embedding, agent system, smart contracts.+### Docs · Walk Avatar++URL: https://three.ws/docs/walk++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.+### Docs · Start HereURL: https://three.ws/docs/start-herediff --git a/public/llms.txt b/public/llms.txtindex f447a2383..386179eab 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -28,6 +28,7 @@ Entry points into the product.- [What is three.ws?](https://three.ws/what-is): Plain-English introduction to three.ws — what a 3D AI agent is, real use-cases, and where to begin.- [Guided Tour](https://three.ws/tour): A 3D guide walks across the live site, points at every feature, and narrates what each one does and how to use it — voice plus an on-screen chat bubble, paced by you.- [Walk](https://three.ws/walk): Your 3D avatar walks anywhere on the web. Live demos across six environments, a Chrome extension, one-tag embeds, and a global distance leaderboard.+- [Feed](https://three.ws/feed): Recent activity from the people and agents you follow on three.ws.## Build@@ -153,6 +154,7 @@ Sign-in, dashboard, billing.Docs, tutorials, and reference.- [Docs](https://three.ws/docs): Full documentation: SDKs, API reference, embedding, agent system, smart contracts.+- [Docs · Walk Avatar](https://three.ws/docs/walk): 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.- [Docs · Start Here](https://three.ws/docs/start-here): Plain-language introduction to three.ws for creators and non-developers — what it is, who it’s for, and where to begin.- [Docs · Make Your First Agent](https://three.ws/docs/make-your-agent): Step-by-step guide to creating a 3D AI agent in the browser with no code required.- [Docs · Share & Embed](https://three.ws/docs/share-and-embed): Three ways to put your agent in front of people: share a link, embed an iframe, or use the web component.diff --git a/public/sitemap/index.html b/public/sitemap/index.htmlindex 078b53f91..0b6b4c3bf 100644--- a/public/sitemap/index.html+++ b/public/sitemap/index.html@@ -65,7 +65,7 @@<main class="sm-wrap"><div class="sm-hero"><h1>Sitemap</h1>- <p>All 290 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>+ <p>All 292 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p><div class="sm-formats"><a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a><a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>@@ -77,7 +77,7 @@</div><div class="sm-filter"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>- <input id="sm-filter-input" type="search" placeholder="Filter 290 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />+ <input id="sm-filter-input" type="search" placeholder="Filter 292 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" /><kbd aria-hidden="true">/</kbd></div><p class="sm-filter-count" id="sm-filter-count" role="status" aria-live="polite"></p>@@ -96,7 +96,7 @@</nav><section class="sm-section" id="main"><header>- <h2>Main<span class="sm-count" data-count>17</span></h2>+ <h2>Main<span class="sm-count" data-count>18</span></h2><p class="sm-section-desc">Entry points into the product.</p></header><ul class="sm-list">@@ -219,6 +219,13 @@<span class="sm-desc">Your 3D avatar walks anywhere on the web. Live demos across six environments, a Chrome extension, one-tag embeds, and a global distance leaderboard.</span></a></li>+ <li>+ <a href="/feed">+ <span class="sm-title">Feed</span>+ <span class="sm-path">/feed</span>+ <span class="sm-desc">Recent activity from the people and agents you follow on three.ws.</span>+ </a>+ </li></ul></section>@@ -983,7 +990,7 @@<section class="sm-section" id="learn"><header>- <h2>Learn<span class="sm-count" data-count>25</span></h2>+ <h2>Learn<span class="sm-count" data-count>26</span></h2><p class="sm-section-desc">Docs, tutorials, and reference.</p></header><ul class="sm-list">@@ -994,6 +1001,13 @@<span class="sm-desc">Full documentation: SDKs, API reference, embedding, agent system, smart contracts.</span></a></li>+ <li>+ <a href="/docs/walk">+ <span class="sm-title">Docs · Walk Avatar</span>+ <span class="sm-path">/docs/walk</span>+ <span class="sm-desc">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.</span>+ </a>+ </li><li><a href="/docs/start-here"><span class="sm-title">Docs · Start Here</span>diff --git a/public/tour/curriculum.json b/public/tour/curriculum.jsonindex 2f43d2995..fefbf99d0 100644--- a/public/tour/curriculum.json+++ b/public/tour/curriculum.json@@ -1,11 +1,27 @@{- "version": 1,- "generatedAt": "2026-06-20T05:33:35.841Z",+ "version": 2,+ "generatedAt": "2026-06-21T07:29:15.186Z","generatedBy": "scripts/build-tour.mjs from data/pages.json","title": "The three.ws Guided Tour","tagline": "A 3D guide walks you through every feature, live, on the real site.",- "estimatedMinutes": 29,- "stopCount": 85,+ "estimatedMinutes": 30,+ "stopCount": 88,+ "tracks": [+ {+ "id": "full",+ "title": "Full tour",+ "description": "Every feature, chapter by chapter.",+ "stopCount": 88,+ "estimatedMinutes": 30+ },+ {+ "id": "quick",+ "title": "Quick highlights",+ "description": "The best of every chapter, in a few minutes.",+ "stopCount": 18,+ "estimatedMinutes": 7+ }+ ],"sections": [{"id": "main",@@ -45,6 +61,7 @@"section": "main","title": "Home","narration": "Here we have Home. Landing page. 3D AI agents that think on IBM watsonx.ai (Granite) — the pitch, live agent demos, and the front door to every flow.",+ "highlight": true,"sectionIntro": "Welcome — I'm your guide. Over the next while I'll walk you through three.ws and show you, hands-on, what every part of the platform does. Let's start at the front door.","targets": ["a[href=\"/create-agent\"], a[href=\"/create\"], .hero a.cta, main a.button"@@ -55,7 +72,8 @@"path": "/what-is","section": "main","title": "What is three.ws?",- "narration": "Next up, What is three.ws?. Plain-English introduction to three.ws — what a 3D AI agent is, real use-cases, and where to begin."+ "narration": "Next up, What is three.ws?. Plain-English introduction to three.ws — what a 3D AI agent is, real use-cases, and where to begin.",+ "highlight": true},{"id": "discover",@@ -63,6 +81,7 @@"section": "main","title": "Discover","narration": "This is Discover. On-chain agent directory (ERC-8004 + Solana). Browse, search, and inspect every registered agent.",+ "highlight": true,"targets": [".agent-card, .grid, [data-agent], main"]@@ -73,79 +92,106 @@"section": "main","title": "Marketplace","narration": "Take a look at Marketplace. Buy access to agents, skills, and avatars from other creators.",+ "highlight": false,"targets": [".card, .grid, [data-skill], main"]},+ {+ "id": "feed",+ "path": "/feed",+ "section": "main",+ "title": "Feed",+ "narration": "Now, Feed. Recent activity from the people and agents you follow on three.ws.",+ "highlight": false+ },+ {+ "id": "walk",+ "path": "/walk",+ "section": "main",+ "title": "Walk",+ "narration": "Let's visit Walk. Your 3D avatar walks anywhere on the web. Live demos across six environments, a Chrome extension, one-tag embeds, and a global distance leaderboard.",+ "highlight": false+ },{"id": "animations","path": "/animations","section": "main","title": "Animation Gallery",- "narration": "Now, Animation Gallery. Browse and preview public animations authored by the three.ws community. Apply any clip to your avatar in the Animation Studio."+ "narration": "Over here is Animation Gallery. Browse and preview public animations authored by the three.ws community. Apply any clip to your avatar in the Animation Studio.",+ "highlight": false},{"id": "irl-privacy","path": "/irl-privacy","section": "main","title": "How location works on IRL",- "narration": "Let's visit How location works on IRL. Placed agents are private by location: they appear only to people physically standing near them, never on a map or a list. What's shared, what isn't, and how your camera, motion, and location are used."+ "narration": "Here's How location works on IRL. Placed agents are private by location: they appear only to people physically standing near them, never on a map or a list. What's shared, what isn't, and how your camera, motion, and location are used.",+ "highlight": false},{"id": "collection","path": "/collection","section": "main","title": "My Collection",- "narration": "Over here is My Collection. View all the skills and subscriptions you've unlocked on three.ws."+ "narration": "Meet My Collection. View all the skills and subscriptions you've unlocked on three.ws.",+ "highlight": false},{"id": "irl","path": "/irl","section": "main","title": "IRL",- "narration": "Here's IRL. Place a 3D avatar in your real environment. Camera AR passthrough, joystick movement, and tap-to-place 3D objects on your floor."+ "narration": "And this — IRL. Place a 3D avatar in your real environment. Camera AR passthrough, joystick movement, and tap-to-place 3D objects on your floor.",+ "highlight": false},{"id": "skills","path": "/skills","section": "main","title": "Skills Marketplace",- "narration": "Meet Skills Marketplace. Browse, search, and install agent skills — tool packs, knowledge bases, and capabilities that make AI agents smarter."+ "narration": "Check out Skills Marketplace. Browse, search, and install agent skills — tool packs, knowledge bases, and capabilities that make AI agents smarter.",+ "highlight": false},{"id": "characters","path": "/characters","section": "main","title": "Characters",- "narration": "And this — Characters. Discover AI characters on three.ws. Chat, trade, and create."+ "narration": "This one is Characters. Discover AI characters on three.ws. Chat, trade, and create.",+ "highlight": false},{"id": "gallery","path": "/gallery","section": "main","title": "Avatar Gallery",- "narration": "Check out Avatar Gallery. Every public 3D avatar in the system, browsable as a grid."+ "narration": "Here we have Avatar Gallery. Every public 3D avatar in the system, browsable as a grid.",+ "highlight": false},{"id": "temporary","path": "/temporary","section": "main","title": "Walk",- "narration": "This one is Walk. Drive a 3D avatar around with a joystick or WASD — toggle the back camera for AR-style passthrough."+ "narration": "Next up, Walk. Drive a 3D avatar around with a joystick or WASD — toggle the back camera for AR-style passthrough.",+ "highlight": false},{"id": "community","path": "/community","section": "main","title": "Community",- "narration": "Here we have Community. Featured creators, builds, and conversations from the three.ws community."+ "narration": "This is Community. Featured creators, builds, and conversations from the three.ws community.",+ "highlight": false},{"id": "create-agent","path": "/create-agent","section": "build","title": "Create an Agent",- "narration": "Next up, Create an Agent. Step-by-step wizard to create a 3D AI agent: name, 3D body, skills, personality, voice, and on-chain identity.",+ "narration": "Take a look at Create an Agent. Step-by-step wizard to create a 3D AI agent: name, 3D body, skills, personality, voice, and on-chain identity.",+ "highlight": true,"sectionIntro": "Now the fun part — building. This is where you give your AI a body: a 3D avatar, a brain, a voice, and the studios to shape all of it.","targets": ["form, .wizard, .step, button"@@ -156,7 +202,8 @@"path": "/forge","section": "build","title": "Forge — Text to 3D",- "narration": "This is Forge — Text to 3D. Type a prompt — or drop in photos or a sketch — and get a downloadable textured 3D model (GLB). Pick from multiple generation engines with live health status.",+ "narration": "Now, Forge — Text to 3D. Type a prompt — or drop in photos or a sketch — and get a downloadable textured 3D model (GLB). Pick from multiple generation engines with live health status.",+ "highlight": true,"targets": ["textarea, input[type=\"text\"], .prompt-input, form"]@@ -166,7 +213,8 @@"path": "/scan","section": "build","title": "3D Scanner — Scan Yourself into 3D",- "narration": "Take a look at 3D Scanner — Scan Yourself into 3D. Point your camera at your face, hold still, and walk away with a rigged 3D avatar — reconstruction runs in about a minute, free, in your browser.",+ "narration": "Let's visit 3D Scanner — Scan Yourself into 3D. Point your camera at your face, hold still, and walk away with a rigged 3D avatar — reconstruction runs in about a minute, free, in your browser.",+ "highlight": true,"targets": ["button, .scan-start, video, .camera"]@@ -176,7 +224,8 @@"path": "/pose","section": "build","title": "Animation Studio",- "narration": "Now, Animation Studio. Pose any three.ws avatar or the built-in mannequin with FK/IK, keyframe a timeline, and preview the motion live. Export an animated GLB or clip JSON, save animations to your account, play them back across the platform, and sell them for USDC.",+ "narration": "Over here is Animation Studio. Pose any three.ws avatar or the built-in mannequin with FK/IK, keyframe a timeline, and preview the motion live. Export an animated GLB or clip JSON, save animations to your account, play them back across the platform, and sell them for USDC.",+ "highlight": false,"targets": ["canvas, .timeline, .pose-controls"]@@ -186,7 +235,8 @@"path": "/voice","section": "build","title": "Voice Lab",- "narration": "Let's visit Voice Lab. Clone your voice from a short recording, then use it for TTS or give it to your agent. Side-by-side comparison of voice models.",+ "narration": "Here's Voice Lab. Clone your voice from a short recording, then use it for TTS or give it to your agent. Side-by-side comparison of voice models.",+ "highlight": false,"targets": ["button, .record, audio"]@@ -196,70 +246,80 @@"path": "/compose","section": "build","title": "Scene Composer",- "narration": "Over here is Scene Composer. Real-time 3D scene composer: forge items from text, attach them to your avatar's skeleton bones, arrange and scale freely, then export your creation or save it as an outfit."+ "narration": "Meet Scene Composer. Real-time 3D scene composer: forge items from text, attach them to your avatar's skeleton bones, arrange and scale freely, then export your creation or save it as an outfit.",+ "highlight": false},{"id": "scene","path": "/scene","section": "build","title": "Scene Studio",- "narration": "Here's Scene Studio. Full 3D scene editor in the browser — import GLB models, arrange them with transform gizmos, edit materials and lights, and export complete scenes."+ "narration": "And this — Scene Studio. Full 3D scene editor in the browser — import GLB models, arrange them with transform gizmos, edit materials and lights, and export complete scenes.",+ "highlight": false},{"id": "create-prompt","path": "/create/prompt","section": "build","title": "Describe it to 3D",- "narration": "Meet Describe it to 3D. Type a description. About a minute later: a rigged 3D avatar you can animate and download."+ "narration": "Check out Describe it to 3D. Type a description. About a minute later: a rigged 3D avatar you can animate and download.",+ "highlight": false},{"id": "create-selfie","path": "/create/selfie","section": "build","title": "Selfie to Avatar",- "narration": "And this — Selfie to Avatar. One selfie. About a minute. A rigged 3D avatar that works everywhere."+ "narration": "This one is Selfie to Avatar. One selfie. About a minute. A rigged 3D avatar that works everywhere.",+ "highlight": false},{"id": "studio","path": "/studio","section": "build","title": "Widget Studio",- "narration": "Check out Widget Studio. Pick an avatar, configure embed options, copy a one-line snippet for your site."+ "narration": "Here we have Widget Studio. Pick an avatar, configure embed options, copy a one-line snippet for your site.",+ "highlight": false},{"id": "hydrate","path": "/hydrate","section": "build","title": "Hydrate",- "narration": "This one is Hydrate. Take an existing on-chain agent (ERC-8004 / Solana) and attach a 3D body, voice, and skills."+ "narration": "Next up, Hydrate. Take an existing on-chain agent (ERC-8004 / Solana) and attach a 3D body, voice, and skills.",+ "highlight": false},{"id": "app","path": "/app","section": "build","title": "Viewer",- "narration": "Here we have Viewer. Drag-and-drop glTF/GLB viewer for inspecting 3D models in the browser."+ "narration": "This is Viewer. Drag-and-drop glTF/GLB viewer for inspecting 3D models in the browser.",+ "highlight": false},{"id": "widgets","path": "/widgets","section": "build","title": "Widgets Gallery",- "narration": "Next up, Widgets Gallery. Pre-built chat, voice, and 3D-avatar widgets you can drop into any page."+ "narration": "Take a look at Widgets Gallery. Pre-built chat, voice, and 3D-avatar widgets you can drop into any page.",+ "highlight": false},{"id": "features","path": "/features","section": "build","title": "Features",- "narration": "This is Features. Full feature overview of the three.ws platform: avatars, agents, on-chain identity, x402 payments, and embedding."+ "narration": "Now, Features. Full feature overview of the three.ws platform: avatars, agents, on-chain identity, x402 payments, and embedding.",+ "highlight": false},{"id": "pay","path": "/pay","section": "crypto","title": "Pay (x402)",- "narration": "Take a look at Pay (x402). Pay-per-call gateway: invoke any x402-protocol paid API with a USDC micro-transaction.",+ "narration": "Let's visit Pay (x402). Pay-per-call gateway: invoke any x402-protocol paid API with a USDC micro-transaction.",+ "highlight": true,"sectionIntro": "Here's what makes three.ws agents truly autonomous — they can hold a wallet and move real money. Let me show you the on-chain side: payments, launches, and live market intelligence.","targets": ["form, input, button"@@ -270,7 +330,8 @@"path": "/x402/studio","section": "crypto","title": "x402 Studio — the Stripe of x402",- "narration": "Now, x402 Studio — the Stripe of x402. Merchant console to run a paid x402 business: products and pricing, payout and agent wallets, a real USDC send/receive with SNS .sol resolution, a drag-and-drop storefront, an embeddable pay-button builder, charity and round-up giving, CORS and security.",+ "narration": "Over here is x402 Studio — the Stripe of x402. Merchant console to run a paid x402 business: products and pricing, payout and agent wallets, a real USDC send/receive with SNS .sol resolution, a drag-and-drop storefront, an embeddable pay-button builder, charity and round-up giving, CORS and security.",+ "highlight": true,"targets": [".console, nav, form, button"]@@ -280,7 +341,8 @@"path": "/launch","section": "crypto","title": "Launch a Coin",- "narration": "Let's visit Launch a Coin. Mint a coin for your 3D AI agent in one flow — pick an agent, set the name, symbol, and image, then launch on pump.fun straight from your wallet with an optional three.ws-branded vanity mint.",+ "narration": "Here's Launch a Coin. Mint a coin for your 3D AI agent in one flow — pick an agent, set the name, symbol, and image, then launch on pump.fun straight from your wallet with an optional three.ws-branded vanity mint.",+ "highlight": true,"targets": ["form, input, button"]@@ -290,7 +352,8 @@"path": "/oracle","section": "crypto","title": "Oracle — AI Conviction Engine",- "narration": "Over here is Oracle — AI Conviction Engine. A fused AI conviction engine for every pump.fun launch: pedigree (who's buying), structure (bundle vs organic), narrative (what story is it riding), and momentum — fused into a single 0–100 conviction score with transparent pillar reasoning.",+ "narration": "Meet Oracle — AI Conviction Engine. A fused AI conviction engine for every pump.fun launch: pedigree (who's buying), structure (bundle vs organic), narrative (what story is it riding), and momentum — fused into a single 0–100 conviction score with transparent pillar reasoning.",+ "highlight": false,"targets": [".score, canvas, .conviction, h1"]@@ -300,7 +363,8 @@"path": "/vanity-wallet","section": "crypto","title": "Solana Vanity Wallet",- "narration": "Here's Solana Vanity Wallet. Grind a Solana address with a custom prefix using your browser's GPU.",+ "narration": "And this — Solana Vanity Wallet. Grind a Solana address with a custom prefix — entirely in your browser, across your CPU cores.",+ "highlight": false,"targets": ["input, button, .grinder"]@@ -310,126 +374,144 @@"path": "/vanity/bounties","section": "crypto","title": "Grind-Bounty Market",- "narration": "Meet Grind-Bounty Market. 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."+ "narration": "Check out Grind-Bounty Market. 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.",+ "highlight": false},{"id": "vanity-gallery","path": "/vanity/gallery","section": "crypto","title": "Proof-of-Grind Gallery",- "narration": "And this — Proof-of-Grind 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."+ "narration": "This one is Proof-of-Grind 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.",+ "highlight": false},{"id": "clash","path": "/clash","section": "crypto","title": "Coin Clash",- "narration": "Check out Coin Clash. Token-gated community warfare. Every coin community is an army — hold the coin, enlist, and rally for your faction in timed battles against other communities."+ "narration": "Here we have Coin Clash. Token-gated community warfare. Every coin community is an army — hold the coin, enlist, and rally for your faction in timed battles against other communities.",+ "highlight": false},{"id": "play-ufo","path": "/play/ufo","section": "crypto","title": "Flappin UFO — dodge asteroids for $THREE",- "narration": "This one is Flappin UFO — dodge asteroids for $THREE. Pilot your UFO through an asteroid field. Connect your Solana wallet, submit your score as your wallet address, and claim your spot on the global $THREE leaderboard."+ "narration": "Next up, Flappin UFO — dodge asteroids for $THREE. Pilot your UFO through an asteroid field. Connect your Solana wallet, submit your score as your wallet address, and claim your spot on the global $THREE leaderboard.",+ "highlight": false},{"id": "ibm-x402-demo","path": "/ibm/x402-demo","section": "crypto","title": "x402 Live Demo (IBM × three.ws)",- "narration": "Here we have x402 Live Demo (IBM × three.ws). A self-contained x402 micropayment demo: pay $0.001 USDC from your own wallet — MetaMask on Base or Phantom on Solana — to call a real three.ws data API. Watch the live HTTP 402 challenge, sign a gasless authorization, and see the on-chain settlement receipt. No backend, no account; built as the public face of the IBM × three.ws partnership."+ "narration": "This is x402 Live Demo (IBM × three.ws). A self-contained x402 micropayment demo: pay $0.001 USDC from your own wallet — MetaMask on Base or Phantom on Solana — to call a real three.ws data API. Watch the live HTTP 402 challenge, sign a gasless authorization, and see the on-chain settlement receipt. No backend, no account; built as the public face of the IBM × three.ws partnership.",+ "highlight": false},{"id": "activity","path": "/activity","section": "crypto","title": "Agent Activity — Oracle conviction in real time",- "narration": "Next up, Agent Activity — Oracle conviction in real time. The trading floor: every Oracle conviction action from every autonomous 3D agent on pump.fun, live. Filter by tier and mode, track outcomes, and copy the winners."+ "narration": "Take a look at Agent Activity — Oracle conviction in real time. The trading floor: every Oracle conviction action from every autonomous 3D agent on pump.fun, live. Filter by tier and mode, track outcomes, and copy the winners.",+ "highlight": false},{"id": "claim-wallet","path": "/claim-wallet","section": "crypto","title": "Claim Your Wallet — Verified pump.fun Track Record",- "narration": "This is Claim Your Wallet — Verified pump.fun Track Record. Paste your Solana wallet to see your provable pump.fun track record — win rate, smart-money score, reputation label, and coin history. Sign in to claim it as your official three.ws Trader Card."+ "narration": "Now, Claim Your Wallet — Verified pump.fun Track Record. Paste your Solana wallet to see your provable pump.fun track record — win rate, smart-money score, reputation label, and coin history. Sign in to claim it as your official three.ws Trader Card.",+ "highlight": false},{"id": "trades","path": "/trades","section": "crypto","title": "Live Trade Feed — Notable pump.fun Exits",- "narration": "Take a look at Live Trade Feed — Notable pump.fun Exits. Real-time feed of every notable pump.fun exit from three.ws AI agents — realized PnL, hold time, exit multiple, conviction tier, and a one-click path to copy the trader."+ "narration": "Let's visit Live Trade Feed — Notable pump.fun Exits. Real-time feed of every notable pump.fun exit from three.ws AI agents — realized PnL, hold time, exit multiple, conviction tier, and a one-click path to copy the trader.",+ "highlight": false},{"id": "trending","path": "/trending","section": "crypto","title": "Trending — Top Agents & Coins on three.ws",- "narration": "Now, Trending — Top Agents & Coins on three.ws. What’s hot on three.ws right now. Top 3D AI agents ranked by real chat activity and top Oracle conviction coins by score, with 24h/7d/all-time windows."+ "narration": "Over here is Trending — Top Agents & Coins on three.ws. What’s hot on three.ws right now. Top 3D AI agents ranked by real chat activity and top Oracle conviction coins by score, with 24h/7d/all-time windows.",+ "highlight": false},{"id": "watchlist","path": "/watchlist","section": "crypto","title": "Watchlist",- "narration": "Let's visit 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."+ "narration": "Here's 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.",+ "highlight": false},{"id": "coin-intel","path": "/coin-intel","section": "crypto","title": "Coin Intelligence",- "narration": "Over here is Coin Intelligence. Every pump.fun launch watched and classified in real time — organic vs bundle, the wallets behind it, a transparent quality score, and a model that learns which signals predict winners."+ "narration": "Meet Coin Intelligence. Every pump.fun launch watched and classified in real time — organic vs bundle, the wallets behind it, a transparent quality score, and a model that learns which signals predict winners.",+ "highlight": false},{"id": "radar","path": "/radar","section": "crypto","title": "Coin Radar",- "narration": "Here's Coin Radar. Live pump.fun launch intelligence: every new coin scored in its first ~90 seconds — bundle vs organic, wallet concentration, dev behaviour, and risk flags from the Coin Intelligence Engine."+ "narration": "And this — Coin Radar. Live pump.fun launch intelligence: every new coin scored in its first ~90 seconds — bundle vs organic, wallet concentration, dev behaviour, and risk flags from the Coin Intelligence Engine.",+ "highlight": false},{"id": "smart-money","path": "/smart-money","section": "crypto","title": "Smart Money Radar — follow the wallets that win on pump.fun",- "narration": "Meet Smart Money Radar — follow the wallets that win on pump.fun. A live first-party reputation graph of every pump.fun wallet. We cross each coin's buyers with the coins that actually graduated, so you can see which wallets keep picking winners — and what the proven money is buying right now."+ "narration": "Check out Smart Money Radar — follow the wallets that win on pump.fun. A live first-party reputation graph of every pump.fun wallet. We cross each coin's buyers with the coins that actually graduated, so you can see which wallets keep picking winners — and what the proven money is buying right now.",+ "highlight": false},{"id": "play-arena","path": "/play/arena","section": "crypto","title": "Sniper Arena — autonomous AI agents trading live",- "narration": "And this — Sniper Arena — autonomous AI agents trading live. Watch three.ws AI agents trade pump.fun autonomously in real time. Live P&L leaderboard, each trade signed by the agent's own wallet and verifiable on-chain."+ "narration": "This one is Sniper Arena — autonomous AI agents trading live. Watch three.ws AI agents trade pump.fun autonomously in real time. Live P&L leaderboard, each trade signed by the agent's own wallet and verifiable on-chain.",+ "highlight": false},{"id": "leaderboard","path": "/leaderboard","section": "crypto","title": "Trader Leaderboard",- "narration": "Check out Trader Leaderboard. Pump.fun traders ranked by a provable, on-chain track record — realized P&L, win rate, drawdown — with every number traceable to its transaction."+ "narration": "Here we have Trader Leaderboard. Pump.fun traders ranked by a provable, on-chain track record — realized P&L, win rate, drawdown — with every number traceable to its transaction.",+ "highlight": false},{"id": "launches","path": "/launches","section": "crypto","title": "Agent Launches",- "narration": "This one is Agent Launches. Live public feed of every coin launched by a three.ws agent — market caps, graduation status, and the agent behind each launch."+ "narration": "Next up, Agent Launches. Live public feed of every coin launched by a three.ws agent — market caps, graduation status, and the agent behind each launch.",+ "highlight": false},{"id": "play-agent-wallet","path": "/play/agent-wallet","section": "crypto","title": "Agent Wallet (x402 on Solana)",- "narration": "Here we have Agent Wallet (x402 on Solana). Watch your 3D avatar walk up to a paid endpoint and pay for it with its agent wallet — a real USDC micropayment signed by the agent and settled on Solana."+ "narration": "This is Agent Wallet (x402 on Solana). Watch your 3D avatar walk up to a paid endpoint and pay for it with its agent wallet — a real USDC micropayment signed by the agent and settled on Solana.",+ "highlight": false},{"id": "club","path": "/club","section": "crypto","title": "Pole Club",- "narration": "Next up, Pole Club. A 3D club where dancers only perform when you send a micro-tip. Pay $0.001 per routine, settled on-chain via x402 on Solana.",+ "narration": "Take a look at Pole Club. A 3D club where dancers only perform when you send a micro-tip. Pay $0.001 per routine, settled on-chain via x402 on Solana.",+ "highlight": false,"targets": ["canvas, .tip-button, [data-tip]"]@@ -439,14 +521,16 @@"path": "/demo","section": "crypto","title": "Agent Economy — NOVA & ORACLE",- "narration": "This is Agent Economy — NOVA & ORACLE. Two three.ws AI agents with real Solana wallets discover services on the x402 bazaar, pay each other in SOL, and display a live market briefing on the TV in their world."+ "narration": "Now, Agent Economy — NOVA & ORACLE. Two three.ws AI agents with real Solana wallets discover services on the x402 bazaar, pay each other in SOL, and display a live market briefing on the TV in their world.",+ "highlight": false},{"id": "constellation","path": "/constellation","section": "crypto","title": "watsonx Constellation",- "narration": "Take a look at watsonx Constellation. Live Solana tokens in a 3D galaxy, positioned in semantic space by IBM Granite embeddings on watsonx.ai. Click a star for a live IBM Granite analysis.",+ "narration": "Let's visit watsonx Constellation. Live Solana tokens in a 3D galaxy, positioned in semantic space by IBM Granite embeddings on watsonx.ai. Click a star for a live IBM Granite analysis.",+ "highlight": false,"targets": ["canvas"]@@ -456,21 +540,24 @@"path": "/avatar-wallet-chat","section": "crypto","title": "Avatar Wallet",- "narration": "Now, Avatar Wallet. An embeddable 3D AI avatar that holds a Solana wallet, chats, and can autonomously send SOL."+ "narration": "Over here is Avatar Wallet. An embeddable 3D AI avatar that holds a Solana wallet, chats, and can autonomously send SOL.",+ "highlight": false},{"id": "coin3d","path": "/coin3d","section": "crypto","title": "Token in 3D",- "narration": "Let's visit Token in 3D. Any pump.fun token as a live 3D scene — a spinning coin medallion with the token's logo, top holders as a galaxy sized by balance, and a graduation ring tracking bonding-curve progress."+ "narration": "Here's Token in 3D. Any pump.fun token as a live 3D scene — a spinning coin medallion with the token's logo, top holders as a galaxy sized by balance, and a graduation ring tracking bonding-curve progress.",+ "highlight": false},{"id": "three-live","path": "/three-live","section": "crypto","title": "$THREE Live · Protocol Pulse",- "narration": "Over here is $THREE Live · Protocol Pulse. The $THREE protocol as a living 3D organism. Real on-chain trades pulse through it in real time — each transaction emits a particle burst, whales send shockwaves, with a live trade feed and a HUD of price, market cap, holders, and volume.",+ "narration": "Meet $THREE Live · Protocol Pulse. The $THREE protocol as a living 3D organism. Real on-chain trades pulse through it in real time — each transaction emits a particle burst, whales send shockwaves, with a live trade feed and a HUD of price, market cap, holders, and volume.",+ "highlight": false,"targets": ["canvas"]@@ -480,105 +567,120 @@"path": "/forever","section": "crypto","title": "Forever — etch a message into Bitcoin",- "narration": "Here's Forever — etch a message into Bitcoin. Inscribe a message onto the Bitcoin blockchain. It stays there. Forever."+ "narration": "And this — Forever — etch a message into Bitcoin. Inscribe a message onto the Bitcoin blockchain. It stays there. Forever.",+ "highlight": false},{"id": "tutor","path": "/tutor","section": "crypto","title": "Pay-As-You-Learn Tutor",- "narration": "Meet Pay-As-You-Learn Tutor. Ask anything and pay a cent per answer. A pay-as-you-learn AI tutor that bills $0.01 per explanation in USDC over x402, with a live itemized session invoice and signed attestation."+ "narration": "Check out Pay-As-You-Learn Tutor. Ask anything and pay a cent per answer. A pay-as-you-learn AI tutor that bills $0.01 per explanation in USDC over x402, with a live itemized session invoice and signed attestation.",+ "highlight": false},{"id": "arbitrage","path": "/arbitrage","section": "crypto","title": "x402 Arbitrage",- "narration": "And this — x402 Arbitrage. Cross-provider price disparities surfaced live from the merged x402 facilitator catalog. Find the cheapest endpoint for any capability."+ "narration": "This one is x402 Arbitrage. Cross-provider price disparities surfaced live from the merged x402 facilitator catalog. Find the cheapest endpoint for any capability.",+ "highlight": false},{"id": "providers","path": "/providers","section": "crypto","title": "x402 Providers",- "narration": "Check out x402 Providers. Quantified operator profiles for the x402 paid API catalog. Service counts, price bands, dominant categories, and the underlying listings."+ "narration": "Here we have x402 Providers. Quantified operator profiles for the x402 paid API catalog. Service counts, price bands, dominant categories, and the underlying listings.",+ "highlight": false},{"id": "shopper","path": "/shopper","section": "crypto","title": "Endpoint Shopper",- "narration": "This one is Endpoint Shopper. Describe a task and set a budget. An AI agent discovers relevant x402 endpoints via the Bazaar, chains them together, and synthesizes a final answer — paying per API call."+ "narration": "Next up, Endpoint Shopper. Describe a task and set a budget. An AI agent discovers relevant x402 endpoints via the Bazaar, chains them together, and synthesizes a final answer — paying per API call.",+ "highlight": false},{"id": "fact-checker","path": "/fact-checker","section": "crypto","title": "Fact Checker",- "narration": "Here we have Fact Checker. Pay $0.10 per claim. The agent searches across authoritative sources, pays per retrieval via x402, and returns a verdict with cited evidence and a signed attestation."+ "narration": "This is Fact Checker. Pay $0.10 per claim. The agent searches across authoritative sources, pays per retrieval via x402, and returns a verdict with cited evidence and a signed attestation.",+ "highlight": false},{"id": "unstoppable","path": "/unstoppable","section": "crypto","title": "Unstoppable Agent",- "narration": "Next up, Unstoppable Agent. Live dashboard for an autonomous agent that funds itself via x402 micropayments. Watch its balance, earnings, costs, and daily reflections in real time."+ "narration": "Take a look at Unstoppable Agent. Live dashboard for an autonomous agent that funds itself via x402 micropayments. Watch its balance, earnings, costs, and daily reflections in real time.",+ "highlight": false},{"id": "gmgn","path": "/gmgn","section": "crypto","title": "GMGN Smart Money",- "narration": "This is GMGN Smart Money. Live smart-money signals narrated by a 3D AI agent. Tracks which wallets are loading on Solana, Ethereum, Base, and BNB Chain in real time."+ "narration": "Now, GMGN Smart Money. Live smart-money signals narrated by a 3D AI agent. Tracks which wallets are loading on Solana, Ethereum, Base, and BNB Chain in real time.",+ "highlight": false},{"id": "bazaar","path": "/bazaar","section": "crypto","title": "x402 Bazaar",- "narration": "Take a look at x402 Bazaar. Search and browse the x402 facilitator catalog. Filter by network, price, and extensions. Pay any service in one click."+ "narration": "Let's visit x402 Bazaar. Search and browse the x402 facilitator catalog. Filter by network, price, and extensions. Pay any service in one click.",+ "highlight": false},{"id": "strategy-lab","path": "/strategy-lab","section": "crypto","title": "Strategy Lab",- "narration": "Now, Strategy Lab. Build DCA and subscription strategies that trade on-chain on your behalf."+ "narration": "Over here is Strategy Lab. Build DCA and subscription strategies that trade on-chain on your behalf.",+ "highlight": false},{"id": "pump-dashboard","path": "/pump-dashboard","section": "crypto","title": "Pump Dashboard",- "narration": "Let's visit Pump Dashboard. Pump.fun trading desk: watchlists, scanner, quotes, portfolio, and live charts."+ "narration": "Here's Pump Dashboard. Pump.fun trading desk: watchlists, scanner, quotes, portfolio, and live charts.",+ "highlight": false},{"id": "pump-live","path": "/pump-live","section": "crypto","title": "Pump Live",- "narration": "Over here is Pump Live. Real-time feed of every pump.fun launch as it happens, with a 3D agent that reacts live."+ "narration": "Meet Pump Live. Real-time feed of every pump.fun launch as it happens, with a 3D agent that reacts live.",+ "highlight": false},{"id": "pump-visualizer","path": "/pump-visualizer","section": "crypto","title": "Pump Visualizer",- "narration": "Here's Pump Visualizer. 3D visualizer of trending pump.fun tokens — live market data rendered as an interactive scene."+ "narration": "And this — Pump Visualizer. 3D visualizer of trending pump.fun tokens — live market data rendered as an interactive scene.",+ "highlight": false},{"id": "pumpfun","path": "/pumpfun","section": "crypto","title": "Pump.fun Stream",- "narration": "Meet Pump.fun Stream. Mint and trade pump.fun agent tokens on Solana. Live feed of every launch."+ "narration": "Check out Pump.fun Stream. Mint and trade pump.fun agent tokens on Solana. Live feed of every launch.",+ "highlight": false},{"id": "brain","path": "/brain","section": "labs","title": "Multi-LLM Brain",- "narration": "And this — Multi-LLM Brain. Send one prompt to Claude, GPT, Qwen, ModelScope, and Groq simultaneously. Side-by-side streaming with latency and token stats.",+ "narration": "This one is Multi-LLM Brain. Send one prompt to Claude, GPT, Qwen, ModelScope, and Groq simultaneously. Side-by-side streaming with latency and token stats.",+ "highlight": true,"sectionIntro": "These are the showcases — the experiments and living demos that show the platform off at full power. Some of my favourites are in here.","targets": ["textarea, input, form"@@ -589,42 +691,56 @@"path": "/labs","section": "labs","title": "Labs Showcase",- "narration": "Check out Labs Showcase. A curated gallery of three.ws's most powerful — and most hidden — features. Find and try things you didn't know existed."+ "narration": "Here we have Labs Showcase. A curated gallery of three.ws's most powerful — and most hidden — features. Find and try things you didn't know existed.",+ "highlight": true+ },+ {+ "id": "walk-leaderboard",+ "path": "/walk-leaderboard",+ "section": "labs",+ "title": "Walk Leaderboard",+ "narration": "Next up, Walk Leaderboard. Global leaderboard for the walking avatar — distance walked, sites visited, and time, ranked daily, weekly, and all-time.",+ "highlight": true},{"id": "playground","path": "/playground","section": "labs","title": "Playground",- "narration": "This one is Playground. Sandbox for experimenting with agents, prompts, and 3D scenes."+ "narration": "This is Playground. Sandbox for experimenting with agents, prompts, and 3D scenes.",+ "highlight": false},{"id": "launchpad","path": "/launchpad","section": "labs","title": "Launchpad Studio",- "narration": "Here we have Launchpad Studio. Build a hosted 3D launchpad, token page, concierge, or showroom on a three.ws subdomain."+ "narration": "Take a look at Launchpad Studio. Build a hosted 3D launchpad, token page, concierge, or showroom on a three.ws subdomain.",+ "highlight": false},{"id": "lipsync-mic","path": "/lipsync/mic","section": "labs","title": "Lipsync (Mic)",- "narration": "Next up, Lipsync (Mic). Feed live mic audio through the viseme analyser and watch the avatar's mouth track your voice in real time."+ "narration": "Now, Lipsync (Mic). Feed live mic audio through the viseme analyser and watch the avatar's mouth track your voice in real time.",+ "highlight": false},{"id": "lipsync","path": "/lipsync","section": "labs","title": "Lipsync (TTS)",- "narration": "This is Lipsync (TTS). Type text, stream it through the avatar's voice, and the mouth animates in real time via wawa-lipsync viseme detection."+ "narration": "Let's visit Lipsync (TTS). Type text, stream it through the avatar's voice, and the mouth animates in real time via wawa-lipsync viseme detection.",+ "highlight": false},{"id": "chat","path": "/chat","section": "agent-tools","title": "Chat",- "narration": "Take a look at Chat. Talk to your agent. Voice, text, and tool-use in one interface.",+ "narration": "Over here is Chat. Talk to your agent. Voice, text, and tool-use in one interface.",+ "highlight": true,"sectionIntro": "Once you've built agents, this is where you talk to them, manage them, and check their reputation.","targets": ["textarea, input, .composer, form"@@ -635,28 +751,32 @@"path": "/agents","section": "agent-tools","title": "Agents Index",- "narration": "Now, Agents Index. Browse every registered agent on three.ws."+ "narration": "Here's Agents Index. Browse every registered agent on three.ws.",+ "highlight": true},{"id": "reputation","path": "/reputation","section": "agent-tools","title": "Reputation Explorer",- "narration": "Let's visit Reputation Explorer. Inspect on-chain reputation scores and attestations for any agent."+ "narration": "Meet Reputation Explorer. Inspect on-chain reputation scores and attestations for any agent.",+ "highlight": true},{"id": "agent","path": "/agent","section": "agent-tools","title": "Agent Home",- "narration": "Over here is Agent Home. Default landing for an agent instance — chat, embed, and remix actions."+ "narration": "And this — Agent Home. Default landing for an agent instance — chat, embed, and remix actions.",+ "highlight": false},{"id": "docs","path": "/docs","section": "learn","title": "Docs",- "narration": "Here's Docs. Full documentation: SDKs, API reference, embedding, agent system, smart contracts.",+ "narration": "Check out Docs. Full documentation: SDKs, API reference, embedding, agent system, smart contracts.",+ "highlight": true,"sectionIntro": "And when you're ready to go deeper on your own, here's where the documentation, guides, and tutorials live. That's the whole tour — let's wrap up.","targets": ["nav, .sidebar, main"@@ -667,35 +787,40 @@"path": "/tutorials","section": "learn","title": "Tutorials",- "narration": "Meet Tutorials. Step-by-step build guides."+ "narration": "This one is Tutorials. Step-by-step build guides.",+ "highlight": true},{"id": "events-build-3d-agents-live","path": "/events/build-3d-agents-live","section": "learn","title": "Building 3D AI Agents Live",- "narration": "And this — Building 3D AI Agents Live. A live build session: from a single prompt to an interactive 3D AI agent embedded in any app, in minutes — then a live Q&A. Hosted by three.ws, in partnership with IBM."+ "narration": "Here we have Building 3D AI Agents Live. A live build session: from a single prompt to an interactive 3D AI agent embedded in any app, in minutes — then a live Q&A. Hosted by three.ws, in partnership with IBM.",+ "highlight": true},{"id": "status","path": "/status","section": "learn","title": "Status",- "narration": "Check out Status. Live operational status and 90-day uptime history for the platform, API, and x402 surfaces — probed every 5 minutes."+ "narration": "Next up, Status. Live operational status and 90-day uptime history for the platform, API, and x402 surfaces — probed every 5 minutes.",+ "highlight": false},{"id": "support","path": "/support","section": "learn","title": "Support",- "narration": "This one is Support. Get help with three.ws — report bugs, ask integration questions, reach support and security via GitHub Issues, Discussions, and email, all in one place."+ "narration": "This is Support. Get help with three.ws — report bugs, ask integration questions, reach support and security via GitHub Issues, Discussions, and email, all in one place.",+ "highlight": false},{"id": "glossary","path": "/glossary","section": "learn","title": "Glossary",- "narration": "Here we have Glossary. Plain-English definitions for the crypto and agent terms used across three.ws — no jargon required to get started."+ "narration": "Take a look at Glossary. Plain-English definitions for the crypto and agent terms used across three.ws — no jargon required to get started.",+ "highlight": false}]}diff --git a/scripts/build-tour.mjs b/scripts/build-tour.mjsindex b17a8d045..b7e27ce44 100644--- a/scripts/build-tour.mjs+++ b/scripts/build-tour.mjs@@ -173,11 +173,24 @@ function escapeRe(s) {const WPM = 150;const STOP_OVERHEAD_S = 9;+// How many leading stops of each chapter belong to the "Quick highlights" track+// — heroes sort first (see orderSection), so the first few stops of a section+// are its clearest, most representative features. The Quick tour plays only+// these (plus every chapter's spoken intro), turning a ~30-minute full walk into+// a ~5-minute sampler that still touches every chapter.+const QUICK_PER_SECTION = 3;++function minutesFor(words, count) {+ return Math.round(words / WPM + (count * STOP_OVERHEAD_S) / 60);+}+function build() {const bySection = loadPages();const stops = [];const sections = [];let totalWords = 0;+ let quickWords = 0;+ let quickCount = 0;for (const id of SECTION_ORDER) {const entry = bySection.get(id);@@ -186,10 +199,17 @@ function build() {sections.push({ id, title: entry.meta.title, intro: SECTION_INTROS[id] || '' });ordered.forEach((page, i) => {const isFirstOfSection = i === 0;+ const highlight = i < QUICK_PER_SECTION;const narration = narrate(page, stops.length);- totalWords += narration.split(/\s+/).length;- if (isFirstOfSection && SECTION_INTROS[id]) {- totalWords += SECTION_INTROS[id].split(/\s+/).length;+ const introWords =+ isFirstOfSection && SECTION_INTROS[id]+ ? SECTION_INTROS[id].split(/\s+/).length+ : 0;+ const stopWords = narration.split(/\s+/).length + introWords;+ totalWords += stopWords;+ if (highlight) {+ quickWords += stopWords;+ quickCount += 1;}stops.push({id: slug(page.path),@@ -197,6 +217,7 @@ function build() {section: id,title: collapse(page.title),narration,+ highlight,...(isFirstOfSection && SECTION_INTROS[id]? { sectionIntro: SECTION_INTROS[id] }: {}),@@ -205,18 +226,33 @@ function build() {});}- const speakingMinutes = totalWords / WPM;- const overheadMinutes = (stops.length * STOP_OVERHEAD_S) / 60;- const estimatedMinutes = Math.round(speakingMinutes + overheadMinutes);+ const estimatedMinutes = minutesFor(totalWords, stops.length);+ const quickMinutes = Math.max(1, minutesFor(quickWords, quickCount));return {- version: 1,+ version: 2,generatedAt: new Date().toISOString(),generatedBy: 'scripts/build-tour.mjs from data/pages.json',title: 'The three.ws Guided Tour',tagline: 'A 3D guide walks you through every feature, live, on the real site.',estimatedMinutes,stopCount: stops.length,+ tracks: [+ {+ id: 'full',+ title: 'Full tour',+ description: 'Every feature, chapter by chapter.',+ stopCount: stops.length,+ estimatedMinutes,+ },+ {+ id: 'quick',+ title: 'Quick highlights',+ description: 'The best of every chapter, in a few minutes.',+ stopCount: quickCount,+ estimatedMinutes: quickMinutes,+ },+ ],sections,stops,};diff --git a/scripts/test-gate.mjs b/scripts/test-gate.mjsindex 25a62fa46..05aa3a3ca 100644--- a/scripts/test-gate.mjs+++ b/scripts/test-gate.mjs@@ -17,11 +17,30 @@* Anything needing a live DB/RPC/browser belongs in `npm test`, not the gate.*/import { execFileSync } from 'child_process';-import { resolve, dirname } from 'path';+import { createRequire } from 'module';+import { resolve, dirname, join } from 'path';import { fileURLToPath } from 'url';const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');+// Resolve vitest's CLI entry through Node module resolution rather than relying+// on the `.bin/vitest` shim (or `npx`'s PATH lookup). Vercel restores a cached+// `node_modules` between builds but does NOT always recreate the `.bin/`+// symlinks — so the vitest *package* is present while `.bin/vitest` is missing,+// and `npx vitest` dies with "vitest: not found" in <1s, failing every deploy+// even though no test regressed. `node <pkg>/vitest.mjs` needs only the package+// directory, which survives the cache intact, so it is immune to the stripped+// bin. If the package itself is genuinely absent the install is broken and the+// deploy SHOULD fail — that case throws below with a clear message.+function resolveVitestCli() {+ const require = createRequire(import.meta.url);+ const pkgJsonPath = require.resolve('vitest/package.json');+ const bin = require(pkgJsonPath).bin;+ const rel = typeof bin === 'string' ? bin : bin?.vitest;+ if (!rel) throw new Error('vitest package.json has no `bin.vitest` entry');+ return join(dirname(pkgJsonPath), rel);+}+const GATE_TESTS = ['tests/solana-confirm.test.js', // reverted-tx → throw (no false-success money path)'tests/http-cache-control.test.js', // cache/no-store boundary; errors never cached@@ -33,8 +52,22 @@ const GATE_TESTS = [];console.log(`[test-gate] running ${GATE_TESTS.length} critical-path test files…`);++let vitestCli;+try {+ vitestCli = resolveVitestCli();+} catch (err) {+ // The vitest package could not be resolved at all — a genuinely broken+ // install, not a code regression. Fail the deploy loudly rather than skip the+ // only automated checkpoint: a silent pass here would let a real money/auth+ // regression ship unguarded.+ console.error(`[test-gate] ✗ cannot resolve the vitest runner: ${err.message}`);+ console.error('[test-gate] the test runner is missing from node_modules — the install is broken; blocking deploy');+ process.exit(1);+}+try {- execFileSync('npx', ['vitest', 'run', ...GATE_TESTS], {+ execFileSync(process.execPath, [vitestCli, 'run', ...GATE_TESTS], {cwd: ROOT,stdio: 'inherit',env: process.env,diff --git a/scripts/verify-x402-discovery.mjs b/scripts/verify-x402-discovery.mjsnew file mode 100644index 000000000..897b64f8b--- /dev/null+++ b/scripts/verify-x402-discovery.mjs@@ -0,0 +1,177 @@+#!/usr/bin/env node+// scripts/verify-x402-discovery.mjs+//+// Verifies that our published x402 discovery document is actually indexable —+// i.e. that crawlers (Coinbase CDP Bazaar / agentic.market, x402scan, 402index)+// will accept each resource rather than silently drop it. It mirrors the checks+// those indexers run:+//+// 1. CDP strict validation — each resource's bazaar `info` MUST validate+// against its own declared `schema` (JSON Schema draft 2020-12). A mismatch+// is what makes CDP return `EXTENSION-RESPONSES: rejected` and skip the+// resource. This is the single most common silent-delisting cause.+// 2. Required 402 fields — resource.url + description; every accept needs+// scheme/network/amount/asset/payTo.+// 3. Network coverage — x402scan indexes Base + Solana only; warn on resources+// that advertise neither (they won't appear there).+// 4. Listing-quality fields — serviceName (≤32 ASCII), tags (≤5, ≤32 ASCII+// each), absolute https iconUrl, a non-trivial description (bare names rank+// poorly), and an output example (agentic.market uses it for result cards).+//+// Usage:+// node scripts/verify-x402-discovery.mjs # checks https://three.ws+// node scripts/verify-x402-discovery.mjs --base=http://localhost:3000+// node scripts/verify-x402-discovery.mjs --json # machine-readable report++import Ajv2020 from 'ajv/dist/2020.js';+import addFormats from 'ajv-formats';++const args = process.argv.slice(2);+const base = (args.find((a) => a.startsWith('--base='))?.slice('--base='.length) || 'https://three.ws').replace(/\/$/, '');+const asJson = args.includes('--json');++const NETWORK_BASE = 'eip155:8453';+const SOLANA_PREFIX = 'solana:';++const ajv = new Ajv2020({ allErrors: true, strict: false });+addFormats(ajv);++function isAbsoluteHttps(u) {+ try {+ return new URL(u).protocol === 'https:';+ } catch {+ return false;+ }+}+function isPrintableAscii(s, max) {+ return typeof s === 'string' && s.length > 0 && s.length <= max && /^[\x20-\x7e]+$/.test(s);+}++// CDP indexes on a per-(resource,tool) basis; MCP rows carry a toolName.+function label(r) {+ return r.toolName ? `${r.path || r.url} :: ${r.toolName}` : r.path || r.url;+}++function checkResource(r) {+ const errors = [];+ const warnings = [];++ // (2) required 402 fields+ if (!r.url) errors.push('missing resource.url');+ if (!r.description || String(r.description).trim().length < 12)+ warnings.push('description missing or very short (<12 chars) — ranks poorly');+ const accepts = Array.isArray(r.accepts) ? r.accepts : [];+ if (!accepts.length) errors.push('no accepts[] — not payable, will not be cataloged');+ accepts.forEach((a, i) => {+ for (const f of ['scheme', 'network', 'amount', 'asset', 'payTo']) {+ if (a[f] == null || a[f] === '') errors.push(`accepts[${i}] missing ${f}`);+ }+ if (typeof a.payTo === 'string' && /\s/.test(a.payTo))+ errors.push(`accepts[${i}].payTo contains whitespace ("${a.payTo}") — clients fail to parse`);+ });++ // (3) network coverage (x402scan = Base + Solana only)+ const nets = accepts.map((a) => a.network || '');+ const hasBase = nets.includes(NETWORK_BASE);+ const hasSolana = nets.some((n) => n.startsWith(SOLANA_PREFIX));+ if (!hasBase && !hasSolana)+ warnings.push('advertises neither Base nor Solana — invisible to x402scan');++ // (4) listing-quality fields+ if (r.serviceName != null && !isPrintableAscii(r.serviceName, 32))+ warnings.push('serviceName not printable-ASCII ≤32 chars');+ if (r.tags != null) {+ if (!Array.isArray(r.tags) || r.tags.length > 5) warnings.push('tags must be an array of ≤5');+ else if (!r.tags.every((t) => isPrintableAscii(t, 32)))+ warnings.push('a tag is not printable-ASCII ≤32 chars');+ }+ if (r.iconUrl != null && !isAbsoluteHttps(r.iconUrl))+ warnings.push('iconUrl is not an absolute https URL');++ // (1) CDP strict validation — bazaar.info vs bazaar.schema+ const bazaar = r.extensions?.bazaar || r.bazaar;+ if (!bazaar) {+ errors.push('no bazaar extension — CDP/agentic.market will not catalog');+ } else {+ if (bazaar.discoverable !== true) warnings.push('bazaar.discoverable is not true');+ if (!bazaar.info) errors.push('bazaar.info missing');+ if (!bazaar.schema) {+ warnings.push('bazaar.schema missing — cannot self-validate (CDP may reject)');+ } else if (bazaar.info) {+ let validate;+ try {+ validate = ajv.compile(bazaar.schema);+ } catch (e) {+ errors.push(`bazaar.schema does not compile: ${e.message}`);+ }+ if (validate && !validate(bazaar.info)) {+ const detail = (validate.errors || [])+ .map((e) => `${e.instancePath || '/'} ${e.message}`)+ .join('; ');+ errors.push(`bazaar.info FAILS its own schema → CDP rejects: ${detail}`);+ }+ }+ if (!bazaar.info?.output?.example)+ warnings.push('no output.example — agentic.market result cards/ranking degraded');+ }++ return { label: label(r), url: r.url, errors, warnings };+}++async function main() {+ const url = `${base}/.well-known/x402.json`;+ const res = await fetch(url);+ if (!res.ok) {+ console.error(`failed to fetch ${url}: HTTP ${res.status}`);+ process.exit(2);+ }+ const doc = await res.json();+ const resources = doc.resources || doc.items || [];+ const report = resources.map(checkResource);++ const failing = report.filter((r) => r.errors.length);+ const warningOnly = report.filter((r) => !r.errors.length && r.warnings.length);+ const clean = report.filter((r) => !r.errors.length && !r.warnings.length);++ if (asJson) {+ console.log(JSON.stringify({ base, total: report.length, failing, warningOnly, report }, null, 2));+ process.exit(failing.length ? 1 : 0);+ }++ console.log(`x402 discovery check — ${url}`);+ console.log(`service: ${doc.service?.name || '?'} resources: ${report.length}\n`);++ for (const r of failing) {+ console.log(`✗ ${r.label}`);+ for (const e of r.errors) console.log(` ERROR ${e}`);+ for (const w of r.warnings) console.log(` warn ${w}`);+ }+ for (const r of warningOnly) {+ console.log(`▲ ${r.label}`);+ for (const w of r.warnings) console.log(` warn ${w}`);+ }++ console.log(`\n--- summary ---`);+ console.log(` ✓ clean: ${clean.length}`);+ console.log(` ▲ warnings: ${warningOnly.length}`);+ console.log(` ✗ will be DROPPED by CDP/indexers: ${failing.length}`);++ // Aggregate the most common issues so the fix is obvious.+ const tally = {};+ for (const r of report) for (const e of r.errors) {+ const key = e.replace(/\(.*?\)/g, '(…)').replace(/→.*/, '→ …').slice(0, 60);+ tally[key] = (tally[key] || 0) + 1;+ }+ const top = Object.entries(tally).sort((a, b) => b[1] - a[1]).slice(0, 8);+ if (top.length) {+ console.log(`\n top errors:`);+ for (const [k, n] of top) console.log(` ${String(n).padStart(3)}× ${k}`);+ }++ process.exit(failing.length ? 1 : 0);+}++main().catch((err) => {+ console.error('fatal:', err.message);+ process.exit(2);+});diff --git a/src/feature-tour/chapters.js b/src/feature-tour/chapters.jsnew file mode 100644index 000000000..1aa75886b--- /dev/null+++ b/src/feature-tour/chapters.js@@ -0,0 +1,280 @@+// chapters.js — the tour's navigation drawer. An 85-stop tour needs a map, so+// this panel lays the whole curriculum out as chapters → stops, marks the one+// you're on, and lets you jump to any of them. It doubles as the settings+// surface: switch between the Quick-highlights and Full tracks, change the+// narration voice, set the playback speed, and search across every stop's title.+// It is pure UI — every action forwards to a handler the director supplies, and+// the director calls setActive()/setTrack()/setVoice()/setSpeed() to keep it in+// sync. Open/close is fully keyboard- and screen-reader-friendly.++const Z_PANEL = 2147483450;++// A curated client-side slice of the platform voice catalog (api/_lib/tts-voices.js).+// Kept small so the menu stays scannable; every id here renders on both the free+// Magpie lane and the OpenAI backstop.+const VOICES = [+ { id: 'nova', name: 'Nova' },+ { id: 'alloy', name: 'Alloy' },+ { id: 'echo', name: 'Echo' },+ { id: 'fable', name: 'Fable' },+ { id: 'onyx', name: 'Onyx' },+ { id: 'sage', name: 'Sage' },+ { id: 'shimmer', name: 'Shimmer' },+];++const SPEEDS = [0.75, 1, 1.25, 1.5];++export class ChapterPanel {+ constructor(curriculum, handlers) {+ this.curriculum = curriculum;+ this.handlers = handlers; // { onJump(abs), onTrack, onVoice, onSpeed, onClose }+ this.open = false;+ this.activeAbs = 0;+ this._query = '';+ this._onKey = this._onKey.bind(this);+ ensureStyles();+ this._build();+ }++ _build() {+ const root = document.createElement('div');+ root.className = 'tws-tour-menu';+ root.innerHTML = `+ <div class="tws-tour-menu__scrim" data-act="close"></div>+ <aside class="tws-tour-menu__panel" role="dialog" aria-modal="false" aria-label="Tour chapters and settings" tabindex="-1">+ <div class="tws-tour-menu__head">+ <div class="tws-tour-menu__title">Tour map</div>+ <button class="tws-tour-menu__x" data-act="close" aria-label="Close menu" title="Close">✕</button>+ </div>+ <div class="tws-tour-menu__settings">+ <label class="tws-tour-menu__field">+ <span class="tws-tour-menu__lbl">Track</span>+ <div class="tws-tour-seg" data-group="track" role="radiogroup" aria-label="Tour length"></div>+ </label>+ <label class="tws-tour-menu__field">+ <span class="tws-tour-menu__lbl">Speed</span>+ <div class="tws-tour-seg" data-group="speed" role="radiogroup" aria-label="Playback speed"></div>+ </label>+ <label class="tws-tour-menu__field">+ <span class="tws-tour-menu__lbl" id="tws-tour-voice-lbl">Voice</span>+ <select class="tws-tour-menu__select" data-act="voice" aria-labelledby="tws-tour-voice-lbl"></select>+ </label>+ </div>+ <div class="tws-tour-menu__search">+ <input type="search" class="tws-tour-menu__input" placeholder="Search features…" aria-label="Search tour stops" autocomplete="off" spellcheck="false" />+ </div>+ <nav class="tws-tour-menu__list" aria-label="Tour chapters"></nav>+ </aside>`;+ document.body.appendChild(root);+ this.root = root;+ this.panel = root.querySelector('.tws-tour-menu__panel');+ this.listEl = root.querySelector('.tws-tour-menu__list');+ this.trackSeg = root.querySelector('[data-group="track"]');+ this.speedSeg = root.querySelector('[data-group="speed"]');+ this.voiceSel = root.querySelector('[data-act="voice"]');+ this.searchInput = root.querySelector('.tws-tour-menu__input');++ this._buildSegments();+ this._buildVoices();+ this._buildList();++ root.addEventListener('click', (e) => {+ if (e.target.closest('[data-act="close"]')) this.close();+ });+ this.trackSeg.addEventListener('click', (e) => {+ const id = e.target.closest('[data-val]')?.dataset.val;+ if (id) this.handlers.onTrack?.(id);+ });+ this.speedSeg.addEventListener('click', (e) => {+ const v = e.target.closest('[data-val]')?.dataset.val;+ if (v) this.handlers.onSpeed?.(Number(v));+ });+ this.voiceSel.addEventListener('change', () => this.handlers.onVoice?.(this.voiceSel.value));+ this.searchInput.addEventListener('input', () => {+ this._query = this.searchInput.value.trim().toLowerCase();+ this._buildList();+ });+ this.listEl.addEventListener('click', (e) => {+ const abs = e.target.closest('[data-abs]')?.dataset.abs;+ if (abs != null) {+ this.handlers.onJump?.(Number(abs));+ this.close();+ }+ });+ }++ _buildSegments() {+ const tracks = this.curriculum.tracks?.length+ ? this.curriculum.tracks+ : [{ id: 'full', title: 'Full' }];+ this.trackSeg.innerHTML = tracks+ .map(+ (t) =>+ `<button class="tws-tour-seg__btn" data-val="${t.id}" role="radio" aria-checked="false" title="${esc(t.description || '')}">${esc(t.title.replace(/ tour| highlights/i, ''))}${t.estimatedMinutes ? ` · ~${t.estimatedMinutes}m` : ''}</button>`,+ )+ .join('');+ this.speedSeg.innerHTML = SPEEDS.map(+ (s) =>+ `<button class="tws-tour-seg__btn" data-val="${s}" role="radio" aria-checked="false">${String(s).replace(/\.?0+$/, '')}×</button>`,+ ).join('');+ }++ _buildVoices() {+ this.voiceSel.innerHTML = VOICES.map(+ (v) => `<option value="${v.id}">${esc(v.name)}</option>`,+ ).join('');+ }++ _buildList() {+ const { sections, stops } = this.curriculum;+ const q = this._query;+ const rows = [];+ for (const section of sections) {+ const items = stops+ .map((s, abs) => ({ s, abs }))+ .filter(({ s }) => s.section === section.id)+ .filter(({ s }) => !q || s.title.toLowerCase().includes(q));+ if (!items.length) continue;+ rows.push(+ `<div class="tws-tour-chap"><span class="tws-tour-chap__t">${esc(section.title)}</span><span class="tws-tour-chap__n">${items.length}</span></div>`,+ );+ for (const { s, abs } of items) {+ rows.push(+ `<button class="tws-tour-stop${abs === this.activeAbs ? ' is-current' : ''}" data-abs="${abs}" aria-current="${abs === this.activeAbs ? 'true' : 'false'}">+ <span class="tws-tour-stop__dot"${s.highlight ? ' data-hl="1"' : ''}></span>+ <span class="tws-tour-stop__title">${esc(s.title)}</span>+ ${s.highlight ? '<span class="tws-tour-stop__star" title="In the Quick highlights">★</span>' : ''}+ </button>`,+ );+ }+ }+ this.listEl.innerHTML =+ rows.join('') ||+ `<div class="tws-tour-menu__empty">No features match “${esc(this._query)}”.</div>`;+ }++ // ── Director-driven sync ────────────────────────────────────────────────────+ setActive(abs) {+ this.activeAbs = abs;+ this.listEl.querySelectorAll('.tws-tour-stop').forEach((el) => {+ const on = Number(el.dataset.abs) === abs;+ el.classList.toggle('is-current', on);+ el.setAttribute('aria-current', on ? 'true' : 'false');+ });+ if (this.open) this._scrollToActive();+ }++ setTrack(track) {+ this._mark(this.trackSeg, track);+ }+ setSpeed(speed) {+ this._mark(this.speedSeg, String(speed));+ }+ setVoice(voice) {+ this.voiceSel.value = voice;+ }++ _mark(seg, val) {+ seg.querySelectorAll('.tws-tour-seg__btn').forEach((b) => {+ const on = b.dataset.val === val;+ b.classList.toggle('is-on', on);+ b.setAttribute('aria-checked', on ? 'true' : 'false');+ });+ }++ // ── Open / close ────────────────────────────────────────────────────────────+ toggle() {+ this.open ? this.close() : this.show();+ }+ show() {+ if (this.open) return;+ this.open = true;+ this.root.classList.add('is-open');+ this._scrollToActive();+ document.addEventListener('keydown', this._onKey, true);+ // Focus the search box for instant filter-and-jump.+ requestAnimationFrame(() => this.searchInput.focus());+ this.handlers.onOpenChange?.(true);+ }+ close() {+ if (!this.open) return;+ this.open = false;+ this.root.classList.remove('is-open');+ document.removeEventListener('keydown', this._onKey, true);+ this.handlers.onOpenChange?.(false);+ }++ _scrollToActive() {+ const el = this.listEl.querySelector('.tws-tour-stop.is-current');+ el?.scrollIntoView({ block: 'center', behavior: 'auto' });+ }++ _onKey(e) {+ // Swallow Escape here so it closes the menu instead of exiting the tour.+ if (e.key === 'Escape') {+ e.stopPropagation();+ e.preventDefault();+ this.close();+ }+ }++ dispose() {+ document.removeEventListener('keydown', this._onKey, true);+ this.root?.remove();+ this.root = null;+ }+}++function esc(s) {+ return String(s == null ? '' : s).replace(+ /[&<>"']/g,+ (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],+ );+}++let _stylesInjected = false;+function ensureStyles() {+ if (_stylesInjected) return;+ _stylesInjected = true;+ const style = document.createElement('style');+ style.id = 'tws-tour-menu-style';+ style.textContent = `+.tws-tour-menu{position:fixed;inset:0;z-index:${Z_PANEL};pointer-events:none;font-family:system-ui,-apple-system,'Segoe UI',sans-serif}+.tws-tour-menu__scrim{position:absolute;inset:0;background:rgba(6,8,12,.5);opacity:0;transition:opacity .3s ease;pointer-events:none}+.tws-tour-menu.is-open .tws-tour-menu__scrim{opacity:1;pointer-events:auto}+.tws-tour-menu__panel{position:absolute;left:0;top:0;height:100%;width:min(360px,86vw);display:flex;flex-direction:column;background:#0e1118;border-right:1px solid rgba(122,162,255,.18);box-shadow:24px 0 60px rgba(0,0,0,.5);transform:translateX(-104%);transition:transform .34s cubic-bezier(.4,0,.2,1);pointer-events:auto;color:#e7eaf2}+.tws-tour-menu.is-open .tws-tour-menu__panel{transform:translateX(0)}+.tws-tour-menu__head{display:flex;align-items:center;justify-content:space-between;padding:16px 18px 12px;border-bottom:1px solid rgba(255,255,255,.07)}+.tws-tour-menu__title{font-weight:700;font-size:16px}+.tws-tour-menu__x{appearance:none;border:none;background:rgba(255,255,255,.06);color:#cfd5e2;width:30px;height:30px;border-radius:9px;cursor:pointer;font-size:13px;display:grid;place-items:center;transition:background .16s ease}+.tws-tour-menu__x:hover{background:rgba(220,70,70,.8);color:#fff}+.tws-tour-menu__settings{padding:14px 18px;display:flex;flex-direction:column;gap:12px;border-bottom:1px solid rgba(255,255,255,.07)}+.tws-tour-menu__field{display:flex;align-items:center;gap:12px;justify-content:space-between}+.tws-tour-menu__lbl{font-size:12.5px;color:#9aa3b6;font-weight:600;flex:0 0 auto;width:48px}+.tws-tour-seg{display:flex;gap:4px;background:rgba(255,255,255,.05);padding:3px;border-radius:10px;flex:1}+.tws-tour-seg__btn{flex:1;appearance:none;border:none;background:transparent;color:#aeb6c6;font:600 12px/1 inherit;padding:7px 6px;border-radius:7px;cursor:pointer;white-space:nowrap;transition:background .16s ease,color .16s ease}+.tws-tour-seg__btn:hover{color:#e7eaf2}+.tws-tour-seg__btn.is-on{background:linear-gradient(90deg,#7aa2ff,#9d7bff);color:#0b0e16}+.tws-tour-seg__btn:focus-visible{outline:2px solid #7aa2ff;outline-offset:1px}+.tws-tour-menu__select{flex:1;appearance:none;background:rgba(255,255,255,.05);color:#e7eaf2;border:1px solid rgba(255,255,255,.12);border-radius:9px;padding:8px 10px;font:600 13px/1 inherit;cursor:pointer}+.tws-tour-menu__select:focus-visible{outline:2px solid #7aa2ff;outline-offset:1px}+.tws-tour-menu__search{padding:12px 18px 8px}+.tws-tour-menu__input{width:100%;box-sizing:border-box;background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.12);border-radius:10px;color:#e7eaf2;font:500 13.5px/1 inherit;padding:10px 12px}+.tws-tour-menu__input::placeholder{color:#7f8aa0}+.tws-tour-menu__input:focus-visible{outline:2px solid #7aa2ff;outline-offset:1px}+.tws-tour-menu__list{flex:1;overflow-y:auto;padding:4px 10px 18px;scrollbar-width:thin}+.tws-tour-chap{display:flex;align-items:center;justify-content:space-between;gap:8px;padding:14px 8px 6px;font-size:11.5px;font-weight:700;letter-spacing:.05em;text-transform:uppercase;color:#7f8aa0;position:sticky;top:0;background:#0e1118}+.tws-tour-chap__n{font-weight:600;color:#5f697e;font-variant-numeric:tabular-nums}+.tws-tour-stop{display:flex;align-items:center;gap:10px;width:100%;text-align:left;appearance:none;border:none;background:transparent;color:#c4ccda;font:500 13.5px/1.3 inherit;padding:9px 8px;border-radius:9px;cursor:pointer;transition:background .14s ease,color .14s ease}+.tws-tour-stop:hover{background:rgba(255,255,255,.05);color:#fff}+.tws-tour-stop.is-current{background:rgba(122,162,255,.16);color:#fff}+.tws-tour-stop__dot{flex:0 0 auto;width:7px;height:7px;border-radius:50%;background:rgba(255,255,255,.22)}+.tws-tour-stop__dot[data-hl="1"]{background:linear-gradient(135deg,#7aa2ff,#9d7bff)}+.tws-tour-stop.is-current .tws-tour-stop__dot{background:#7aa2ff;box-shadow:0 0 0 3px rgba(122,162,255,.3)}+.tws-tour-stop__title{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}+.tws-tour-stop__star{flex:0 0 auto;color:#9d7bff;font-size:11px}+.tws-tour-menu__empty{padding:30px 14px;text-align:center;color:#7f8aa0;font-size:13px}+@media (prefers-reduced-motion:reduce){.tws-tour-menu__panel{transition:none}.tws-tour-menu__scrim{transition:none}}+`;+ document.head.appendChild(style);+}diff --git a/src/feature-tour/controls.js b/src/feature-tour/controls.jsindex 8c381ac0e..3b9cd1fd6 100644--- a/src/feature-tour/controls.js+++ b/src/feature-tour/controls.js@@ -18,6 +18,7 @@ export class TourControls {bar.setAttribute('role', 'group');bar.setAttribute('aria-label', 'Guided tour controls');bar.innerHTML = `+ <button class="tws-tour-btn" data-act="menu" aria-label="Chapters and settings" title="Chapters & settings" aria-haspopup="dialog" aria-expanded="false">☰</button><button class="tws-tour-btn" data-act="prev" aria-label="Previous feature" title="Previous">⏮</button><button class="tws-tour-btn tws-tour-btn--play" data-act="toggle" aria-label="Pause tour" title="Pause / resume">⏸</button><button class="tws-tour-btn" data-act="next" aria-label="Next feature" title="Next">⏭</button>@@ -27,13 +28,16 @@ export class TourControls {<div class="tws-tour-track__fill"></div></div></div>+ <button class="tws-tour-btn tws-tour-btn--speed" data-act="speed" aria-label="Playback speed" title="Playback speed">1×</button><button class="tws-tour-btn" data-act="mute" aria-label="Mute narration" title="Mute / unmute voice">🔊</button><button class="tws-tour-btn tws-tour-btn--exit" data-act="exit" aria-label="Exit tour" title="Exit tour">✕</button>`;document.body.appendChild(bar);this.bar = bar;+ this.menuBtn = bar.querySelector('[data-act="menu"]');this.playBtn = bar.querySelector('[data-act="toggle"]');this.muteBtn = bar.querySelector('[data-act="mute"]');+ this.speedBtn = bar.querySelector('[data-act="speed"]');this.chapterEl = bar.querySelector('.tws-tour-chapter');this.countEl = bar.querySelector('.tws-tour-count');this.track = bar.querySelector('.tws-tour-track');@@ -42,9 +46,11 @@ export class TourControls {bar.addEventListener('click', (e) => {const act = e.target.closest('[data-act]')?.dataset.act;if (!act) return;- if (act === 'prev') this.handlers.onPrev?.();+ if (act === 'menu') this.handlers.onMenu?.();+ else if (act === 'prev') this.handlers.onPrev?.();else if (act === 'next') this.handlers.onNext?.();else if (act === 'toggle') this.handlers.onToggle?.();+ else if (act === 'speed') this.handlers.onSpeed?.();else if (act === 'mute') this.handlers.onMute?.();else if (act === 'exit') this.handlers.onExit?.();});@@ -86,6 +92,18 @@ export class TourControls {this.muteBtn.setAttribute('aria-label', muted ? 'Unmute narration' : 'Mute narration');}+ setSpeed(speed) {+ // Show a tidy "1×" / "1.5×" label; drop the trailing ".0".+ const label = (Number(speed) || 1).toFixed(2).replace(/\.?0+$/, '');+ this.speedBtn.textContent = label + '×';+ this.speedBtn.setAttribute('aria-label', `Playback speed ${label} times — tap to change`);+ }++ setMenuOpen(open) {+ this.menuBtn.setAttribute('aria-expanded', open ? 'true' : 'false');+ this.menuBtn.classList.toggle('is-active', open);+ }+dispose() {this.bar?.remove();this.bar = null;@@ -111,6 +129,8 @@ function ensureStyles() {.tws-tour-btn:focus-visible{outline:2px solid #7aa2ff;outline-offset:2px}.tws-tour-btn--play{background:rgba(122,162,255,.9);color:#0b0e16}.tws-tour-btn--play:hover{background:rgba(122,162,255,1)}+.tws-tour-btn--speed{width:auto;min-width:40px;padding:0 9px;font-size:13px;font-weight:700;font-variant-numeric:tabular-nums}+.tws-tour-btn.is-active{background:rgba(122,162,255,.28);color:#cdd8ff}.tws-tour-btn--exit:hover{background:rgba(220,70,70,.85)}.tws-tour-meta{display:flex;flex-direction:column;gap:5px;min-width:160px;flex:1}.tws-tour-meta__top{display:flex;justify-content:space-between;align-items:baseline;gap:8px;font-size:12px}diff --git a/src/feature-tour/curriculum.js b/src/feature-tour/curriculum.jsindex 73fd7de8c..0fd88d052 100644--- a/src/feature-tour/curriculum.js+++ b/src/feature-tour/curriculum.js@@ -5,7 +5,8 @@// survives a full-page navigation between stops on different routes.const CURRICULUM_URL = '/tour/curriculum.json';-const STATE_KEY = 'tws:tour:state';+const STATE_KEY = 'tws:tour:state'; // live, per-tab tour (sessionStorage)+const RESUME_KEY = 'tws:tour:resume'; // durable cross-session memory (localStorage)let _cache = null;@@ -28,7 +29,15 @@ export function normalizePath(pathname = location.pathname) {return p === '' ? '/' : p;}-const DEFAULT_STATE = { active: false, index: 0, paused: false, muted: false, voice: 'nova' };+const DEFAULT_STATE = {+ active: false,+ index: 0,+ track: 'full',+ paused: false,+ muted: false,+ voice: 'nova',+ speed: 1,+};export function readState() {try {@@ -47,6 +56,12 @@ export function writeState(patch) {} catch {/* private mode / disabled storage — tour still runs within this page */}+ // Mirror durable preferences + progress so a returning visitor (new tab,+ // next day) can pick the tour back up. The live sequencing still reads from+ // sessionStorage; this is the cross-session memory only.+ if (next.active) {+ writeResume({ index: next.index, track: next.track, voice: next.voice, speed: next.speed });+ }return next;}@@ -58,6 +73,55 @@ export function clearState() {}}+// ── Cross-session memory (localStorage) ──────────────────────────────────────+// Remembers where a visitor got to and their voice/speed preferences across+// sessions, plus whether they've ever finished the tour. Never drives live+// sequencing — only the /tour page's "resume" / "completed" affordances and the+// director's preference defaults read it.+const DEFAULT_RESUME = { index: 0, track: 'full', voice: 'nova', speed: 1, completed: false };++export function readResume() {+ try {+ const raw = localStorage.getItem(RESUME_KEY);+ if (!raw) return { ...DEFAULT_RESUME };+ return { ...DEFAULT_RESUME, ...JSON.parse(raw) };+ } catch {+ return { ...DEFAULT_RESUME };+ }+}++export function writeResume(patch) {+ const next = { ...readResume(), ...patch };+ try {+ localStorage.setItem(RESUME_KEY, JSON.stringify(next));+ } catch {+ /* storage unavailable — cross-session resume simply won't persist */+ }+ return next;+}++export function markCompleted() {+ writeResume({ completed: true, index: 0 });+}++// ── Playlists ────────────────────────────────────────────────────────────────+// A track is a view over the curriculum: an ordered list of absolute stop+// indices to actually visit. 'full' is every stop; 'quick' is the highlighted+// heroes. Pure (no storage) so the sequencing logic and tests can build it+// freely. Always non-empty — an unknown track or a curriculum with no highlights+// falls back to the full list so the tour can never strand itself with nothing+// to play.+export function buildPlaylist(curriculum, track = 'full') {+ const all = curriculum.stops.map((_, i) => i);+ if (track !== 'quick') return all;+ const quick = all.filter((i) => curriculum.stops[i].highlight);+ return quick.length ? quick : all;+}++export function trackMeta(curriculum, track = 'full') {+ return (curriculum.tracks || []).find((t) => t.id === track) || null;+}+// Index of the first stop on a given path, or -1. Used to snap the tour back// onto the route when a visitor navigates by hand.export function stopIndexForPath(curriculum, pathname = location.pathname) {diff --git a/src/feature-tour/director.js b/src/feature-tour/director.jsindex d19451997..349f6661e 100644--- a/src/feature-tour/director.js+++ b/src/feature-tour/director.js@@ -5,12 +5,23 @@// the next stop lives on another route it persists progress and navigates; the// tour re-hydrates from sessionStorage on the new page and picks up exactly// where it left off. One module owns all of that sequencing and every control.+//+// Navigation is expressed over a *playlist* — the ordered list of stop indices+// the chosen track visits (the Full track is every stop; the Quick track is the+// highlighted heroes). `pos` is where we are in that playlist; `index` is the+// absolute curriculum stop it points at. Switching tracks re-derives the+// playlist and re-anchors `pos` to the nearest stop, so the tour never loses its+// place. The chapter panel can jump to any stop, expanding to the Full track if+// the requested stop isn't in the current one.import {loadCurriculum,readState,writeState,clearState,+ readResume,+ markCompleted,+ buildPlaylist,normalizePath,stopIndexForPath,sectionTitle,@@ -19,17 +30,23 @@ import { GuideAvatar } from './guide-avatar.js';import { Spotlight } from './spotlight.js';import { Narrator } from './narrator.js';import { TourControls } from './controls.js';+import { ChapterPanel } from './chapters.js';const ADVANCE_BEAT_MS = 900; // pause between finishing a stop and moving onconst Z_BEAM = 2147483280;+const SPEED_CYCLE = [1, 1.25, 1.5, 0.75];export class TourDirector {constructor() {this.curriculum = null;+ this.playlist = [];+ this.pos = 0;this.index = 0;+ this.track = 'full';this.paused = false;this.muted = false;this.voice = 'nova';+ this.speed = 1;this.mounted = false;this.offRoute = false;this._runToken = 0;@@ -43,13 +60,30 @@ export class TourDirector {// ── Entry points ──────────────────────────────────────────────────────────// Begin a fresh tour from the very first stop (called by the "Start tour"- // button / ?tour=start). Navigates to stop 0's page if we're elsewhere.- async start() {+ // button / ?tour=start). `track` chooses Quick vs Full; voice/speed default to+ // the visitor's remembered preferences. Navigates to stop 0's page if needed.+ async start(track) {await this._ensureCurriculum();- writeState({ active: true, index: 0, paused: false });- this.index = 0;+ const prefs = readResume();+ this.track = track || 'full';+ this.voice = prefs.voice || 'nova';+ this.speed = prefs.speed || 1;+ this.muted = false;this.paused = false;- const first = this.curriculum.stops[0];+ this._seenSections = new Set();+ this.playlist = buildPlaylist(this.curriculum, this.track);+ this.pos = 0;+ this.index = this.playlist[0] ?? 0;+ writeState({+ active: true,+ index: this.index,+ track: this.track,+ voice: this.voice,+ speed: this.speed,+ paused: false,+ muted: false,+ });+ const first = this.curriculum.stops[this.index];if (normalizePath(first.path) !== normalizePath()) {this._navigate(first.path);return;@@ -66,6 +100,9 @@ export class TourDirector {this.paused = state.paused;this.muted = state.muted;this.voice = state.voice || 'nova';+ this.speed = state.speed || 1;+ this.track = state.track || 'full';+ this.playlist = buildPlaylist(this.curriculum, this.track);const here = stopIndexForPath(this.curriculum, location.pathname);const wanted = state.index || 0;@@ -80,6 +117,7 @@ export class TourDirector {this.index = wanted; // wandered off the route entirelythis.offRoute = true;}+ this.pos = this._posForAbs(this.index);await this._mount();if (this.offRoute) {@@ -103,15 +141,28 @@ export class TourDirector {this.avatar = new GuideAvatar();await this.avatar.mount();this.controls = new TourControls({- onPrev: () => this._goTo(this.index - 1),- onNext: () => this._goTo(this.index + 1),+ onMenu: () => this.panel?.toggle(),+ onPrev: () => this._go(this.pos - 1),+ onNext: () => this._go(this.pos + 1),onToggle: () => this._togglePause(),- onSeek: (i) => this._goTo(i),+ onSeek: (i) => this._go(i),+ onSpeed: () => this._cycleSpeed(),onMute: () => this._toggleMute(),onExit: () => this.exit(),});+ this.panel = new ChapterPanel(this.curriculum, {+ onJump: (abs) => this._jumpToAbs(abs),+ onTrack: (t) => this._applyTrack(t),+ onSpeed: (v) => this._setSpeed(v),+ onVoice: (v) => this._setVoice(v),+ onOpenChange: (open) => this.controls.setMenuOpen(open),+ });this.controls.setMuted(this.muted);this.controls.setPaused(this.paused);+ this.controls.setSpeed(this.speed);+ this.panel.setTrack(this.track);+ this.panel.setSpeed(this.speed);+ this.panel.setVoice(this.voice);document.addEventListener('keydown', this._onKey);}@@ -124,6 +175,7 @@ export class TourDirector {if (!stop) return this._finish();this._syncControls();+ this.panel?.setActive(this.index);writeState({ index: this.index });// Chapter bridge — spoken once per section per session.@@ -161,37 +213,33 @@ export class TourDirector {if (this.paused) return;this._advanceTimer = setTimeout(() => {if (token === this._runToken) this._advance();- }, ADVANCE_BEAT_MS);+ }, ADVANCE_BEAT_MS / this.speed);}// Show caption + speak; resolves when the voice (or timed fallback) ends.async _present(text, token) {this.avatar.say(text);- await this.narrator.speak(text, { muted: this.muted, voice: this.voice });+ await this.narrator.speak(text, { muted: this.muted, voice: this.voice, speed: this.speed });}_advance() {- const next = this.index + 1;- if (next >= this.curriculum.stops.length) return this._finish();- this.index = next;- writeState({ index: next });- const stop = this.curriculum.stops[next];- if (normalizePath(stop.path) === normalizePath()) {- this._runCurrent();- } else {- this._navigate(stop.path);- }+ if (this.pos + 1 >= this.playlist.length) return this._finish();+ this._go(this.pos + 1);}- // Jump to an arbitrary stop (prev / next / scrub). Navigates if off-page.- _goTo(i) {- const clamped = Math.max(0, Math.min(this.curriculum.stops.length - 1, i));- this._runToken++; // cancel anything in flight+ // Go to a playlist position (prev / next / scrub / advance / jump). Cancels+ // anything in flight, then runs the stop here or navigates if it's off-page.+ _go(pos) {+ if (!this.playlist.length) return;+ const clamped = Math.max(0, Math.min(this.playlist.length - 1, pos));+ this._runToken++;clearTimeout(this._advanceTimer);this.narrator?.cancel();- this.index = clamped;- writeState({ index: clamped });- const stop = this.curriculum.stops[clamped];+ this.pos = clamped;+ this.index = this.playlist[clamped];+ writeState({ index: this.index });+ this.panel?.setActive(this.index);+ const stop = this.curriculum.stops[this.index];if (normalizePath(stop.path) === normalizePath()) {this._runCurrent();} else {@@ -199,6 +247,14 @@ export class TourDirector {}}+ // Jump to an absolute curriculum stop from the chapter panel. If it isn't in+ // the current track's playlist, expand to the Full track so every stop is+ // reachable, then go to it.+ _jumpToAbs(abs) {+ if (this.playlist.indexOf(abs) < 0) this._applyTrack('full', { silent: true });+ this._go(this._posForAbs(abs));+ }+_togglePause() {this.paused = !this.paused;writeState({ paused: this.paused });@@ -208,7 +264,7 @@ export class TourDirector {this.narrator.cancel();this._runToken++; // freeze the current sequence} else if (this.offRoute) {- this._goTo(this.index);+ this._go(this.pos);} else {// Resume re-narrates the current stop, then continues.const token = ++this._runToken;@@ -227,6 +283,66 @@ export class TourDirector {}}+ // ── Track / speed / voice ───────────────────────────────────────────────────+ _applyTrack(track, { silent = false } = {}) {+ if (track === this.track) return;+ const abs = this.index;+ this.track = track;+ this.playlist = buildPlaylist(this.curriculum, track);+ this.pos = this._posForAbs(abs);+ this.index = this.playlist[this.pos];+ writeState({ track, index: this.index });+ this.panel?.setTrack(track);+ this._syncControls();+ if (!silent) this._go(this.pos); // re-anchor to the (possibly new) stop+ }++ _cycleSpeed() {+ const i = SPEED_CYCLE.indexOf(this.speed);+ this._setSpeed(SPEED_CYCLE[(i + 1) % SPEED_CYCLE.length]);+ }++ _setSpeed(value) {+ const next = Math.min(2, Math.max(0.5, Number(value) || 1));+ if (next === this.speed) return;+ this.speed = next;+ writeState({ speed: next });+ this.controls?.setSpeed(next);+ this.panel?.setSpeed(next);+ // Re-narrate the current stop at the new rate if we're actively playing.+ if (!this.paused && !this.offRoute && this.mounted) {+ const token = ++this._runToken;+ this._narrateAndMaybeAdvance(token);+ }+ }++ _setVoice(value) {+ if (!value || value === this.voice) return;+ this.voice = value;+ writeState({ voice: value });+ this.panel?.setVoice(value);+ if (!this.paused && !this.offRoute && this.mounted) {+ const token = ++this._runToken;+ this._narrateAndMaybeAdvance(token);+ }+ }++ // Playlist position for an absolute stop index — exact match, else nearest.+ _posForAbs(abs) {+ const p = this.playlist.indexOf(abs);+ if (p >= 0) return p;+ let best = 0;+ let bestD = Infinity;+ this.playlist.forEach((a, i) => {+ const d = Math.abs(a - abs);+ if (d < bestD) {+ bestD = d;+ best = i;+ }+ });+ return best;+ }+// ── Off-route recovery ────────────────────────────────────────────────────_showOffRoute() {this._stopBeam();@@ -236,6 +352,7 @@ export class TourDirector {writeState({ paused: true });this.controls.setPaused(true);this._syncControls();+ this.panel?.setActive(this.index);this.avatar.say('We stepped off the tour — press play and I’ll take you back to where we were.');}@@ -248,6 +365,7 @@ export class TourDirector {this.avatar.point();const outro = "And that's the whole platform. You've seen how to build an agent, give it a body and a voice, take it on-chain, and put it to work. Go make something — I'll be around if you want to walk it again.";await this._present(outro, token);+ markCompleted();clearState();this._showCompletion();}@@ -272,7 +390,7 @@ export class TourDirector {const act = e.target.closest('[data-act]')?.dataset.act;if (act === 'restart') {card.remove();- this.start();+ this.start(this.track);} else if (act === 'close') {card.remove();this.exit();@@ -293,6 +411,7 @@ export class TourDirector {this.spotlight?.dispose();this.avatar?.dispose();this.controls?.dispose();+ this.panel?.dispose();this._doneCard?.remove();this.mounted = false;}@@ -369,8 +488,8 @@ export class TourDirector {const stop = this.curriculum.stops[this.index];this.controls.update({chapter: sectionTitle(this.curriculum, stop.section),- index: this.index,- total: this.curriculum.stops.length,+ index: this.pos,+ total: this.playlist.length,});}@@ -380,14 +499,19 @@ export class TourDirector {}_onKey(e) {+ if (this.panel?.open) return; // the panel owns the keyboard while it's upif (isTypingTarget(e.target)) return;if (e.key === ' ' || e.key === 'k') {e.preventDefault();this._togglePause();} else if (e.key === 'ArrowRight') {- this._goTo(this.index + 1);+ this._go(this.pos + 1);} else if (e.key === 'ArrowLeft') {- this._goTo(this.index - 1);+ this._go(this.pos - 1);+ } else if (e.key === 'm' || e.key === 'M') {+ this._toggleMute();+ } else if (e.key === 'c' || e.key === 'C') {+ this.panel?.toggle();} else if (e.key === 'Escape') {this.exit();}diff --git a/src/feature-tour/index.js b/src/feature-tour/index.jsindex 2cd366977..5ce86ca84 100644--- a/src/feature-tour/index.js+++ b/src/feature-tour/index.js@@ -18,8 +18,8 @@ export function createFeatureTour() {isActive() {return readState().active === true;},- start() {- return ensure().start();+ start(track) {+ return ensure().start(track);},resume() {return ensure().resume();@@ -33,9 +33,11 @@ export function createFeatureTour() {bootstrap() {if (typeof window === 'undefined') return;if (window.top !== window.self) return; // never inside an embed/iframe- const param = new URLSearchParams(location.search).get('tour');+ const params = new URLSearchParams(location.search);+ const param = params.get('tour');if (param === 'start') {- ensure().start();+ const track = params.get('track') === 'quick' ? 'quick' : 'full';+ ensure().start(track);} else if (param === '0') {director?.exit();} else if (param === '1' || readState().active) {diff --git a/src/feature-tour/narrator.js b/src/feature-tour/narrator.jsindex 87d97522a..64fb6eaa7 100644--- a/src/feature-tour/narrator.js+++ b/src/feature-tour/narrator.js@@ -17,19 +17,21 @@ export class Narrator {this._finishCurrent = null;}- estimateMs(text) {+ estimateMs(text, speed = 1) {const words = String(text || '').trim().split(/\s+/).filter(Boolean).length;- return Math.max(1600, (words / WPM) * 60000 + 600);+ const base = Math.max(1600, (words / WPM) * 60000 + 600);+ return base / clampSpeed(speed);}// Speak `text`; resolves when playback (or the timed fallback) completes.- async speak(text, { muted = false, voice = 'nova' } = {}) {+ async speak(text, { muted = false, voice = 'nova', speed = 1 } = {}) {this.cancel();const token = ++this._token;+ const rate = clampSpeed(speed);const clean = String(text || '').trim();if (!clean) return;if (muted) {- await this._sleep(this.estimateMs(clean), token);+ await this._sleep(this.estimateMs(clean, rate), token);return;}@@ -38,7 +40,7 @@ export class Narrator {const res = await fetch('/api/tts/speak', {method: 'POST',headers: { 'content-type': 'application/json' },- body: JSON.stringify({ text: clean.slice(0, 4096), voice, format: 'mp3' }),+ body: JSON.stringify({ text: clean.slice(0, 4096), voice, speed: rate, format: 'mp3' }),});if (token !== this._token) return; // canceled while fetchingif (!res.ok) throw new Error(`tts ${res.status}`);@@ -46,6 +48,10 @@ export class Narrator {if (token !== this._token) return;url = URL.createObjectURL(blob);const audio = new Audio(url);+ // The server renders the OpenAI lane at `speed`, but the free Magpie+ // lane ignores it — so also nudge playbackRate as a client-side backstop+ // that works on whichever lane answered. (1× leaves audio untouched.)+ audio.playbackRate = rate;this.audio = audio;await new Promise((resolve) => {let done = false;@@ -104,3 +110,9 @@ export class Narrator {this.cancel();}}++function clampSpeed(s) {+ const n = Number(s);+ if (!Number.isFinite(n)) return 1;+ return Math.min(2, Math.max(0.5, n));+}diff --git a/src/walk-companion-click-to-walk.js b/src/walk-companion-click-to-walk.jsnew file mode 100644index 000000000..e94b9043a--- /dev/null+++ b/src/walk-companion-click-to-walk.js@@ -0,0 +1,673 @@+// Click-to-walk navigation for the corner companion (Task 35).+// ============================================================+// Point at an empty patch of the page and the companion avatar walks there —+// gliding along a smooth, obstacle-aware path, easing into its arrival, and+// turning to face the direction it travels. A faint dotted route and a ripple+// at the destination make the intent legible; a footprint trail fades behind.+//+// WHY this shape (and not "rooted corner avatar"):+// The SDK companion (walk-sdk/src/companion.js) is a fixed-corner WebGL canvas+// whose avatar walks *in place* and only rotates to follow the cursor — it never+// translates across the document. We never edit the SDK (same rule the trails &+// transitions siblings follow). So "walk to a point" is realised by translating+// the companion's *host element* across the viewport with a CSS transform, while+// driving the live controller's walk/idle state and yaw so the rig animates and+// faces its heading. When the avatar arrives it settles back to idle; the host+// keeps its new spot until the next destination or a viewport resize re-anchors.+//+// ACTIVATION RULE (deliberately non-hijacking — see report):+// · Fine pointer (mouse/trackpad): a plain primary-button click on *empty+// space* — i.e. the event target is not, and is not inside, an interactive+// or blocking element — with no modifier keys. Clicks on links, buttons,+// inputs, [role=button], [contenteditable], labels, summaries, scrollbars,+// the companion itself, or any [data-walk-block] are left 100% to the page.+// · Coarse pointer (touch): a *long-press* (≥550ms, finger held still) on+// empty space. Taps, scrolls and flings are never disturbed.+// We listen in the capture phase but NEVER call preventDefault on an eligible+// real interaction — empty-space clicks have no default to suppress, so normal+// link/button behaviour is provably untouched.+//+// SETTING: a toggle persisted to localStorage under the companion's own key+// convention (`${prefix}:companion:clicktowalk`), surfaced as a pill slotted+// into the companion chrome alongside the trails/transitions toggles. Default+// ON. Under prefers-reduced-motion the avatar still goes to the point, but+// instantly (no glide, no path animation) per the motion contract.+//+// This module is owned by src/walk-companion.js, which calls+// installClickToWalk() once on load. Side-effect free on import.++import { prefersReducedMotion, isCoarsePointer } from '../walk-sdk/src/internal/storage.js';++// ── Tunables ──────────────────────────────────────────────────────────────────+const WALK_SPEED = 520; // px / second the host glides across the page+const ARRIVAL_MS = 260; // easing window as it settles onto the target+const MIN_TRAVEL = 8; // ignore micro-moves (px) — reads as a mis-click+const LONG_PRESS_MS = 550; // touch: hold this long (still) to direct the avatar+const TOUCH_SLOP = 12; // px of finger drift that cancels a long-press+const BLOCK_INFLATE = 14; // px each obstacle box is grown by for clearance+const MAX_DETOUR_DEPTH = 4; // recursion cap for the corner-routing pathfinder+const RIPPLE_MS = 620;+const FOOTPRINT_FADE_MS = 2000; // spec: footprint trail fades after ~2s+const Z_FX = 2147482998; // just under the trail layer (…999) & companion (…000)++// ── Persistence (mirrors the companion's `${prefix}:companion:*` convention) ───+let PREF_KEY = 'walk:companion:clicktowalk';++function isEnabledPref() {+ try {+ // Default ON: an absent key means the visitor never opted out.+ return localStorage.getItem(PREF_KEY) !== '0';+ } catch {+ return true;+ }+}+function setEnabledPref(on) {+ try {+ localStorage.setItem(PREF_KEY, on ? '1' : '0');+ } catch {+ /* private mode / disabled storage — non-fatal */+ }+}++// ── Interactive-target detection ───────────────────────────────────────────────+// An "empty space" click is one whose target neither IS nor sits INSIDE anything+// the visitor could plausibly be interacting with. Anything matched here is left+// entirely to the page — we never intercept it.+const INTERACTIVE_SELECTOR = [+ 'a[href]',+ 'button',+ 'input',+ 'select',+ 'textarea',+ 'label',+ 'summary',+ 'details',+ 'option',+ '[role="button"]',+ '[role="link"]',+ '[role="menuitem"]',+ '[role="tab"]',+ '[role="checkbox"]',+ '[role="switch"]',+ '[contenteditable]',+ '[contenteditable="true"]',+ '[tabindex]:not([tabindex="-1"])',+ '[onclick]',+ '.walk-companion', // the companion itself (canvas + its chrome)+ '[data-walk-block]', // explicit no-walk zones double as no-hijack zones+].join(',');++function isInteractiveTarget(el) {+ if (!el || typeof el.closest !== 'function') return true; // be conservative+ if (el.closest(INTERACTIVE_SELECTOR)) return true;+ // Text the visitor may be selecting — don't steal a selection-drag's mouseup.+ const sel = (typeof getSelection === 'function' && getSelection()) || null;+ if (sel && !sel.isCollapsed && String(sel).trim()) return true;+ return false;+}++// ── Obstacle model ─────────────────────────────────────────────────────────────+// Each [data-walk-block] becomes an axis-aligned rectangle in viewport coords,+// inflated for clearance. Recomputed at the start of every walk so it reflects+// the live layout (scroll, responsive reflow, lazy content).+function collectObstacles() {+ const rects = [];+ const blocks = document.querySelectorAll('[data-walk-block]');+ for (const el of blocks) {+ const r = el.getBoundingClientRect();+ if (r.width <= 0 || r.height <= 0) continue;+ rects.push({+ left: r.left - BLOCK_INFLATE,+ top: r.top - BLOCK_INFLATE,+ right: r.right + BLOCK_INFLATE,+ bottom: r.bottom + BLOCK_INFLATE,+ });+ }+ return rects;+}++function pointInRect(x, y, r) {+ return x >= r.left && x <= r.right && y >= r.top && y <= r.bottom;+}++// Liang–Barsky segment/rect intersection — true if [a,b] crosses rect interior.+function segmentHitsRect(ax, ay, bx, by, r) {+ if (pointInRect(ax, ay, r) || pointInRect(bx, by, r)) return true;+ const dx = bx - ax;+ const dy = by - ay;+ let t0 = 0;+ let t1 = 1;+ const edges = [+ [-dx, ax - r.left],+ [dx, r.right - ax],+ [-dy, ay - r.top],+ [dy, r.bottom - ay],+ ];+ for (const [p, q] of edges) {+ if (p === 0) {+ if (q < 0) return false; // parallel and outside this slab+ } else {+ const t = q / p;+ if (p < 0) {+ if (t > t1) return false;+ if (t > t0) t0 = t;+ } else {+ if (t < t0) return false;+ if (t < t1) t1 = t;+ }+ }+ }+ return t0 <= t1;+}++function firstBlocking(ax, ay, bx, by, obstacles) {+ let best = null;+ let bestDist = Infinity;+ for (const r of obstacles) {+ if (!segmentHitsRect(ax, ay, bx, by, r)) continue;+ const cx = (r.left + r.right) / 2;+ const cy = (r.top + r.bottom) / 2;+ const d = (cx - ax) ** 2 + (cy - ay) ** 2;+ if (d < bestDist) {+ bestDist = d;+ best = r;+ }+ }+ return best;+}++// Route from (ax,ay) to (bx,by) around obstacles by detouring through the+// blocking box's corners. For each blocker we try its four (slightly outset)+// corners, recurse on the two legs, and keep the shortest collision-free path.+// Depth-capped so pathological layouts still terminate; on cap we accept the+// straight line (the host simply glides through, which is benign).+function planPath(ax, ay, bx, by, obstacles, depth = 0) {+ const blocker = firstBlocking(ax, ay, bx, by, obstacles);+ if (!blocker || depth >= MAX_DETOUR_DEPTH) return [{ x: bx, y: by }];++ const pad = 2;+ const corners = [+ { x: blocker.left - pad, y: blocker.top - pad },+ { x: blocker.right + pad, y: blocker.top - pad },+ { x: blocker.right + pad, y: blocker.bottom + pad },+ { x: blocker.left - pad, y: blocker.bottom + pad },+ ];++ let best = null;+ let bestLen = Infinity;+ for (const c of corners) {+ // Skip corners that are themselves buried inside another obstacle.+ if (obstacles.some((r) => r !== blocker && pointInRect(c.x, c.y, r))) continue;+ const legA = planPath(ax, ay, c.x, c.y, obstacles, depth + 1);+ const legB = planPath(c.x, c.y, bx, by, obstacles, depth + 1);+ const path = [...legA, ...legB];+ const len = pathLength(ax, ay, path);+ if (len < bestLen) {+ bestLen = len;+ best = path;+ }+ }+ return best || [{ x: bx, y: by }];+}++function pathLength(sx, sy, pts) {+ let len = 0;+ let px = sx;+ let py = sy;+ for (const p of pts) {+ len += Math.hypot(p.x - px, p.y - py);+ px = p.x;+ py = p.y;+ }+ return len;+}++// ── Visual feedback layer (route, ripple, footprints) ──────────────────────────+function makeFxLayer() {+ const layer = document.createElement('div');+ layer.className = 'walk-c2w-fx';+ layer.setAttribute('aria-hidden', 'true');+ layer.style.cssText = [+ 'position:fixed',+ 'inset:0',+ `z-index:${Z_FX}`,+ 'pointer-events:none',+ 'overflow:visible',+ 'contain:layout style',+ ].join(';');+ const svgNS = 'http://www.w3.org/2000/svg';+ const svg = document.createElementNS(svgNS, 'svg');+ svg.setAttribute('width', '100%');+ svg.setAttribute('height', '100%');+ svg.style.cssText = 'position:absolute;inset:0;overflow:visible';+ const route = document.createElementNS(svgNS, 'polyline');+ route.setAttribute('fill', 'none');+ route.setAttribute('stroke-width', '2');+ route.setAttribute('stroke-linecap', 'round');+ route.setAttribute('stroke-linejoin', 'round');+ route.setAttribute('stroke-dasharray', '2 8');+ route.setAttribute('opacity', '0');+ svg.appendChild(route);+ layer.appendChild(svg);+ document.body.appendChild(layer);+ return { layer, route };+}++function accentColor() {+ try {+ const v = getComputedStyle(document.documentElement).getPropertyValue('--accent').trim();+ if (v) return v;+ } catch {+ /* SSR / no DOM */+ }+ return '#7aa2ff';+}++let _fxStyleInjected = false;+function ensureFxStyles() {+ if (_fxStyleInjected) return;+ _fxStyleInjected = true;+ const s = document.createElement('style');+ s.id = 'walk-c2w-style';+ s.textContent = `+@keyframes walk-c2w-ripple{from{transform:translate(-50%,-50%) scale(.2);opacity:.8}to{transform:translate(-50%,-50%) scale(1);opacity:0}}+@keyframes walk-c2w-foot-out{to{opacity:0;transform:translate(-50%,-50%) rotate(var(--c2w-rot)) scale(.7)}}+.walk-c2w-ripple{position:absolute;width:46px;height:46px;border-radius:50%;border:2px solid var(--accent,#7aa2ff);will-change:transform,opacity;animation:walk-c2w-ripple ${RIPPLE_MS}ms cubic-bezier(0,0,0.2,1) forwards}+.walk-c2w-foot{position:absolute;width:9px;height:14px;border-radius:50% 50% 45% 45%;will-change:transform,opacity;opacity:.7}+.walk-c2w-cursor,.walk-c2w-cursor *{cursor:none}+@media (prefers-reduced-motion:reduce){.walk-c2w-ripple{animation-duration:1ms}}+`;+ document.head.appendChild(s);+}++function spawnRipple(layer, x, y) {+ const r = document.createElement('div');+ r.className = 'walk-c2w-ripple';+ r.style.left = `${x}px`;+ r.style.top = `${y}px`;+ r.style.borderColor = accentColor();+ layer.appendChild(r);+ setTimeout(() => r.remove(), RIPPLE_MS + 60);+}++// Drop one footprint glyph along the travelled path, alternating L/R, fading+// over ~2s (spec). `side` flips per call; `ang` is the travel heading (rad).+function spawnFootprint(layer, x, y, ang, side, color) {+ const nx = Math.cos(ang + Math.PI / 2) * 6 * side;+ const ny = Math.sin(ang + Math.PI / 2) * 6 * side;+ const f = document.createElement('div');+ f.className = 'walk-c2w-foot';+ const deg = (ang * 180) / Math.PI + 90;+ f.style.left = `${x + nx}px`;+ f.style.top = `${y + ny}px`;+ f.style.background = color;+ f.style.setProperty('--c2w-rot', `${deg}deg`);+ f.style.transform = `translate(-50%,-50%) rotate(${deg}deg)`;+ f.style.animation = `walk-c2w-foot-out ${FOOTPRINT_FADE_MS}ms linear forwards`;+ layer.appendChild(f);+ setTimeout(() => f.remove(), FOOTPRINT_FADE_MS + 60);+}++// ── The walker ─────────────────────────────────────────────────────────────────+// Owns one animation at a time. `getInstance` returns the live companion+// instance (re-resolved every walk so avatar swaps / playground round-trips just+// work). We translate instance.host via a transform offset from its resting+// fixed-corner position, drive the controller's walk state, and steer the rig+// yaw toward the travel heading.+function createWalker(getInstance, fx) {+ let raf = 0;+ let footSide = 1;++ function stop() {+ if (raf) cancelAnimationFrame(raf);+ raf = 0;+ }++ // The host's resting anchor (its untranslated screen rect). We translate from+ // there, so the avatar's *feet* — near the host's bottom-centre — land on the+ // target point.+ function anchorOf(host) {+ const prev = host.style.transform;+ host.style.transform = 'none';+ const r = host.getBoundingClientRect();+ host.style.transform = prev;+ return { footX: r.left + r.width / 2, footY: r.top + r.height * 0.86 };+ }++ function applyOffset(host, dx, dy) {+ host.style.transform = `translate(${dx}px, ${dy}px)`;+ }++ function currentOffset(host) {+ const m = /translate\(\s*(-?[\d.]+)px\s*,\s*(-?[\d.]+)px/.exec(host.style.transform || '');+ return m ? { dx: parseFloat(m[1]), dy: parseFloat(m[2]) } : { dx: 0, dy: 0 };+ }++ // Walk to a viewport point. Returns a promise that resolves on arrival (or+ // immediately if there's nothing to do), so link/button delegation can chain.+ function walkTo(targetX, targetY) {+ const inst = getInstance();+ const host = inst?.host;+ if (!host || !inst.mounted) return Promise.resolve(false);++ const anchor = anchorOf(host);+ const start = currentOffset(host);+ // Where the feet currently are (anchor + current offset).+ const fromX = anchor.footX + start.dx;+ const fromY = anchor.footY + start.dy;++ const dist = Math.hypot(targetX - fromX, targetY - fromY);+ spawnRipple(fx.layer, targetX, targetY);+ if (dist < MIN_TRAVEL) return Promise.resolve(false);++ const obstacles = collectObstacles();+ const path = planPath(fromX, fromY, targetX, targetY, obstacles);+ // Prepend the live start so the route polyline & segment walk are complete.+ const pts = [{ x: fromX, y: fromY }, ...path];++ drawRoute(pts);++ const reduced = prefersReducedMotion();+ if (reduced) {+ // Instant move — honour the motion contract; no glide, no per-frame walk.+ const last = pts[pts.length - 1];+ applyOffset(host, last.x - anchor.footX, last.y - anchor.footY);+ faceHeading(inst, pts[pts.length - 2] || pts[0], last);+ clearRoute();+ return Promise.resolve(true);+ }++ return animateAlong(inst, host, anchor, pts);+ }++ function faceHeading(inst, from, to) {+ // Map screen travel direction → a yaw the SDK rig understands. The SDK+ // clamps cursor-follow yaw to ±0.7 around centre; we reuse that range so a+ // leftward walk turns the avatar left, rightward turns right.+ const dx = to.x - from.x;+ const sign = Math.abs(dx) < 1 ? 0 : Math.sign(dx);+ const yaw = sign * 0.55;+ // Steer via the SDK's own target so its smoothing eases the turn, and lock+ // out cursor-follow for the duration by parking the "last cursor" time.+ if (typeof inst._targetYaw === 'number') inst._targetYaw = yaw;+ }++ function animateAlong(inst, host, anchor, pts) {+ stop();+ return new Promise((resolve) => {+ // Precompute cumulative segment lengths for constant-speed traversal.+ const segs = [];+ let total = 0;+ for (let i = 1; i < pts.length; i++) {+ const len = Math.hypot(pts[i].x - pts[i - 1].x, pts[i].y - pts[i - 1].y);+ segs.push({ a: pts[i - 1], b: pts[i], len, start: total });+ total += len;+ }+ if (total < 1) {+ clearRoute();+ resolve(true);+ return;+ }+ const travelMs = (total / WALK_SPEED) * 1000;+ const t0 = performance.now();+ let footAcc = 0;+ let lastX = pts[0].x;+ let lastY = pts[0].y;+ const color = accentColor();++ inst.controller?.setState('walk');++ const step = (now) => {+ const live = getInstance();+ if (!live || live !== inst || !inst.mounted) {+ // Companion vanished mid-walk (disable / swap / playground). Bail+ // cleanly — the new instance starts fresh at its corner.+ clearRoute();+ resolve(false);+ return;+ }+ const elapsed = now - t0;+ const linear = Math.min(1, elapsed / travelMs);+ // Ease only the final ARRIVAL_MS so most of the trip is steady pace.+ let eased = linear;+ const arriveFrac = Math.min(0.5, ARRIVAL_MS / travelMs);+ if (linear > 1 - arriveFrac) {+ const local = (linear - (1 - arriveFrac)) / arriveFrac;+ eased = 1 - arriveFrac + arriveFrac * (1 - (1 - local) ** 3);+ }+ const along = eased * total;++ // Find the active segment and interpolate the foot position.+ let seg = segs[segs.length - 1];+ for (const s of segs) {+ if (along <= s.start + s.len) {+ seg = s;+ break;+ }+ }+ const local = seg.len > 0 ? (along - seg.start) / seg.len : 1;+ const fx2 = seg.a.x + (seg.b.x - seg.a.x) * local;+ const fy2 = seg.a.y + (seg.b.y - seg.a.y) * local;+ applyOffset(host, fx2 - anchor.footX, fy2 - anchor.footY);+ faceHeading(inst, seg.a, seg.b);++ // Drop footprints at a steady stride along the real travelled path.+ footAcc += Math.hypot(fx2 - lastX, fy2 - lastY);+ const ang = Math.atan2(seg.b.y - seg.a.y, seg.b.x - seg.a.x);+ while (footAcc >= 30) {+ footAcc -= 30;+ spawnFootprint(fx.layer, lastX, lastY, ang, footSide, color);+ footSide *= -1;+ }+ lastX = fx2;+ lastY = fy2;++ if (linear >= 1) {+ inst.controller?.setState('idle');+ clearRoute();+ resolve(true);+ return;+ }+ raf = requestAnimationFrame(step);+ };+ raf = requestAnimationFrame(step);+ });+ }++ function drawRoute(pts) {+ if (prefersReducedMotion()) return;+ fx.route.setAttribute('points', pts.map((p) => `${p.x.toFixed(1)},${p.y.toFixed(1)}`).join(' '));+ fx.route.setAttribute('stroke', accentColor());+ fx.route.setAttribute('opacity', '0.55');+ }+ function clearRoute() {+ fx.route.animate?.([{ opacity: 0.55 }, { opacity: 0 }], { duration: 240, fill: 'forwards' });+ fx.route.setAttribute('opacity', '0');+ }++ return { walkTo, stop };+}++// ── Settings toggle (slotted into the companion chrome) ────────────────────────+// Matches the trails/transitions sibling buttons: a small round control in the+// host's top-right cluster, revealed on hover/focus, persisted on click.+function injectToggle(host) {+ if (!host || host.querySelector('.walk-companion-c2w')) return;+ const btn = document.createElement('button');+ btn.type = 'button';+ btn.className = 'walk-companion-c2w';+ btn.setAttribute('aria-label', 'Toggle click-to-walk navigation');+ btn.setAttribute('aria-pressed', isEnabledPref() ? 'true' : 'false');+ btn.title = isEnabledPref() ? 'Click-to-walk: on' : 'Click-to-walk: off';+ btn.textContent = '➜';+ btn.style.cssText = [+ 'position:absolute',+ 'top:2px',+ 'right:80px', // left of close(2)/swap(28)/trail(54)+ 'z-index:3',+ 'width:22px',+ 'height:22px',+ 'border:none',+ 'border-radius:50%',+ 'background:rgba(12,14,20,.55)',+ 'color:#fff',+ 'font-size:12px',+ 'line-height:1',+ 'cursor:pointer',+ 'pointer-events:auto',+ 'opacity:0',+ 'transition:opacity .2s ease,background .2s ease',+ 'display:grid',+ 'place-items:center',+ 'padding:0',+ ].join(';');+ syncToggleVisual(btn);++ const styleId = 'walk-companion-c2w-toggle-style';+ if (!document.getElementById(styleId)) {+ const s = document.createElement('style');+ s.id = styleId;+ s.textContent =+ '.walk-companion:hover .walk-companion-c2w,.walk-companion:focus-within .walk-companion-c2w{opacity:1}' ++ '.walk-companion-c2w:focus-visible{outline:2px solid #7aa2ff;outline-offset:2px;opacity:1}' ++ '@media (pointer:coarse){.walk-companion-c2w{opacity:1;right:88px}}';+ document.head.appendChild(s);+ }++ btn.addEventListener('click', (e) => {+ e.stopPropagation();+ setEnabledPref(!isEnabledPref());+ syncToggleVisual(btn);+ });+ host.appendChild(btn);+}++function syncToggleVisual(btn) {+ const on = isEnabledPref();+ btn.setAttribute('aria-pressed', on ? 'true' : 'false');+ btn.title = on ? 'Click-to-walk: on' : 'Click-to-walk: off';+ btn.style.background = on ? 'rgba(122,162,255,.45)' : 'rgba(12,14,20,.55)';+ btn.style.color = on ? '#fff' : 'rgba(255,255,255,.5)';+}++// ── Public install ─────────────────────────────────────────────────────────────+/**+ * Wire click-to-walk navigation to the companion.+ * @param {object} opts+ * @param {() => (object|null)} opts.getInstance returns the live WalkCompanion+ * instance (with .host, .mounted, .controller, ._targetYaw).+ * @param {() => (HTMLElement|null)} [opts.getHostEl] returns the companion host+ * for injecting the settings toggle (defaults to getInstance().host).+ * @param {string} [opts.storageKey] localStorage key for the on/off pref.+ * @returns {() => void} uninstall function.+ */+export function installClickToWalk({ getInstance, getHostEl, storageKey } = {}) {+ if (typeof document === 'undefined') return () => {};+ if (storageKey) PREF_KEY = storageKey;+ const resolveInst = typeof getInstance === 'function' ? getInstance : () => null;++ ensureFxStyles();+ const fx = makeFxLayer();+ const walker = createWalker(resolveInst, fx);++ const ready = () => {+ const inst = (() => {+ try {+ return resolveInst();+ } catch {+ return null;+ }+ })();+ return isEnabledPref() && inst && inst.mounted && inst.host;+ };++ // ── Fine-pointer: plain empty-space click ────────────────────────────────────+ function onClickCapture(e) {+ if (e.button !== 0 || e.altKey || e.metaKey || e.ctrlKey || e.shiftKey) return;+ if (e.pointerType === 'touch') return; // touch handled by long-press below+ if (!ready()) return;+ if (isInteractiveTarget(e.target)) return; // never hijack real controls+ // Empty-space clicks have no default action, so we don't preventDefault —+ // normal link/button navigation is provably untouched.+ walker.walkTo(e.clientX, e.clientY);+ }++ // ── Coarse-pointer: long-press on empty space ────────────────────────────────+ let pressTimer = 0;+ let pressX = 0;+ let pressY = 0;+ let pressTarget = null;++ function clearPress() {+ if (pressTimer) clearTimeout(pressTimer);+ pressTimer = 0;+ pressTarget = null;+ }+ function onTouchStart(e) {+ if (!isCoarsePointer()) return;+ if (e.touches && e.touches.length > 1) return clearPress();+ if (!ready()) return;+ const t = e.touches ? e.touches[0] : e;+ if (!t) return;+ if (isInteractiveTarget(t.target)) return; // leave taps on controls alone+ pressX = t.clientX;+ pressY = t.clientY;+ pressTarget = t.target;+ clearTimeout(pressTimer);+ pressTimer = setTimeout(() => {+ pressTimer = 0;+ // Fire only if the finger is still on empty space — a long stationary+ // press, not a tap or a scroll.+ if (pressTarget && !isInteractiveTarget(pressTarget)) {+ walker.walkTo(pressX, pressY);+ }+ }, LONG_PRESS_MS);+ }+ function onTouchMove(e) {+ if (!pressTimer) return;+ const t = e.touches ? e.touches[0] : e;+ if (!t) return;+ if (Math.hypot(t.clientX - pressX, t.clientY - pressY) > TOUCH_SLOP) clearPress();+ }++ document.addEventListener('click', onClickCapture, { capture: true });+ document.addEventListener('touchstart', onTouchStart, { capture: true, passive: true });+ document.addEventListener('touchmove', onTouchMove, { capture: true, passive: true });+ document.addEventListener('touchend', clearPress, { capture: true });+ document.addEventListener('touchcancel', clearPress, { capture: true });+ // A resize re-anchors the host: snap any in-progress glide offset away so the+ // avatar returns to its corner rather than floating at a stale coordinate.+ const onResize = () => {+ walker.stop();+ const inst = resolveInst();+ if (inst?.host) inst.host.style.transform = '';+ };+ window.addEventListener('resize', onResize, { passive: true });++ // Inject the settings toggle once the host exists (poll briefly after mount),+ // and re-inject after avatar swaps / playground round-trips replace the host.+ let tries = 0;+ const tryInject = () => {+ const host = (() => {+ try {+ return (typeof getHostEl === 'function' ? getHostEl() : resolveInst()?.host) || null;+ } catch {+ return null;+ }+ })();+ if (host) injectToggle(host);+ if (tries++ < 600) setTimeout(tryInject, 500); // keep re-asserting on swaps+ };+ tryInject();++ return function uninstall() {+ document.removeEventListener('click', onClickCapture, { capture: true });+ document.removeEventListener('touchstart', onTouchStart, { capture: true });+ document.removeEventListener('touchmove', onTouchMove, { capture: true });+ document.removeEventListener('touchend', clearPress, { capture: true });+ document.removeEventListener('touchcancel', clearPress, { capture: true });+ window.removeEventListener('resize', onResize);+ walker.stop();+ fx.layer.remove();+ };+}diff --git a/src/walk-companion.js b/src/walk-companion.jsindex 3b6eca973..598dd1ee8 100644--- a/src/walk-companion.js+++ b/src/walk-companion.js@@ -15,6 +15,7 @@import { createWalkCompanion } from '../walk-sdk/src/companion.js';import { installTransitions } from './walk-companion-transitions.js';import { createWalkTrails2D, createTrailSetting, TRAIL_STYLE_LABELS } from './walk-trails.js';+import { installClickToWalk } from './walk-companion-click-to-walk.js';const walk = createWalkCompanion({// Static GLBs and the animation manifest are served from this origin.@@ -237,4 +238,21 @@ walk.trails = {trailRaf = requestAnimationFrame(trailTick);+// ── Click-to-walk navigation (Task 35) ──────────────────────────────────────+// Clicking an empty patch of the page (or long-pressing on touch) sends the+// companion avatar gliding to that spot, routing around [data-walk-block]+// elements, facing its heading, and easing into arrival. We never edit the SDK:+// the walker translates the live instance's host element and drives its+// controller's walk/idle state + yaw. The on/off pref persists under the+// companion's own key namespace (`${prefix}:companion:clicktowalk`), and the+// settings pill is slotted into the same chrome as the trails/transitions+// toggles. We hand it the live instance getter so it survives avatar swaps and+// playground round-trips.+const C2W_KEY = `${(walk.config?.keys?.enabled || 'three:companion:enabled').split(':')[0]}:companion:clicktowalk`;+installClickToWalk({+ getInstance: () => walk.instance,+ getHostEl: companionHost,+ storageKey: C2W_KEY,+});+walk.bootstrap();diff --git a/src/walk-session.js b/src/walk-session.jsnew file mode 100644index 000000000..84069ae49--- /dev/null+++ b/src/walk-session.js@@ -0,0 +1,408 @@+// Walk session persistence — resume where you left off.+//+// Captures the live /walk state (selected avatar, environment, camera mode, last+// position/heading, trail style, recent gestures, companion prefs, multiplayer+// room) and restores it on the next visit so returning to /walk continues from+// the last known state instead of starting over.+//+// Two storage tiers, last-write-wins:+// · Signed-in users sync to /api/walk/session (PUT/GET), so the same state+// follows them across browsers and devices.+// · Everyone falls back to localStorage — the anonymous/offline path, and the+// instant local cache even for signed-in users (the server read overlays it+// when fresher).+//+// Saves are debounced (a burst of changes collapses into one write), throttled to+// at most every 30s while active, and flushed once on pagehide via sendBeacon so a+// closed tab still records the final state. Restore applies only a snapshot that+// is < 7 days old and surfaces a small "Welcome back" toast with a "Start fresh"+// action that wipes the saved state.+//+// The walk runtime (src/walk.js) owns the actual scene; this module is a thin+// state mirror. walk.js passes `capture` (read live state → snapshot) and+// `restore` (apply a snapshot → scene) callbacks; everything else — storage,+// auth tiering, debouncing, the toast — lives here.++import { log } from './shared/log.js';++const LS_KEY = 'twx_walk_session';+const ENDPOINT = '/api/walk/session';+const MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000; // restore only snapshots < 7 days old+const SAVE_DEBOUNCE_MS = 1500; // collapse a burst of changes into one write+const SAVE_THROTTLE_MS = 30_000; // at most one periodic save per 30s while active+const SCHEMA_VERSION = 1;++// ── localStorage tier ───────────────────────────────────────────────────────++function readLocal() {+ try {+ const raw = localStorage.getItem(LS_KEY);+ if (!raw) return null;+ const parsed = JSON.parse(raw);+ if (!parsed || typeof parsed !== 'object') return null;+ return parsed;+ } catch {+ return null;+ }+}++function writeLocal(envelope) {+ try {+ localStorage.setItem(LS_KEY, JSON.stringify(envelope));+ } catch {+ // Private mode / quota — the server tier (when signed in) still persists,+ // and an in-tab session keeps running regardless.+ }+}++function clearLocal() {+ try {+ localStorage.removeItem(LS_KEY);+ } catch {+ /* nothing more we can do */+ }+}++// ── server tier ─────────────────────────────────────────────────────────────+// A GET that 401s means "not signed in" → localStorage is the source of truth.+// Any non-2xx/401 (offline, 5xx) degrades to localStorage too, never throws.++async function fetchServerState() {+ try {+ const res = await fetch(ENDPOINT, {+ method: 'GET',+ credentials: 'include',+ headers: { accept: 'application/json' },+ });+ if (res.status === 401) return { signedIn: false, state: null, updatedAt: null };+ if (res.status === 204) return { signedIn: true, state: null, updatedAt: null };+ if (!res.ok) return { signedIn: null, state: null, updatedAt: null };+ const data = await res.json().catch(() => null);+ return {+ signedIn: true,+ state: data?.state ?? null,+ updatedAt: data?.updatedAt ? Date.parse(data.updatedAt) : null,+ };+ } catch {+ // Offline / network error — treat as "unknown auth", fall back to local.+ return { signedIn: null, state: null, updatedAt: null };+ }+}++async function putServerState(state) {+ try {+ const res = await fetch(ENDPOINT, {+ method: 'PUT',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ state }),+ });+ return res.ok;+ } catch {+ return false;+ }+}++// ── public controller ───────────────────────────────────────────────────────++/**+ * Wire walk session persistence into the running /walk page.+ *+ * @param {object} opts+ * @param {() => (object|null)} opts.capture Read the live scene → a plain snapshot.+ * @param {(snapshot: object) => void} opts.restore Apply a snapshot → the scene.+ * @returns {{+ * ready: Promise<{ restored: boolean, source: 'server'|'local'|null }>,+ * save: () => void,+ * touch: () => void,+ * startFresh: () => void,+ * isSignedIn: () => (boolean|null),+ * }}+ */+export function createWalkSession({ capture, restore }) {+ if (typeof capture !== 'function' || typeof restore !== 'function') {+ throw new Error('createWalkSession requires capture() and restore() callbacks');+ }++ let signedIn = null; // null = unknown until first server read resolves+ let debounceTimer = 0;+ let lastSaveAt = 0;+ let destroyed = false;++ // Build the persisted envelope from the current live state.+ function envelope() {+ const state = capture() || {};+ state.savedAt = Date.now();+ return { v: SCHEMA_VERSION, savedAt: state.savedAt, state };+ }++ function persistNow() {+ if (destroyed) return;+ const env = envelope();+ lastSaveAt = Date.now();+ writeLocal(env); // always cache locally (instant, offline-safe)+ if (signedIn) putServerState(env.state); // cross-device sync for authed users+ }++ // Debounced save: a burst of meaningful changes collapses into one write.+ function save() {+ if (destroyed) return;+ clearTimeout(debounceTimer);+ debounceTimer = setTimeout(persistNow, SAVE_DEBOUNCE_MS);+ }++ // Throttled periodic save while active (the 30s heartbeat). Skips the write if+ // a save already happened within the window, so it never competes with `save`.+ function touch() {+ if (destroyed) return;+ if (Date.now() - lastSaveAt < SAVE_THROTTLE_MS) return;+ persistNow();+ }++ // Final flush on pagehide. The snapshot is committed to localStorage+ // synchronously (the durable record that survives the unload), and for+ // signed-in users a fire-and-forget keepalive PUT lets the last state reach+ // the server so cross-device sync catches it even when the tab is closing.+ function flushOnHide() {+ if (destroyed) return;+ clearTimeout(debounceTimer);+ const env = envelope();+ writeLocal(env);+ if (signedIn) {+ // keepalive lets the request outlive the page; best-effort, never awaited.+ try {+ fetch(ENDPOINT, {+ method: 'PUT',+ credentials: 'include',+ keepalive: true,+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ state: env.state }),+ }).catch(() => {});+ } catch {+ /* best-effort */+ }+ }+ }++ // Wipe every tier and clear the in-memory cadence so nothing re-saves the old+ // state. Surfaced as the "Start fresh" toast action.+ function startFresh() {+ clearTimeout(debounceTimer);+ lastSaveAt = Date.now(); // suppress an immediate periodic re-save+ clearLocal();+ if (signedIn) {+ // Persist an empty snapshot so the cleared state syncs across devices too.+ putServerState({});+ }+ }++ // Resolve the freshest available snapshot, restore it, and report what was+ // applied. Server wins when signed in and fresher-or-equal; otherwise local.+ async function bootstrap() {+ const local = readLocal();+ const server = await fetchServerState();+ signedIn = server.signedIn;++ const candidates = [];+ if (server.state && Object.keys(server.state).length) {+ const at = server.updatedAt || serverSavedAt(server.state) || 0;+ candidates.push({ source: 'server', state: server.state, at });+ }+ if (local?.state && Object.keys(local.state).length) {+ candidates.push({ source: 'local', state: local.state, at: local.savedAt || 0 });+ }+ if (!candidates.length) return { restored: false, source: null };++ // Freshest wins; ties favour the server (cross-device truth).+ candidates.sort((a, b) => b.at - a.at || (a.source === 'server' ? -1 : 1));+ const best = candidates[0];++ // Freshness gate — never resurrect a stale world the user has moved on from.+ if (!best.at || Date.now() - best.at > MAX_AGE_MS) {+ return { restored: false, source: null };+ }++ try {+ restore(best.state);+ } catch (err) {+ log.warn('[walk-session] restore failed:', err?.message || err);+ return { restored: false, source: null };+ }++ // If the server held a snapshot but the user isn't signed in here, the local+ // copy is now authoritative; if signed-in but only local existed, sync it up+ // so the other devices converge. Both are cheap last-write-wins writes.+ if (best.source === 'local' && signedIn) putServerState(best.state);++ return { restored: true, source: best.source, savedAt: best.at };+ }++ const ready = bootstrap();++ // 30s heartbeat while the tab is visible — the periodic snapshot from the spec.+ const heartbeat = setInterval(() => {+ if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return;+ touch();+ }, SAVE_THROTTLE_MS);++ // Snapshot on the way out (tab close / navigation / background on mobile).+ const onPageHide = () => flushOnHide();+ const onVisibility = () => {+ if (document.visibilityState === 'hidden') flushOnHide();+ };+ window.addEventListener('pagehide', onPageHide);+ window.addEventListener('beforeunload', onPageHide);+ document.addEventListener('visibilitychange', onVisibility);++ function destroy() {+ destroyed = true;+ clearTimeout(debounceTimer);+ clearInterval(heartbeat);+ window.removeEventListener('pagehide', onPageHide);+ window.removeEventListener('beforeunload', onPageHide);+ document.removeEventListener('visibilitychange', onVisibility);+ }++ return {+ ready,+ save,+ touch,+ startFresh,+ destroy,+ isSignedIn: () => signedIn,+ };+}++function serverSavedAt(state) {+ const v = state && typeof state.savedAt === 'number' ? state.savedAt : 0;+ return Number.isFinite(v) ? v : 0;+}++// ── "Welcome back" toast ─────────────────────────────────────────────────────+// A small, self-contained, dismissible toast announcing the resume with a+// "Start fresh" action. Canvas-first page, so it ships its own minimal styling+// using brand custom properties rather than pulling in a component.++export function showWelcomeBackToast({ onStartFresh, sceneLabel } = {}) {+ if (typeof document === 'undefined') return;++ const host = document.createElement('div');+ host.className = 'walk-resume-toast';+ host.setAttribute('role', 'status');+ host.setAttribute('aria-live', 'polite');+ host.style.cssText = [+ 'position:fixed',+ 'left:50%',+ 'bottom:calc(env(safe-area-inset-bottom,0) + 88px)',+ 'transform:translateX(-50%) translateY(12px)',+ 'z-index:62',+ 'display:flex',+ 'align-items:center',+ 'gap:14px',+ 'max-width:min(92vw,440px)',+ 'padding:11px 12px 11px 18px',+ 'border-radius:14px',+ 'background:rgba(17,17,20,0.92)',+ 'border:1px solid rgba(255,255,255,0.12)',+ 'box-shadow:0 12px 40px rgba(0,0,0,0.5)',+ 'backdrop-filter:blur(16px)',+ '-webkit-backdrop-filter:blur(16px)',+ 'color:#f4f5f8',+ 'font:500 13px/1.35 var(--font-body,Inter,system-ui,sans-serif)',+ 'opacity:0',+ 'transition:opacity .28s ease,transform .28s ease',+ ].join(';');++ const text = document.createElement('div');+ text.style.cssText = 'flex:1;min-width:0';+ const title = document.createElement('div');+ title.style.cssText = 'font-weight:700;font-size:13px;margin-bottom:1px';+ title.textContent = 'Welcome back';+ const sub = document.createElement('div');+ sub.style.cssText = 'font-size:12px;color:rgba(255,255,255,0.62)';+ sub.textContent = sceneLabel+ ? `Resumed where you left off in ${sceneLabel}.`+ : 'Resumed where you left off.';+ text.append(title, sub);++ const freshBtn = document.createElement('button');+ freshBtn.type = 'button';+ freshBtn.textContent = 'Start fresh';+ freshBtn.style.cssText = [+ 'appearance:none',+ 'flex:0 0 auto',+ 'border:1px solid rgba(255,255,255,0.2)',+ 'background:rgba(255,255,255,0.06)',+ 'color:#fff',+ 'border-radius:999px',+ 'padding:6px 14px',+ 'font:inherit',+ 'font-size:12px',+ 'font-weight:600',+ 'cursor:pointer',+ 'transition:background .15s ease,border-color .15s ease',+ ].join(';');+ freshBtn.addEventListener('mouseenter', () => {+ freshBtn.style.background = 'rgba(255,255,255,0.14)';+ freshBtn.style.borderColor = 'rgba(255,255,255,0.34)';+ });+ freshBtn.addEventListener('mouseleave', () => {+ freshBtn.style.background = 'rgba(255,255,255,0.06)';+ freshBtn.style.borderColor = 'rgba(255,255,255,0.2)';+ });++ const closeBtn = document.createElement('button');+ closeBtn.type = 'button';+ closeBtn.setAttribute('aria-label', 'Dismiss');+ closeBtn.textContent = '×';+ closeBtn.style.cssText = [+ 'appearance:none',+ 'flex:0 0 auto',+ 'border:none',+ 'background:transparent',+ 'color:rgba(255,255,255,0.5)',+ 'font:400 20px/1 system-ui,sans-serif',+ 'cursor:pointer',+ 'padding:2px 6px',+ 'border-radius:8px',+ 'transition:color .15s ease',+ ].join(';');+ closeBtn.addEventListener('mouseenter', () => (closeBtn.style.color = '#fff'));+ closeBtn.addEventListener('mouseleave', () => (closeBtn.style.color = 'rgba(255,255,255,0.5)'));++ let dismissTimer = 0;+ function dismiss() {+ clearTimeout(dismissTimer);+ host.style.opacity = '0';+ host.style.transform = 'translateX(-50%) translateY(12px)';+ setTimeout(() => host.remove(), 320);+ }++ freshBtn.addEventListener('click', () => {+ try {+ onStartFresh?.();+ } catch (err) {+ log.warn('[walk-session] start-fresh failed:', err?.message || err);+ }+ title.textContent = 'Starting fresh';+ sub.textContent = 'Your saved walk has been cleared.';+ freshBtn.remove();+ clearTimeout(dismissTimer);+ dismissTimer = setTimeout(dismiss, 2200);+ });+ closeBtn.addEventListener('click', dismiss);+ host.addEventListener('keydown', (e) => {+ if (e.key === 'Escape') dismiss();+ });++ host.append(text, freshBtn, closeBtn);+ document.body.appendChild(host);+ requestAnimationFrame(() => {+ host.style.opacity = '1';+ host.style.transform = 'translateX(-50%) translateY(0)';+ });+ // Auto-dismiss after a while if untouched; the action stays available until then.+ dismissTimer = setTimeout(dismiss, 12_000);++ return { dismiss };+}diff --git a/src/walk.js b/src/walk.jsindex 53d9c4128..f1309e0d2 100644--- a/src/walk.js+++ b/src/walk.js@@ -63,6 +63,7 @@ import {} from './walk-environments.js';import { log } from './shared/log.js';import { createWalkTrails3D, createTrailSetting, TRAIL_STYLE_LABELS } from './walk-trails.js';+import { createWalkSession, showWelcomeBackToast } from './walk-session.js';const AVATAR_URL_DEFAULT = '/avatars/default.glb';@@ -1404,6 +1405,37 @@ async function loadAvatar() {}}+// Swap the live avatar to a different GLB. Shared by the in-page avatar picker and+// by session restore so both paths build, frame, animate, and broadcast the new+// avatar identically. Throws on load failure so callers can surface it.+async function applyAvatarSwap(url, id) {+ const loader = new GLTFLoader();+ const gltf = await loader.loadAsync(url);+ if (avatar) avatarRig.remove(avatar);+ avatar = gltf.scene;+ avatarTemplate = gltf.scene;+ avatar.traverse((n) => {+ if (n.isMesh) {+ n.castShadow = true;+ n.receiveShadow = false;+ }+ });+ 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);+ avatarHeight = height;+ CAM_OFFSET.set(0, height * 1.05, height * 1.95);+ CAM_LOOK_OFFSET.set(0, height * 0.6, 0);+ if (cameraMode === 'firstperson') avatar.visible = false;+ animationManager.attach(avatar);+ animationManager.crossfadeTo(motionToClipName(currentMotion), 0);+ resolvedAvatarUrl = url;+ setSelectedAvatar(id, url);+ setWalkMetricsAvatarId(id);+ net?.sendAvatar(url, id || '');+}+// ── Gestures (Task 14) ─────────────────────────────────────────────────────// The expressive emote system lives in src/walk-gestures.js: wave / dance / sit// / point / cheer / agree / disagree / talking, driven through the animation@@ -2286,6 +2318,39 @@ function setWalkMetricsAvatarId(id) {walkMetricsAvatarId = id && UUID_RE.test(id) ? id : null;}+// ── Walk session persistence (resume where you left off) ──────────────────────+// Mirrors the live scene state so a returning visitor resumes from where they+// left off. The avatar picker (a scoped block far below) updates these via+// setSelectedAvatar(); the env/camera/gesture/trail paths feed the same module+// through walkSession.save(). The controller persists to localStorage for+// everyone and syncs to /api/walk/session for signed-in users.+let selectedAvatarId =+ (() => {+ const id = new URLSearchParams(location.search).get('avatar');+ return id && UUID_RE.test(id) ? id : null;+ })();+let selectedAvatarUrl = null; // resolved on swap; null = default avatar+const recentGestures = []; // most-recent-first, capped at 5++function setSelectedAvatar(id, url) {+ selectedAvatarId = id && UUID_RE.test(id) ? id : null;+ selectedAvatarUrl = url || null;+}++// Record a gesture into the most-recent-first ring (deduped), capped at 5, and+// persist. Surfaces the user's recent gestures so a return visit can prioritise+// them. Called from the gesture-play wrapper installed in setupGestures().+function recordRecentGesture(name) {+ if (!name || typeof name !== 'string') return;+ const i = recentGestures.indexOf(name);+ if (i !== -1) recentGestures.splice(i, 1);+ recentGestures.unshift(name);+ if (recentGestures.length > 5) recentGestures.length = 5;+ walkSession?.save();+}++let walkSession = null;+// Per-session accumulators. `pending*` hold metrics earned since the last flush;// `session*` hold lifetime-of-session totals used for achievement thresholds and// the distinct-environment set.diff --git a/tests/feature-tour-curriculum.test.js b/tests/feature-tour-curriculum.test.jsnew file mode 100644index 000000000..fa08da01d--- /dev/null+++ b/tests/feature-tour-curriculum.test.js@@ -0,0 +1,81 @@+/**+ * Feature Tour curriculum + track playlists — unit tests.+ *+ * The tour is driven by a generated curriculum (scripts/build-tour.mjs →+ * public/tour/curriculum.json) and navigated over a *playlist* of stop indices+ * derived per track. These tests pin the two invariants the runtime relies on:+ * 1. The generated curriculum is well-formed — every stop carries a boolean+ * `highlight`, and the declared `tracks` metadata agrees with the stops.+ * 2. buildPlaylist() yields the right index lists for each track, always+ * non-empty, and degrades to the full list when a curriculum has no+ * highlights or an unknown track is requested.+ */++import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { describe, it, expect } from 'vitest';+import { buildPlaylist, trackMeta } from '../src/feature-tour/curriculum.js';++const curriculum = JSON.parse(+ readFileSync(resolve(__dirname, '../public/tour/curriculum.json'), 'utf8'),+);++describe('generated curriculum', () => {+ it('has stops, sections, and both tracks', () => {+ expect(curriculum.stops.length).toBeGreaterThan(0);+ expect(curriculum.sections.length).toBeGreaterThan(0);+ const ids = (curriculum.tracks || []).map((t) => t.id).sort();+ expect(ids).toEqual(['full', 'quick']);+ });++ it('marks every stop with a boolean highlight flag', () => {+ for (const stop of curriculum.stops) {+ expect(typeof stop.highlight).toBe('boolean');+ }+ });++ it('keeps track metadata consistent with the stops', () => {+ const highlights = curriculum.stops.filter((s) => s.highlight).length;+ expect(trackMeta(curriculum, 'full').stopCount).toBe(curriculum.stops.length);+ expect(trackMeta(curriculum, 'quick').stopCount).toBe(highlights);+ // Quick is a true subset and a meaningful sample of the whole.+ expect(highlights).toBeGreaterThan(0);+ expect(highlights).toBeLessThan(curriculum.stops.length);+ });++ it('includes a highlight at the start of every chapter', () => {+ for (const section of curriculum.sections) {+ const first = curriculum.stops.find((s) => s.section === section.id);+ expect(first.highlight, `first stop of ${section.id} should be a highlight`).toBe(true);+ }+ });+});++describe('buildPlaylist', () => {+ it('returns every stop index for the full track', () => {+ const full = buildPlaylist(curriculum, 'full');+ expect(full).toHaveLength(curriculum.stops.length);+ expect(full[0]).toBe(0);+ expect(full[full.length - 1]).toBe(curriculum.stops.length - 1);+ });++ it('returns only highlighted indices for the quick track', () => {+ const quick = buildPlaylist(curriculum, 'quick');+ expect(quick.length).toBe(curriculum.stops.filter((s) => s.highlight).length);+ expect(quick.every((i) => curriculum.stops[i].highlight)).toBe(true);+ // Strictly increasing — playlists preserve curriculum order.+ for (let i = 1; i < quick.length; i++) expect(quick[i]).toBeGreaterThan(quick[i - 1]);+ // The first stop (home) anchors both tracks.+ expect(quick[0]).toBe(0);+ });++ it('defaults to the full track for an unknown track id', () => {+ expect(buildPlaylist(curriculum, 'nope')).toHaveLength(curriculum.stops.length);+ expect(buildPlaylist(curriculum)).toHaveLength(curriculum.stops.length);+ });++ it('falls back to the full list when no stops are highlighted', () => {+ const flat = { stops: [{ highlight: false }, { highlight: false }] };+ expect(buildPlaylist(flat, 'quick')).toEqual([0, 1]);+ });+});diff --git a/tests/x402-checkout-prepare.test.js b/tests/x402-checkout-prepare.test.jsnew file mode 100644index 000000000..3a4e76659--- /dev/null+++ b/tests/x402-checkout-prepare.test.js@@ -0,0 +1,67 @@+import { describe, it, expect } from 'vitest';+import { PublicKey } from '@solana/web3.js';++import { acceptSchema, prepareSchema } from '../api/x402-checkout.js';++// The 402 challenge's `accept` is built from operator env (X402_PAY_TO_SOLANA /+// X402_FEE_PAYER_SOLANA). Those values are pasted into dashboards and routinely+// carry a trailing newline. An untrimmed address makes prepare throw+// "Non-base58 character" inside `new PublicKey()` — an opaque 500 that took down+// every USDC checkout at the club door. The schema must trim it back to a valid+// address so the transaction still builds.+const PAY_TO = 'wwwwwDxFWRn7grgr3Esrsg5C6NvDoDHSA4gaCffccrU';+const FEE_PAYER = '2wKupLR9q6wXYppw8Gr2NvWxKBUqm4PPJKkQfoxHDBg4';+const USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';+const BUYER = 'wwwPqsM4N7T9J69tB82nLyzxqsH159j4orftLTQfUGV';++const challengeAccept = (overrides = {}) => ({+ scheme: 'exact',+ amount: '10000',+ maxTimeoutSeconds: 60,+ network: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',+ payTo: PAY_TO,+ asset: USDC,+ extra: { name: 'USDC', decimals: 6, feePayer: FEE_PAYER },+ ...overrides,+});++describe('x402-checkout acceptSchema — whitespace-tolerant addresses', () => {+ it('trims a trailing newline on payTo so PublicKey construction succeeds', () => {+ const accept = challengeAccept({ payTo: `${PAY_TO}\n` });+ const parsed = acceptSchema.parse(accept);+ expect(parsed.payTo).toBe(PAY_TO);+ // The exact call that 500'd in prepare before the trim landed.+ expect(() => new PublicKey(parsed.payTo)).not.toThrow();+ });++ it('trims whitespace on every address field (asset, feePayer)', () => {+ const accept = challengeAccept({+ asset: ` ${USDC}`,+ extra: { name: 'USDC', decimals: 6, feePayer: `${FEE_PAYER}\r\n` },+ });+ const parsed = acceptSchema.parse(accept);+ expect(parsed.asset).toBe(USDC);+ expect(parsed.extra.feePayer).toBe(FEE_PAYER);+ });++ it('still rejects an address that is malformed beyond whitespace', () => {+ expect(() => acceptSchema.parse(challengeAccept({ payTo: 'too-short' }))).toThrow();+ });+});++describe('x402-checkout prepareSchema', () => {+ it('trims the buyer address from the posted body', () => {+ const parsed = prepareSchema.parse({ accept: challengeAccept(), buyer: `${BUYER}\n` });+ expect(parsed.buyer).toBe(BUYER);+ expect(() => new PublicKey(parsed.buyer)).not.toThrow();+ });++ it('trims donation (tip) recipient addresses', () => {+ const parsed = prepareSchema.parse({+ accept: challengeAccept(),+ buyer: BUYER,+ tips: [{ to: `${USDC}\n`, amount: '1000' }],+ });+ expect(parsed.tips[0].to).toBe(USDC);+ });+});