Skip to content

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.

feat: tour-sdk package, auto-rig on avatar create, resilient Solana RPC

nirholas8407170f2f0f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a999707b3..895fbfe02 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -24,6 +24,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Discover and character feeds load faster under heavy traffic** — The Discover grid and the published-agents (Characters) feed now serve from the edge cache, so a surge of visitors is absorbed at the CDN instead of re-running a database scan on every request. Pages stay fast and consistent even during a rush, and a stale-while-revalidate window keeps them warm between refreshes. (`/discover`) `[improvement, infra]`
- **Discover and Marketplace now browse the same way** — Searching, filtering, and sorting agents now work identically on /discover and /marketplace. Both pages share one polished control bar — debounced search, filter chips, and sort — and your choices are saved in the page address, so a filtered view is shareable and the browser back button restores it. Loading, empty, and error states were unified too: a search that matches nothing shows a clear 'no results' panel with a one-click 'Clear filters', and a failed load offers a retry instead of a blank grid. (`/discover`) `[improvement]`
- **Empty pages now guide you instead of going blank** — Across the dashboard and marketplace, anywhere a list can be empty now explains what belongs there, why it's useful, and the next step — instead of a bare 'No data' line. Your Agents, Avatars, Analytics, Brain, embed policies, the marketplace, and My Agents each greet a fresh account with a short plain-language intro and a clear button to create your first one (plus a 'What's an agent?' link). Filtered searches that return nothing now say so and offer to clear the filter. It's the same designed component everywhere, so the whole platform feels consistent and never abandoned. (`/dashboard`) `[improvement]`
+- **Every avatar you create now auto-rigs so it can move** — A 3D model can only walk, wave, and emote if it has a skeleton. Until now only prompt and selfie avatars got one automatically — a GLB you uploaded, imported by link, or generated in chat would land as a frozen statue. Now every creation path auto-rigs: drop in a static model and the platform quietly builds a skeleton in the background and swaps the animation-ready version in place, so the avatar (and the agent it backs) can play the full motion library. Models that already carry a skeleton — like Avaturn characters — are left untouched, never re-rigged. If rigging isn't available on a deployment, you still get your model, exactly as before. `[feature, improvement]`
- **Every Forge quality tier now runs on free engines** — Forge's quality tiers — Draft, Standard, and High — all generate on zero-cost engines now: Draft and Standard on the fast free NVIDIA lane, and High on the higher-fidelity, fully textured free HuggingFace engine. Higher tiers buy you genuinely better geometry and textures, not a different bill behind the scenes. Photo-to-3D at any tier routes straight to a free engine too, so a generation never quietly falls back to a paid lane. The High tier stays a $THREE holder perk (or a one-off pay-per-use) — that's the price of premium quality, not a cost we're passing through. (`/forge`) `[improvement, feature]`
- **Follows and reviews now ring the notification bell** — Following someone now actually reaches them: when a new follower arrives, it shows up in your notification bell with a link straight to their profile. And when someone reviews one of your agents, you get a notification with their rating. Both flow through the same in-app notification center you already use for payments and sales — no new place to check. Re-following or editing an existing review won't re-notify, so the bell stays signal, not noise. (`/feed`) `[feature, improvement]`
- **Forge hardened for a traffic surge — faster loads, protected free lanes** — We scaled Forge for the influx of new users. The engine catalog and live health status now serve from the edge cache, so the page loads instantly even under heavy traffic instead of recomputing on every visit. We also added a platform-wide safety valve on paid generation: if demand ever spikes past the shared paid budget, the free engines (NVIDIA and Hugging Face) stay fully open and you get a clear 'try a free engine' message instead of a hard failure — your own bring-your-own-key engines are never affected. Net result: Forge stays fast and available as we grow, and free 3D generation never gets crowded out. (`/forge`) `[infra, improvement]`
@@ -47,12 +48,14 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Pay-per-call endpoints accept Solana USDC payments again** — Paying for any x402 endpoint with Solana USDC was failing the moment the wallet tried to build the payment — the platform's receiving address was being published with a stray invisible character, so a correctly-built payment got rejected as going to the wrong recipient. Payment addresses are now cleaned before they're ever advertised, so Solana USDC payments to paid endpoints go through and settle as expected. `[fix]`
- **Pay-what-you-want pricing for skills** — Creators can now price a skill as “pay what you want” with an optional minimum; buyers name their price at checkout and the fee, referral, and revenue math all use the actual amount paid. (`/marketplace`) `[feature]`
- **Payment hardening and a steadier holder leaderboard** — Two behind-the-scenes reliability and safety fixes. Agent payment invoices now verify that the wallet paying is actually linked to your account before an invoice is created, closing a gap that let bogus payment requests be generated against any agent. And the $THREE holder leaderboard, its share card, and the token stats panel no longer each kick off a full on-chain holder scan during a traffic spike — one scan now serves everyone and refreshes the shared snapshot, so the leaderboard stays fast and responsive under load. Nothing to do on your end. (`/leaderboard`) `[security, fix, infra]`
+- **Pick your own guide for the product tour** — The 3D guide who walks you through the product tour now starts as Ava, our photoreal full-body character — and you can swap her for anyone in the cast. Open the tour menu and use the new Guide picker to choose any avatar (your own custom ones included); the tour switches on the spot and remembers your pick. She also obeys gravity now, just like your character on the Walk pages: she drops in and plants her feet on the ground instead of hovering. `[feature, improvement]`
- **Platform-wide hardening: payment integrity, security, and scale** — A broad reliability pass across the parts of three.ws that move real money and serve heavy traffic. On the money side: bundle purchases and agent payments are now verified on-chain before anything unlocks, each payment is credited exactly once, withdrawals can't be processed twice, and recurring subscriptions can't be double-billed. On the security side: a set of input-handling and link-safety fixes across pages, stronger protection for custodial keys at rest, and tighter checks on outbound agent payments so funds only ever move in the expected asset. On the scale side: the busiest directory, profile, and feed pages now ride a short cache and run far fewer database queries, so they stay fast as the community grows. Most of this is invisible by design — it's the plumbing that keeps the platform correct and quick under load. `[security, improvement, infra]`
- **Profiles you can edit — and follow** — Your three.ws profile at three.ws/u/<your-username> is now a real social home. Edit it in place: add a bio, a profile picture and banner image, your location, and a website link — all from an Edit button on your own profile. You can now follow other creators and agents, and they can follow you; every profile shows live follower and following counts you can tap to browse the lists, with one-tap follow buttons throughout. And there's a new Feed at three.ws/feed that gathers the latest avatars, agents, and coin launches from everyone you follow, newest first. Find your profile and Feed links from your account page. (`/feed`) `[feature]`
- **Provably-fair vanity grinder now listed in the x402 bazaar** — The provably-fair Solana vanity grinder — which returns a signed, independently-verifiable receipt proving the key was ground fresh and never kept — is now published in the x402 discovery catalog, so paying agents and bazaar crawlers can find and call it directly. (`/vanity/verify`) `[feature, sdk]`
- **Regrinding an agent's vanity wallet no longer risks its funds** — The compact "Vanity address" card on an agent's page used to replace a wallet by deleting the old one and creating the new one separately — so if the old wallet held SOL or tokens, they could be left behind. It now uses the same money-safe path as the rest of the platform: any balance is automatically swept to the new vanity address first, and the switch only completes once the funds have moved (and only after the server confirms the new address really matches your pattern). Same one-click experience, but your funds follow the wallet. `[fix, security]`
- **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]`
+- **Solana stays online even if our paid RPC goes dark** — Everything onchain — paying, minting, balances, name lookups — depends on a Solana RPC node answering. When our primary paid node was throttled or its plan lapsed, some of those reads could error out. The platform now falls through a deeper chain: the paid node first, then several backup providers, then five independent public nodes (each verified live), so a request only fails if every one of them is down at the same moment. The embeddable payment widget and Solana name registration were moved onto the same resilient connection. `[fix, infra]`
- **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]`
- **USDC checkout no longer fails when an RPC node hiccups** — Paying with USDC at a door (like the Pole Club cover charge) could occasionally fail with an "internal error" right after you connected your wallet, if our Solana RPC briefly returned a malformed reply while building your payment. The checkout now shrugs that off and builds the transaction anyway, so a flaky node no longer turns you away at the door. Nothing was ever charged when this happened. `[fix]`
diff --git a/api/_lib/auto-rig.js b/api/_lib/auto-rig.js
new file mode 100644
index 000000000..f38b86d61
--- /dev/null
+++ b/api/_lib/auto-rig.js
@@ -0,0 +1,214 @@
+// Auto-rig on create — upgrade any freshly-created static avatar into an
+// animation-ready (skeleton-bearing) one, the same way Avaturn ships rigged
+// avatars. The reconstruct (prompt → avatar / selfie → avatar) pipeline already
+// auto-rigs inline via reconstruct-finalize.js; this brings the SAME capability
+// to every OTHER way an avatar — and therefore a 3D agent — can be born: a GLB
+// upload, a URL import, or a chat/MCP "text → 3D avatar" forge save. No matter
+// the path, the avatar ends up able to walk, wave, and emote.
+//
+// The decision mirrors reconstruct-finalize's gate exactly so the two never
+// diverge:
+// • Already rigged (a skeleton is present — e.g. an Avaturn export, a
+// Mixamo/VRM upload, or any skinned GLB)? Do nothing. We never re-rig a
+// usable skeleton; canonicalization at ingest already lets it drive the
+// clip library.
+// • No rerig model configured (provider.supportsMode('rerig') === false)?
+// Do nothing — the avatar stays a static mesh, exactly as before. Rigging is
+// dormant until REPLICATE_RERIG_MODEL is set.
+// • Otherwise submit a 'rerig' job tagged { auto_rig: true } against the
+// stored mesh and let the shared completion stage (the Replicate webhook and
+// the regenerate-status poll) swap the rigged GLB in place on the SAME
+// avatar row when it lands — so the agent the user already owns simply
+// becomes animation-ready, with no sibling avatar to manage.
+//
+// Best-effort by contract: maybeAutoRigAvatar never throws into its caller. A
+// creation request must succeed whether or not rigging could be kicked off; the
+// worst case is the avatar stays static — the identical graceful state we had
+// before this existed.
+
+import { randomUUID } from 'crypto';
+import { sql } from './db.js';
+import { putObject, publicUrl } from './r2.js';
+import { storageKeyFor } from './avatars.js';
+import { getRegenProvider } from './regen-provider.js';
+import { inspectGlb, isValidGlbHeader } from './glb-inspect.js';
+
+const MAX_GLB_BYTES = 64 * 1024 * 1024; // matches reconstruct-finalize's ceiling
+
+// Does this rig signal indicate a usable skeleton? Mirrors classifyRig
+// (src/shared/rig-classify.js) on the snake_case source_meta shape so the
+// server-side gate and the client-side badge agree on what "rigged" means.
+export function rigInfoIsRigged(rigInfo) {
+ if (!rigInfo) return false;
+ if (rigInfo.is_rigged === true) return true;
+ const joints = rigInfo.skeleton_joint_count;
+ return typeof joints === 'number' && joints > 0;
+}
+
+async function fetchGlbBuffer(url) {
+ const resp = await fetch(url);
+ if (!resp.ok) throw new Error(`fetch glb: ${resp.status}`);
+ const len = Number(resp.headers.get('content-length') || 0);
+ if (len && len > MAX_GLB_BYTES) throw new Error(`glb too large: ${len} bytes`);
+ const buf = Buffer.from(await resp.arrayBuffer());
+ if (buf.length > MAX_GLB_BYTES) throw new Error(`glb too large: ${buf.length} bytes`);
+ return buf;
+}
+
+// Re-run bone-name + up-axis canonicalization on a rigged GLB so the new
+// skeleton lands in the canonical convention the clip retargeter expects —
+// identical to the canonicalization every other stored avatar gets at ingest.
+async function canonicalize(buf) {
+ try {
+ const { canonicalizeGLBBones } = await import('../../src/glb-canonicalize.js');
+ const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
+ const canonical = canonicalizeGLBBones(ab);
+ if (canonical.renamed > 0 || canonical.orientationCorrected) return Buffer.from(canonical.buffer);
+ } catch (err) {
+ console.warn('[auto-rig] canonicalize skipped:', err?.message);
+ }
+ return buf;
+}
+
+/**
+ * Decide whether a just-created avatar should be auto-rigged and, if so, submit
+ * the rerig job. Never throws — returns a small status object the caller can log
+ * or ignore.
+ *
+ * @param {Object} opts
+ * @param {string} opts.userId — owner of the avatar.
+ * @param {{ id: string, storage_key: string }} opts.avatar — the created row.
+ * @param {Object|null} [opts.rigInfo] — source_meta rig signal { is_rigged, skeleton_joint_count }.
+ * @param {string} [opts.source] — provenance tag for the job params (e.g. 'upload', 'studio').
+ * @returns {Promise<{ queued: boolean, jobId?: string, skipped?: string }>}
+ */
+export async function maybeAutoRigAvatar({ userId, avatar, rigInfo, source = 'upload' }) {
+ try {
+ if (!avatar?.id || !avatar?.storage_key) return { queued: false, skipped: 'no_avatar' };
+
+ // Already animation-ready (Avaturn, VRM, Mixamo, any skinned GLB) — leave it.
+ if (rigInfoIsRigged(rigInfo)) return { queued: false, skipped: 'already_rigged' };
+
+ let provider;
+ try {
+ provider = await getRegenProvider();
+ } catch {
+ return { queued: false, skipped: 'no_provider' };
+ }
+ const canRig =
+ provider?.instance &&
+ typeof provider.instance.supportsMode === 'function' &&
+ provider.instance.supportsMode('rerig');
+ if (!canRig) return { queued: false, skipped: 'no_rig_model' };
+
+ const sourceUrl = publicUrl(avatar.storage_key);
+ let submission;
+ try {
+ submission = await provider.instance.submit({
+ userId,
+ sourceAvatarId: avatar.id,
+ mode: 'rerig',
+ params: { auto_rig: true, source },
+ sourceUrl,
+ sourceStorageKey: avatar.storage_key,
+ });
+ } catch (err) {
+ console.warn('[auto-rig] submit failed:', err?.message);
+ return { queued: false, skipped: 'submit_failed' };
+ }
+
+ const jobId = `${provider.name}-${randomUUID()}`;
+ await sql`
+ insert into avatar_regen_jobs
+ (job_id, user_id, source_avatar_id, mode, params, status, provider, ext_job_id, created_at, updated_at)
+ values
+ (${jobId}, ${userId}, ${avatar.id}, ${'rerig'}, ${JSON.stringify({ auto_rig: true, source })}, 'queued', ${provider.name}, ${submission.extJobId ?? null}, now(), now())
+ `;
+ return { queued: true, jobId };
+ } catch (err) {
+ // A creation flow must never fail because auto-rig couldn't start.
+ console.warn('[auto-rig] maybeAutoRigAvatar error:', err?.message);
+ return { queued: false, skipped: 'error' };
+ }
+}
+
+/**
+ * Completion stage for an auto-rig job: the rerig model finished, so fetch the
+ * rigged GLB, canonicalize it, store it durably, and swap it in place on the
+ * source avatar — flipping it to animation-ready without creating a sibling.
+ * Shared by the Replicate webhook and the regenerate-status poll so both
+ * completion paths produce an identical result.
+ *
+ * @returns {Promise<{ status: 'done', resultAvatarId?: string }>}
+ */
+export async function finalizeAutoRigStage({ userId, jobId, job, glbUrl }) {
+ const avatarId = job.source_avatar_id;
+ const closeJob = (resultAvatarId = null) =>
+ sql`
+ update avatar_regen_jobs
+ set result_avatar_id = ${resultAvatarId}, status = 'done', updated_at = now()
+ where job_id = ${jobId} and user_id = ${userId}
+ `;
+
+ if (!avatarId || !glbUrl) {
+ await closeJob();
+ return { status: 'done' };
+ }
+
+ const rows = await sql`
+ select id, slug, storage_key, source_meta, tags
+ from avatars
+ where id = ${avatarId} and owner_id = ${userId} and deleted_at is null
+ limit 1
+ `;
+ if (!rows[0]) {
+ // Avatar was deleted between submit and completion — nothing to upgrade.
+ await closeJob(avatarId);
+ return { status: 'done', resultAvatarId: avatarId };
+ }
+ const av = rows[0];
+
+ let glbBuf = await fetchGlbBuffer(glbUrl);
+ glbBuf = await canonicalize(glbBuf);
+ const info = isValidGlbHeader(glbBuf) ? inspectGlb(glbBuf) : null;
+
+ // Write the rigged GLB to a fresh key so a CDN never serves the stale static
+ // bytes, then re-point the avatar at it. The original static object is kept
+ // (referenced in source_meta) as a provenance + fallback breadcrumb.
+ const slug = `rigged-${Math.random().toString(36).slice(2, 8)}`;
+ const newKey = storageKeyFor({ userId, slug });
+ await putObject({
+ key: newKey,
+ body: glbBuf,
+ contentType: 'model/gltf-binary',
+ metadata: { source: 'auto-rig', avatar_id: avatarId, job_id: jobId },
+ });
+
+ const meta = {
+ ...(av.source_meta || {}),
+ is_rigged: true,
+ auto_rigged: true,
+ rig_provider: 'auto-rig',
+ rig_job_id: jobId,
+ unrigged_storage_key: av.storage_key,
+ };
+ if (info) {
+ meta.skeleton_joint_count = info.skeletonJointCount;
+ meta.skin_count = info.skinCount;
+ meta.node_count = info.nodeCount;
+ meta.animation_count = info.animationCount;
+ }
+ const tags = Array.from(new Set([...(av.tags || []).filter((t) => t !== 'unrigged'), 'rigged']));
+
+ await sql`
+ update avatars
+ set storage_key = ${newKey},
+ size_bytes = ${glbBuf.length},
+ source_meta = ${JSON.stringify(meta)}::jsonb,
+ tags = ${tags}::text[],
+ updated_at = now()
+ where id = ${avatarId} and owner_id = ${userId}
+ `;
+ await closeJob(avatarId);
+ return { status: 'done', resultAvatarId: avatarId };
+}
diff --git a/api/_lib/solana/connection.js b/api/_lib/solana/connection.js
index cb6adc47c..f2894593d 100644
--- a/api/_lib/solana/connection.js
+++ b/api/_lib/solana/connection.js
@@ -11,10 +11,15 @@
//
// Priority (per network): the caller's explicit url (if any) → Helius → Alchemy
// → dRPC (authenticated) → Ankr (authenticated only) → operator-supplied
-// SOLANA_RPC_FALLBACK_URLS → PublicNode → the keyless public endpoint, always
-// last. We never depend on the public endpoint alone — it is the most
-// aggressively rate-limited (the source of the `getBalance 429` log noise) — and
-// we never include a keyless Ankr URL, which Ankr now answers with a hard 403.
+// SOLANA_RPC_FALLBACK_URLS → PublicNode → Leo RPC (keyless FREE tier) → Tatum →
+// therpc → the official mainnet-beta endpoint, always last. We never depend on the
+// public endpoint alone — it is the most aggressively rate-limited (the source of
+// the `getBalance 429` log noise) — and we never include a keyless Ankr URL, which
+// Ankr now answers with a hard 403. The keyless tail (PublicNode + Leo RPC + Tatum
+// + therpc + mainnet-beta) is what keeps checkout serving when a paid plan lapses:
+// all five were verified serving live getLatestBlockhash/getAccountInfo on Solana
+// mainnet, so even with every API key dead the chain still resolves a working node
+// instead of erroring out.
//
// To survive a single provider's quota running dry (e.g. a paid Helius plan
// exhausting its monthly requests), register free-tier keys at several providers
@@ -172,6 +177,23 @@ export function solanaRpcEndpoints(network = 'mainnet', url = null) {
// uses) so failover lands on a working endpoint instead of depending on the
// aggressively rate-limited public mainnet-beta endpoint alone.
'https://solana-rpc.publicnode.com',
+ // Leo RPC keyless FREE tier — a second un-throttled keyless lane so the
+ // chain still has depth when every paid key is exhausted (e.g. a Helius plan
+ // lapsing mid-billing-cycle). Verified serving getAccountInfo on mainnet.
+ 'https://solana.leorpc.com/?api_key=FREE',
+ // Tatum + therpc — two more keyless public lanes. PublicNode, Leo RPC and
+ // Tatum were each verified serving getAccountInfo (the method whose malformed
+ // response 500'd checkout); therpc was verified on getLatestBlockhash but is
+ // flaky on getAccountInfo (intermittently returns an empty body), so it sits
+ // last before mainnet-beta and leans on the classifyRpcBody guard to fail over
+ // when it returns garbage — it adds redundancy for the methods it serves
+ // without ever handing web3.js something it can't parse. With mainnet-beta this
+ // is five keyless fallbacks: a request only errors if all five are down at
+ // once. The free public-RPC pool has thinned (most providers now 401/403/429
+ // keyless), so this set is curated to ones that actually respond — re-verify
+ // any that start cooling persistently in the failover logs.
+ 'https://api.tatum.io/v3/blockchain/node/solana-mainnet',
+ 'https://solana.therpc.io',
PUBLIC_MAINNET,
]);
}
@@ -185,6 +207,78 @@ function maskUrl(url) {
}
}
+// JSON-RPC error codes that mean "this provider can't serve you right now" — a
+// capacity/quota/auth/staleness problem the NEXT provider may not share, so we
+// fail over instead of surfacing it. Crucially this is how an exhausted paid plan
+// answers: HTTP 200 with `{"error":{"code":-32429,"message":"max usage reached"}}`
+// — no rotate-worthy HTTP status, so without this it leaks straight to the caller.
+// Method/data errors (-32600 invalid request, -32601 method not found, -32602
+// invalid params, -32002 tx simulation failed) are deterministic across providers
+// and are intentionally excluded — rotating on those would just retry a guaranteed
+// failure on every lane.
+const PROVIDER_CAPACITY_CODES = new Set([
+ -32429, // Helius / common: max usage / quota reached
+ -32029, // OnFinality / common: too many requests
+ -32052, // Ankr: key not allowed / forbidden
+ -32005, // node is behind by N slots — a fresher node may answer
+ -32004, // block/slot not available yet — another node may have it
+]);
+
+function isProviderCapacityError(rpcError) {
+ if (!rpcError || typeof rpcError !== 'object') return false;
+ if (PROVIDER_CAPACITY_CODES.has(rpcError.code)) return true;
+ return /too many requests|rate.?limit|quota|usage limit|credits?\s*exhausted|forbidden|api key|unauthor|max usage/i.test(
+ String(rpcError.message || ''),
+ );
+}
+
+// Classify a 200-status RPC body. Returns null when it's a usable JSON-RPC
+// response web3.js can parse; otherwise a {status, reason, log, bodyText} telling
+// the rotating fetch to fail over. This is the guard that turns the recurring
+// `StructError: Expected the value to satisfy a union … but received:` into a
+// transparent failover: that error is web3.js choking on a 200 body that is NOT a
+// well-formed JSON-RPC response (empty, HTML interstitial, truncated JSON, or a
+// `{jsonrpc,id}` envelope with neither `result` nor `error`). We detect every one
+// of those shapes here — plus provider-capacity JSON-RPC errors — and route past
+// the bad node instead of handing the caller something it cannot parse.
+export function classifyRpcBody(body) {
+ const trimmed = (body || '').trim();
+ if (trimmed === '') return { status: 502, reason: 'empty body', log: '200 but empty body', bodyText: '' };
+ if (trimmed[0] === '<') return { status: 502, reason: 'HTML body', log: '200 but HTML body', bodyText: '' };
+ let parsed;
+ try {
+ parsed = JSON.parse(trimmed);
+ } catch {
+ return { status: 502, reason: 'unparseable body', log: '200 but unparseable JSON', bodyText: '' };
+ }
+ // Single response or a JSON-RPC batch array — every element must be a valid envelope.
+ const items = Array.isArray(parsed) ? parsed : [parsed];
+ if (items.length === 0) {
+ return { status: 502, reason: 'empty batch', log: '200 but empty JSON-RPC batch', bodyText: '' };
+ }
+ for (const item of items) {
+ if (!item || typeof item !== 'object') {
+ return { status: 502, reason: 'malformed envelope', log: '200 but malformed JSON-RPC envelope', bodyText: '' };
+ }
+ const hasResult = 'result' in item;
+ const hasError = 'error' in item;
+ if (!hasResult && !hasError) {
+ // Neither field present — the exact shape that produces the empty-`received:`
+ // StructError. `result: null` is fine (the key is present); this catches a
+ // genuinely truncated/garbage envelope.
+ return { status: 502, reason: 'missing result/error', log: '200 but JSON-RPC envelope missing result/error', bodyText: '' };
+ }
+ if (hasError && isProviderCapacityError(item.error)) {
+ const code = item.error?.code ?? '';
+ const msg = String(item.error?.message || '');
+ // status 429 → cooldownMsFor scans the message for a quota signal and parks
+ // a truly-exhausted plan for hours rather than re-hitting it every call.
+ return { status: 429, reason: `provider error ${code}`.trim(), log: `200 + provider error ${code} ${msg.slice(0, 48)}`.trim(), bodyText: msg };
+ }
+ }
+ return null;
+}
+
// Rotate this endpoint out of service on a 401/403 (bad/expired key on this
// provider only), 404/408/410 (the endpoint URL itself is dead, misrouted, or
// timing out — a live JSON-RPC node answers a POST with method-not-found as a
@@ -247,29 +341,28 @@ export function makeRotatingFetch(endpoints) {
continue;
}
// A healthy 2xx status is not a guarantee of a usable body. Under load
- // some providers answer a JSON-RPC POST with 200 + an empty payload or
- // 200 + an HTML interstitial/error page instead of a 5xx. web3.js then
- // runs that through its superstruct result schema and throws
- // `StructError: Expected the value to satisfy a union of type | type,
- // but received:` (the empty/garbage body) straight to the caller,
- // WITHOUT rotating, because a parse error carries no rotate-worthy HTTP
- // status. That single failure mode produced the recurring StructError
- // noise across getBalance / getLatestBlockhash / getSignaturesForAddress
- // / getBuyQuote. Detect the poison body here and fail over to the next
- // provider instead of handing web3.js something it cannot parse.
+ // (or with an exhausted paid plan) some providers answer a JSON-RPC POST
+ // with 200 + an empty payload, an HTML interstitial, a truncated body, a
+ // `{jsonrpc,id}` envelope missing `result`, or a 200 + JSON-RPC capacity
+ // error. web3.js runs any of those through its superstruct result schema
+ // and throws `StructError: Expected the value to satisfy a union of
+ // type | type, but received:` straight to the caller WITHOUT rotating,
+ // because a parse error carries no rotate-worthy HTTP status — the single
+ // failure mode behind the recurring StructError noise across getBalance /
+ // getLatestBlockhash / getAccountInfo / getSignaturesForAddress. classify
+ // the body here and fail over instead of handing web3.js something it
+ // cannot parse.
const okBody = await resp.text();
- const firstChar = okBody.trimStart()[0];
- if (okBody.trim() === '' || firstChar === '<') {
+ const bad = classifyRpcBody(okBody);
+ if (bad) {
const alreadyCooling = isEndpointCooling(url);
- // Treat like a transient provider 5xx: short cooldown, not a long
- // quota park. The endpoint is up but momentarily returning garbage.
- const ms = markEndpointCooldown(url, 502, '');
+ const ms = markEndpointCooldown(url, bad.status, bad.bodyText || '');
if (!alreadyCooling) {
console.log(
- `[solana-rpc] ${maskUrl(url)} 200 but ${okBody.trim() === '' ? 'empty' : 'non-JSON'} body — cooling ${Math.round(ms / 60_000)}m, failing over`,
+ `[solana-rpc] ${maskUrl(url)} ${bad.log} — cooling ${Math.round(ms / 60_000)}m, failing over`,
);
}
- lastErr = new Error(`solana rpc non-JSON-RPC body @ ${maskUrl(url)}`);
+ lastErr = new Error(`solana rpc ${bad.reason} @ ${maskUrl(url)}`);
continue;
}
// Body already consumed above; hand web3.js a fresh Response carrying
diff --git a/api/avatars/_actions.js b/api/avatars/_actions.js
index a5a629a74..3bc877a0f 100644
--- a/api/avatars/_actions.js
+++ b/api/avatars/_actions.js
@@ -18,6 +18,7 @@ import { isValidGlbHeader } from '../_lib/glb-inspect.js';
import { getRegenProvider, getRegenProviderByName, getRegenProviderForJob, BYOK_REGEN_PROVIDERS } from '../_lib/regen-provider.js';
import { resolveProviderKey } from '../_lib/forge-provider-key.js';
import { finalizeReconstructStage, pollRiggingStage } from '../_lib/reconstruct-finalize.js';
+import { finalizeAutoRigStage } from '../_lib/auto-rig.js';
import { textToImage } from '../_mcp3d/text-to-image.js';
// ── presign ───────────────────────────────────────────────────────────────────
@@ -522,6 +523,25 @@ const handleRegenerateStatus = wrap(async (req, res) => {
}
}
+ // Auto-rig completion (browser-poll fallback to the webhook) — a static
+ // upload/import/forge avatar finished its 'rerig' job. Upgrade it in place so
+ // it becomes animation-ready. Gated on auto_rig so the manual rig panel (which
+ // materializes a sibling client-side) is untouched.
+ if (
+ job.status === 'done' &&
+ job.mode === 'rerig' &&
+ job.params?.auto_rig === true &&
+ !job.result_avatar_id &&
+ job.result_glb_url
+ ) {
+ try {
+ const result = await finalizeAutoRigStage({ userId, jobId, job, glbUrl: job.result_glb_url });
+ job = { ...job, status: result.status, result_avatar_id: result.resultAvatarId ?? job.result_avatar_id };
+ } catch (err) {
+ job = { ...job, error: job.error || `auto-rig finalize failed: ${err?.message}` };
+ }
+ }
+
const response = { ok: true, jobId: job.job_id, status: job.status };
if (job.result_avatar_id) response.resultAvatarId = job.result_avatar_id;
if (job.result_glb_url) response.resultGlbUrl = job.result_glb_url;
diff --git a/api/avatars/from-forge.js b/api/avatars/from-forge.js
index 6b5d740fd..409b64f9e 100644
--- a/api/avatars/from-forge.js
+++ b/api/avatars/from-forge.js
@@ -30,6 +30,7 @@ import { putObject } from '../_lib/r2.js';
import { isValidGlbHeader, inspectGlb } from '../_lib/glb-inspect.js';
import { fetchSafePublicUrl, SsrfBlockedError } from '../_lib/ssrf-guard.js';
import { provisionAvatarAgent } from '../_lib/avatar-agent.js';
+import { maybeAutoRigAvatar } from '../_lib/auto-rig.js';
import { limits } from '../_lib/rate-limit.js';
import { recordEvent } from '../_lib/usage.js';
import { env } from '../_lib/env.js';
@@ -155,6 +156,19 @@ export default wrap(async (req, res) => {
provisionAvatarAgent({ userId: auth.userId, avatarId: avatar.id, avatarName: avatar.name }),
);
+ // Auto-rig if the forged mesh arrived static (e.g. a mesh_forge save) so the
+ // agent's avatar can animate. A no-op when it's already rigged — forge_avatar
+ // and the chat forge tool deliver a rigged GLB and pass rigged:true — or when
+ // no rerig model is configured. Upgraded in place once the job completes.
+ queueMicrotask(() =>
+ maybeAutoRigAvatar({
+ userId: auth.userId,
+ avatar,
+ rigInfo: { is_rigged: rigged || info.isRigged === true, skeleton_joint_count: info.skeletonJointCount ?? null },
+ source: 'studio',
+ }),
+ );
+
recordEvent({
userId: auth.userId,
apiKeyId: auth.apiKeyId,
diff --git a/api/avatars/index.js b/api/avatars/index.js
index 7915d4a36..02b9f720a 100644
--- a/api/avatars/index.js
+++ b/api/avatars/index.js
@@ -9,6 +9,7 @@ import { HeadObjectCommand } from '@aws-sdk/client-s3';
import { env } from '../_lib/env.js';
import { sql } from '../_lib/db.js';
import { provisionAvatarAgent } from '../_lib/avatar-agent.js';
+import { maybeAutoRigAvatar } from '../_lib/auto-rig.js';
import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
import { parse, createAvatarBody } from '../_lib/validate.js';
import { recordEvent } from '../_lib/usage.js';
@@ -143,6 +144,20 @@ async function handleCreate(req, res) {
queueMicrotask(() =>
provisionAvatarAgent({ userId: auth.userId, avatarId: avatar.id, avatarName: avatar.name }),
);
+
+ // Auto-rig any static upload/import so the agent's avatar can animate, the
+ // same way Avaturn ships rigged avatars. A no-op when the GLB already has a
+ // skeleton (the inspection above stamped is_rigged) or no rerig model is
+ // configured. Fire-and-forget — the avatar is upgraded in place once the
+ // rig job lands (webhook / status poll); 201 returns immediately.
+ queueMicrotask(() =>
+ maybeAutoRigAvatar({
+ userId: auth.userId,
+ avatar,
+ rigInfo: body.source_meta,
+ source: body.source || 'upload',
+ }),
+ );
}
recordEvent({
diff --git a/api/webhooks/replicate.js b/api/webhooks/replicate.js
index dfa17184b..6a3d95b2e 100644
--- a/api/webhooks/replicate.js
+++ b/api/webhooks/replicate.js
@@ -24,6 +24,7 @@ import { createHmac, timingSafeEqual } from 'node:crypto';
import { sql } from '../_lib/db.js';
import { json, method, wrap, error } from '../_lib/http.js';
import { finalizeReconstructStage } from '../_lib/reconstruct-finalize.js';
+import { finalizeAutoRigStage } from '../_lib/auto-rig.js';
const REPLAY_WINDOW_SECONDS = 5 * 60;
@@ -171,7 +172,7 @@ export default wrap(async (req, res) => {
// simple equality match. Skip silently if the prediction isn't ours —
// other Replicate apps in the same account can land here harmlessly.
const rows = await sql`
- select job_id, user_id, status, result_avatar_id, mode, params
+ select job_id, user_id, status, result_avatar_id, mode, params, source_avatar_id
from avatar_regen_jobs
where ext_job_id = ${extJobId}
limit 1
@@ -221,5 +222,24 @@ export default wrap(async (req, res) => {
}
}
+ // Auto-rig completion — a static upload/import/forge avatar was sent through a
+ // 'rerig' job tagged auto_rig. Swap the rigged GLB in place on the source
+ // avatar now so it becomes animation-ready without waiting on a browser poll
+ // (MCP/headless creations never poll). Same SSRF host-pin as above.
+ if (
+ nextStatus === 'done' &&
+ nextGlbUrl &&
+ isAllowedResultUrl(nextGlbUrl) &&
+ job.mode === 'rerig' &&
+ job.params?.auto_rig === true &&
+ !job.result_avatar_id
+ ) {
+ try {
+ await finalizeAutoRigStage({ userId: job.user_id, jobId: job.job_id, job, glbUrl: nextGlbUrl });
+ } catch (err) {
+ console.warn('[replicate-webhook] auto-rig finalize failed', { jobId: job.job_id, error: err?.message });
+ }
+ }
+
return json(res, 200, { ok: true, verified, jobId: job.job_id, status: nextStatus });
});
diff --git a/data/changelog.json b/data/changelog.json
index 0288c294e..de09abca1 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,24 @@
{
"$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": "Every avatar you create now auto-rigs so it can move",
+ "summary": "A 3D model can only walk, wave, and emote if it has a skeleton. Until now only prompt and selfie avatars got one automatically — a GLB you uploaded, imported by link, or generated in chat would land as a frozen statue. Now every creation path auto-rigs: drop in a static model and the platform quietly builds a skeleton in the background and swaps the animation-ready version in place, so the avatar (and the agent it backs) can play the full motion library. Models that already carry a skeleton — like Avaturn characters — are left untouched, never re-rigged. If rigging isn't available on a deployment, you still get your model, exactly as before.",
+ "tags": [
+ "feature",
+ "improvement"
+ ]
+ },
+ {
+ "date": "2026-06-21",
+ "title": "Pick your own guide for the product tour",
+ "summary": "The 3D guide who walks you through the product tour now starts as Ava, our photoreal full-body character — and you can swap her for anyone in the cast. Open the tour menu and use the new Guide picker to choose any avatar (your own custom ones included); the tour switches on the spot and remembers your pick. She also obeys gravity now, just like your character on the Walk pages: she drops in and plants her feet on the ground instead of hovering.",
+ "tags": [
+ "feature",
+ "improvement"
+ ]
+ },
{
"date": "2026-06-21",
"title": "USDC checkout no longer fails when an RPC node hiccups",
@@ -9,6 +27,15 @@
"fix"
]
},
+ {
+ "date": "2026-06-21",
+ "title": "Solana stays online even if our paid RPC goes dark",
+ "summary": "Everything onchain — paying, minting, balances, name lookups — depends on a Solana RPC node answering. When our primary paid node was throttled or its plan lapsed, some of those reads could error out. The platform now falls through a deeper chain: the paid node first, then several backup providers, then five independent public nodes (each verified live), so a request only fails if every one of them is down at the same moment. The embeddable payment widget and Solana name registration were moved onto the same resilient connection.",
+ "tags": [
+ "fix",
+ "infra"
+ ]
+ },
{
"date": "2026-06-21",
"title": "Arm your agent gets its own setup page",
diff --git a/package.json b/package.json
index eee1ab890..2643e0b99 100644
--- a/package.json
+++ b/package.json
@@ -53,7 +53,8 @@
"packages/ibm-x402-mcp",
"packages/three-token-mcp",
"packages/threews-avatar-mcp",
- "walk-sdk"
+ "walk-sdk",
+ "tour-sdk"
],
"main": "src/app.js",
"browserslist": [
diff --git a/public/changelog.json b/public/changelog.json
index abb08290a..377f55e13 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-21T09:24:07.978Z",
+ "generated_at": "2026-06-21T09:59:56.909Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -192,6 +192,17 @@
"improvement"
]
},
+ {
+ "date": "2026-06-21",
+ "type": "update",
+ "title": "Every avatar you create now auto-rigs so it can move",
+ "summary": "A 3D model can only walk, wave, and emote if it has a skeleton. Until now only prompt and selfie avatars got one automatically — a GLB you uploaded, imported by link, or generated in chat would land as a frozen statue. Now every creation path auto-rigs: drop in a static model and the platform quietly builds a skeleton in the background and swaps the animation-ready version in place, so the avatar (and the agent it backs) can play the full motion library. Models that already carry a skeleton — like Avaturn characters — are left untouched, never re-rigged. If rigging isn't available on a deployment, you still get your model, exactly as before.",
+ "link": null,
+ "tags": [
+ "feature",
+ "improvement"
+ ]
+ },
{
"date": "2026-06-21",
"type": "update",
@@ -441,6 +452,17 @@
"infra"
]
},
+ {
+ "date": "2026-06-21",
+ "type": "update",
+ "title": "Pick your own guide for the product tour",
+ "summary": "The 3D guide who walks you through the product tour now starts as Ava, our photoreal full-body character — and you can swap her for anyone in the cast. Open the tour menu and use the new Guide picker to choose any avatar (your own custom ones included); the tour switches on the spot and remembers your pick. She also obeys gravity now, just like your character on the Walk pages: she drops in and plants her feet on the ground instead of hovering.",
+ "link": null,
+ "tags": [
+ "feature",
+ "improvement"
+ ]
+ },
{
"date": "2026-06-21",
"type": "update",
@@ -505,6 +527,17 @@
"improvement"
]
},
+ {
+ "date": "2026-06-21",
+ "type": "update",
+ "title": "Solana stays online even if our paid RPC goes dark",
+ "summary": "Everything onchain — paying, minting, balances, name lookups — depends on a Solana RPC node answering. When our primary paid node was throttled or its plan lapsed, some of those reads could error out. The platform now falls through a deeper chain: the paid node first, then several backup providers, then five independent public nodes (each verified live), so a request only fails if every one of them is down at the same moment. The embeddable payment widget and Solana name registration were moved onto the same resilient connection.",
+ "link": null,
+ "tags": [
+ "fix",
+ "infra"
+ ]
+ },
{
"date": "2026-06-21",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 46a3a0cfa..6a3492025 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -150,6 +150,14 @@
<category>improvement</category>
<description>Across the dashboard and marketplace, anywhere a list can be empty now explains what belongs there, why it's useful, and the next step — instead of a bare 'No data' line. Your Agents, Avatars, Analytics, Brain, embed policies, the marketplace, and My Agents each greet a fresh account with a short plain-language intro and a clear button to create your first one (plus a 'What's an agent?' link). Filtered searches that return nothing now say so and offer to clear the filter. It's the same designed component everywhere, so the whole platform feels consistent and never abandoned.</description>
</item>
+ <item>
+ <title>Every avatar you create now auto-rigs so it can move</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-21:Every avatar you create now auto-rigs so it can move</guid>
+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>A 3D model can only walk, wave, and emote if it has a skeleton. Until now only prompt and selfie avatars got one automatically — a GLB you uploaded, imported by link, or generated in chat would land as a frozen statue. Now every creation path auto-rigs: drop in a static model and the platform quietly builds a skeleton in the background and swaps the animation-ready version in place, so the avatar (and the agent it backs) can play the full motion library. Models that already carry a skeleton — like Avaturn characters — are left untouched, never re-rigged. If rigging isn't available on a deployment, you still get your model, exactly as before.</description>
+ </item>
<item>
<title>Every Forge quality tier now runs on free engines</title>
<link>https://three.ws/forge</link>
@@ -334,6 +342,14 @@
<category>security</category>
<description>Two behind-the-scenes reliability and safety fixes. Agent payment invoices now verify that the wallet paying is actually linked to your account before an invoice is created, closing a gap that let bogus payment requests be generated against any agent. And the $THREE holder leaderboard, its share card, and the token stats panel no longer each kick off a full on-chain holder scan during a traffic spike — one scan now serves everyone and refreshes the shared snapshot, so the leaderboard stays fast and responsive under load. Nothing to do on your end.</description>
</item>
+ <item>
+ <title>Pick your own guide for the product tour</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-21:Pick your own guide for the product tour</guid>
+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>The 3D guide who walks you through the product tour now starts as Ava, our photoreal full-body character — and you can swap her for anyone in the cast. Open the tour menu and use the new Guide picker to choose any avatar (your own custom ones included); the tour switches on the spot and remembers your pick. She also obeys gravity now, just like your character on the Walk pages: she drops in and plants her feet on the ground instead of hovering.</description>
+ </item>
<item>
<title>Platform-wide hardening: payment integrity, security, and scale</title>
<link>https://three.ws/changelog</link>
@@ -382,6 +398,14 @@
<category>improvement</category>
<description>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.</description>
</item>
+ <item>
+ <title>Solana stays online even if our paid RPC goes dark</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-21:Solana stays online even if our paid RPC goes dark</guid>
+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>Everything onchain — paying, minting, balances, name lookups — depends on a Solana RPC node answering. When our primary paid node was throttled or its plan lapsed, some of those reads could error out. The platform now falls through a deeper chain: the paid node first, then several backup providers, then five independent public nodes (each verified live), so a request only fails if every one of them is down at the same moment. The embeddable payment widget and Solana name registration were moved onto the same resilient connection.</description>
+ </item>
<item>
<title>The $THREE page now spells out why to hold — four real utility pillars</title>
<link>https://three.ws/three-token</link>
diff --git a/public/features.json b/public/features.json
index 243e2da59..728471295 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-21T09:24:07.962Z",
+ "generated_at": "2026-06-21T09:59:56.898Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/public/x402-pay-core.js b/public/x402-pay-core.js
index 0b7c280b8..a831492c7 100644
--- a/public/x402-pay-core.js
+++ b/public/x402-pay-core.js
@@ -184,7 +184,11 @@ function solanaRpcUrl() {
if (meta?.content) return meta.content;
}
if (typeof window !== 'undefined' && window.SOLANA_RPC_URL) return window.SOLANA_RPC_URL;
- return 'https://api.mainnet-beta.solana.com';
+ // Last resort: our same-origin proxy, which fails over across Helius → Alchemy →
+ // dRPC → five keyless public lanes, so the balance read survives any single
+ // provider (an expired Helius plan included) being down. Absolute URL so the
+ // widget still resolves a working RPC when embedded on a third-party origin.
+ return 'https://three.ws/api/solana-rpc';
}
// Sum the owner's SPL balance for `mint`. Returns a BigInt of atomic units, or
diff --git a/public/x402.js b/public/x402.js
index 63fdb4be0..b9ff424cf 100644
--- a/public/x402.js
+++ b/public/x402.js
@@ -189,7 +189,11 @@ function solanaRpcUrl() {
const meta = typeof document !== 'undefined' && document.querySelector('meta[name="solana-rpc-url"]');
if (meta?.content) return meta.content;
if (typeof window !== 'undefined' && window.SOLANA_RPC_URL) return window.SOLANA_RPC_URL;
- return 'https://api.mainnet-beta.solana.com';
+ // Last resort: our same-origin proxy, which fails over across Helius → Alchemy →
+ // dRPC → five keyless public lanes, so the balance read survives any single
+ // provider (an expired Helius plan included) being down. Absolute URL so the
+ // widget still resolves a working RPC when embedded on a third-party origin.
+ return 'https://three.ws/api/solana-rpc';
}
async function readSolanaBalanceAtomic(owner, mint) {
try {
diff --git a/scripts/render-club-outside.mjs b/scripts/render-club-outside.mjs
new file mode 100644
index 000000000..b7e72a882
--- /dev/null
+++ b/scripts/render-club-outside.mjs
@@ -0,0 +1,160 @@
+// Render the "standing outside the club" mix to a downloadable file.
+//
+// Reproduces, offline, exactly what the /club entrance plays at clarity 0 —
+// the music bed + room ambience run through the outdoor effects chain from
+// src/club-audio.js (ensureContext / setClarity at f=0):
+//
+// music (club.mp3 × 0.85) + ambience (loop × 0.35)
+// → lowshelf +10 dB @ 90 Hz (_fx.bass)
+// → lowpass 420 Hz, Q 1.0 (_fx.lowpass)
+// → split: dry × 0.22 + convolution × 0.85 (_fx.dry / _fx.outdoorWet)
+// → master × 0.75 (MASTER_GAIN)
+// → brick-wall limiter (-1.5 dBFS, 20:1) (this.limiter)
+//
+// The convolution reverb uses the same synthetic impulse response the browser
+// builds at runtime — _buildIR(duration=5.0, decay=1.0, density=0.32): sparse
+// noise with a (1 - i/len)^decay envelope, each channel normalised to unit
+// energy. We seed the noise deterministically so re-runs are byte-stable.
+//
+// Usage: node scripts/render-club-outside.mjs [outBasePath]
+// Requires ffmpeg (same dependency as scripts/build-club-audio.mjs).
+
+import { spawnSync } from 'node:child_process';
+import { writeFileSync, mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, dirname } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const ROOT = join(__dirname, '..');
+const AUDIO = join(ROOT, 'public', 'club', 'audio');
+
+// ── Outdoor effects-chain constants (mirrored from src/club-audio.js) ──────────
+const MUSIC_GAIN = 0.85;
+const AMBIENCE_GAIN = 0.35;
+const MASTER_GAIN = 0.75;
+const OUT = { freq: 420, q: 1.0, bass: 10, dry: 0.22, outWet: 0.85 };
+const IR = { duration: 5.0, decay: 1.0, density: 0.32 };
+const RATE = 44100;
+
+// Deterministic PRNG (mulberry32) so the IR — and thus the render — is stable.
+function mulberry32(seed) {
+ let a = seed >>> 0;
+ return () => {
+ a |= 0;
+ a = (a + 0x6d2b79f5) | 0;
+ let t = Math.imul(a ^ (a >>> 15), 1 | a);
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+// _buildIR(duration, decay, density) → stereo float32 WAV, channels unit-energy.
+function buildImpulseWav() {
+ const len = Math.floor(RATE * IR.duration);
+ const chans = [new Float32Array(len), new Float32Array(len)];
+ for (let c = 0; c < 2; c++) {
+ const rnd = mulberry32(0x3eeb + c); // distinct stream per channel
+ const ch = chans[c];
+ let sumSq = 0;
+ for (let i = 0; i < len; i++) {
+ const r =
+ IR.density >= 1
+ ? rnd() * 2 - 1
+ : rnd() < IR.density
+ ? rnd() * 2 - 1
+ : 0;
+ const v = r * Math.pow(1 - i / len, IR.decay);
+ ch[i] = v;
+ sumSq += v * v;
+ }
+ const norm = sumSq > 0 ? 1 / Math.sqrt(sumSq) : 1;
+ for (let i = 0; i < len; i++) ch[i] *= norm;
+ }
+ return encodeWavFloat32(chans, RATE);
+}
+
+function encodeWavFloat32(channels, rate) {
+ const n = channels[0].length;
+ const numCh = channels.length;
+ const bytesPerSample = 4;
+ const blockAlign = numCh * bytesPerSample;
+ const dataLen = n * blockAlign;
+ const buf = Buffer.alloc(44 + dataLen);
+ buf.write('RIFF', 0);
+ buf.writeUInt32LE(36 + dataLen, 4);
+ buf.write('WAVE', 8);
+ buf.write('fmt ', 12);
+ buf.writeUInt32LE(16, 16);
+ buf.writeUInt16LE(3, 20); // IEEE float
+ buf.writeUInt16LE(numCh, 22);
+ buf.writeUInt32LE(rate, 24);
+ buf.writeUInt32LE(rate * blockAlign, 28);
+ buf.writeUInt16LE(blockAlign, 32);
+ buf.writeUInt16LE(bytesPerSample * 8, 34);
+ buf.write('data', 36);
+ buf.writeUInt32LE(dataLen, 40);
+ let off = 44;
+ for (let i = 0; i < n; i++) {
+ for (let c = 0; c < numCh; c++) {
+ buf.writeFloatLE(channels[c][i], off);
+ off += 4;
+ }
+ }
+ return buf;
+}
+
+const outBase = process.argv[2] || join(ROOT, 'club-outside');
+const tmp = mkdtempSync(join(tmpdir(), 'club-outside-'));
+const irPath = join(tmp, 'outdoor-ir.wav');
+
+try {
+ writeFileSync(irPath, buildImpulseWav());
+ console.log(`Built outdoor IR: ${IR.duration}s, density ${IR.density} → ${irPath}`);
+
+ // acompressor threshold is linear amplitude: -1.5 dBFS = 10^(-1.5/20).
+ const limThresh = Math.pow(10, -1.5 / 20).toFixed(4);
+
+ const filter = [
+ `[0:a]volume=${MUSIC_GAIN},aformat=sample_rates=${RATE}:channel_layouts=stereo[music]`,
+ `[1:a]volume=${AMBIENCE_GAIN},aformat=sample_rates=${RATE}:channel_layouts=stereo[amb]`,
+ `[music][amb]amix=inputs=2:duration=first:normalize=0[mix]`,
+ // lowshelf bass + lowpass muffle
+ `[mix]bass=g=${OUT.bass}:f=90[bassed]`,
+ `[bassed]lowpass=f=${OUT.freq}:width_type=q:width=${OUT.q}[lp]`,
+ `[lp]asplit=2[lpd][lpw]`,
+ `[lpd]volume=${OUT.dry}[dry]`,
+ // through-the-door convolution reverb
+ `[lpw][2:a]afir=gtype=none:dry=0:wet=1[rev]`,
+ `[rev]volume=${OUT.outWet}[wet]`,
+ `[dry][wet]amix=inputs=2:duration=first:normalize=0[summed]`,
+ `[summed]volume=${MASTER_GAIN}[mastered]`,
+ `[mastered]acompressor=threshold=${limThresh}:ratio=20:attack=3:release=250:knee=1:detection=peak[out]`,
+ ].join(';');
+
+ const common = [
+ '-hide_banner', '-y',
+ '-i', join(AUDIO, 'club.mp3'),
+ '-stream_loop', '-1', '-i', join(AUDIO, 'ambience.mp3'),
+ '-i', irPath,
+ '-filter_complex', filter,
+ '-map', '[out]',
+ ];
+
+ const renders = [
+ { ext: 'mp3', args: ['-c:a', 'libmp3lame', '-q:a', '2'] },
+ { ext: 'ogg', args: ['-c:a', 'libvorbis', '-q:a', '5'] },
+ ];
+
+ for (const r of renders) {
+ const out = `${outBase}.${r.ext}`;
+ console.log(`Rendering ${out} …`);
+ const res = spawnSync('ffmpeg', [...common, ...r.args, out], { stdio: ['ignore', 'ignore', 'inherit'] });
+ if (res.status !== 0) {
+ throw new Error(`ffmpeg failed for ${r.ext} (exit ${res.status})`);
+ }
+ console.log(` ✓ ${out}`);
+ }
+} finally {
+ rmSync(tmp, { recursive: true, force: true });
+}
diff --git a/src/feature-tour/chapters.js b/src/feature-tour/chapters.js
index 1aa75886b..06cfda27f 100644
--- a/src/feature-tour/chapters.js
+++ b/src/feature-tour/chapters.js
@@ -7,6 +7,8 @@
// the director calls setActive()/setTrack()/setVoice()/setSpeed() to keep it in
// sync. Open/close is fully keyboard- and screen-reader-friendly.
+import { createAvatarPicker } from '../../walk-sdk/src/picker.js';
+
const Z_PANEL = 2147483450;
// A curated client-side slice of the platform voice catalog (api/_lib/tts-voices.js).
@@ -25,9 +27,14 @@ const VOICES = [
const SPEEDS = [0.75, 1, 1.25, 1.5];
export class ChapterPanel {
- constructor(curriculum, handlers) {
+ constructor(curriculum, handlers, avatarConfig = {}) {
this.curriculum = curriculum;
- this.handlers = handlers; // { onJump(abs), onTrack, onVoice, onSpeed, onClose }
+ this.handlers = handlers; // { onJump(abs), onTrack, onVoice, onSpeed, onAvatar, onClose }
+ // The avatar roster the guide can wear, plus who it's wearing now.
+ this.avatars = avatarConfig.avatars || [];
+ this.currentAvatarId = avatarConfig.currentId || null;
+ this.assetBase = avatarConfig.assetBase || '';
+ this.docsUrl = avatarConfig.docsUrl || null;
this.open = false;
this.activeAbs = 0;
this._query = '';
@@ -59,6 +66,18 @@ export class ChapterPanel {
<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>
+ ${
+ this.avatars.length
+ ? `<label class="tws-tour-menu__field">
+ <span class="tws-tour-menu__lbl">Guide</span>
+ <button type="button" class="tws-tour-menu__avatar" data-act="avatar" aria-haspopup="dialog" aria-label="Change the guide avatar">
+ <span class="tws-tour-menu__avatar-orb" aria-hidden="true"></span>
+ <span class="tws-tour-menu__avatar-name">Avatar</span>
+ <span class="tws-tour-menu__avatar-chev" aria-hidden="true">▾</span>
+ </button>
+ </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" />
@@ -72,10 +91,12 @@ export class ChapterPanel {
this.trackSeg = root.querySelector('[data-group="track"]');
this.speedSeg = root.querySelector('[data-group="speed"]');
this.voiceSel = root.querySelector('[data-act="voice"]');
+ this.avatarBtn = root.querySelector('[data-act="avatar"]');
this.searchInput = root.querySelector('.tws-tour-menu__input');
this._buildSegments();
this._buildVoices();
+ this._renderAvatarBtn();
this._buildList();
root.addEventListener('click', (e) => {
@@ -90,6 +111,7 @@ export class ChapterPanel {
if (v) this.handlers.onSpeed?.(Number(v));
});
this.voiceSel.addEventListener('change', () => this.handlers.onVoice?.(this.voiceSel.value));
+ this.avatarBtn?.addEventListener('click', () => this._openAvatarPicker());
this.searchInput.addEventListener('input', () => {
this._query = this.searchInput.value.trim().toLowerCase();
this._buildList();
@@ -125,6 +147,65 @@ export class ChapterPanel {
).join('');
}
+ // ── Guide avatar picker ─────────────────────────────────────────────────────
+ // Reuses the Walk SDK's avatar picker so the tour offers the exact same cast a
+ // visitor can pick anywhere else. The picker is responsibility-free — it just
+ // fires onSelect; we persist + hot-swap through the director's onAvatar handler.
+ _renderAvatarBtn() {
+ if (!this.avatarBtn) return;
+ const orb = this.avatarBtn.querySelector('.tws-tour-menu__avatar-orb');
+ const name = this.avatarBtn.querySelector('.tws-tour-menu__avatar-name');
+ const entry = this.avatars.find((a) => a.id === this.currentAvatarId);
+ if (entry) {
+ name.textContent = entry.name;
+ if (entry.accent) orb.style.setProperty('--wp-accent', entry.accent);
+ if (entry.thumb) {
+ orb.style.backgroundImage = `url('${this.assetBase}${entry.thumb}')`;
+ orb.textContent = '';
+ } else {
+ orb.style.backgroundImage = 'none';
+ orb.textContent = entry.emoji || '🧍';
+ }
+ } else {
+ // A user-generated avatar that isn't in the static roster.
+ name.textContent = 'Your avatar';
+ orb.style.backgroundImage = 'none';
+ orb.textContent = '✨';
+ }
+ }
+
+ _openAvatarPicker() {
+ if (!this.avatars.length) return;
+ if (!this._picker) {
+ this._picker = createAvatarPicker({
+ avatars: this.avatars,
+ currentId: this.currentAvatarId,
+ assetBase: this.assetBase,
+ docsUrl: this.docsUrl,
+ // Float above the playback bar, clear of the left-docked menu.
+ anchor: { right: 16, bottom: 92 },
+ onSelect: (entry) => this._onAvatarPicked(entry),
+ });
+ }
+ this._picker.setCurrent(this.currentAvatarId);
+ // The menu scrim sits above the picker, so step the menu aside to reveal it.
+ this.close();
+ this._picker.show();
+ }
+
+ _onAvatarPicked(entry) {
+ this.currentAvatarId = entry.id;
+ this._renderAvatarBtn();
+ this.handlers.onAvatar?.(entry);
+ }
+
+ // Director-driven sync: reflect an avatar change that happened elsewhere.
+ setAvatarCurrent(id) {
+ this.currentAvatarId = id;
+ this._renderAvatarBtn();
+ this._picker?.setCurrent(id);
+ }
+
_buildList() {
const { sections, stops } = this.curriculum;
const q = this._query;
@@ -220,6 +301,8 @@ export class ChapterPanel {
dispose() {
document.removeEventListener('keydown', this._onKey, true);
+ this._picker?.destroy();
+ this._picker = null;
this.root?.remove();
this.root = null;
}
@@ -258,6 +341,12 @@ function ensureStyles() {
.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__avatar{flex:1;display:flex;align-items:center;gap:9px;background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.12);border-radius:9px;padding:5px 10px 5px 5px;color:#e7eaf2;font:600 13px/1 inherit;cursor:pointer;transition:background .16s ease,border-color .16s ease}
+.tws-tour-menu__avatar:hover{background:rgba(255,255,255,.09);border-color:rgba(122,162,255,.4)}
+.tws-tour-menu__avatar:focus-visible{outline:2px solid #7aa2ff;outline-offset:1px}
+.tws-tour-menu__avatar-orb{flex:0 0 auto;width:26px;height:26px;border-radius:50%;display:grid;place-items:center;font-size:14px;background:radial-gradient(circle at 35% 30%,rgba(255,255,255,.35),transparent 60%),var(--wp-accent,#7aa2ff);background-size:cover;background-position:center;box-shadow:inset 0 -4px 8px rgba(0,0,0,.25)}
+.tws-tour-menu__avatar-name{flex:1;text-align:left;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
+.tws-tour-menu__avatar-chev{flex:0 0 auto;color:#9aa3b6;font-size:11px}
.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}
diff --git a/src/feature-tour/director.js b/src/feature-tour/director.js
index d15badec6..17fa818d6 100644
--- a/src/feature-tour/director.js
+++ b/src/feature-tour/director.js
@@ -159,13 +159,22 @@ export class TourDirector {
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.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),
+ onAvatar: (entry) => this._setAvatar(entry),
+ onOpenChange: (open) => this.controls.setMenuOpen(open),
+ },
+ {
+ avatars: this.avatar.avatars(),
+ currentId: this.avatar.currentAvatarId(),
+ docsUrl: '/avatar-studio',
+ },
+ );
this.controls.setMuted(this.muted);
this.controls.setPaused(this.paused);
this.controls.setSpeed(this.speed);
@@ -343,6 +352,15 @@ export class TourDirector {
}
}
+ // Swap the guide to any avatar the visitor picks. The guide persists the choice
+ // (shared with the site-wide Walk Companion) and resolves to the entry actually
+ // shown — the fallback if the pick failed to load — which we echo back to the
+ // panel so its button and the picker's check mark stay truthful.
+ async _setAvatar(entry) {
+ const shown = await this.avatar.setAvatar(entry);
+ if (shown?.id) this.panel?.setAvatarCurrent(shown.id);
+ }
+
// ── Free roam ───────────────────────────────────────────────────────────────
// Hand the stage to the visitor: freeze the guided sequence and let them drive
// the guide around the page (free-roam.js). Toggling off — or any navigation /
diff --git a/src/feature-tour/guide-avatar.js b/src/feature-tour/guide-avatar.js
index 61e7f1d0b..1f5ea335d 100644
--- a/src/feature-tour/guide-avatar.js
+++ b/src/feature-tour/guide-avatar.js
@@ -27,6 +27,18 @@ const CANVAS_H = 240;
const MARGIN = 16;
const Z_AVATAR = 2147483300;
+// Gravity, mirrored from the walk platformer (src/walk.js GRAVITY = -14) so the
+// guide obeys the same physics the visitor sees there: it falls onto the ground
+// plane and stays planted, never floating mid-air. SPAWN_DROP is how far above
+// the floor the guide spawns so it visibly settles when it first appears.
+const GRAVITY = -14;
+const SPAWN_DROP = 0.32;
+
+// The platform's recurring default character — "Ava", the photoreal full-body
+// humanoid (/avatars/realistic-female.glb). The same rig stands in as the guide
+// NPC in the walk world, so the tour guide matches her by default.
+const DEFAULT_GUIDE_AVATAR = 'realistic-female';
+
export class GuideAvatar {
constructor() {
this.config = resolveConfig({
@@ -34,6 +46,7 @@ export class GuideAvatar {
apiBase: '',
manifestUrl: '/animations/manifest.json',
docsUrl: '/avatar-studio',
+ defaultAvatarId: DEFAULT_GUIDE_AVATAR,
});
this.host = null;
this.renderer = null;
@@ -49,6 +62,11 @@ export class GuideAvatar {
this._walking = false;
this._reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;
this._pos = { x: 0, y: 0 };
+ // Vertical physics state — height above the ground plane and its velocity.
+ // Gravity in _tick pulls _y down to 0 and holds it there (see GRAVITY).
+ this._groundY = 0;
+ this._y = 0;
+ this._vy = 0;
this._tick = this._tick.bind(this);
}
@@ -112,7 +130,7 @@ export class GuideAvatar {
const savedId = lsGet(this.config.keys.avatar) || this.config.defaultAvatarId;
const entry = resolveAvatarEntry(savedId, this.config);
const fallback = resolveAvatarEntry(this.config.defaultAvatarId, this.config);
- const { model, controller } = await loadWalkAvatar(entry, {
+ const { model, controller, entry: active } = await loadWalkAvatar(entry, {
assetBase: this.config.assetBase,
apiBase: this.config.apiBase,
manifestUrl: this.config.manifestUrl,
@@ -120,9 +138,70 @@ export class GuideAvatar {
});
this.model = model;
this.controller = controller;
+ this._entry = active;
this._frame(model, this.rig, this.camera);
}
+ // ── Live avatar swap ───────────────────────────────────────────────────────
+ // Hot-swap the guide to any roster (or user-generated) avatar. Persists the
+ // choice to the shared Walk Companion key so it sticks across the tour and the
+ // rest of the site, then disposes the old rig and drops the new one in under
+ // gravity. Resolves to the entry actually shown (the fallback if the pick fails
+ // to load), so the picker UI can reflect what really happened.
+ async setAvatar(idOrEntry) {
+ const entry =
+ typeof idOrEntry === 'string' ? resolveAvatarEntry(idOrEntry, this.config) : idOrEntry;
+ if (!entry) return this._entry;
+ lsSet(this.config.keys.avatar, entry.id);
+ // Headless (WebGL/GLB failed) or not yet built — remember the pick; it
+ // applies on the next successful mount.
+ if (this._headless || !this.rig) {
+ this._entry = entry;
+ return entry;
+ }
+ const fallback = resolveAvatarEntry(this.config.defaultAvatarId, this.config);
+ try {
+ const { model, controller, entry: active } = await loadWalkAvatar(entry, {
+ assetBase: this.config.assetBase,
+ apiBase: this.config.apiBase,
+ manifestUrl: this.config.manifestUrl,
+ fallbackEntry: fallback,
+ });
+ // The guide may have been torn down while the GLB was loading.
+ if (!this.rig) {
+ model.traverse((n) => n.isMesh && disposeMesh(n));
+ controller.dispose?.();
+ return this._entry;
+ }
+ if (this.model) {
+ this.rig.remove(this.model);
+ this.model.traverse((n) => n.isMesh && disposeMesh(n));
+ }
+ this.controller?.dispose();
+ this._yaw = 0;
+ this._targetYaw = 0;
+ this.rig.rotation.y = 0;
+ this.model = model;
+ this.controller = controller;
+ this._entry = active;
+ this._frame(model, this.rig, this.camera);
+ return active;
+ } catch (err) {
+ console.warn('[tour] guide avatar swap failed:', err?.message || err);
+ return this._entry;
+ }
+ }
+
+ // The roster the guide can switch between, and the id it's currently wearing —
+ // surfaced so the tour's settings UI can build a picker without reaching into
+ // the SDK config itself.
+ avatars() {
+ return this.config.avatars;
+ }
+ currentAvatarId() {
+ return this._entry?.id || lsGet(this.config.keys.avatar) || this.config.defaultAvatarId;
+ }
+
_frame(model, rig, camera) {
const box = new Box3().setFromObject(model);
const size = box.getSize(new Vector3());
@@ -134,6 +213,13 @@ export class GuideAvatar {
const height = Math.max(0.6, size.y);
camera.position.set(0, height * 0.62, height * 2.2);
camera.lookAt(0, height * 0.52, 0);
+ // Feet rest at rig-local y = 0; gravity in _tick drives rig.position.y down
+ // to the ground plane. Spawn a touch above it so the guide drops and settles
+ // onto the floor when it first appears — the same fall the walk platformer
+ // applies. Honour reduced-motion by starting already grounded.
+ this._y = this._reduced ? this._groundY : this._groundY + SPAWN_DROP;
+ this._vy = 0;
+ rig.position.y = this._y;
}
// ── Public choreography API ───────────────────────────────────────────────
@@ -283,7 +369,18 @@ export class GuideAvatar {
this.clock.update();
const dt = Math.min(this.clock.getDelta(), 0.05);
this._yaw += (this._targetYaw - this._yaw) * 0.12;
- if (this.rig) this.rig.rotation.y = this._yaw;
+ if (this.rig) {
+ this.rig.rotation.y = this._yaw;
+ // Gravity: integrate velocity, land on the ground plane, hold there —
+ // the same model the walk platformer uses so the guide is never airborne.
+ this._vy += GRAVITY * dt;
+ this._y += this._vy * dt;
+ if (this._y <= this._groundY) {
+ this._y = this._groundY;
+ if (this._vy < 0) this._vy = 0;
+ }
+ this.rig.position.y = this._y;
+ }
this.controller?.update(dt);
this.renderer.render(this.scene, this.camera);
this._raf = requestAnimationFrame(this._tick);
@@ -324,6 +421,13 @@ function lsGet(key) {
return null;
}
}
+function lsSet(key, value) {
+ try {
+ localStorage.setItem(key, value);
+ } catch {
+ /* private mode / quota — the swap still applies for this session */
+ }
+}
function disposeMesh(n) {
n.geometry?.dispose?.();
const mats = Array.isArray(n.material) ? n.material : [n.material];
diff --git a/src/solana/sns-subdomain.js b/src/solana/sns-subdomain.js
index 3f4d1e252..f718fa166 100644
--- a/src/solana/sns-subdomain.js
+++ b/src/solana/sns-subdomain.js
@@ -19,8 +19,9 @@
*/
import { createHash } from 'node:crypto';
-import { Connection, Keypair, PublicKey, TransactionMessage, VersionedTransaction } from '@solana/web3.js';
+import { Keypair, PublicKey, TransactionMessage, VersionedTransaction } from '@solana/web3.js';
import bs58 from 'bs58';
+import { solanaConnection } from '../../api/_lib/solana/connection.js';
const DEFAULT_RPC_URL = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
@@ -167,7 +168,10 @@ export async function createNamedSubdomain({
const newOwnerKey = new PublicKey(newOwner);
const parentKp = loadParentOwnerKeypair();
- const connection = new Connection(rpcUrl, 'confirmed');
+ // Failover-aware connection: rotates the resolved url across Helius → Alchemy →
+ // dRPC → the keyless public lanes so subdomain registration never dies on a
+ // single provider being down (an expired Helius plan included).
+ const connection = solanaConnection({ url: rpcUrl, commitment: 'confirmed' });
const availability = await checkSubdomainAvailability({
connection,
diff --git a/tests/api/solana-rpc-endpoints.test.js b/tests/api/solana-rpc-endpoints.test.js
index 135d79017..a6c2278b1 100644
--- a/tests/api/solana-rpc-endpoints.test.js
+++ b/tests/api/solana-rpc-endpoints.test.js
@@ -13,6 +13,7 @@ import {
solanaRpcEndpoints,
shouldRotate,
makeRotatingFetch,
+ classifyRpcBody,
} from '../../api/_lib/solana/connection.js';
const KEYS = [
@@ -46,12 +47,29 @@ describe('solanaRpcEndpoints', () => {
expect(eps.some((u) => u.startsWith('https://rpc.ankr.com/') && !/\/solana\/.+/.test(u))).toBe(false);
});
- it('includes PublicNode and the public endpoint as keyless fallbacks', () => {
+ it('includes PublicNode, Leo RPC, and the public endpoint as keyless fallbacks', () => {
const eps = solanaRpcEndpoints('mainnet');
expect(eps).toContain('https://solana-rpc.publicnode.com');
+ expect(eps).toContain('https://solana.leorpc.com/?api_key=FREE');
expect(eps).toContain('https://api.mainnet-beta.solana.com');
});
+ it('keeps five working keyless lanes even with every API key absent', () => {
+ // Helius/Alchemy/dRPC/Ankr all unset (the "paid plan lapsed" state): the
+ // chain must still resolve a usable node, never collapse to one throttled lane.
+ // Five independent public nodes were each verified answering live mainnet RPC,
+ // so a request only errors if all five are down at once.
+ const eps = solanaRpcEndpoints('mainnet');
+ const keyless = [
+ 'https://solana-rpc.publicnode.com',
+ 'https://solana.leorpc.com/?api_key=FREE',
+ 'https://api.tatum.io/v3/blockchain/node/solana-mainnet',
+ 'https://solana.therpc.io',
+ 'https://api.mainnet-beta.solana.com',
+ ];
+ for (const u of keyless) expect(eps).toContain(u);
+ });
+
it('keeps the public mainnet-beta endpoint last (most rate-limited)', () => {
const eps = solanaRpcEndpoints('mainnet');
expect(eps[eps.length - 1]).toBe('https://api.mainnet-beta.solana.com');
@@ -182,4 +200,84 @@ describe('makeRotatingFetch poison-body failover', () => {
const resp = await fetchImpl(a, { method: 'POST', body: '{}' });
expect(await resp.text()).toBe(errBody);
});
+
+ it('fails over a 200 envelope missing both result and error (the StructError shape)', async () => {
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ // `{jsonrpc,id}` with no result/error — what web3.js choked on with the
+ // empty-`received:` StructError that 500'd the club-cover prepare step.
+ const a = 'https://poison-noresult.example/sol';
+ const b = 'https://healthy.example/sol';
+ mockResponses({ [a]: { body: '{"jsonrpc":"2.0","id":1}' }, [b]: { body: json } });
+ const resp = await makeRotatingFetch([a, b])(a, { method: 'POST', body: '{}' });
+ expect(await resp.text()).toBe(json);
+ });
+
+ it('fails over a 200 + provider quota error (exhausted paid plan) to the next lane', async () => {
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ // How an exhausted Helius plan answers: HTTP 200, JSON-RPC error -32429.
+ const quota = '{"jsonrpc":"2.0","error":{"code":-32429,"message":"max usage reached"},"id":1}';
+ const a = 'https://exhausted.example/sol';
+ const b = 'https://healthy.example/sol';
+ mockResponses({ [a]: { body: quota }, [b]: { body: json } });
+ const resp = await makeRotatingFetch([a, b])(a, { method: 'POST', body: '{}' });
+ expect(await resp.text()).toBe(json);
+ });
+
+ it('fails over a truncated JSON body to the next lane', async () => {
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ const a = 'https://truncated.example/sol';
+ const b = 'https://healthy.example/sol';
+ mockResponses({ [a]: { body: '{"jsonrpc":"2.0","result":{"val' }, [b]: { body: json } });
+ const resp = await makeRotatingFetch([a, b])(a, { method: 'POST', body: '{}' });
+ expect(await resp.text()).toBe(json);
+ });
+});
+
+// classifyRpcBody is the single source of truth for "is this 200 body usable?".
+// It turns the recurring StructError (web3.js choking on a malformed 200) into a
+// rotate signal instead of a thrown error reaching the caller.
+describe('classifyRpcBody', () => {
+ it('accepts a normal JSON-RPC success (result present, even when null)', () => {
+ expect(classifyRpcBody('{"jsonrpc":"2.0","result":{"value":null},"id":1}')).toBeNull();
+ expect(classifyRpcBody('{"jsonrpc":"2.0","result":null,"id":1}')).toBeNull();
+ // Tatum omits the jsonrpc/id echo but carries `result` — still usable.
+ expect(classifyRpcBody('{"result":{"context":{"slot":1},"value":null}}')).toBeNull();
+ });
+
+ it('accepts a deterministic JSON-RPC request error (must surface, not rotate)', () => {
+ expect(classifyRpcBody('{"jsonrpc":"2.0","error":{"code":-32602,"message":"Invalid params"},"id":1}')).toBeNull();
+ expect(classifyRpcBody('{"jsonrpc":"2.0","error":{"code":-32002,"message":"Transaction simulation failed"},"id":1}')).toBeNull();
+ });
+
+ it('flags empty, HTML, and truncated bodies', () => {
+ expect(classifyRpcBody('')?.reason).toBe('empty body');
+ expect(classifyRpcBody(' ')?.reason).toBe('empty body');
+ expect(classifyRpcBody('<!DOCTYPE html><html>502</html>')?.reason).toBe('HTML body');
+ expect(classifyRpcBody('{"jsonrpc":"2.0","result":{')?.reason).toBe('unparseable body');
+ });
+
+ it('flags a 200 envelope missing both result and error', () => {
+ expect(classifyRpcBody('{"jsonrpc":"2.0","id":1}')?.reason).toBe('missing result/error');
+ });
+
+ it('flags provider capacity/quota/auth errors for failover', () => {
+ // Quota → status 429 so the cooldown picks the long quota park.
+ const quota = classifyRpcBody('{"jsonrpc":"2.0","error":{"code":-32429,"message":"max usage reached"},"id":1}');
+ expect(quota?.status).toBe(429);
+ for (const [code, msg] of [
+ [-32029, 'Too Many Requests'],
+ [-32052, 'API key is not allowed'],
+ [0, 'rate limit exceeded'],
+ [0, 'forbidden'],
+ ]) {
+ expect(classifyRpcBody(`{"jsonrpc":"2.0","error":{"code":${code},"message":"${msg}"},"id":1}`)).not.toBeNull();
+ }
+ });
+
+ it('validates every element of a JSON-RPC batch', () => {
+ const goodBatch = '[{"jsonrpc":"2.0","result":1,"id":1},{"jsonrpc":"2.0","result":2,"id":2}]';
+ expect(classifyRpcBody(goodBatch)).toBeNull();
+ const badBatch = '[{"jsonrpc":"2.0","result":1,"id":1},{"jsonrpc":"2.0","id":2}]';
+ expect(classifyRpcBody(badBatch)?.reason).toBe('missing result/error');
+ });
});
diff --git a/tests/auto-rig-gate.test.js b/tests/auto-rig-gate.test.js
new file mode 100644
index 000000000..cd37d9139
--- /dev/null
+++ b/tests/auto-rig-gate.test.js
@@ -0,0 +1,46 @@
+// The auto-rig-on-create gate must agree exactly with the client rig classifier
+// (src/shared/rig-classify.js): a usable skeleton is never re-rigged, a confirmed
+// static mesh is, and an un-inspected ("unknown") mesh is rigged on creation so
+// every avatar that lands ends up animation-ready — the Avaturn-parity contract.
+
+import { describe, it, expect } from 'vitest';
+import { rigInfoIsRigged } from '../api/_lib/auto-rig.js';
+import { classifyRig } from '../src/shared/rig-classify.js';
+
+describe('rigInfoIsRigged — auto-rig skip gate', () => {
+ it('skips when the GLB carries a skeleton flag (e.g. Avaturn export)', () => {
+ expect(rigInfoIsRigged({ is_rigged: true })).toBe(true);
+ });
+
+ it('skips when a positive joint count is present', () => {
+ expect(rigInfoIsRigged({ skeleton_joint_count: 52 })).toBe(true);
+ expect(rigInfoIsRigged({ is_rigged: false, skeleton_joint_count: 52 })).toBe(true);
+ });
+
+ it('rigs a confirmed static mesh', () => {
+ expect(rigInfoIsRigged({ is_rigged: false })).toBe(false);
+ expect(rigInfoIsRigged({ is_rigged: false, skeleton_joint_count: 0 })).toBe(false);
+ });
+
+ it('rigs an un-inspected (unknown) mesh and a missing signal', () => {
+ expect(rigInfoIsRigged(null)).toBe(false);
+ expect(rigInfoIsRigged({})).toBe(false);
+ expect(rigInfoIsRigged(undefined)).toBe(false);
+ });
+
+ // The server gate and the client badge must never disagree about a GLB.
+ it('agrees with classifyRig across the signal matrix', () => {
+ const cases = [
+ { is_rigged: true },
+ { is_rigged: false },
+ { skeleton_joint_count: 30 },
+ { skeleton_joint_count: 0 },
+ { is_rigged: false, skeleton_joint_count: 12 },
+ {},
+ ];
+ for (const meta of cases) {
+ const client = classifyRig({ source_meta: meta }).rigged;
+ expect(rigInfoIsRigged(meta)).toBe(client);
+ }
+ });
+});
diff --git a/tour-sdk/LICENSE b/tour-sdk/LICENSE
new file mode 100644
index 000000000..8e2251ab4
--- /dev/null
+++ b/tour-sdk/LICENSE
@@ -0,0 +1,180 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship made available under
+ the License, as indicated by a copyright notice that is included in
+ or attached to the work (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other transformations
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean, as submitted to the Licensor for inclusion
+ in the Work by the copyright owner or by an individual or Legal Entity
+ authorized to submit on behalf of the copyright owner. For the purposes
+ of this definition, "submitted" means any form of electronic, verbal,
+ or written communication sent to the Licensor or its representatives,
+ including but not limited to communication on electronic mailing lists,
+ source code control systems, and issue tracking systems that are managed
+ by, or on behalf of, the Licensor for the purpose of discussing and
+ improving the Work, but excluding communication that is conspicuously
+ marked or designated in writing by the copyright owner as "Not a
+ Contribution."
+
+ "Contributor" shall mean Licensor and any Legal Entity on behalf of
+ whom a Contribution has been received by the Licensor and included
+ within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by the combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a cross-claim
+ or counterclaim in a lawsuit) alleging that the Work or any
+ Contribution embodied within the Work constitutes direct or contributory
+ patent infringement, then any patent licenses granted to You under
+ this License for that Work shall terminate as of the date such
+ litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or Derivative
+ Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, You must include a readable copy of the
+ attribution notices contained within such NOTICE file, in
+ at least one of the following places: within a NOTICE text
+ file distributed as part of the Derivative Works; within
+ the Source form or documentation, if provided along with the
+ Derivative Works; or, within a display generated by the
+ Derivative Works, if and wherever such third-party notices
+ normally appear. The contents of the NOTICE file are for
+ informational purposes only and do not modify the License.
+ You may add Your own attribution notices within Derivative
+ Works that You distribute, alongside or in addition to the
+ NOTICE text from the Work, provided that such additional
+ attribution notices cannot be construed as modifying the License.
+
+ You may add Your own license statement for Your modifications and
+ may provide additional grant of rights to use, copy, modify, merge,
+ publish, distribute, sublicense, and/or sell copies of the
+ Derivative Works, and to permit persons to whom the Derivative Works
+ are furnished to do so.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or reproducing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or exemplary damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or all other
+ commercial damages or losses), even if such Contributor has been
+ advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may offer only
+ conditions consistent with this License.
+
+ END OF TERMS AND CONDITIONS
+
+ Copyright 2026 nirholas
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/tour-sdk/README.md b/tour-sdk/README.md
new file mode 100644
index 000000000..3cf2b1ac3
--- /dev/null
+++ b/tour-sdk/README.md
@@ -0,0 +1,248 @@
+# @three-ws/tour
+
+> A **3D guide that walks your live site and narrates it.** A small avatar walks across the real page, spotlights each feature, points at it with a beam, and speaks a line about it — a guided product tour that runs on your actual DOM, not a slideshow. Powered by [Three.js](https://threejs.org) and [@three-ws/walk](https://www.npmjs.com/package/@three-ws/walk).
+
+The guide walks from feature to feature across your real pages. At each stop it
+dims the page, rings the element it's talking about, walks over and gestures at
+it, and narrates a line — with synthesized voice if you wire a TTS endpoint, or
+paced captions if you don't. It **survives full-page navigation** (state lives in
+`sessionStorage`), so a tour can span your whole multi-page app and pick up
+exactly where it left off on the next route. Visitors get a playback bar
+(prev / play / next / speed / mute), a searchable **chapter map**, **Quick** vs
+**Full** tracks, and a **free-roam** mode to drive the guide themselves.
+
+This is the engine behind the guided tour on [three.ws](https://three.ws).
+
+---
+
+## Install
+
+```bash
+npm install @three-ws/tour @three-ws/walk three
+```
+
+`three` and `@three-ws/walk` are **peer dependencies** — bring your own copies
+(`three` >= 0.150, `@three-ws/walk` >= 0.1). You also need to serve the avatar
+assets `@three-ws/walk` needs (avatar GLBs + the shared animation manifest) — see
+that package's README. Point the tour at them with `assetBase` / `manifestUrl`.
+
+---
+
+## Quick start
+
+```js
+import { createFeatureTour } from '@three-ws/tour';
+
+const tour = createFeatureTour({
+ curriculum: '/tour/curriculum.json', // what to visit + say (see below)
+ ttsEndpoint: '/api/tts/speak', // optional — omit for silent captions
+});
+
+// Let a "Take the tour" button anywhere on the site start it:
+document.querySelector('#take-the-tour')?.addEventListener('click', () => tour.start());
+
+// Honour deep-links (?tour=start / ?tour=1) and rehydrate an in-progress tour
+// on every page load. Call once, early.
+tour.bootstrap();
+```
+
+Because the tour spans pages, load this module on **every** page (or lazy-load it
+when a tour starts / is in progress) and call `bootstrap()` so it re-hydrates
+after each navigation. Expose the controller globally if your nav button lives in
+a different bundle:
+
+```js
+window.__featureTour = tour;
+```
+
+### Deep links
+
+With the default `deepLinkParam: 'tour'`:
+
+| URL | Effect |
+| --- | --- |
+| `?tour=start` | Begin the Full tour (`&track=quick` for the Quick track) |
+| `?tour=1` | Resume an in-progress tour |
+| `?tour=0` | Exit the tour |
+
+---
+
+## The curriculum
+
+A tour is driven by a **curriculum** — a JSON document describing what the guide
+visits and what it says. Each stop is a route plus a line of narration, grouped
+into chapters and split into tracks. The full schema is in
+[`curriculum.schema.json`](./curriculum.schema.json); a minimal one:
+
+```json
+{
+ "tracks": [
+ { "id": "full", "title": "Full tour" },
+ { "id": "quick", "title": "Quick highlights" }
+ ],
+ "sections": [
+ { "id": "main", "title": "Overview", "intro": "Welcome — let me show you around." }
+ ],
+ "stops": [
+ {
+ "path": "/",
+ "section": "main",
+ "title": "Home",
+ "narration": "Here's the front door — start a project right from here.",
+ "highlight": true,
+ "targets": ["a.cta", ".hero a.button"]
+ }
+ ]
+}
+```
+
+- **`path`** — the route the stop lives on. The tour navigates there when needed.
+- **`narration`** — what the guide says.
+- **`targets`** — ordered CSS selectors for the element to spotlight; the first
+ visible match wins. If none match, the guide falls back to the page heading /
+ primary call-to-action. You can also tag an element with `data-tour-target` in
+ your HTML instead of listing selectors.
+- **`highlight`** — include this stop in the **Quick** track.
+- **`sectionIntro`** — a spoken chapter bridge (usually on the first stop of a
+ section).
+
+Pass it as a URL (`curriculum: '/tour/curriculum.json'`) or inline
+(`curriculum: { stops: [...] }`).
+
+### Generating a curriculum from your pages
+
+If you already maintain a sitemap / pages manifest, generate the curriculum
+instead of hand-writing it. `buildCurriculum()` turns a pages document into a
+curriculum; narration comes from each page's own description, so it stays
+truthful as your site changes.
+
+```js
+import { buildCurriculum } from '@three-ws/tour';
+
+const curriculum = buildCurriculum(pagesDoc, {
+ sectionOrder: ['main', 'build', 'learn'],
+ sectionIntros: { main: "Welcome — let's start at the front door." },
+ sectionHeroes: { main: ['/', '/pricing'] }, // shown first + seed the Quick track
+ targets: { '/': ['a.cta'] },
+ deny: ['/login', '/legal'], // skip these paths
+ quickPerSection: 3,
+ title: 'Acme Guided Tour',
+});
+```
+
+Or from the command line in a build step / CI:
+
+```bash
+# generate
+tour-build-curriculum --pages pages.json --config tour.config.json --out public/tour/curriculum.json
+
+# fail the build if the committed curriculum is stale
+tour-build-curriculum --pages pages.json --config tour.config.json --out public/tour/curriculum.json --check
+```
+
+The input `pagesDoc` is `{ sections: [{ id, title, pages: [{ path, title, description, added, auth }] }] }`.
+
+---
+
+## Narration (TTS)
+
+Set `ttsEndpoint` to a URL that accepts `POST { text, voice, speed, format }` and
+returns an audio response (e.g. `audio/mpeg`). The narrator plays it and advances
+the tour when it ends. The voice picker in the chapter panel sends the chosen
+`voice` id; customise the list with the `voices` option.
+
+**No endpoint?** The tour still runs — narration becomes captions paced to the
+reading time of each line. The same graceful fallback kicks in if a request
+fails, so a flaky TTS service never breaks the tour.
+
+---
+
+## Options
+
+| Option | Default | Description |
+| --- | --- | --- |
+| `curriculum` | `'/tour/curriculum.json'` | URL to fetch, or an inline curriculum object. |
+| `ttsEndpoint` | `null` | `POST { text, voice, speed, format }` → audio. Omit for silent captions. |
+| `defaultVoice` | `'nova'` | Default narration voice id. |
+| `voices` | built-in set | `[{ id, name }]` shown in the voice picker. |
+| `guideAvatarId` | `'realistic-female'` | Avatar the guide loads (a `@three-ws/walk` roster id, or your own). |
+| `assetBase` | `''` | Base URL for avatar GLB assets. |
+| `apiBase` | `''` | Base URL for the avatar GLB proxy (user-generated avatars). |
+| `manifestUrl` | `'/animations/manifest.json'` | Shared-animation manifest URL. |
+| `avatarStorageKey` | `'walk:companion:avatar'` | localStorage key for the visitor's chosen avatar, so the guide matches their Walk Companion. |
+| `navigate` | `location.assign` | How to move between routes — override for an SPA router. |
+| `deepLinkParam` | `'tour'` | Query param `bootstrap()` reads. |
+| `companion` | `{ global: '__walkCompanion', changeEvent: 'walk-companion:change' }` | De-dupes the on-screen avatar by standing down a `@three-ws/walk` companion during the tour. Set `false` to disable. |
+| `storagePrefix` | `'tws:tour'` | Prefix for the tour's sessionStorage/localStorage keys. |
+| `copy` | neutral defaults | Override the outro, off-route message, and completion card (`title`, `body`, `primary: { label, href }`, `restartLabel`, `closeLabel`). |
+
+### SPA routers
+
+`location.assign` triggers a real navigation. If your app is a client-side SPA,
+pass `navigate` so stop-to-stop transitions use your router:
+
+```js
+createFeatureTour({
+ curriculum,
+ navigate: (path) => router.push(path),
+});
+```
+
+The tour re-hydrates from storage after each navigation, so your router just
+needs to land on the new path — `bootstrap()` (or a `resume()` call on route
+change) does the rest.
+
+---
+
+## API
+
+```js
+const tour = createFeatureTour(options);
+
+tour.start('quick' | 'full'); // begin a tour
+tour.resume(); // re-hydrate an in-progress tour after navigation
+tour.exit(); // tear everything down
+tour.isActive(); // boolean — is a tour running?
+tour.bootstrap(); // honour the deep-link param + rehydrate
+tour.director; // the live TourDirector (once one exists)
+tour.config; // the fully-resolved config
+```
+
+Also exported for advanced/standalone use: `TourDirector`, `resolveTourConfig`,
+`buildCurriculum`, `buildPlaylist`, `trackMeta`, `loadCurriculum`,
+`createTourState`, `stopIndexForPath`, `sectionTitle`, `normalizePath`,
+`DEFAULT_VOICES`, `DEFAULT_COPY`, `VERSION`.
+
+---
+
+## Keyboard & accessibility
+
+- **Space / K** play-pause · **← / →** prev / next · **M** mute · **C** chapter
+ map · **R** free roam · **Esc** close menu / exit.
+- The playback bar, chapter map, and completion card use semantic roles, ARIA
+ labels, focus-visible rings, and a live progress slider.
+- Honours `prefers-reduced-motion` throughout (no walk glide, no pulse, instant
+ spotlight).
+- Degrades gracefully: if WebGL or the avatar GLB fails to load, captions, the
+ spotlight, and the pointer beam still work — the guide just loses its body.
+
+---
+
+## How it works
+
+`createFeatureTour()` resolves your options and returns a thin controller. The
+`TourDirector` walks a **playlist** (the stop indices for the chosen track),
+resolving each stop's on-page target, spotlighting it (`spotlight.js`), walking
+the `GuideAvatar` over to point at it, drawing the pointer beam, and speaking via
+the `Narrator`. Cross-page state lives in `sessionStorage` (live sequencing) and
+`localStorage` (durable resume + preferences). The chapter map, playback bar, and
+free-roam are independent UI modules the director coordinates.
+
+The guide avatar reuses `@three-ws/walk`'s loader and animation retargeting, so
+any humanoid rig animates correctly and never freezes in a T-pose.
+
+---
+
+## License
+
+Apache-2.0 © three.ws
diff --git a/tour-sdk/bin/tour-build-curriculum.mjs b/tour-sdk/bin/tour-build-curriculum.mjs
new file mode 100644
index 000000000..c9177528e
--- /dev/null
+++ b/tour-sdk/bin/tour-build-curriculum.mjs
@@ -0,0 +1,85 @@
+#!/usr/bin/env node
+// tour-build-curriculum — generate a tour curriculum from a pages document.
+// =========================================================================
+// Reads a JSON "pages" document and writes a tour curriculum (see
+// curriculum.schema.json). Curation options — section order, chapter intros,
+// hero ordering, denied paths, per-page anchors — come from an optional config
+// file so the curriculum is reproducible and version-controlled.
+//
+// tour-build-curriculum --pages pages.json --out public/tour/curriculum.json
+// tour-build-curriculum --pages pages.json --config tour.config.json --out curriculum.json
+// tour-build-curriculum --pages pages.json --out curriculum.json --check
+//
+// --check exits non-zero if the file on disk differs from a fresh build (minus
+// the volatile generatedAt timestamp) — wire it into CI to catch a stale tour.
+
+import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';
+import { dirname, resolve } from 'node:path';
+import { buildCurriculum } from '../src/build-curriculum.js';
+
+function parseArgs(argv) {
+ const args = { check: false };
+ for (let i = 0; i < argv.length; i++) {
+ const a = argv[i];
+ if (a === '--check') args.check = true;
+ else if (a === '--pages') args.pages = argv[++i];
+ else if (a === '--config') args.config = argv[++i];
+ else if (a === '--out') args.out = argv[++i];
+ else if (a === '-h' || a === '--help') args.help = true;
+ }
+ return args;
+}
+
+function usage() {
+ console.log(
+ `Usage: tour-build-curriculum --pages <pages.json> --out <curriculum.json> [--config <config.json>] [--check]
+
+ --pages Path to the pages document ({ sections: [{ id, title, pages: [...] }] }).
+ --out Path to write the curriculum JSON.
+ --config Optional curation options passed to buildCurriculum (sectionOrder,
+ sectionIntros, sectionHeroes, targets, deny, denyPrefix, title, …).
+ --check Fail if <out> is missing or differs from a fresh build.`,
+ );
+}
+
+function stable(obj) {
+ // Stable stringify ignoring generatedAt so --check doesn't flap on timestamp.
+ const clone = JSON.parse(JSON.stringify(obj));
+ delete clone.generatedAt;
+ return JSON.stringify(clone);
+}
+
+function main() {
+ const args = parseArgs(process.argv.slice(2));
+ if (args.help || !args.pages || !args.out) {
+ usage();
+ process.exit(args.help ? 0 : 1);
+ }
+
+ const pagesDoc = JSON.parse(readFileSync(resolve(args.pages), 'utf8'));
+ const opts = args.config ? JSON.parse(readFileSync(resolve(args.config), 'utf8')) : {};
+ const next = { ...buildCurriculum(pagesDoc, opts), generatedAt: new Date().toISOString() };
+ const outPath = resolve(args.out);
+
+ if (args.check) {
+ if (!existsSync(outPath)) {
+ console.error(`curriculum missing — run without --check to generate ${args.out}`);
+ process.exit(1);
+ }
+ const current = JSON.parse(readFileSync(outPath, 'utf8'));
+ if (stable(current) !== stable(next)) {
+ console.error(`curriculum is stale — re-run tour-build-curriculum to regenerate ${args.out}`);
+ process.exit(1);
+ }
+ console.log(`curriculum OK — ${next.stopCount} stops, ~${next.estimatedMinutes} min`);
+ return;
+ }
+
+ mkdirSync(dirname(outPath), { recursive: true });
+ writeFileSync(outPath, JSON.stringify(next, null, '\t') + '\n');
+ console.log(
+ `Wrote ${args.out} — ${next.stopCount} stops across ${next.sections.length} chapters, ~${next.estimatedMinutes} min.`,
+ );
+}
+
+main();
diff --git a/tour-sdk/build.mjs b/tour-sdk/build.mjs
new file mode 100644
index 000000000..099647baa
--- /dev/null
+++ b/tour-sdk/build.mjs
@@ -0,0 +1,50 @@
+#!/usr/bin/env node
+// Build @three-ws/tour into a self-contained, publishable ES module.
+// ==================================================================
+// esbuild bundles every source module into dist/index.mjs, leaving the two
+// peer dependencies external so consumers bring their own copies:
+// · three (+ three/addons/*) — the 3D engine
+// · @three-ws/walk — the avatar loader the guide reuses
+//
+// Styles are injected at runtime by each module, so dist/style.css is an empty
+// placeholder kept only so a side-effect `import '@three-ws/tour/style.css'`
+// resolves for build tooling that expects it.
+
+import { build } from 'esbuild';
+import { mkdirSync, writeFileSync, rmSync } from 'node:fs';
+import { dirname, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const here = dirname(fileURLToPath(import.meta.url));
+const outDir = resolve(here, 'dist');
+
+rmSync(outDir, { recursive: true, force: true });
+mkdirSync(outDir, { recursive: true });
+
+const result = await build({
+ entryPoints: [resolve(here, 'src/index.js')],
+ outdir: outDir,
+ bundle: true,
+ format: 'esm',
+ splitting: true,
+ platform: 'browser',
+ target: 'es2020',
+ // Peer dependencies — never inline them.
+ external: ['three', 'three/addons/*', '@three-ws/walk'],
+ outExtension: { '.js': '.mjs' },
+ entryNames: '[name]',
+ chunkNames: 'chunk-[name]-[hash]',
+ legalComments: 'none',
+ metafile: true,
+ logLevel: 'info',
+});
+
+writeFileSync(
+ resolve(outDir, 'style.css'),
+ '/* @three-ws/tour — styles are injected at runtime by the tour director and its UI modules. */\n',
+);
+
+const out = Object.keys(result.metafile.outputs)
+ .map((p) => p.replace(/^.*tour-sdk\//, ''))
+ .sort();
+console.log('[tour-sdk] built:\n ' + out.join('\n '));
diff --git a/tour-sdk/curriculum.schema.json b/tour-sdk/curriculum.schema.json
new file mode 100644
index 000000000..55fadbf66
--- /dev/null
+++ b/tour-sdk/curriculum.schema.json
@@ -0,0 +1,68 @@
+{
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "$id": "https://three.ws/tour/curriculum.schema.json",
+ "title": "@three-ws/tour curriculum",
+ "description": "The document that drives a guided tour: what the 3D guide visits and what it says. Hand-author it, or generate it with buildCurriculum().",
+ "type": "object",
+ "required": ["stops"],
+ "properties": {
+ "version": { "type": "integer", "description": "Schema version. Current is 2." },
+ "generatedAt": { "type": "string", "description": "ISO timestamp of when the curriculum was generated (optional)." },
+ "generatedBy": { "type": "string", "description": "Tool that produced the curriculum (optional)." },
+ "title": { "type": "string", "description": "Human title of the tour." },
+ "tagline": { "type": "string", "description": "Short subtitle shown on a tour landing page." },
+ "estimatedMinutes": { "type": "number", "description": "Estimated length of the full tour." },
+ "stopCount": { "type": "integer", "description": "Number of stops (mirrors stops.length)." },
+ "tracks": {
+ "type": "array",
+ "description": "Selectable views over the stops. 'full' visits every stop; 'quick' visits only highlighted stops. At least one track is recommended.",
+ "items": {
+ "type": "object",
+ "required": ["id", "title"],
+ "properties": {
+ "id": { "type": "string", "description": "Track id. 'full' and 'quick' have built-in playlist semantics." },
+ "title": { "type": "string" },
+ "description": { "type": "string" },
+ "stopCount": { "type": "integer" },
+ "estimatedMinutes": { "type": "number" }
+ }
+ }
+ },
+ "sections": {
+ "type": "array",
+ "description": "Chapter headers, in render order. Each stop's `section` references a section `id`. Optional — if omitted, chapters are inferred from the stops.",
+ "items": {
+ "type": "object",
+ "required": ["id", "title"],
+ "properties": {
+ "id": { "type": "string" },
+ "title": { "type": "string" },
+ "intro": { "type": "string", "description": "Spoken bridge said when the guide first enters this chapter." }
+ }
+ }
+ },
+ "stops": {
+ "type": "array",
+ "minItems": 1,
+ "description": "The ordered list of features the guide visits.",
+ "items": {
+ "type": "object",
+ "required": ["path", "narration"],
+ "properties": {
+ "id": { "type": "string", "description": "Stable id for the stop (e.g. a slug of the path)." },
+ "path": { "type": "string", "description": "Route the stop lives on, e.g. '/pricing'. The tour navigates here when needed; '/' and trailing-slash variants are normalized." },
+ "section": { "type": "string", "description": "Section id this stop belongs to." },
+ "title": { "type": "string", "description": "Short feature name shown in the chapter map." },
+ "narration": { "type": "string", "description": "The line the guide speaks at this stop." },
+ "highlight": { "type": "boolean", "description": "Whether this stop is part of the Quick-highlights track." },
+ "sectionIntro": { "type": "string", "description": "If set, spoken once before this stop as the chapter's bridge (usually only on the first stop of a section)." },
+ "targets": {
+ "type": "array",
+ "description": "Ordered CSS selectors for the on-page element to spotlight. The first visible match wins; if none match, the guide falls back to the page heading / primary CTA. You can also mark an element in your HTML with [data-tour-target].",
+ "items": { "type": "string" }
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/tour-sdk/examples/curriculum.example.json b/tour-sdk/examples/curriculum.example.json
new file mode 100644
index 000000000..47bd0315a
--- /dev/null
+++ b/tour-sdk/examples/curriculum.example.json
@@ -0,0 +1,63 @@
+{
+ "version": 2,
+ "title": "Acme Guided Tour",
+ "tagline": "A 3D guide walks you through every feature, live, on the real site.",
+ "estimatedMinutes": 4,
+ "stopCount": 5,
+ "tracks": [
+ { "id": "full", "title": "Full tour", "description": "Every feature, chapter by chapter.", "stopCount": 5, "estimatedMinutes": 4 },
+ { "id": "quick", "title": "Quick highlights", "description": "The best of every chapter, in a few minutes.", "stopCount": 3, "estimatedMinutes": 2 }
+ ],
+ "sections": [
+ { "id": "main", "title": "Overview", "intro": "Welcome — I'm your guide. Let me show you around, starting at the front door." },
+ { "id": "build", "title": "Build", "intro": "Now the fun part — let's look at what you can make here." }
+ ],
+ "stops": [
+ {
+ "id": "home",
+ "path": "/",
+ "section": "main",
+ "title": "Home",
+ "narration": "Here we have the home page — the front door to everything Acme does. Start a new project right from here.",
+ "highlight": true,
+ "sectionIntro": "Welcome — I'm your guide. Let me show you around, starting at the front door.",
+ "targets": ["a.cta", ".hero a.button"]
+ },
+ {
+ "id": "pricing",
+ "path": "/pricing",
+ "section": "main",
+ "title": "Pricing",
+ "narration": "Next up, pricing. Simple, transparent plans that scale with your team.",
+ "highlight": true,
+ "targets": ["[data-tour-target]", ".pricing-table"]
+ },
+ {
+ "id": "docs",
+ "path": "/docs",
+ "section": "main",
+ "title": "Docs",
+ "narration": "This is the documentation — guides, references, and tutorials whenever you want to go deeper.",
+ "highlight": false
+ },
+ {
+ "id": "studio",
+ "path": "/studio",
+ "section": "build",
+ "title": "Studio",
+ "narration": "Meet the Studio — where you actually build. Everything you create starts on this canvas.",
+ "highlight": true,
+ "sectionIntro": "Now the fun part — let's look at what you can make here.",
+ "targets": ["canvas", ".editor"]
+ },
+ {
+ "id": "deploy",
+ "path": "/deploy",
+ "section": "build",
+ "title": "Deploy",
+ "narration": "And this — deploy. One click ships what you built to the world.",
+ "highlight": false,
+ "targets": ["button[type=\"submit\"]", ".deploy-btn"]
+ }
+ ]
+}
diff --git a/tour-sdk/package.json b/tour-sdk/package.json
new file mode 100644
index 000000000..4a666eab0
--- /dev/null
+++ b/tour-sdk/package.json
@@ -0,0 +1,77 @@
+{
+ "name": "@three-ws/tour",
+ "version": "0.1.0",
+ "description": "A 3D guide avatar that walks across your live site, spotlights real features, points at them, and narrates each one — a guided product tour that runs on the real DOM, not a slideshow. Powered by Three.js and @three-ws/walk.",
+ "keywords": [
+ "3d",
+ "avatar",
+ "three.js",
+ "webgl",
+ "product-tour",
+ "onboarding",
+ "guided-tour",
+ "walkthrough",
+ "tour",
+ "narration",
+ "tts",
+ "spotlight",
+ "agent"
+ ],
+ "author": "three.ws <[email protected]> (https://three.ws)",
+ "license": "Apache-2.0",
+ "homepage": "https://three.ws/tour",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/nirholas/three.ws.git",
+ "directory": "tour-sdk"
+ },
+ "bugs": {
+ "url": "https://github.com/nirholas/three.ws/issues"
+ },
+ "type": "module",
+ "main": "./dist/index.mjs",
+ "module": "./dist/index.mjs",
+ "types": "./types/index.d.ts",
+ "bin": {
+ "tour-build-curriculum": "./bin/tour-build-curriculum.mjs"
+ },
+ "exports": {
+ ".": {
+ "types": "./types/index.d.ts",
+ "import": "./dist/index.mjs",
+ "default": "./dist/index.mjs"
+ },
+ "./curriculum": {
+ "types": "./types/index.d.ts",
+ "import": "./dist/index.mjs",
+ "default": "./dist/index.mjs"
+ },
+ "./curriculum.schema.json": "./curriculum.schema.json",
+ "./style.css": "./dist/style.css"
+ },
+ "files": [
+ "dist",
+ "src",
+ "bin",
+ "types",
+ "curriculum.schema.json",
+ "examples",
+ "README.md",
+ "LICENSE"
+ ],
+ "scripts": {
+ "build": "node build.mjs",
+ "test": "vitest run",
+ "prepublishOnly": "npm run build"
+ },
+ "peerDependencies": {
+ "@three-ws/walk": ">=0.1.0",
+ "three": ">=0.150.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "publishConfig": {
+ "access": "public"
+ }
+}
diff --git a/tour-sdk/src/build-curriculum.js b/tour-sdk/src/build-curriculum.js
new file mode 100644
index 000000000..01d265d4f
--- /dev/null
+++ b/tour-sdk/src/build-curriculum.js
@@ -0,0 +1,221 @@
+// build-curriculum.js — turn a "pages" document into a tour curriculum.
+// =====================================================================
+// The tour is driven by a curriculum (see curriculum.schema.json): an ordered
+// list of stops, each a route to visit + a line to say, grouped into chapters
+// with optional spoken intros, and split into tracks (Full / Quick). You can
+// hand-author that JSON, or generate it from a description of your site's pages
+// with this pure function — no filesystem, so it runs in a build step or the
+// browser. The companion CLI (bin/tour-build-curriculum.mjs) wraps it to read a
+// JSON file and write the curriculum out.
+//
+// Input shape (a superset of a typical sitemap/pages manifest):
+// {
+// sections: [
+// { id: 'main', title: 'Overview', pages: [
+// { path: '/', title: 'Home', description: 'The front door.', added: '2024-01-02', auth: 'public' },
+// ...
+// ] },
+// ...
+// ]
+// }
+//
+// Everything host-specific (section order, chapter intros, hero ordering, denied
+// paths, per-page anchors) is an option with a sensible default.
+
+const DEFAULT_CONNECTORS = [
+ 'Here we have',
+ 'Next up,',
+ 'This is',
+ 'Take a look at',
+ 'Now,',
+ "Let's visit",
+ 'Over here is',
+ "Here's",
+ 'Meet',
+ 'And this —',
+ 'Check out',
+ 'This one is',
+];
+
+// Words-per-minute for synthesized speech, plus per-stop overhead for the
+// walk-in, the point gesture, and a beat to read the bubble.
+const DEFAULT_WPM = 150;
+const DEFAULT_STOP_OVERHEAD_S = 9;
+
+/**
+ * Build a tour curriculum from a pages document.
+ *
+ * @param {{sections: Array<{id:string,title:string,pages:Array<object>}>}} pagesDoc
+ * @param {object} [opts]
+ * @param {string[]} [opts.sectionOrder] Section ids in render order. Defaults
+ * to the order they appear in pagesDoc.
+ * @param {Object<string,string>} [opts.sectionIntros] Spoken chapter bridges,
+ * keyed by section id. The first stop of a section carries its intro.
+ * @param {Object<string,string[]>} [opts.sectionHeroes] Per-section ordered
+ * list of hero paths shown first (and used to seed the Quick track).
+ * @param {Object<string,string[]>} [opts.targets] Per-path CSS selector lists
+ * the guide should point at; falls back to a heuristic at runtime.
+ * @param {string[]} [opts.deny] Exact paths to skip.
+ * @param {string[]} [opts.denyPrefix] Path prefixes to skip wholesale.
+ * @param {boolean} [opts.skipAuthRequired] Skip pages with auth==='required'
+ * (default true).
+ * @param {number} [opts.quickPerSection] Leading stops per chapter in the Quick
+ * track (default 3).
+ * @param {string[]} [opts.connectors] Spoken openers, cycled per stop.
+ * @param {string} [opts.title] Curriculum title.
+ * @param {string} [opts.tagline] Curriculum tagline.
+ * @param {number} [opts.wpm] Narration words-per-minute estimate.
+ * @param {number} [opts.stopOverheadS] Per-stop overhead seconds estimate.
+ * @returns {object} a curriculum object matching curriculum.schema.json
+ */
+export function buildCurriculum(pagesDoc, opts = {}) {
+ const sectionsIn = Array.isArray(pagesDoc?.sections) ? pagesDoc.sections : [];
+ const sectionIntros = opts.sectionIntros || {};
+ const sectionHeroes = opts.sectionHeroes || {};
+ const targets = opts.targets || {};
+ const deny = new Set(opts.deny || []);
+ const denyPrefix = opts.denyPrefix || [];
+ const skipAuth = opts.skipAuthRequired !== false;
+ const quickPerSection = Number.isFinite(opts.quickPerSection) ? opts.quickPerSection : 3;
+ const connectors = opts.connectors?.length ? opts.connectors : DEFAULT_CONNECTORS;
+ const wpm = opts.wpm || DEFAULT_WPM;
+ const overhead = opts.stopOverheadS ?? DEFAULT_STOP_OVERHEAD_S;
+ const order = opts.sectionOrder?.length ? opts.sectionOrder : sectionsIn.map((s) => s.id);
+
+ const bySection = new Map();
+ for (const section of sectionsIn) {
+ const kept = (section.pages || []).filter(
+ (p) =>
+ p &&
+ p.path &&
+ !(skipAuth && p.auth === 'required') &&
+ !deny.has(p.path) &&
+ !denyPrefix.some((prefix) => p.path.startsWith(prefix)),
+ );
+ if (kept.length) bySection.set(section.id, { meta: section, pages: kept });
+ }
+
+ const stops = [];
+ const sections = [];
+ let totalWords = 0;
+ let quickWords = 0;
+ let quickCount = 0;
+
+ for (const id of order) {
+ const entry = bySection.get(id);
+ if (!entry) continue;
+ const ordered = orderSection(sectionHeroes[id] || [], entry.pages);
+ const intro = sectionIntros[id] || '';
+ sections.push({ id, title: entry.meta.title || titleCase(id), intro });
+ ordered.forEach((page, i) => {
+ const isFirstOfSection = i === 0;
+ const highlight = i < quickPerSection;
+ const narration = narrate(page, stops.length, connectors);
+ const introWords = isFirstOfSection && intro ? intro.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),
+ path: page.path,
+ section: id,
+ title: collapse(page.title),
+ narration,
+ highlight,
+ ...(isFirstOfSection && intro ? { sectionIntro: intro } : {}),
+ ...(targets[page.path] ? { targets: targets[page.path] } : {}),
+ });
+ });
+ }
+
+ const estimatedMinutes = minutesFor(totalWords, stops.length, wpm, overhead);
+ const quickMinutes = Math.max(1, minutesFor(quickWords, quickCount, wpm, overhead));
+
+ return {
+ version: 2,
+ generatedBy: '@three-ws/tour buildCurriculum',
+ title: opts.title || 'Guided Tour',
+ tagline: opts.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,
+ };
+}
+
+// Order a section's pages: heroes first (in their declared order), then the rest
+// by recency (newest features are usually the most interesting to show).
+function orderSection(heroes, pages) {
+ const heroRank = new Map(heroes.map((path, i) => [path, i]));
+ return [...pages].sort((a, b) => {
+ const ra = heroRank.has(a.path) ? heroRank.get(a.path) : Infinity;
+ const rb = heroRank.has(b.path) ? heroRank.get(b.path) : Infinity;
+ if (ra !== rb) return ra - rb;
+ const da = a.added || '';
+ const db = b.added || '';
+ if (da !== db) return da < db ? 1 : -1;
+ return (a.title || '').localeCompare(b.title || '');
+ });
+}
+
+// Turn a page's title + description into a spoken paragraph.
+function narrate(page, index, connectors) {
+ const connector = connectors[index % connectors.length];
+ const title = collapse(page.title);
+ let desc = collapse(page.description || '');
+ // Strip a leading "<Title> — " / "<Title>:" the description sometimes repeats,
+ // so the guide doesn't say the name twice.
+ const dup = new RegExp(`^${escapeRe(title)}\\s*[—:-]\\s*`, 'i');
+ desc = desc.replace(dup, '');
+ desc = ensureSentence(desc);
+ return `${connector} ${ensureSentence(title).replace(/\.$/, '')}. ${desc}`.trim();
+}
+
+function minutesFor(words, count, wpm, overhead) {
+ return Math.round(words / wpm + (count * overhead) / 60);
+}
+
+function collapse(s) {
+ return String(s || '').replace(/\s+/g, ' ').trim();
+}
+function ensureSentence(s) {
+ s = collapse(s);
+ if (!s) return s;
+ return /[.!?]$/.test(s) ? s : s + '.';
+}
+function escapeRe(s) {
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+}
+function slug(path) {
+ return (
+ String(path)
+ .replace(/^\/+/, '')
+ .replace(/\/+$/, '')
+ .replace(/[^a-z0-9]+/gi, '-')
+ .toLowerCase() || 'home'
+ );
+}
+function titleCase(id) {
+ return String(id || '')
+ .replace(/[-_]+/g, ' ')
+ .replace(/\b\w/g, (c) => c.toUpperCase());
+}
diff --git a/tour-sdk/src/chapters.js b/tour-sdk/src/chapters.js
new file mode 100644
index 000000000..1c816d540
--- /dev/null
+++ b/tour-sdk/src/chapters.js
@@ -0,0 +1,296 @@
+// chapters.js — the tour's navigation drawer. A long 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 tracks (e.g. Quick highlights vs Full), 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;
+
+// Fallback voice catalogue if a host doesn't pass one. Kept small so the menu
+// stays scannable.
+const FALLBACK_VOICES = [
+ { id: 'nova', name: 'Nova' },
+ { id: 'alloy', name: 'Alloy' },
+ { id: 'fable', name: 'Fable' },
+];
+
+const SPEEDS = [0.75, 1, 1.25, 1.5];
+
+export class ChapterPanel {
+ constructor(curriculum, handlers, voices) {
+ this.curriculum = curriculum;
+ this.handlers = handlers; // { onJump(abs), onTrack, onVoice, onSpeed, onOpenChange }
+ this.voices = Array.isArray(voices) && voices.length ? voices : FALLBACK_VOICES;
+ 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 = this.voices
+ .map((v) => `<option value="${esc(v.id)}">${esc(v.name)}</option>`)
+ .join('');
+ }
+
+ _buildList() {
+ const { sections = [], stops } = this.curriculum;
+ const q = this._query;
+ const rows = [];
+ // Stops whose section isn't declared in `sections` still need a home, so
+ // render any leftover sections referenced only by stops, in first-seen order.
+ const sectionList = sections.length ? sections : inferSections(stops);
+ for (const section of sectionList) {
+ 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;
+ }
+}
+
+// Derive section headers from the stops themselves when a curriculum omits the
+// top-level `sections` array — first-seen order, titled by the section id.
+function inferSections(stops) {
+ const seen = new Map();
+ for (const s of stops) {
+ const id = s.section || 'tour';
+ if (!seen.has(id)) seen.set(id, { id, title: titleCase(id) });
+ }
+ return [...seen.values()];
+}
+
+function titleCase(id) {
+ return String(id || '')
+ .replace(/[-_]+/g, ' ')
+ .replace(/\b\w/g, (c) => c.toUpperCase());
+}
+
+function esc(s) {
+ return String(s == null ? '' : s).replace(
+ /[&<>"']/g,
+ (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[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/tour-sdk/src/config.js b/tour-sdk/src/config.js
new file mode 100644
index 000000000..ffed96638
--- /dev/null
+++ b/tour-sdk/src/config.js
@@ -0,0 +1,122 @@
+// Configuration resolution for @three-ws/tour.
+// ============================================
+// One options object flows from createFeatureTour() to the director and every
+// sub-module. Defaults are brand-neutral and degrade gracefully — a tour with no
+// options still runs (it fetches /tour/curriculum.json, paces captions to the
+// text when no TTS endpoint is wired, and navigates with location.assign). Every
+// host-specific concern — where the curriculum lives, how speech is synthesized,
+// how pages navigate, what the guide looks like, and the closing copy — is an
+// option you override, never a value baked into the engine.
+
+// Built-in narration voices offered in the chapter panel's voice picker. These
+// ids match the common OpenAI-compatible TTS voice set; a host whose endpoint
+// speaks a different catalogue passes its own `voices`.
+export const DEFAULT_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' },
+];
+
+// Neutral closing/recovery copy. Every string is overridable via opts.copy so a
+// host can speak in its own voice without touching the engine.
+export const DEFAULT_COPY = {
+ // Spoken once at the very end, before the completion card appears.
+ outro:
+ "And that's the tour. Thanks for walking through it with me — explore on your own whenever you're ready.",
+ // Spoken when the visitor hand-navigates off the tour route.
+ offRoute:
+ 'We stepped off the tour — press play and I’ll take you back to where we were.',
+ completion: {
+ title: 'Tour complete 🎉',
+ body: "That's the whole tour. Where to next?",
+ // Optional primary call-to-action button. Omitted when null.
+ primary: null, // e.g. { label: 'Get started', href: '/start' }
+ restartLabel: 'Take it again',
+ closeLabel: 'Explore on my own',
+ },
+};
+
+function isObject(v) {
+ return v != null && typeof v === 'object';
+}
+
+// Deep-ish merge for the copy block only (one level of nesting: completion).
+function resolveCopy(opts = {}) {
+ const copy = { ...DEFAULT_COPY, ...opts };
+ copy.completion = { ...DEFAULT_COPY.completion, ...(opts.completion || {}) };
+ return copy;
+}
+
+/**
+ * Resolve caller options into the fully-defaulted config the engine runs on.
+ *
+ * @param {object} [opts]
+ * @param {string|object} [opts.curriculum] URL to fetch the curriculum from,
+ * or an already-loaded curriculum object. Default '/tour/curriculum.json'.
+ * @param {string|null} [opts.ttsEndpoint] POST endpoint that turns
+ * `{ text, voice, speed, format }` into an audio response. When null
+ * (the default) narration plays as silent captions paced to the text.
+ * @param {string} [opts.defaultVoice] Default narration voice id.
+ * @param {Array<{id,name}>} [opts.voices] Voice catalogue for the picker.
+ * @param {string} [opts.guideAvatarId] Avatar id the guide loads by default.
+ * @param {string} [opts.assetBase] Base URL for avatar GLB assets.
+ * @param {string} [opts.apiBase] Base URL for the avatar GLB proxy.
+ * @param {string} [opts.manifestUrl] Shared-animation manifest URL.
+ * @param {string} [opts.avatarStorageKey] localStorage key holding the
+ * visitor's chosen avatar (defaults to the @three-ws/walk companion key,
+ * so the guide matches whoever they walk with).
+ * @param {(path:string)=>void} [opts.navigate] How to move to another route.
+ * @param {string} [opts.deepLinkParam] Query param that opens the tour.
+ * @param {boolean|object} [opts.companion] Walk-companion de-dupe integration.
+ * false disables it; an object customises the change-event name.
+ * @param {string} [opts.storagePrefix] Prefix for tour state storage keys.
+ * @param {object} [opts.copy] Override outro / off-route /
+ * completion strings.
+ * @returns {object} the resolved config
+ */
+export function resolveTourConfig(opts = {}) {
+ const prefix = opts.storagePrefix || 'tws:tour';
+ const companion =
+ opts.companion === false
+ ? null
+ : {
+ // The global object @three-ws/walk exposes its companion through.
+ global: (isObject(opts.companion) && opts.companion.global) || '__walkCompanion',
+ // The event it dispatches when it mounts/unmounts.
+ changeEvent:
+ (isObject(opts.companion) && opts.companion.changeEvent) || 'walk-companion:change',
+ };
+
+ return {
+ curriculum: opts.curriculum ?? '/tour/curriculum.json',
+ ttsEndpoint: opts.ttsEndpoint === undefined ? null : opts.ttsEndpoint,
+ defaultVoice: opts.defaultVoice || 'nova',
+ voices: Array.isArray(opts.voices) && opts.voices.length ? opts.voices : DEFAULT_VOICES,
+
+ guideAvatarId: opts.guideAvatarId || 'realistic-female',
+ assetBase: opts.assetBase || '',
+ apiBase: opts.apiBase || '',
+ manifestUrl: opts.manifestUrl || '/animations/manifest.json',
+ avatarStorageKey: opts.avatarStorageKey || 'walk:companion:avatar',
+
+ navigate:
+ typeof opts.navigate === 'function'
+ ? opts.navigate
+ : (path) => {
+ location.assign(path);
+ },
+ deepLinkParam: opts.deepLinkParam || 'tour',
+ companion,
+
+ copy: resolveCopy(opts.copy),
+
+ keys: {
+ state: `${prefix}:state`, // live, per-tab tour (sessionStorage)
+ resume: `${prefix}:resume`, // durable cross-session memory (localStorage)
+ },
+ };
+}
diff --git a/tour-sdk/src/controls.js b/tour-sdk/src/controls.js
new file mode 100644
index 000000000..1615c74f1
--- /dev/null
+++ b/tour-sdk/src/controls.js
@@ -0,0 +1,156 @@
+// controls.js — the tour's playback bar: chapter + progress readout, a
+// clickable scrub track, and previous / play-pause / next / mute / exit. It is
+// pure UI — every button forwards to a handler the director supplies, and the
+// director calls back into update()/setPaused()/setMuted() to keep it in sync.
+
+const Z_CONTROLS = 2147483400;
+
+export class TourControls {
+ constructor(handlers) {
+ this.handlers = handlers; // { onPrev, onNext, onToggle, onSeek, onMute, onExit }
+ ensureStyles();
+ this._build();
+ }
+
+ _build() {
+ const bar = document.createElement('div');
+ bar.className = 'tws-tour-bar';
+ 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>
+ <div class="tws-tour-meta">
+ <div class="tws-tour-meta__top"><span class="tws-tour-chapter"></span><span class="tws-tour-count"></span></div>
+ <div class="tws-tour-track" role="slider" aria-label="Tour progress" tabindex="0" aria-valuemin="1" aria-valuemax="1" aria-valuenow="1">
+ <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="roam" aria-label="Free roam — drive the guide yourself" title="Free roam" aria-pressed="false">🧭</button>
+ <button class="tws-tour-btn" data-act="mute" aria-label="Mute narration" title="Mute / unmute voice">🔊</button>
+ <button class="tws-tour-btn tws-tour-btn--exit" data-act="exit" aria-label="Exit tour" title="Exit tour">✕</button>
+ `;
+ 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.roamBtn = bar.querySelector('[data-act="roam"]');
+ this.chapterEl = bar.querySelector('.tws-tour-chapter');
+ this.countEl = bar.querySelector('.tws-tour-count');
+ this.track = bar.querySelector('.tws-tour-track');
+ this.fill = bar.querySelector('.tws-tour-track__fill');
+
+ bar.addEventListener('click', (e) => {
+ const act = e.target.closest('[data-act]')?.dataset.act;
+ if (!act) return;
+ 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 === 'roam') this.handlers.onRoam?.();
+ else if (act === 'mute') this.handlers.onMute?.();
+ else if (act === 'exit') this.handlers.onExit?.();
+ });
+ this.track.addEventListener('click', (e) => this._seekFromEvent(e));
+ this.track.addEventListener('keydown', (e) => {
+ if (e.key === 'ArrowRight') this.handlers.onNext?.();
+ else if (e.key === 'ArrowLeft') this.handlers.onPrev?.();
+ });
+ requestAnimationFrame(() => bar.classList.add('is-in'));
+ }
+
+ _seekFromEvent(e) {
+ const rect = this.track.getBoundingClientRect();
+ const frac = clamp((e.clientX - rect.left) / rect.width, 0, 1);
+ const total = this._total || 1;
+ const index = Math.round(frac * (total - 1));
+ this.handlers.onSeek?.(index);
+ }
+
+ update({ chapter, index, total }) {
+ this._total = total;
+ this.chapterEl.textContent = chapter || '';
+ this.countEl.textContent = `${index + 1} / ${total}`;
+ const frac = total > 1 ? index / (total - 1) : 1;
+ this.fill.style.width = (frac * 100).toFixed(1) + '%';
+ this.track.setAttribute('aria-valuemax', String(total));
+ this.track.setAttribute('aria-valuenow', String(index + 1));
+ this.track.setAttribute('aria-valuetext', `${chapter}, feature ${index + 1} of ${total}`);
+ }
+
+ setPaused(paused) {
+ this.playBtn.textContent = paused ? '▶' : '⏸';
+ this.playBtn.setAttribute('aria-label', paused ? 'Resume tour' : 'Pause tour');
+ this.bar.classList.toggle('is-paused', paused);
+ }
+
+ setMuted(muted) {
+ this.muteBtn.textContent = muted ? '🔇' : '🔊';
+ 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);
+ }
+
+ setRoam(on) {
+ this.roamBtn.setAttribute('aria-pressed', on ? 'true' : 'false');
+ this.roamBtn.classList.toggle('is-active', on);
+ this.roamBtn.setAttribute('title', on ? 'Rejoin the tour' : 'Free roam');
+ this.bar.classList.toggle('is-roaming', on);
+ }
+
+ dispose() {
+ this.bar?.remove();
+ this.bar = null;
+ }
+}
+
+function clamp(n, lo, hi) {
+ return Math.min(hi, Math.max(lo, n));
+}
+
+let _stylesInjected = false;
+function ensureStyles() {
+ if (_stylesInjected) return;
+ _stylesInjected = true;
+ const style = document.createElement('style');
+ style.id = 'tws-tour-bar-style';
+ style.textContent = `
+.tws-tour-bar{position:fixed;left:50%;bottom:18px;transform:translateX(-50%) translateY(14px);z-index:${Z_CONTROLS};display:flex;align-items:center;gap:8px;padding:8px 12px;background:rgba(14,16,22,.92);backdrop-filter:blur(10px);border:1px solid rgba(255,255,255,.1);border-radius:16px;box-shadow:0 16px 40px rgba(0,0,0,.45);opacity:0;transition:opacity .35s ease,transform .35s ease;font-family:system-ui,-apple-system,'Segoe UI',sans-serif;max-width:min(560px,calc(100vw - 24px))}
+.tws-tour-bar.is-in{opacity:1;transform:translateX(-50%) translateY(0)}
+.tws-tour-btn{appearance:none;border:none;background:rgba(255,255,255,.06);color:#eef1f6;width:36px;height:36px;border-radius:10px;font-size:15px;line-height:1;cursor:pointer;display:grid;place-items:center;transition:background .18s ease,transform .12s ease}
+.tws-tour-btn:hover{background:rgba(122,162,255,.22)}
+.tws-tour-btn:active{transform:scale(.92)}
+.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}
+.tws-tour-chapter{color:#aeb6c6;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
+.tws-tour-count{color:#7f8aa0;font-variant-numeric:tabular-nums;white-space:nowrap}
+.tws-tour-track{position:relative;height:6px;border-radius:99px;background:rgba(255,255,255,.12);cursor:pointer}
+.tws-tour-track:focus-visible{outline:2px solid #7aa2ff;outline-offset:3px}
+.tws-tour-track__fill{position:absolute;left:0;top:0;height:100%;border-radius:99px;background:linear-gradient(90deg,#7aa2ff,#9d7bff);transition:width .4s ease}
+@media (max-width:560px){.tws-tour-meta{min-width:96px}.tws-tour-chapter{max-width:120px}}
+@media (prefers-reduced-motion:reduce){.tws-tour-bar,.tws-tour-track__fill{transition:opacity .2s ease}}
+`;
+ document.head.appendChild(style);
+}
diff --git a/tour-sdk/src/curriculum.js b/tour-sdk/src/curriculum.js
new file mode 100644
index 000000000..a102e530f
--- /dev/null
+++ b/tour-sdk/src/curriculum.js
@@ -0,0 +1,156 @@
+// curriculum.js — load the tour curriculum and own the cross-page tour state.
+// ===========================================================================
+// The curriculum (what the guide visits + says) is a plain JSON document — see
+// curriculum.schema.json. A host supplies it as a URL to fetch or an inline
+// object (config.curriculum). The live state (active? which stop? paused?
+// muted?) lives in sessionStorage so the tour survives a full-page navigation
+// between stops on different routes; durable progress/preferences live in
+// localStorage so a returning visitor can pick the tour back up.
+//
+// The pure helpers (normalizePath, buildPlaylist, trackMeta, stopIndexForPath,
+// sectionTitle) operate on a curriculum object and hold no state, so the
+// sequencing logic and tests can use them freely. The IO/state surface is bound
+// to a host's config through createTourState() / loadCurriculum().
+
+let _cache = null;
+
+// Load the curriculum from config.curriculum — either an inline object (used as
+// is) or a URL to fetch (cached after the first successful load).
+export async function loadCurriculum(config) {
+ const source = config?.curriculum ?? '/tour/curriculum.json';
+ if (source && typeof source === 'object') {
+ assertCurriculum(source);
+ return source;
+ }
+ if (_cache) return _cache;
+ const res = await fetch(source, { cache: 'force-cache' });
+ if (!res.ok) throw new Error(`tour curriculum ${res.status}`);
+ const data = await res.json();
+ assertCurriculum(data);
+ _cache = data;
+ return data;
+}
+
+function assertCurriculum(data) {
+ if (!data || !Array.isArray(data.stops) || !data.stops.length) {
+ throw new Error('tour curriculum empty');
+ }
+}
+
+// Normalize a pathname to match curriculum stop paths ("/" stays "/", others
+// lose any trailing slash). Query and hash are irrelevant to which stop we're on.
+export function normalizePath(pathname = location.pathname) {
+ const p = pathname.replace(/\/+$/, '');
+ return p === '' ? '/' : p;
+}
+
+const DEFAULT_STATE = {
+ active: false,
+ index: 0,
+ track: 'full',
+ paused: false,
+ muted: false,
+ voice: 'nova',
+ speed: 1,
+};
+
+const DEFAULT_RESUME = { index: 0, track: 'full', voice: 'nova', speed: 1, completed: false };
+
+// Bind the per-host state surface to its storage keys + default voice. Returns
+// the same read/write/clear functions the director relies on, scoped so two
+// tours with different storagePrefixes never collide.
+export function createTourState(config) {
+ const STATE_KEY = config.keys.state;
+ const RESUME_KEY = config.keys.resume;
+ const baseState = { ...DEFAULT_STATE, voice: config.defaultVoice };
+ const baseResume = { ...DEFAULT_RESUME, voice: config.defaultVoice };
+
+ function readResume() {
+ try {
+ const raw = localStorage.getItem(RESUME_KEY);
+ if (!raw) return { ...baseResume };
+ return { ...baseResume, ...JSON.parse(raw) };
+ } catch {
+ return { ...baseResume };
+ }
+ }
+
+ 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;
+ }
+
+ function readState() {
+ try {
+ const raw = sessionStorage.getItem(STATE_KEY);
+ if (!raw) return { ...baseState };
+ return { ...baseState, ...JSON.parse(raw) };
+ } catch {
+ return { ...baseState };
+ }
+ }
+
+ function writeState(patch) {
+ const next = { ...readState(), ...patch };
+ try {
+ sessionStorage.setItem(STATE_KEY, JSON.stringify(next));
+ } 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;
+ }
+
+ function clearState() {
+ try {
+ sessionStorage.removeItem(STATE_KEY);
+ } catch {
+ /* ignore */
+ }
+ }
+
+ function markCompleted() {
+ writeResume({ completed: true, index: 0 });
+ }
+
+ return { readState, writeState, clearState, readResume, writeResume, markCompleted };
+}
+
+// ── 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) {
+ const target = normalizePath(pathname);
+ return curriculum.stops.findIndex((s) => normalizePath(s.path) === target);
+}
+
+export function sectionTitle(curriculum, id) {
+ return (curriculum.sections || []).find((s) => s.id === id)?.title || '';
+}
diff --git a/tour-sdk/src/director.js b/tour-sdk/src/director.js
new file mode 100644
index 000000000..e42e4ee1d
--- /dev/null
+++ b/tour-sdk/src/director.js
@@ -0,0 +1,669 @@
+// director.js — the brain of the tour. It walks the curriculum stop by stop:
+// for each one it finds the real on-page element to showcase, spotlights it,
+// walks the guide avatar over to point at it, draws a beam from the avatar to
+// the feature, speaks the narration, and — unless paused — advances. When 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,
+ createTourState,
+ buildPlaylist,
+ normalizePath,
+ stopIndexForPath,
+ sectionTitle,
+} from './curriculum.js';
+import { resolveTourConfig } from './config.js';
+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';
+import { FreeRoam } from './free-roam.js';
+
+const ADVANCE_BEAT_MS = 900; // pause between finishing a stop and moving on
+const Z_BEAM = 2147483280;
+const SPEED_CYCLE = [1, 1.25, 1.5, 0.75];
+
+export class TourDirector {
+ constructor(config) {
+ this.config = config && config.keys ? config : resolveTourConfig(config);
+ this.state = createTourState(this.config);
+ this.curriculum = null;
+ this.playlist = [];
+ this.pos = 0;
+ this.index = 0;
+ this.track = 'full';
+ this.paused = false;
+ this.muted = false;
+ this.voice = this.config.defaultVoice;
+ this.speed = 1;
+ this.mounted = false;
+ this.offRoute = false;
+ this.roam = false;
+ this._runToken = 0;
+ this._advanceTimer = 0;
+ this._seenSections = new Set();
+ this._beamRaf = 0;
+ this._beamActive = false;
+ this._onKey = this._onKey.bind(this);
+ }
+
+ // ── Entry points ──────────────────────────────────────────────────────────
+
+ // Begin a fresh tour from the very first stop (called by the host's "Start
+ // tour" action / the deep-link). `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();
+ const prefs = this.state.readResume();
+ this.track = track || 'full';
+ this.voice = prefs.voice || this.config.defaultVoice;
+ this.speed = prefs.speed || 1;
+ this.muted = false;
+ this.paused = false;
+ this._seenSections = new Set();
+ this.playlist = buildPlaylist(this.curriculum, this.track);
+ this.pos = 0;
+ this.index = this.playlist[0] ?? 0;
+ this.state.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;
+ }
+ await this._mount();
+ this._runCurrent();
+ }
+
+ // Re-hydrate on a normal page load when a tour is already in progress.
+ async resume() {
+ const state = this.state.readState();
+ if (!state.active) return;
+ await this._ensureCurriculum();
+ this.paused = state.paused;
+ this.muted = state.muted;
+ this.voice = state.voice || this.config.defaultVoice;
+ 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;
+ if (normalizePath(this.curriculum.stops[wanted]?.path) === normalizePath()) {
+ this.index = wanted; // arrived exactly where we were heading
+ this.offRoute = false;
+ } else if (here >= 0) {
+ this.index = here; // visitor hand-navigated to another stop's page
+ this.offRoute = false;
+ this.state.writeState({ index: here });
+ } else {
+ this.index = wanted; // wandered off the route entirely
+ this.offRoute = true;
+ }
+ this.pos = this._posForAbs(this.index);
+
+ await this._mount();
+ if (this.offRoute) {
+ this._showOffRoute();
+ } else {
+ this._runCurrent();
+ }
+ }
+
+ async _ensureCurriculum() {
+ if (!this.curriculum) this.curriculum = await loadCurriculum(this.config);
+ }
+
+ // ── Mounting ──────────────────────────────────────────────────────────────
+ async _mount() {
+ if (this.mounted) return;
+ this.mounted = true;
+ // A companion avatar (e.g. the @three-ws/walk corner mascot) would just be a
+ // second body on screen during the tour, so stand it down (and its
+ // click-to-walk, which would otherwise fight free roam) and bring it back
+ // when the tour ends.
+ this._suppressCompanion();
+ this._buildBeam();
+ this.spotlight = new Spotlight();
+ this.narrator = new Narrator(this.config);
+ this.avatar = new GuideAvatar(this.config);
+ await this.avatar.mount();
+ this.freeRoam = new FreeRoam(this.avatar);
+ this.controls = new TourControls({
+ onMenu: () => this.panel?.toggle(),
+ onPrev: () => this._go(this.pos - 1),
+ onNext: () => this._go(this.pos + 1),
+ onToggle: () => this._togglePause(),
+ onSeek: (i) => this._go(i),
+ onSpeed: () => this._cycleSpeed(),
+ onRoam: () => this._toggleRoam(),
+ 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.config.voices,
+ );
+ 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);
+ }
+
+ // ── Running a stop ────────────────────────────────────────────────────────
+ async _runCurrent() {
+ const token = ++this._runToken;
+ clearTimeout(this._advanceTimer);
+ this.offRoute = false;
+ const stop = this.curriculum.stops[this.index];
+ if (!stop) return this._finish();
+
+ this._syncControls();
+ this.panel?.setActive(this.index);
+ this.state.writeState({ index: this.index });
+
+ // Chapter bridge — spoken once per section per session.
+ if (stop.sectionIntro && !this._seenSections.has(stop.section)) {
+ this._seenSections.add(stop.section);
+ await this.avatar.park();
+ if (token !== this._runToken) return;
+ this.avatar.point();
+ await this._present(stop.sectionIntro, token);
+ if (token !== this._runToken) return;
+ }
+
+ // Move to the feature and point at it.
+ const target = this._resolveTarget(stop);
+ if (target) {
+ await this.spotlight.highlight(target);
+ if (token !== this._runToken) return;
+ await this.avatar.approach(this.spotlight.getRect() || rectOf(target));
+ if (token !== this._runToken) return;
+ this._startBeam();
+ } else {
+ this.spotlight.highlight(null);
+ this._stopBeam();
+ await this.avatar.park();
+ if (token !== this._runToken) return;
+ }
+ this.avatar.point();
+
+ await this._narrateAndMaybeAdvance(token);
+ }
+
+ async _narrateAndMaybeAdvance(token) {
+ await this._present(this.curriculum.stops[this.index].narration, token);
+ if (token !== this._runToken) return;
+ if (this.paused) return;
+ this._advanceTimer = setTimeout(() => {
+ if (token === this._runToken) this._advance();
+ }, 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, speed: this.speed });
+ }
+
+ _advance() {
+ if (this.pos + 1 >= this.playlist.length) return this._finish();
+ this._go(this.pos + 1);
+ }
+
+ // 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;
+ if (this.roam) {
+ // Any explicit navigation leaves free roam and resumes the guided tour.
+ this.roam = false;
+ this.freeRoam?.disable();
+ this.controls?.setRoam(false);
+ }
+ const clamped = Math.max(0, Math.min(this.playlist.length - 1, pos));
+ this._runToken++;
+ clearTimeout(this._advanceTimer);
+ this.narrator?.cancel();
+ this.pos = clamped;
+ this.index = this.playlist[clamped];
+ this.state.writeState({ index: this.index });
+ this.panel?.setActive(this.index);
+ const stop = this.curriculum.stops[this.index];
+ if (normalizePath(stop.path) === normalizePath()) {
+ this._runCurrent();
+ } else {
+ this._navigate(stop.path);
+ }
+ }
+
+ // 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() {
+ if (this.roam) return this._exitRoam(); // play rejoins the tour from roam
+ this.paused = !this.paused;
+ this.state.writeState({ paused: this.paused });
+ this.controls.setPaused(this.paused);
+ if (this.paused) {
+ clearTimeout(this._advanceTimer);
+ this.narrator.cancel();
+ this._runToken++; // freeze the current sequence
+ } else if (this.offRoute) {
+ this._go(this.pos);
+ } else {
+ // Resume re-narrates the current stop, then continues.
+ const token = ++this._runToken;
+ this._narrateAndMaybeAdvance(token);
+ }
+ }
+
+ _toggleMute() {
+ this.muted = !this.muted;
+ this.state.writeState({ muted: this.muted });
+ this.controls.setMuted(this.muted);
+ this.narrator.cancel();
+ if (!this.paused) {
+ const token = ++this._runToken;
+ this._narrateAndMaybeAdvance(token);
+ }
+ }
+
+ // ── 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];
+ this.state.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;
+ this.state.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;
+ this.state.writeState({ voice: value });
+ this.panel?.setVoice(value);
+ if (!this.paused && !this.offRoute && this.mounted) {
+ const token = ++this._runToken;
+ this._narrateAndMaybeAdvance(token);
+ }
+ }
+
+ // ── Free roam ───────────────────────────────────────────────────────────────
+ // Hand the stage to the visitor: freeze the guided sequence and let them drive
+ // the guide around the page (free-roam.js). Toggling off — or any navigation /
+ // play — rejoins the tour at the current stop.
+ _toggleRoam() {
+ this.roam ? this._exitRoam() : this._enterRoam();
+ }
+
+ _enterRoam() {
+ if (this.roam) return;
+ this.roam = true;
+ this._runToken++; // freeze whatever the guide was doing
+ clearTimeout(this._advanceTimer);
+ this.narrator?.cancel();
+ this._stopBeam();
+ this.spotlight?.highlight(null);
+ this.avatar?.hideBubble();
+ this.panel?.close();
+ this.controls?.setRoam(true);
+ this.freeRoam?.enable();
+ }
+
+ _exitRoam() {
+ if (!this.roam) return;
+ this.roam = false;
+ this.freeRoam?.disable();
+ this.controls?.setRoam(false);
+ // Rejoining the tour means playing again from the current stop.
+ this.paused = false;
+ this.controls?.setPaused(false);
+ this.state.writeState({ paused: false });
+ this._go(this.pos);
+ }
+
+ // ── Companion suppression (de-dupe the on-screen avatar) ─────────────────────
+ _suppressCompanion() {
+ const cfg = this.config.companion;
+ if (!cfg) return;
+ const w = window[cfg.global];
+ if (!w) return;
+ this._companionWasOn = !!(w.instance?.mounted || (w.isEnabled && w.isEnabled()));
+ const hide = () => {
+ try {
+ if (w.instance?.mounted) w.instance.unmount();
+ } catch {
+ /* companion mid-mount — the change listener will catch it */
+ }
+ };
+ hide();
+ // The companion auto-mounts on load (and on playground return); re-hide it
+ // whenever it reappears while the tour owns the screen.
+ this._onCompanionChange = hide;
+ window.addEventListener(cfg.changeEvent, this._onCompanionChange);
+ }
+
+ _restoreCompanion() {
+ const cfg = this.config.companion;
+ if (cfg && this._onCompanionChange) {
+ window.removeEventListener(cfg.changeEvent, this._onCompanionChange);
+ this._onCompanionChange = null;
+ }
+ if (!cfg) return;
+ const w = window[cfg.global];
+ if (!w || !this._companionWasOn) return;
+ try {
+ if (!w.instance?.mounted) (w.instance ? w.instance.mount() : w.enable?.());
+ } catch {
+ /* non-fatal — the companion will re-mount on the next page load */
+ }
+ }
+
+ // Playlist position for an absolute stop index — exact match, else nearest.
+ _posForAbs(abs) {
+ const p = this.playlist.indexOf(abs);
+ 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();
+ this.spotlight.highlight(null);
+ this.avatar.park();
+ this.paused = true;
+ this.state.writeState({ paused: true });
+ this.controls.setPaused(true);
+ this._syncControls();
+ this.panel?.setActive(this.index);
+ this.avatar.say(this.config.copy.offRoute);
+ }
+
+ // ── Finish ────────────────────────────────────────────────────────────────
+ async _finish() {
+ const token = ++this._runToken;
+ this._stopBeam();
+ this.spotlight.highlight(null);
+ await this.avatar.park();
+ this.avatar.point();
+ await this._present(this.config.copy.outro, token);
+ this.state.markCompleted();
+ this.state.clearState();
+ this._showCompletion();
+ }
+
+ _showCompletion() {
+ const done = this.config.copy.completion;
+ const card = document.createElement('div');
+ card.className = 'tws-tour-done';
+ const primary = done.primary
+ ? `<a class="tws-tour-done__btn tws-tour-done__btn--primary" href="${escAttr(done.primary.href)}">${escHtml(done.primary.label)}</a>`
+ : '';
+ card.innerHTML = `
+ <div class="tws-tour-done__inner" role="dialog" aria-label="Tour complete">
+ <div class="tws-tour-done__title">${escHtml(done.title)}</div>
+ <p class="tws-tour-done__body">${escHtml(done.body)}</p>
+ <div class="tws-tour-done__actions">
+ ${primary}
+ <button class="tws-tour-done__btn" data-act="restart">${escHtml(done.restartLabel)}</button>
+ <button class="tws-tour-done__btn" data-act="close">${escHtml(done.closeLabel)}</button>
+ </div>
+ </div>`;
+ ensureDoneStyles();
+ document.body.appendChild(card);
+ requestAnimationFrame(() => card.classList.add('is-in'));
+ card.addEventListener('click', (e) => {
+ const act = e.target.closest('[data-act]')?.dataset.act;
+ if (act === 'restart') {
+ card.remove();
+ this.start(this.track);
+ } else if (act === 'close') {
+ card.remove();
+ this.exit();
+ }
+ });
+ this._doneCard = card;
+ }
+
+ // ── Teardown ──────────────────────────────────────────────────────────────
+ exit() {
+ this._runToken++;
+ clearTimeout(this._advanceTimer);
+ this.state.clearState();
+ this._stopBeam();
+ this._beam?.remove();
+ document.removeEventListener('keydown', this._onKey);
+ this.roam = false;
+ this.freeRoam?.disable();
+ this.narrator?.dispose();
+ this.spotlight?.dispose();
+ this.avatar?.dispose();
+ this.controls?.dispose();
+ this.panel?.dispose();
+ this._doneCard?.remove();
+ this._restoreCompanion();
+ this.mounted = false;
+ }
+
+ // ── Target resolution ─────────────────────────────────────────────────────
+ _resolveTarget(stop) {
+ const selectors = [
+ ...(stop.targets || []),
+ '[data-tour-target]',
+ 'main h1, .hero h1, h1',
+ 'a.cta, .btn-primary, button[type="submit"], main a.button, .hero a',
+ ];
+ for (const sel of selectors) {
+ let el;
+ try {
+ el = document.querySelector(sel);
+ } catch {
+ continue;
+ }
+ if (isVisible(el)) return el;
+ }
+ return null;
+ }
+
+ // ── Pointer beam (avatar → feature) ───────────────────────────────────────
+ _buildBeam() {
+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
+ svg.setAttribute('class', 'tws-tour-beam');
+ svg.style.cssText = `position:fixed;inset:0;width:100vw;height:100vh;z-index:${Z_BEAM};pointer-events:none;opacity:0;transition:opacity .3s ease`;
+ svg.innerHTML = `
+ <defs>
+ <marker id="tws-tour-arrow" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
+ <path d="M0,0 L10,5 L0,10 z" fill="rgba(122,162,255,.95)"/>
+ </marker>
+ </defs>
+ <line class="tws-tour-beam__line" stroke="rgba(122,162,255,.9)" stroke-width="2.5" stroke-dasharray="2 7" stroke-linecap="round" marker-end="url(#tws-tour-arrow)"/>
+ `;
+ document.body.appendChild(svg);
+ this._beam = svg;
+ this._beamLine = svg.querySelector('.tws-tour-beam__line');
+ }
+
+ _startBeam() {
+ if (this._beamActive) return;
+ this._beamActive = true;
+ this._beam.style.opacity = '1';
+ const tick = () => {
+ if (!this._beamActive) return;
+ const rect = this.spotlight.getRect();
+ const head = this.avatar.headScreen();
+ if (rect && head) {
+ // Aim at the nearest edge of the feature, not dead-center, so the
+ // arrow lands on the box rather than burying itself inside it.
+ const tx = clamp(head.x, rect.left, rect.left + rect.width);
+ const ty = clamp(head.y, rect.top, rect.top + rect.height);
+ this._beamLine.setAttribute('x1', head.x);
+ this._beamLine.setAttribute('y1', head.y);
+ this._beamLine.setAttribute('x2', tx);
+ this._beamLine.setAttribute('y2', ty);
+ }
+ this._beamRaf = requestAnimationFrame(tick);
+ };
+ this._beamRaf = requestAnimationFrame(tick);
+ }
+
+ _stopBeam() {
+ this._beamActive = false;
+ cancelAnimationFrame(this._beamRaf);
+ if (this._beam) this._beam.style.opacity = '0';
+ }
+
+ // ── Misc ──────────────────────────────────────────────────────────────────
+ _syncControls() {
+ const stop = this.curriculum.stops[this.index];
+ this.controls.update({
+ chapter: sectionTitle(this.curriculum, stop.section),
+ index: this.pos,
+ total: this.playlist.length,
+ });
+ }
+
+ _navigate(path) {
+ // Progress is already persisted; the new page's bootstrap calls resume().
+ this.config.navigate(path);
+ }
+
+ _onKey(e) {
+ if (this.panel?.open) return; // the panel owns the keyboard while it's up
+ if (isTypingTarget(e.target)) return;
+ if (e.key === ' ' || e.key === 'k') {
+ e.preventDefault();
+ this._togglePause();
+ } else if (e.key === 'ArrowRight') {
+ this._go(this.pos + 1);
+ } else if (e.key === 'ArrowLeft') {
+ 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 === 'r' || e.key === 'R') {
+ this._toggleRoam();
+ } else if (e.key === 'Escape') {
+ if (this.roam) this._exitRoam();
+ else this.exit();
+ }
+ }
+}
+
+// ── helpers ──────────────────────────────────────────────────────────────────
+function clamp(n, lo, hi) {
+ return Math.min(hi, Math.max(lo, n));
+}
+function rectOf(el) {
+ const r = el.getBoundingClientRect();
+ return { left: r.left, top: r.top, width: r.width, height: r.height, cx: r.left + r.width / 2, cy: r.top + r.height / 2 };
+}
+function isVisible(el) {
+ if (!el || !el.isConnected) return false;
+ const r = el.getBoundingClientRect();
+ if (r.width < 4 || r.height < 4) return false;
+ const style = getComputedStyle(el);
+ return style.visibility !== 'hidden' && style.display !== 'none' && Number(style.opacity) > 0.05;
+}
+function isTypingTarget(el) {
+ if (!el) return false;
+ const tag = el.tagName;
+ return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || el.isContentEditable;
+}
+function escHtml(s) {
+ return String(s == null ? '' : s).replace(
+ /[&<>"']/g,
+ (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c],
+ );
+}
+function escAttr(s) {
+ return escHtml(s);
+}
+
+let _doneStyles = false;
+function ensureDoneStyles() {
+ if (_doneStyles) return;
+ _doneStyles = true;
+ const style = document.createElement('style');
+ style.textContent = `
+.tws-tour-done{position:fixed;inset:0;z-index:2147483500;display:grid;place-items:center;background:rgba(6,8,12,.6);backdrop-filter:blur(6px);opacity:0;transition:opacity .35s ease;font-family:system-ui,-apple-system,'Segoe UI',sans-serif}
+.tws-tour-done.is-in{opacity:1}
+.tws-tour-done__inner{background:#11141c;border:1px solid rgba(122,162,255,.25);border-radius:20px;padding:28px 30px;max-width:380px;text-align:center;box-shadow:0 30px 80px rgba(0,0,0,.5)}
+.tws-tour-done__title{font-size:22px;font-weight:700;color:#f2f4f8;margin-bottom:8px}
+.tws-tour-done__body{color:#aeb6c6;font-size:14px;line-height:1.5;margin:0 0 20px}
+.tws-tour-done__actions{display:flex;flex-direction:column;gap:10px}
+.tws-tour-done__btn{appearance:none;border:1px solid rgba(255,255,255,.14);background:rgba(255,255,255,.05);color:#eef1f6;padding:11px 16px;border-radius:11px;font-size:14px;font-weight:600;cursor:pointer;text-decoration:none;display:block;transition:background .18s ease,border-color .18s ease}
+.tws-tour-done__btn:hover{background:rgba(255,255,255,.1)}
+.tws-tour-done__btn--primary{background:linear-gradient(90deg,#7aa2ff,#9d7bff);color:#0b0e16;border-color:transparent}
+.tws-tour-done__btn--primary:hover{filter:brightness(1.06)}
+`;
+ document.head.appendChild(style);
+}
diff --git a/tour-sdk/src/free-roam.js b/tour-sdk/src/free-roam.js
new file mode 100644
index 000000000..7e42c69c3
--- /dev/null
+++ b/tour-sdk/src/free-roam.js
@@ -0,0 +1,177 @@
+// free-roam.js — hand the stage to the visitor. When the guided tour is paused
+// into "free roam", this lets you drive the guide around the page yourself:
+// · Click any empty patch of the page → the guide walks there.
+// · Grab the guide and drag it anywhere.
+// · Drag it to the top or bottom edge → the page scrolls under it, so you can
+// walk it up and down the whole document, not just the current viewport.
+// It reuses the GuideAvatar's own walk choreography (walkTo / place / settle),
+// so the rig animates and faces its heading exactly as it does on the tour.
+//
+// Activation mirrors the corner companion's click-to-walk contract: we listen in
+// the capture phase but only ever act on empty space (never links, buttons,
+// inputs, canvases or [data-walk-block]) and never call preventDefault on a real
+// page interaction — so normal clicking is provably untouched. Dragging the
+// guide itself does preventDefault, because the guide has no page behaviour to
+// preserve.
+
+const EDGE = 96; // px band at top/bottom of the viewport that auto-scrolls
+const SCROLL_MAX = 22; // px per frame at the very edge
+const RIPPLE_MS = 600;
+const Z_FX = 2147483090; // under the spotlight (…100), over the page
+
+// Elements whose clicks belong to the page, never to "walk there".
+const INTERACTIVE = 'a,button,input,textarea,select,label,summary,[role="button"],[contenteditable],[contenteditable="true"],canvas,video,iframe,[data-walk-block]';
+
+export function isInteractiveTarget(el) {
+ return !!(el && el.closest && el.closest(INTERACTIVE));
+}
+
+export class FreeRoam {
+ constructor(avatar) {
+ this.avatar = avatar;
+ this.enabled = false;
+ this.dragging = false;
+ this._grab = { x: 0, y: 0 };
+ this._ptr = { x: 0, y: 0 };
+ this._scrollRaf = 0;
+ this._reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;
+ this._onDown = this._onDown.bind(this);
+ this._onMove = this._onMove.bind(this);
+ this._onUp = this._onUp.bind(this);
+ ensureStyles();
+ }
+
+ enable() {
+ if (this.enabled) return;
+ this.enabled = true;
+ this.avatar.setInteractive(true);
+ document.addEventListener('pointerdown', this._onDown, true);
+ this._hint = makeHint();
+ }
+
+ disable() {
+ if (!this.enabled) return;
+ this.enabled = false;
+ this._endDrag();
+ document.removeEventListener('pointerdown', this._onDown, true);
+ this.avatar.setInteractive(false);
+ this.avatar.settle();
+ this._hint?.remove();
+ this._hint = null;
+ }
+
+ // ── Pointer handling ────────────────────────────────────────────────────────
+ _onDown(e) {
+ if (!this.enabled || e.button !== 0 || e.altKey || e.metaKey || e.ctrlKey || e.shiftKey) return;
+ const host = this.avatar.host;
+ if (host && host.contains(e.target)) {
+ // Grab the guide itself → drag.
+ const r = host.getBoundingClientRect();
+ this._grab = { x: e.clientX - r.left, y: e.clientY - r.top };
+ this._ptr = { x: e.clientX, y: e.clientY };
+ this.dragging = true;
+ document.addEventListener('pointermove', this._onMove, true);
+ document.addEventListener('pointerup', this._onUp, true);
+ document.addEventListener('pointercancel', this._onUp, true);
+ this._startScrollLoop();
+ this._dismissHint();
+ e.preventDefault();
+ return;
+ }
+ if (isInteractiveTarget(e.target)) return; // leave real page clicks alone
+ // Click on empty space → walk the guide there, centered under the click.
+ const s = this.avatar.size();
+ this.avatar.walkTo({ x: e.clientX - s.w / 2, y: e.clientY - s.h / 2 });
+ if (!this._reduced) ripple(e.clientX, e.clientY);
+ this._dismissHint();
+ }
+
+ _onMove(e) {
+ if (!this.dragging) return;
+ this._ptr = { x: e.clientX, y: e.clientY };
+ this.avatar.place({ x: e.clientX - this._grab.x, y: e.clientY - this._grab.y });
+ }
+
+ _onUp() {
+ this._endDrag();
+ }
+
+ _endDrag() {
+ cancelAnimationFrame(this._scrollRaf);
+ this._scrollRaf = 0;
+ if (!this.dragging) return;
+ this.dragging = false;
+ document.removeEventListener('pointermove', this._onMove, true);
+ document.removeEventListener('pointerup', this._onUp, true);
+ document.removeEventListener('pointercancel', this._onUp, true);
+ this.avatar.settle();
+ }
+
+ // While dragging near the top/bottom edge, scroll the page and keep the guide
+ // pinned under the pointer so it appears to walk the document up/down.
+ _startScrollLoop() {
+ if (this._reduced) return;
+ const tick = () => {
+ if (!this.dragging) return;
+ const y = this._ptr.y;
+ const h = window.innerHeight;
+ let dy = 0;
+ if (y < EDGE) dy = -SCROLL_MAX * (1 - y / EDGE);
+ else if (y > h - EDGE) dy = SCROLL_MAX * (1 - (h - y) / EDGE);
+ if (dy) {
+ window.scrollBy(0, dy);
+ this.avatar.place({ x: this._ptr.x - this._grab.x, y: this._ptr.y - this._grab.y });
+ }
+ this._scrollRaf = requestAnimationFrame(tick);
+ };
+ this._scrollRaf = requestAnimationFrame(tick);
+ }
+
+ _dismissHint() {
+ if (!this._hint) return;
+ this._hint.classList.remove('is-in');
+ const el = this._hint;
+ this._hint = null;
+ setTimeout(() => el.remove(), 300);
+ }
+}
+
+// ── FX ─────────────────────────────────────────────────────────────────────────
+function ripple(x, y) {
+ const r = document.createElement('div');
+ r.className = 'tws-roam-ripple';
+ r.style.left = x + 'px';
+ r.style.top = y + 'px';
+ document.body.appendChild(r);
+ setTimeout(() => r.remove(), RIPPLE_MS);
+}
+
+function makeHint() {
+ const h = document.createElement('div');
+ h.className = 'tws-roam-hint';
+ h.setAttribute('role', 'status');
+ h.innerHTML =
+ '<span class="tws-roam-hint__dot"></span>Free roam — click anywhere to walk me there, or drag me around. Press ▶ to rejoin the tour.';
+ document.body.appendChild(h);
+ requestAnimationFrame(() => h.classList.add('is-in'));
+ return h;
+}
+
+let _stylesInjected = false;
+function ensureStyles() {
+ if (_stylesInjected) return;
+ _stylesInjected = true;
+ const style = document.createElement('style');
+ style.id = 'tws-tour-roam-style';
+ style.textContent = `
+.tws-tour-guide.is-roam{pointer-events:auto;cursor:grab}
+.tws-tour-guide.is-roam:active{cursor:grabbing}
+.tws-roam-ripple{position:fixed;z-index:${Z_FX};width:14px;height:14px;margin:-7px 0 0 -7px;border-radius:50%;border:2px solid rgba(122,162,255,.9);pointer-events:none;animation:tws-roam-ripple ${RIPPLE_MS}ms ease-out forwards}
+@keyframes tws-roam-ripple{0%{transform:scale(.4);opacity:.9}100%{transform:scale(3.4);opacity:0}}
+.tws-roam-hint{position:fixed;left:50%;top:18px;transform:translateX(-50%) translateY(-12px);z-index:${Z_FX};display:flex;align-items:center;gap:9px;max-width:min(560px,92vw);padding:10px 16px;background:rgba(14,16,22,.94);backdrop-filter:blur(10px);border:1px solid rgba(122,162,255,.3);border-radius:99px;color:#e7eaf2;font:600 13px/1.3 system-ui,-apple-system,'Segoe UI',sans-serif;box-shadow:0 12px 34px rgba(0,0,0,.45);opacity:0;transition:opacity .3s ease,transform .3s ease;pointer-events:none}
+.tws-roam-hint.is-in{opacity:1;transform:translateX(-50%) translateY(0)}
+.tws-roam-hint__dot{width:8px;height:8px;border-radius:50%;background:linear-gradient(135deg,#7aa2ff,#9d7bff);box-shadow:0 0 10px rgba(122,162,255,.8);flex:0 0 auto}
+@media (prefers-reduced-motion:reduce){.tws-roam-hint{transition:opacity .2s ease}.tws-roam-ripple{display:none}}
+`;
+ document.head.appendChild(style);
+}
diff --git a/tour-sdk/src/guide-avatar.js b/tour-sdk/src/guide-avatar.js
new file mode 100644
index 000000000..d844b8cf0
--- /dev/null
+++ b/tour-sdk/src/guide-avatar.js
@@ -0,0 +1,390 @@
+// guide-avatar.js — the tour guide's body. A small, always-on-top 3D avatar
+// that walks across the viewport to stand beside whatever the tour is showing,
+// turns to face it, gestures at it, and carries a speech bubble above its head.
+//
+// It reuses the published @three-ws/walk avatar loader (loadWalkAvatar) so the
+// guide is the same rig family the Walk Companion drives and can never freeze in
+// a bind/T-pose, and the same simple controller surface — setState('walk' |
+// 'idle') + playWave() — drives the walk-in and the point gesture. By default it
+// reads the visitor's chosen companion avatar (config.avatarStorageKey), so the
+// guide matches whoever they walk with; otherwise it loads config.guideAvatarId.
+
+import {
+ AmbientLight,
+ Box3,
+ Timer,
+ DirectionalLight,
+ Group,
+ HemisphereLight,
+ PerspectiveCamera,
+ Scene,
+ Vector3,
+ WebGLRenderer,
+} from 'three';
+import { loadWalkAvatar, resolveConfig, resolveAvatarEntry } from '@three-ws/walk';
+
+const CANVAS_W = 168;
+const CANVAS_H = 240;
+const MARGIN = 16;
+const Z_AVATAR = 2147483300;
+
+// Gravity, mirrored from the walk platformer so the guide obeys the same physics
+// the visitor sees there: it falls onto the ground plane and stays planted,
+// never floating mid-air. SPAWN_DROP is how far above the floor the guide spawns
+// so it visibly settles when it first appears.
+const GRAVITY = -14;
+const SPAWN_DROP = 0.32;
+
+export class GuideAvatar {
+ constructor(tourConfig = {}) {
+ // Feed the host's avatar settings into the walk SDK's config resolver, which
+ // gives us the roster, the default avatar entry, and the storage keys.
+ this.config = resolveConfig({
+ assetBase: tourConfig.assetBase || '',
+ apiBase: tourConfig.apiBase || '',
+ manifestUrl: tourConfig.manifestUrl || '/animations/manifest.json',
+ defaultAvatarId: tourConfig.guideAvatarId || 'realistic-female',
+ });
+ // Which avatar the guide adopts: the visitor's saved companion choice if
+ // present, else the configured guide default.
+ this.avatarStorageKey = tourConfig.avatarStorageKey || this.config.keys.avatar;
+ this.host = null;
+ this.renderer = null;
+ this.scene = null;
+ this.camera = null;
+ this.rig = null;
+ this.model = null;
+ this.controller = null;
+ this.clock = null;
+ this._raf = 0;
+ this._yaw = 0;
+ this._targetYaw = 0;
+ this._walking = false;
+ this._reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;
+ this._pos = { x: 0, y: 0 };
+ // Vertical physics state — height above the ground plane and its velocity.
+ // Gravity in _tick pulls _y down to 0 and holds it there (see GRAVITY).
+ this._groundY = 0;
+ this._y = 0;
+ this._vy = 0;
+ this._tick = this._tick.bind(this);
+ }
+
+ async mount() {
+ ensureStyles();
+ this._buildDom();
+ // The DOM host (and its speech bubble) is built first, so even if WebGL or
+ // the avatar GLB fail to load the tour degrades gracefully: captions still
+ // show above the moving host, and the spotlight + pointer beam still work.
+ // The guide just loses its rendered body rather than breaking the tour.
+ try {
+ await this._buildScene();
+ this.clock = new Timer();
+ this._raf = requestAnimationFrame(this._tick);
+ } catch (err) {
+ console.warn('[tour] guide avatar failed to load — continuing without a rendered body:', err?.message || err);
+ this._headless = true;
+ this.canvas?.remove();
+ }
+ // Park bottom-right until the first stop moves it.
+ const start = { x: window.innerWidth - CANVAS_W - MARGIN, y: window.innerHeight - CANVAS_H - MARGIN };
+ this._setPos(start, false);
+ }
+
+ _buildDom() {
+ const host = document.createElement('div');
+ host.className = 'tws-tour-guide';
+ host.setAttribute('role', 'complementary');
+ host.setAttribute('aria-label', 'Tour guide');
+ host.innerHTML = `
+ <div class="tws-tour-guide__bubble" hidden></div>
+ <canvas class="tws-tour-guide__canvas" width="${CANVAS_W}" height="${CANVAS_H}"></canvas>
+ `;
+ document.body.appendChild(host);
+ this.host = host;
+ this.canvas = host.querySelector('.tws-tour-guide__canvas');
+ this.bubble = host.querySelector('.tws-tour-guide__bubble');
+ requestAnimationFrame(() => host.classList.add('is-in'));
+ }
+
+ async _buildScene() {
+ const renderer = new WebGLRenderer({ canvas: this.canvas, alpha: true, antialias: true });
+ renderer.setPixelRatio(Math.min(window.devicePixelRatio, 1.5));
+ renderer.setSize(CANVAS_W, CANVAS_H, false);
+ this.renderer = renderer;
+
+ const scene = new Scene();
+ this.scene = scene;
+ scene.add(new AmbientLight(0xffffff, 0.9));
+ const hemi = new HemisphereLight(0xbcd6ff, 0x202830, 0.7);
+ hemi.position.set(0, 4, 0);
+ scene.add(hemi);
+ const sun = new DirectionalLight(0xffffff, 1.6);
+ sun.position.set(2, 5, 4);
+ scene.add(sun);
+
+ this.camera = new PerspectiveCamera(40, CANVAS_W / CANVAS_H, 0.05, 100);
+ this.rig = new Group();
+ scene.add(this.rig);
+
+ const savedId = lsGet(this.avatarStorageKey) || this.config.defaultAvatarId;
+ const entry = resolveAvatarEntry(savedId, this.config);
+ const fallback = resolveAvatarEntry(this.config.defaultAvatarId, this.config);
+ const { model, controller } = await loadWalkAvatar(entry, {
+ assetBase: this.config.assetBase,
+ apiBase: this.config.apiBase,
+ manifestUrl: this.config.manifestUrl,
+ fallbackEntry: fallback,
+ });
+ this.model = model;
+ this.controller = controller;
+ this._frame(model, this.rig, this.camera);
+ }
+
+ _frame(model, rig, camera) {
+ const box = new Box3().setFromObject(model);
+ const size = box.getSize(new Vector3());
+ const center = box.getCenter(new Vector3());
+ model.position.x -= center.x;
+ model.position.z -= center.z;
+ model.position.y -= box.min.y;
+ rig.add(model);
+ const height = Math.max(0.6, size.y);
+ camera.position.set(0, height * 0.62, height * 2.2);
+ camera.lookAt(0, height * 0.52, 0);
+ // Feet rest at rig-local y = 0; gravity in _tick drives rig.position.y down
+ // to the ground plane. Spawn a touch above it so the guide drops and settles
+ // onto the floor when it first appears — the same fall the walk platformer
+ // applies. Honour reduced-motion by starting already grounded.
+ this._y = this._reduced ? this._groundY : this._groundY + SPAWN_DROP;
+ this._vy = 0;
+ rig.position.y = this._y;
+ }
+
+ // ── Public choreography API ───────────────────────────────────────────────
+
+ // Walk the avatar to a screen position (top-left of its canvas). Resolves
+ // when it arrives. The CSS transition does the gliding; we just flip the
+ // controller into its walk cycle for the duration.
+ walkTo(pos) {
+ const clamped = {
+ x: clamp(pos.x, MARGIN, window.innerWidth - CANVAS_W - MARGIN),
+ y: clamp(pos.y, MARGIN, window.innerHeight - CANVAS_H - MARGIN),
+ };
+ const dx = clamped.x - this._pos.x;
+ const dy = clamped.y - this._pos.y;
+ const dist = Math.hypot(dx, dy);
+ if (dist < 4) {
+ this._setPos(clamped, false);
+ return Promise.resolve();
+ }
+ // Face the direction of travel so the walk reads naturally.
+ this._targetYaw = clamp((dx / window.innerWidth) * 1.6, -0.7, 0.7);
+ const durMs = this._reduced ? 0 : clamp(dist * 1.6, 420, 1500);
+ this.controller?.setState('walk');
+ this._walking = true;
+ this._setPos(clamped, !this._reduced, durMs);
+ return new Promise((resolve) => {
+ clearTimeout(this._walkTimer);
+ this._walkTimer = setTimeout(() => {
+ this._walking = false;
+ this.controller?.setState('idle');
+ resolve();
+ }, durMs + 30);
+ });
+ }
+
+ // Compute a resting spot beside a target rect (viewport coords), preferring
+ // whichever side has room, and walk there + turn to face the target.
+ async approach(rect) {
+ const pos = this._spotBeside(rect);
+ await this.walkTo(pos);
+ this._faceRect(rect);
+ }
+
+ // Park in a neutral corner and face forward (whole-page stops).
+ async park() {
+ await this.walkTo({
+ x: window.innerWidth - CANVAS_W - MARGIN,
+ y: window.innerHeight - CANVAS_H - MARGIN,
+ });
+ this._targetYaw = 0;
+ }
+
+ // Point at the current target: a wave-style gesture toward it.
+ point() {
+ this.controller?.playWave();
+ }
+
+ // ── Free-roam hooks ─────────────────────────────────────────────────────────
+ // The canvas host is pointer-events:none during the guided tour so it never
+ // eats page clicks; free-roam flips it interactive so the guide can be grabbed.
+ setInteractive(on) {
+ if (!this.host) return;
+ this.host.style.pointerEvents = on ? 'auto' : 'none';
+ this.host.classList.toggle('is-roam', !!on);
+ }
+
+ // Footprint of the avatar host, for centering it under a pointer.
+ size() {
+ const r = this.host?.getBoundingClientRect();
+ return { w: r?.width || CANVAS_W, h: r?.height || CANVAS_H };
+ }
+
+ // Instant placement (drag / edge-scroll follow): clamp to the viewport, face
+ // the direction of travel, run the walk cycle, and auto-settle to idle shortly
+ // after movement stops so a parked guide isn't stuck mid-stride.
+ place(pos) {
+ const s = this.size();
+ const x = clamp(pos.x, MARGIN, window.innerWidth - s.w - MARGIN);
+ const y = clamp(pos.y, MARGIN, window.innerHeight - s.h - MARGIN);
+ const dx = x - this._pos.x;
+ if (Math.abs(dx) > 1) this._targetYaw = clamp((dx / window.innerWidth) * 2, -0.7, 0.7);
+ this.controller?.setState('walk');
+ this._walking = true;
+ clearTimeout(this._settleTimer);
+ this._settleTimer = setTimeout(() => this.settle(), 180);
+ this._setPos({ x, y }, false);
+ }
+
+ settle() {
+ clearTimeout(this._settleTimer);
+ this._walking = false;
+ this._targetYaw = 0;
+ this.controller?.setState('idle');
+ }
+
+ _spotBeside(rect) {
+ const gap = 22;
+ const rightX = rect.left + rect.width + gap;
+ const leftX = rect.left - CANVAS_W - gap;
+ let x;
+ if (rightX + CANVAS_W <= window.innerWidth - MARGIN) x = rightX;
+ else if (leftX >= MARGIN) x = leftX;
+ else x = clamp(rect.cx - CANVAS_W / 2, MARGIN, window.innerWidth - CANVAS_W - MARGIN);
+ const y = clamp(rect.cy - CANVAS_H * 0.58, MARGIN, window.innerHeight - CANVAS_H - MARGIN);
+ return { x, y };
+ }
+
+ _faceRect(rect) {
+ const avatarCx = this._pos.x + CANVAS_W / 2;
+ this._targetYaw = clamp((rect.cx - avatarCx) / window.innerWidth, -0.6, 0.6);
+ }
+
+ // Approximate screen position of the avatar's head — origin for the pointer
+ // beam the director draws to the highlighted element.
+ headScreen() {
+ return { x: this._pos.x + CANVAS_W / 2, y: this._pos.y + CANVAS_H * 0.18 };
+ }
+
+ // ── Speech bubble ─────────────────────────────────────────────────────────
+ say(text) {
+ if (!this.bubble) return;
+ this.bubble.textContent = text;
+ this.bubble.hidden = false;
+ requestAnimationFrame(() => this.bubble.classList.add('is-in'));
+ }
+ hideBubble() {
+ if (!this.bubble) return;
+ this.bubble.classList.remove('is-in');
+ setTimeout(() => {
+ if (this.bubble) this.bubble.hidden = true;
+ }, 280);
+ }
+
+ // ── Internals ─────────────────────────────────────────────────────────────
+ _setPos(pos, animate, durMs = 600) {
+ this._pos = pos;
+ if (!this.host) return;
+ this.host.style.transition = animate
+ ? `left ${durMs}ms cubic-bezier(.34,.02,.2,1), top ${durMs}ms cubic-bezier(.34,.02,.2,1)`
+ : 'none';
+ this.host.style.left = pos.x + 'px';
+ this.host.style.top = pos.y + 'px';
+ }
+
+ _tick() {
+ if (!this.host) return;
+ this.clock.update();
+ const dt = Math.min(this.clock.getDelta(), 0.05);
+ this._yaw += (this._targetYaw - this._yaw) * 0.12;
+ if (this.rig) {
+ this.rig.rotation.y = this._yaw;
+ // Gravity: integrate velocity, land on the ground plane, hold there —
+ // the same model the walk platformer uses so the guide is never airborne.
+ this._vy += GRAVITY * dt;
+ this._y += this._vy * dt;
+ if (this._y <= this._groundY) {
+ this._y = this._groundY;
+ if (this._vy < 0) this._vy = 0;
+ }
+ this.rig.position.y = this._y;
+ }
+ this.controller?.update(dt);
+ this.renderer.render(this.scene, this.camera);
+ this._raf = requestAnimationFrame(this._tick);
+ }
+
+ dispose() {
+ cancelAnimationFrame(this._raf);
+ clearTimeout(this._walkTimer);
+ clearTimeout(this._settleTimer);
+ this._raf = 0;
+ try {
+ this.controller?.dispose();
+ } catch {
+ /* non-fatal */
+ }
+ if (this.scene) {
+ this.scene.traverse((n) => {
+ if (n.isMesh) disposeMesh(n);
+ });
+ }
+ if (this.renderer) {
+ this.renderer.dispose();
+ this.renderer.forceContextLoss?.();
+ }
+ this.host?.remove();
+ this.host = null;
+ }
+}
+
+// ── helpers ──────────────────────────────────────────────────────────────────
+function clamp(n, lo, hi) {
+ return Math.min(hi, Math.max(lo, n));
+}
+function lsGet(key) {
+ try {
+ return localStorage.getItem(key);
+ } catch {
+ return null;
+ }
+}
+function disposeMesh(n) {
+ n.geometry?.dispose?.();
+ const mats = Array.isArray(n.material) ? n.material : [n.material];
+ mats.forEach((m) => {
+ if (!m) return;
+ for (const v of Object.values(m)) if (v && v.isTexture) v.dispose();
+ m.dispose?.();
+ });
+}
+
+let _stylesInjected = false;
+function ensureStyles() {
+ if (_stylesInjected) return;
+ _stylesInjected = true;
+ const style = document.createElement('style');
+ style.id = 'tws-tour-guide-style';
+ style.textContent = `
+.tws-tour-guide{position:fixed;left:0;top:0;width:${CANVAS_W}px;height:${CANVAS_H}px;z-index:${Z_AVATAR};pointer-events:none;opacity:0;transform:translateY(10px);transition:opacity .4s ease,transform .4s ease;-webkit-user-select:none;user-select:none}
+.tws-tour-guide.is-in{opacity:1;transform:translateY(0)}
+.tws-tour-guide__canvas{position:absolute;inset:0;width:100%;height:100%;filter:drop-shadow(0 16px 20px rgba(0,0,0,.34))}
+.tws-tour-guide__bubble{position:absolute;left:50%;bottom:calc(100% - 30px);transform:translateX(-50%) translateY(8px);width:max-content;max-width:320px;background:rgba(18,20,28,.96);color:#f2f4f8;font:500 13px/1.45 system-ui,-apple-system,'Segoe UI',sans-serif;padding:10px 13px;border-radius:14px;border:1px solid rgba(122,162,255,.28);box-shadow:0 12px 30px rgba(0,0,0,.4);opacity:0;transition:opacity .3s ease,transform .3s ease;text-align:left}
+.tws-tour-guide__bubble.is-in{opacity:1;transform:translateX(-50%) translateY(0)}
+.tws-tour-guide__bubble::after{content:'';position:absolute;left:50%;top:100%;transform:translateX(-50%);border:7px solid transparent;border-top-color:rgba(18,20,28,.96)}
+@media (max-width:560px){.tws-tour-guide{width:128px;height:182px}.tws-tour-guide__bubble{max-width:230px;font-size:12px}}
+@media (prefers-reduced-motion:reduce){.tws-tour-guide,.tws-tour-guide__bubble{transition:opacity .2s ease}}
+`;
+ document.head.appendChild(style);
+}
diff --git a/tour-sdk/src/index.js b/tour-sdk/src/index.js
new file mode 100644
index 000000000..8600f5f08
--- /dev/null
+++ b/tour-sdk/src/index.js
@@ -0,0 +1,102 @@
+// @three-ws/tour — a 3D guide that walks your live site and narrates it.
+// =====================================================================
+// A small avatar walks across the real page, spotlights each feature, points at
+// it with a beam, and speaks a line about it — a guided product tour that runs
+// on your actual DOM, not a slideshow. It survives full-page navigation (state
+// in sessionStorage), offers Quick/Full tracks, a searchable chapter map, free
+// roam, and adjustable voice/speed. `three` and `@three-ws/walk` are peer
+// dependencies — bring your own copies.
+//
+// Quick start (auto-mount + deep-link, app-style):
+//
+// import { createFeatureTour } from '@three-ws/tour';
+// const tour = createFeatureTour({
+// curriculum: '/tour/curriculum.json', // or an inline object
+// ttsEndpoint: '/api/tts/speak', // optional — captions pace without it
+// });
+// window.__featureTour = tour; // let your nav button call it
+// tour.bootstrap(); // honour ?tour=… and rehydrate
+//
+// Or drive it yourself:
+//
+// const tour = createFeatureTour();
+// tour.start('quick'); // begin the Quick-highlights track
+// tour.resume(); // pick up an in-progress tour after a navigation
+// tour.exit(); // tear everything down
+
+import { TourDirector } from './director.js';
+import { resolveTourConfig } from './config.js';
+import { createTourState } from './curriculum.js';
+
+export const VERSION = '0.1.0';
+
+/**
+ * Create a tour controller. Returns a small object the host drives:
+ * `start(track)`, `resume()`, `exit()`, `isActive()`, `bootstrap()`, plus the
+ * live `director` once one exists.
+ *
+ * @param {object} [options] see resolveTourConfig for the full option list.
+ */
+export function createFeatureTour(options = {}) {
+ const config = resolveTourConfig(options);
+ const state = createTourState(config);
+ let director = null;
+ const ensure = () => (director ||= new TourDirector(config));
+
+ const control = {
+ get director() {
+ return director;
+ },
+ get config() {
+ return config;
+ },
+ isActive() {
+ return state.readState().active === true;
+ },
+ start(track) {
+ return ensure().start(track);
+ },
+ resume() {
+ return ensure().resume();
+ },
+ exit() {
+ director?.exit();
+ },
+ // Auto-mount / deep-link behaviour. Safe to call once on load. With the
+ // default deepLinkParam 'tour': `?tour=start` begins (optionally
+ // `&track=quick`), `?tour=0` exits, `?tour=1` (or an already-active tour)
+ // resumes. Never runs inside an embed/iframe.
+ bootstrap() {
+ if (typeof window === 'undefined') return;
+ if (window.top !== window.self) return; // never inside an embed/iframe
+ const params = new URLSearchParams(location.search);
+ const param = params.get(config.deepLinkParam);
+ if (param === 'start') {
+ const track = params.get('track') === 'quick' ? 'quick' : 'full';
+ ensure().start(track);
+ } else if (param === '0') {
+ director?.exit();
+ } else if (param === '1' || state.readState().active) {
+ ensure().resume();
+ }
+ },
+ };
+
+ return control;
+}
+
+// Engine internals, exported for advanced/standalone use.
+export { TourDirector } from './director.js';
+export { resolveTourConfig, DEFAULT_VOICES, DEFAULT_COPY } from './config.js';
+export {
+ loadCurriculum,
+ createTourState,
+ buildPlaylist,
+ trackMeta,
+ stopIndexForPath,
+ sectionTitle,
+ normalizePath,
+} from './curriculum.js';
+
+// Curriculum authoring helper — turn a pages document into a tour curriculum.
+export { buildCurriculum } from './build-curriculum.js';
diff --git a/tour-sdk/src/narrator.js b/tour-sdk/src/narrator.js
new file mode 100644
index 000000000..7fa345752
--- /dev/null
+++ b/tour-sdk/src/narrator.js
@@ -0,0 +1,121 @@
+// narrator.js — speak a stop's narration and resolve when the audio finishes,
+// so the director can advance in time with the voice. The host supplies a TTS
+// endpoint (config.ttsEndpoint) that turns { text, voice, speed, format } into
+// an audio response; when no endpoint is configured, or when muted, or when the
+// request fails, it falls back to a timed silence sized to the text so captions
+// still pace correctly. Every call is cancelable (skip / pause / exit) via a
+// monotonic token — a stale fetch or audio that returns after a cancel is
+// ignored.
+
+const WPM = 150;
+
+export class Narrator {
+ constructor(config = {}) {
+ this.endpoint = config.ttsEndpoint || null;
+ this.audio = null;
+ this._token = 0;
+ this._sleepTimer = 0;
+ this._sleepResolve = null;
+ this._finishCurrent = null;
+ }
+
+ estimateMs(text, speed = 1) {
+ const words = String(text || '').trim().split(/\s+/).filter(Boolean).length;
+ 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', speed = 1 } = {}) {
+ this.cancel();
+ const token = ++this._token;
+ const rate = clampSpeed(speed);
+ const clean = String(text || '').trim();
+ if (!clean) return;
+ // No endpoint or muted → keep the caption up for its reading time.
+ if (!this.endpoint || muted) {
+ await this._sleep(this.estimateMs(clean, rate), token);
+ return;
+ }
+
+ let url = null;
+ try {
+ const res = await fetch(this.endpoint, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ text: clean.slice(0, 4096), voice, speed: rate, format: 'mp3' }),
+ });
+ if (token !== this._token) return; // canceled while fetching
+ if (!res.ok) throw new Error(`tts ${res.status}`);
+ const blob = await res.blob();
+ if (token !== this._token) return;
+ url = URL.createObjectURL(blob);
+ const audio = new Audio(url);
+ // Some lanes render the requested `speed` server-side and some ignore 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;
+ const finish = () => {
+ if (done) return;
+ done = true;
+ resolve();
+ };
+ this._finishCurrent = finish;
+ audio.addEventListener('ended', finish);
+ audio.addEventListener('error', finish);
+ audio.play().catch(finish);
+ });
+ } catch {
+ if (token !== this._token) return;
+ // TTS unavailable — keep the caption on screen for its reading time.
+ await this._sleep(this.estimateMs(clean), token);
+ } finally {
+ if (url) URL.revokeObjectURL(url);
+ if (token === this._token) {
+ this.audio = null;
+ this._finishCurrent = null;
+ }
+ }
+ }
+
+ _sleep(ms, token) {
+ return new Promise((resolve) => {
+ this._sleepResolve = resolve;
+ this._sleepTimer = setTimeout(() => {
+ if (token === this._token) resolve();
+ }, ms);
+ });
+ }
+
+ // Stop any in-flight speech/sleep and invalidate pending callbacks.
+ cancel() {
+ this._token++;
+ clearTimeout(this._sleepTimer);
+ this._sleepTimer = 0;
+ if (this._sleepResolve) {
+ this._sleepResolve();
+ this._sleepResolve = null;
+ }
+ try {
+ this.audio?.pause();
+ } catch {
+ /* ignore */
+ }
+ if (this._finishCurrent) this._finishCurrent();
+ this._finishCurrent = null;
+ this.audio = null;
+ }
+
+ dispose() {
+ 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/tour-sdk/src/spotlight.js b/tour-sdk/src/spotlight.js
new file mode 100644
index 000000000..122897f33
--- /dev/null
+++ b/tour-sdk/src/spotlight.js
@@ -0,0 +1,117 @@
+// spotlight.js — dim the page and ring the element the guide is pointing at.
+// A single transparent "hole" element casts a huge box-shadow over everything
+// else, so the highlighted feature stays lit while the rest recedes. The hole
+// tracks the target every frame (scroll, resize, layout shifts) and exposes its
+// live rect so the avatar and the pointer beam can aim at it.
+
+const Z_BACKDROP = 2147483100;
+
+let _stylesInjected = false;
+function ensureStyles() {
+ if (_stylesInjected) return;
+ _stylesInjected = true;
+ const style = document.createElement('style');
+ style.id = 'tws-tour-spotlight-style';
+ style.textContent = `
+.tws-tour-spot{position:fixed;z-index:${Z_BACKDROP};border-radius:12px;pointer-events:none;
+ box-shadow:0 0 0 9999px rgba(8,10,16,.62),0 0 0 2px rgba(122,162,255,.9),0 0 28px 6px rgba(122,162,255,.55) inset;
+ transition:left .45s cubic-bezier(.4,0,.2,1),top .45s cubic-bezier(.4,0,.2,1),width .45s cubic-bezier(.4,0,.2,1),height .45s cubic-bezier(.4,0,.2,1),opacity .3s ease;
+ opacity:0}
+.tws-tour-spot.is-in{opacity:1}
+.tws-tour-spot::after{content:'';position:absolute;inset:-2px;border-radius:14px;border:2px solid rgba(122,162,255,.55);animation:tws-tour-pulse 1.8s ease-in-out infinite}
+@keyframes tws-tour-pulse{0%,100%{transform:scale(1);opacity:.7}50%{transform:scale(1.012);opacity:.25}}
+@media (prefers-reduced-motion:reduce){.tws-tour-spot{transition:opacity .2s ease}.tws-tour-spot::after{animation:none}}
+`;
+ document.head.appendChild(style);
+}
+
+export class Spotlight {
+ constructor() {
+ ensureStyles();
+ this.el = document.createElement('div');
+ this.el.className = 'tws-tour-spot';
+ this.el.setAttribute('aria-hidden', 'true');
+ document.body.appendChild(this.el);
+ this.target = null;
+ this._raf = 0;
+ this._rect = null;
+ this._track = this._track.bind(this);
+ }
+
+ // Highlight an element. Pass null to fade the spotlight out (whole-page stop).
+ async highlight(el) {
+ this.target = el || null;
+ if (!el) {
+ this.el.classList.remove('is-in');
+ this._rect = null;
+ return;
+ }
+ await scrollIntoViewIfNeeded(el);
+ this._track();
+ this.el.classList.add('is-in');
+ if (!this._raf) this._raf = requestAnimationFrame(this._track);
+ }
+
+ _track() {
+ this._raf = 0;
+ const el = this.target;
+ if (!el || !el.isConnected) {
+ this.el.classList.remove('is-in');
+ this._rect = null;
+ return;
+ }
+ const r = el.getBoundingClientRect();
+ // Ignore zero-size / off-screen elements (e.g. display:none mid-tour).
+ if (r.width < 1 && r.height < 1) {
+ this.el.classList.remove('is-in');
+ } else {
+ const pad = 8;
+ const left = Math.max(0, r.left - pad);
+ const top = Math.max(0, r.top - pad);
+ const width = Math.min(window.innerWidth, r.right + pad) - left;
+ const height = Math.min(window.innerHeight, r.bottom + pad) - top;
+ this.el.style.left = left + 'px';
+ this.el.style.top = top + 'px';
+ this.el.style.width = width + 'px';
+ this.el.style.height = height + 'px';
+ this.el.classList.add('is-in');
+ this._rect = { left, top, width, height, cx: left + width / 2, cy: top + height / 2 };
+ }
+ this._raf = requestAnimationFrame(this._track);
+ }
+
+ // Live viewport rect of the current highlight, or null.
+ getRect() {
+ return this._rect;
+ }
+
+ clear() {
+ this.target = null;
+ this._rect = null;
+ this.el.classList.remove('is-in');
+ }
+
+ dispose() {
+ cancelAnimationFrame(this._raf);
+ this.el?.remove();
+ }
+}
+
+function scrollIntoViewIfNeeded(el) {
+ return new Promise((resolve) => {
+ const r = el.getBoundingClientRect();
+ const fullyVisible = r.top >= 64 && r.bottom <= window.innerHeight - 64;
+ if (fullyVisible) {
+ resolve();
+ return;
+ }
+ const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;
+ el.scrollIntoView({
+ behavior: reduced ? 'auto' : 'smooth',
+ block: 'center',
+ inline: 'nearest',
+ });
+ // Resolve after the smooth-scroll settles (or immediately if reduced).
+ setTimeout(resolve, reduced ? 0 : 480);
+ });
+}
diff --git a/tour-sdk/test/build-curriculum.test.mjs b/tour-sdk/test/build-curriculum.test.mjs
new file mode 100644
index 000000000..840913267
--- /dev/null
+++ b/tour-sdk/test/build-curriculum.test.mjs
@@ -0,0 +1,105 @@
+// buildCurriculum — turning a pages document into a well-formed curriculum.
+
+import { describe, it, expect } from 'vitest';
+import { buildCurriculum } from '../src/build-curriculum.js';
+import { buildPlaylist, trackMeta } from '../src/curriculum.js';
+
+const pagesDoc = {
+ sections: [
+ {
+ id: 'main',
+ title: 'Overview',
+ pages: [
+ { path: '/', title: 'Home', description: 'The front door.', added: '2024-01-01' },
+ { path: '/pricing', title: 'Pricing', description: 'Pricing — simple plans.', added: '2024-02-01' },
+ { path: '/login', title: 'Log in', description: 'Sign in.', auth: 'required' },
+ { path: '/secret', title: 'Secret', description: 'Hidden.' },
+ ],
+ },
+ {
+ id: 'build',
+ title: 'Build',
+ pages: [
+ { path: '/studio', title: 'Studio', description: 'Build things.', added: '2024-03-01' },
+ { path: '/deploy', title: 'Deploy', description: 'Ship it.', added: '2024-01-15' },
+ ],
+ },
+ { id: 'empty', title: 'Empty', pages: [] },
+ ],
+};
+
+describe('buildCurriculum', () => {
+ const cur = buildCurriculum(pagesDoc, {
+ sectionOrder: ['main', 'build'],
+ sectionIntros: { main: 'Welcome.', build: 'Now the fun part.' },
+ sectionHeroes: { main: ['/', '/pricing'] },
+ targets: { '/': ['a.cta'] },
+ deny: ['/secret'],
+ quickPerSection: 1,
+ title: 'Acme Tour',
+ });
+
+ it('produces a versioned, well-formed curriculum', () => {
+ expect(cur.version).toBe(2);
+ expect(cur.title).toBe('Acme Tour');
+ expect(Array.isArray(cur.stops)).toBe(true);
+ expect(cur.stopCount).toBe(cur.stops.length);
+ });
+
+ it('skips auth-required and denied pages', () => {
+ const paths = cur.stops.map((s) => s.path);
+ expect(paths).not.toContain('/login'); // auth: required
+ expect(paths).not.toContain('/secret'); // denied
+ expect(paths).toContain('/');
+ expect(paths).toContain('/studio');
+ });
+
+ it('drops empty sections', () => {
+ expect(cur.sections.map((s) => s.id)).toEqual(['main', 'build']);
+ });
+
+ it('orders heroes first, then remaining pages newest-first', () => {
+ const buildStops = cur.stops.filter((s) => s.section === 'build').map((s) => s.path);
+ // No heroes declared for build → newest (2024-03-01 studio) before older deploy.
+ expect(buildStops).toEqual(['/studio', '/deploy']);
+ const mainStops = cur.stops.filter((s) => s.section === 'main').map((s) => s.path);
+ expect(mainStops[0]).toBe('/'); // hero order honoured
+ expect(mainStops[1]).toBe('/pricing');
+ });
+
+ it('marks quickPerSection leading stops of each chapter as highlights', () => {
+ // quickPerSection: 1 → exactly the first stop of each section.
+ const highlights = cur.stops.filter((s) => s.highlight);
+ expect(highlights.map((s) => s.path).sort()).toEqual(['/', '/studio']);
+ });
+
+ it('keeps track metadata consistent with the stops', () => {
+ expect(trackMeta(cur, 'full').stopCount).toBe(cur.stops.length);
+ expect(trackMeta(cur, 'quick').stopCount).toBe(cur.stops.filter((s) => s.highlight).length);
+ expect(buildPlaylist(cur, 'quick')).toEqual(
+ cur.stops.map((s, i) => (s.highlight ? i : -1)).filter((i) => i >= 0),
+ );
+ });
+
+ it('attaches the section intro to the first stop of each chapter only', () => {
+ const firstMain = cur.stops.find((s) => s.section === 'main');
+ expect(firstMain.sectionIntro).toBe('Welcome.');
+ const laterMain = cur.stops.filter((s) => s.section === 'main')[1];
+ expect(laterMain.sectionIntro).toBeUndefined();
+ });
+
+ it('carries through per-path targets and synthesises narration', () => {
+ const home = cur.stops.find((s) => s.path === '/');
+ expect(home.targets).toEqual(['a.cta']);
+ expect(home.narration).toContain('Home');
+ // The leading "Pricing — " in the description isn't repeated after the title.
+ const pricing = cur.stops.find((s) => s.path === '/pricing');
+ expect(pricing.narration).not.toMatch(/Pricing\.\s*Pricing/);
+ });
+
+ it('handles an empty document without throwing', () => {
+ const empty = buildCurriculum({ sections: [] });
+ expect(empty.stops).toEqual([]);
+ expect(empty.stopCount).toBe(0);
+ });
+});
diff --git a/tour-sdk/test/config.test.mjs b/tour-sdk/test/config.test.mjs
new file mode 100644
index 000000000..8446e3129
--- /dev/null
+++ b/tour-sdk/test/config.test.mjs
@@ -0,0 +1,80 @@
+// Config resolution — the contract every host-specific concern flows through.
+
+import { describe, it, expect } from 'vitest';
+import { resolveTourConfig, DEFAULT_VOICES, DEFAULT_COPY } from '../src/config.js';
+
+describe('resolveTourConfig defaults', () => {
+ it('applies brand-neutral, graceful defaults', () => {
+ const c = resolveTourConfig();
+ expect(c.curriculum).toBe('/tour/curriculum.json');
+ expect(c.ttsEndpoint).toBeNull(); // silent captions out of the box
+ expect(c.defaultVoice).toBe('nova');
+ expect(c.voices).toBe(DEFAULT_VOICES);
+ expect(c.guideAvatarId).toBe('realistic-female');
+ expect(c.manifestUrl).toBe('/animations/manifest.json');
+ expect(c.avatarStorageKey).toBe('walk:companion:avatar');
+ expect(c.deepLinkParam).toBe('tour');
+ expect(typeof c.navigate).toBe('function');
+ expect(c.keys).toEqual({ state: 'tws:tour:state', resume: 'tws:tour:resume' });
+ expect(c.copy.outro).toBe(DEFAULT_COPY.outro);
+ expect(c.copy.completion.primary).toBeNull();
+ });
+
+ it('defaults the walk-companion integration on', () => {
+ const c = resolveTourConfig();
+ expect(c.companion).toEqual({
+ global: '__walkCompanion',
+ changeEvent: 'walk-companion:change',
+ });
+ });
+});
+
+describe('resolveTourConfig overrides', () => {
+ it('threads through explicit values', () => {
+ const navigate = () => {};
+ const c = resolveTourConfig({
+ curriculum: { stops: [{ path: '/', narration: 'hi' }] },
+ ttsEndpoint: '/api/tts/speak',
+ defaultVoice: 'fable',
+ guideAvatarId: 'fox',
+ navigate,
+ deepLinkParam: 'guide',
+ });
+ expect(c.ttsEndpoint).toBe('/api/tts/speak');
+ expect(c.defaultVoice).toBe('fable');
+ expect(c.guideAvatarId).toBe('fox');
+ expect(c.navigate).toBe(navigate);
+ expect(c.deepLinkParam).toBe('guide');
+ expect(c.curriculum).toEqual({ stops: [{ path: '/', narration: 'hi' }] });
+ });
+
+ it('scopes storage keys to storagePrefix', () => {
+ const c = resolveTourConfig({ storagePrefix: 'acme:tour' });
+ expect(c.keys).toEqual({ state: 'acme:tour:state', resume: 'acme:tour:resume' });
+ });
+
+ it('disables the companion integration when companion is false', () => {
+ expect(resolveTourConfig({ companion: false }).companion).toBeNull();
+ });
+
+ it('customises the companion change-event name', () => {
+ const c = resolveTourConfig({ companion: { changeEvent: 'acme:companion' } });
+ expect(c.companion).toEqual({ global: '__walkCompanion', changeEvent: 'acme:companion' });
+ });
+
+ it('deep-merges copy while keeping unspecified defaults', () => {
+ const c = resolveTourConfig({
+ copy: { outro: 'bye!', completion: { primary: { label: 'Go', href: '/start' } } },
+ });
+ expect(c.copy.outro).toBe('bye!');
+ expect(c.copy.offRoute).toBe(DEFAULT_COPY.offRoute); // untouched default
+ expect(c.copy.completion.primary).toEqual({ label: 'Go', href: '/start' });
+ expect(c.copy.completion.title).toBe(DEFAULT_COPY.completion.title); // untouched
+ });
+
+ it('ignores an empty voices array and keeps the default catalogue', () => {
+ expect(resolveTourConfig({ voices: [] }).voices).toBe(DEFAULT_VOICES);
+ const custom = [{ id: 'x', name: 'X' }];
+ expect(resolveTourConfig({ voices: custom }).voices).toBe(custom);
+ });
+});
diff --git a/tour-sdk/test/curriculum.test.mjs b/tour-sdk/test/curriculum.test.mjs
new file mode 100644
index 000000000..a14a88c39
--- /dev/null
+++ b/tour-sdk/test/curriculum.test.mjs
@@ -0,0 +1,84 @@
+// Pure curriculum helpers + playlist invariants — the same guarantees the
+// runtime relies on, independent of the DOM.
+
+import { describe, it, expect } from 'vitest';
+import {
+ buildPlaylist,
+ trackMeta,
+ stopIndexForPath,
+ sectionTitle,
+ normalizePath,
+} from '../src/curriculum.js';
+
+const curriculum = {
+ tracks: [
+ { id: 'full', title: 'Full tour', stopCount: 4 },
+ { id: 'quick', title: 'Quick highlights', stopCount: 2 },
+ ],
+ sections: [
+ { id: 'main', title: 'Overview' },
+ { id: 'build', title: 'Build' },
+ ],
+ stops: [
+ { path: '/', section: 'main', title: 'Home', highlight: true },
+ { path: '/pricing', section: 'main', title: 'Pricing', highlight: false },
+ { path: '/studio', section: 'build', title: 'Studio', highlight: true },
+ { path: '/deploy', section: 'build', title: 'Deploy', highlight: false },
+ ],
+};
+
+describe('buildPlaylist', () => {
+ it('returns every stop index for the full track', () => {
+ expect(buildPlaylist(curriculum, 'full')).toEqual([0, 1, 2, 3]);
+ });
+
+ it('returns only highlighted indices for the quick track, in order', () => {
+ const quick = buildPlaylist(curriculum, 'quick');
+ expect(quick).toEqual([0, 2]);
+ expect(quick.every((i) => curriculum.stops[i].highlight)).toBe(true);
+ });
+
+ it('defaults to the full track for an unknown / missing track id', () => {
+ expect(buildPlaylist(curriculum, 'nope')).toHaveLength(4);
+ expect(buildPlaylist(curriculum)).toHaveLength(4);
+ });
+
+ 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]);
+ });
+});
+
+describe('trackMeta', () => {
+ it('finds a declared track', () => {
+ expect(trackMeta(curriculum, 'quick').stopCount).toBe(2);
+ });
+ it('returns null for an unknown track', () => {
+ expect(trackMeta(curriculum, 'nope')).toBeNull();
+ expect(trackMeta({}, 'full')).toBeNull();
+ });
+});
+
+describe('stopIndexForPath', () => {
+ it('matches a stop by normalized path', () => {
+ expect(stopIndexForPath(curriculum, '/studio')).toBe(2);
+ expect(stopIndexForPath(curriculum, '/studio/')).toBe(2); // trailing slash
+ expect(stopIndexForPath(curriculum, '/missing')).toBe(-1);
+ });
+});
+
+describe('sectionTitle', () => {
+ it('resolves a section id to its title', () => {
+ expect(sectionTitle(curriculum, 'build')).toBe('Build');
+ expect(sectionTitle(curriculum, 'nope')).toBe('');
+ expect(sectionTitle({}, 'main')).toBe('');
+ });
+});
+
+describe('normalizePath', () => {
+ it('keeps root as "/" and strips trailing slashes elsewhere', () => {
+ expect(normalizePath('/')).toBe('/');
+ expect(normalizePath('/a/b/')).toBe('/a/b');
+ expect(normalizePath('')).toBe('/');
+ });
+});
diff --git a/tour-sdk/test/state.test.mjs b/tour-sdk/test/state.test.mjs
new file mode 100644
index 000000000..ad1f3009c
--- /dev/null
+++ b/tour-sdk/test/state.test.mjs
@@ -0,0 +1,128 @@
+// Cross-page tour state + inline curriculum loading + the free-roam activation
+// guard — the DOM-touching surfaces, exercised under jsdom.
+
+import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'vitest';
+import { JSDOM } from 'jsdom';
+import { createTourState, loadCurriculum } from '../src/curriculum.js';
+import { resolveTourConfig } from '../src/config.js';
+
+let dom;
+
+beforeAll(() => {
+ dom = new JSDOM('<!doctype html><body></body>', { url: 'https://example.test/' });
+ global.window = dom.window;
+ global.document = dom.window.document;
+ global.localStorage = dom.window.localStorage;
+ global.sessionStorage = dom.window.sessionStorage;
+ global.matchMedia = () => ({ matches: false });
+ dom.window.matchMedia = global.matchMedia;
+});
+
+afterAll(() => {
+ delete global.window;
+ delete global.document;
+ delete global.localStorage;
+ delete global.sessionStorage;
+ delete global.matchMedia;
+});
+
+beforeEach(() => {
+ localStorage.clear();
+ sessionStorage.clear();
+});
+
+describe('createTourState', () => {
+ const config = resolveTourConfig({ storagePrefix: 'acme:tour', defaultVoice: 'fable' });
+ const state = createTourState(config);
+
+ it('returns defaults (with the configured voice) when nothing is stored', () => {
+ const s = state.readState();
+ expect(s.active).toBe(false);
+ expect(s.voice).toBe('fable');
+ expect(s.index).toBe(0);
+ });
+
+ it('round-trips live state through sessionStorage under the prefixed key', () => {
+ state.writeState({ active: true, index: 3, track: 'quick' });
+ expect(state.readState().index).toBe(3);
+ expect(sessionStorage.getItem('acme:tour:state')).toContain('"index":3');
+ });
+
+ it('mirrors durable progress to localStorage only while active', () => {
+ state.writeState({ active: true, index: 5, track: 'full', voice: 'echo', speed: 1.25 });
+ const resume = state.readResume();
+ expect(resume.index).toBe(5);
+ expect(resume.voice).toBe('echo');
+ expect(resume.speed).toBe(1.25);
+ expect(localStorage.getItem('acme:tour:resume')).toBeTruthy();
+ });
+
+ it('clearState wipes live state but leaves durable resume', () => {
+ state.writeState({ active: true, index: 7 });
+ state.clearState();
+ expect(state.readState().active).toBe(false);
+ expect(state.readResume().index).toBe(7); // durable memory survives
+ });
+
+ it('markCompleted records completion and resets the resume index', () => {
+ state.writeState({ active: true, index: 9 });
+ state.markCompleted();
+ const resume = state.readResume();
+ expect(resume.completed).toBe(true);
+ expect(resume.index).toBe(0);
+ });
+
+ it('isolates two tours with different prefixes', () => {
+ const a = createTourState(resolveTourConfig({ storagePrefix: 'a' }));
+ const b = createTourState(resolveTourConfig({ storagePrefix: 'b' }));
+ a.writeState({ active: true, index: 1 });
+ b.writeState({ active: true, index: 2 });
+ expect(a.readState().index).toBe(1);
+ expect(b.readState().index).toBe(2);
+ });
+});
+
+describe('loadCurriculum', () => {
+ it('uses an inline curriculum object as-is', async () => {
+ const inline = { stops: [{ path: '/', narration: 'hi' }] };
+ const cur = await loadCurriculum(resolveTourConfig({ curriculum: inline }));
+ expect(cur).toBe(inline);
+ });
+
+ it('rejects an empty inline curriculum', async () => {
+ await expect(loadCurriculum(resolveTourConfig({ curriculum: { stops: [] } }))).rejects.toThrow(
+ /empty/,
+ );
+ });
+});
+
+describe('free-roam activation guard', () => {
+ let isInteractiveTarget;
+
+ beforeAll(async () => {
+ ({ isInteractiveTarget } = await import('../src/free-roam.js'));
+ });
+
+ function make(html) {
+ document.body.innerHTML = html;
+ return document.body.firstElementChild;
+ }
+
+ it('treats links, buttons, inputs and canvases as page interactions', () => {
+ expect(isInteractiveTarget(make('<a href="/x">x</a>'))).toBe(true);
+ expect(isInteractiveTarget(make('<button>x</button>'))).toBe(true);
+ expect(isInteractiveTarget(make('<input>'))).toBe(true);
+ expect(isInteractiveTarget(make('<canvas></canvas>'))).toBe(true);
+ expect(isInteractiveTarget(make('<div data-walk-block>x</div>'))).toBe(true);
+ });
+
+ it('counts a child of an interactive element as interactive', () => {
+ const a = make('<a href="/x"><span>deep</span></a>');
+ expect(isInteractiveTarget(a.querySelector('span'))).toBe(true);
+ });
+
+ it('treats plain empty space as walkable (not interactive)', () => {
+ expect(isInteractiveTarget(make('<div><p>just text</p></div>'))).toBe(false);
+ expect(isInteractiveTarget(null)).toBe(false);
+ });
+});
diff --git a/tour-sdk/types/index.d.ts b/tour-sdk/types/index.d.ts
new file mode 100644
index 000000000..3657ecdda
--- /dev/null
+++ b/tour-sdk/types/index.d.ts
@@ -0,0 +1,213 @@
+// Type definitions for @three-ws/tour
+
+export declare const VERSION: string;
+
+/** A selectable view over the curriculum's stops. */
+export interface TourTrack {
+ id: string;
+ title: string;
+ description?: string;
+ stopCount?: number;
+ estimatedMinutes?: number;
+}
+
+/** A chapter header; stops reference it by `id`. */
+export interface TourSection {
+ id: string;
+ title: string;
+ /** Spoken bridge said when the guide first enters this chapter. */
+ intro?: string;
+}
+
+/** One feature the guide visits. */
+export interface TourStop {
+ id?: string;
+ /** Route the stop lives on, e.g. "/pricing". */
+ path: string;
+ /** Section id this stop belongs to. */
+ section?: string;
+ /** Short feature name shown in the chapter map. */
+ title?: string;
+ /** The line the guide speaks at this stop. */
+ narration: string;
+ /** Whether this stop is part of the Quick-highlights track. */
+ highlight?: boolean;
+ /** Spoken once before this stop as the chapter's bridge. */
+ sectionIntro?: string;
+ /** Ordered CSS selectors for the element to spotlight; first visible wins. */
+ targets?: string[];
+}
+
+/** The document that drives a tour. See curriculum.schema.json. */
+export interface TourCurriculum {
+ version?: number;
+ generatedAt?: string;
+ generatedBy?: string;
+ title?: string;
+ tagline?: string;
+ estimatedMinutes?: number;
+ stopCount?: number;
+ tracks?: TourTrack[];
+ sections?: TourSection[];
+ stops: TourStop[];
+}
+
+/** A narration voice offered in the chapter panel's picker. */
+export interface TourVoice {
+ id: string;
+ name: string;
+}
+
+/** Closing/recovery copy. Every field is overridable. */
+export interface TourCopy {
+ outro?: string;
+ offRoute?: string;
+ completion?: {
+ title?: string;
+ body?: string;
+ primary?: { label: string; href: string } | null;
+ restartLabel?: string;
+ closeLabel?: string;
+ };
+}
+
+/** Walk-companion de-dupe integration. */
+export interface CompanionConfig {
+ /** Global object the companion is exposed through (default "__walkCompanion"). */
+ global?: string;
+ /** Event the companion dispatches on mount/unmount (default "walk-companion:change"). */
+ changeEvent?: string;
+}
+
+/** Options accepted by createFeatureTour / resolveTourConfig. */
+export interface TourOptions {
+ /** URL to fetch the curriculum from, or an already-loaded curriculum object. */
+ curriculum?: string | TourCurriculum;
+ /**
+ * POST endpoint that turns `{ text, voice, speed, format }` into an audio
+ * response. When omitted, narration plays as silent captions paced to the text.
+ */
+ ttsEndpoint?: string | null;
+ defaultVoice?: string;
+ voices?: TourVoice[];
+ guideAvatarId?: string;
+ assetBase?: string;
+ apiBase?: string;
+ manifestUrl?: string;
+ avatarStorageKey?: string;
+ /** How to move to another route (default: location.assign). */
+ navigate?: (path: string) => void;
+ /** Query param that opens the tour (default "tour"). */
+ deepLinkParam?: string;
+ /** Walk-companion integration. `false` disables it. */
+ companion?: boolean | CompanionConfig;
+ /** Prefix for tour state storage keys (default "tws:tour"). */
+ storagePrefix?: string;
+ copy?: TourCopy;
+}
+
+/** The fully-resolved config the engine runs on. */
+export interface ResolvedTourConfig {
+ curriculum: string | TourCurriculum;
+ ttsEndpoint: string | null;
+ defaultVoice: string;
+ voices: TourVoice[];
+ guideAvatarId: string;
+ assetBase: string;
+ apiBase: string;
+ manifestUrl: string;
+ avatarStorageKey: string;
+ navigate: (path: string) => void;
+ deepLinkParam: string;
+ companion: { global: string; changeEvent: string } | null;
+ copy: Required<TourCopy>;
+ keys: { state: string; resume: string };
+}
+
+/** The controller returned by createFeatureTour. */
+export interface FeatureTour {
+ readonly director: TourDirector | null;
+ readonly config: ResolvedTourConfig;
+ /** True if a tour is currently active (persisted in sessionStorage). */
+ isActive(): boolean;
+ /** Begin a fresh tour. `track` defaults to "full". */
+ start(track?: string): Promise<void>;
+ /** Re-hydrate an in-progress tour after a page navigation. */
+ resume(): Promise<void>;
+ /** Tear everything down. */
+ exit(): void;
+ /** Honour the deep-link query param and rehydrate. Safe to call once on load. */
+ bootstrap(): void;
+}
+
+/** Cross-page tour state bound to a config's storage keys. */
+export interface TourState {
+ readState(): Record<string, unknown>;
+ writeState(patch: Record<string, unknown>): Record<string, unknown>;
+ clearState(): void;
+ readResume(): Record<string, unknown>;
+ writeResume(patch: Record<string, unknown>): Record<string, unknown>;
+ markCompleted(): void;
+}
+
+/** Create a tour controller. */
+export declare function createFeatureTour(options?: TourOptions): FeatureTour;
+
+/** The tour engine. createFeatureTour wraps this; use directly for full control. */
+export declare class TourDirector {
+ constructor(config?: TourOptions | ResolvedTourConfig);
+ readonly config: ResolvedTourConfig;
+ start(track?: string): Promise<void>;
+ resume(): Promise<void>;
+ exit(): void;
+}
+
+export declare function resolveTourConfig(opts?: TourOptions): ResolvedTourConfig;
+export declare const DEFAULT_VOICES: TourVoice[];
+export declare const DEFAULT_COPY: Required<TourCopy>;
+
+export declare function loadCurriculum(config: { curriculum?: string | TourCurriculum }): Promise<TourCurriculum>;
+export declare function createTourState(config: ResolvedTourConfig): TourState;
+export declare function buildPlaylist(curriculum: TourCurriculum, track?: string): number[];
+export declare function trackMeta(curriculum: TourCurriculum, track?: string): TourTrack | null;
+export declare function stopIndexForPath(curriculum: TourCurriculum, pathname?: string): number;
+export declare function sectionTitle(curriculum: TourCurriculum, id: string): string;
+export declare function normalizePath(pathname?: string): string;
+
+/** Options for buildCurriculum. */
+export interface BuildCurriculumOptions {
+ sectionOrder?: string[];
+ sectionIntros?: Record<string, string>;
+ sectionHeroes?: Record<string, string[]>;
+ targets?: Record<string, string[]>;
+ deny?: string[];
+ denyPrefix?: string[];
+ skipAuthRequired?: boolean;
+ quickPerSection?: number;
+ connectors?: string[];
+ title?: string;
+ tagline?: string;
+ wpm?: number;
+ stopOverheadS?: number;
+}
+
+/** A page in the input document buildCurriculum consumes. */
+export interface PageEntry {
+ path: string;
+ title?: string;
+ description?: string;
+ added?: string;
+ auth?: string;
+ [key: string]: unknown;
+}
+
+/** The input document buildCurriculum consumes. */
+export interface PagesDocument {
+ sections: Array<{ id: string; title?: string; pages: PageEntry[] }>;
+}
+
+/** Turn a pages document into a tour curriculum. */
+export declare function buildCurriculum(
+ pagesDoc: PagesDocument,
+ opts?: BuildCurriculumOptions,
+): TourCurriculum;