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: x402-modal/payment-modal build + server adapters, walk-sdk polish, page-agent docs

nirholas768589c3b883
diff --git a/page-agent-sdk/docs/api-reference.md b/page-agent-sdk/docs/api-reference.md
new file mode 100644
index 000000000..8efc5413c
--- /dev/null
+++ b/page-agent-sdk/docs/api-reference.md
@@ -0,0 +1,363 @@
+# API reference 🟡
+
+The complete public surface of `@three-ws/page-agent`. Everything here is
+exported from the package entry and typed in
+[`types/index.d.ts`](../types/index.d.ts).
+
+- [PageAgent](#pageagent) — the drop-in controller
+- [HTML: `<page-agent>` element](#html-page-agent-element)
+- [HTML: `data-page-agent` script](#html-attributes)
+- [Catalog](#catalog) — agents + helpers
+- [Building blocks](#building-blocks) — `AvatarStage`, `SpeechNarrator`, `AvatarPicker`
+- [Lipsync engine](#lipsync-engine)
+- [Types](#types)
+
+---
+
+## `PageAgent`
+
+```ts
+import { PageAgent } from '@three-ws/page-agent';
+const guide = new PageAgent(config?);
+```
+
+The controller docks a rigged 3D agent to the page corner with a control bar,
+caption bubble, drag-to-move, and page narration. It appends itself to
+`document.body` — you don't mount it into an element.
+
+> Throws `'[page-agent] requires a browser environment'` if constructed where
+> `window` is undefined (SSR). Construct it in a client-only effect.
+
+### Config
+
+| Option | Type | Default | Notes |
+|--------|------|---------|-------|
+| `agent` | `string` | persisted → `'sol'` | Initial rigged agent id. |
+| `agents` | `string[]` | all | Allow-list of ids shown in the picker. Invalid/empty falls back to the full roster. |
+| `assetBase` | `string` | `https://three.ws/avatars/` | Base URL for agent GLBs. |
+| `position` | `'bottom-right' \| 'bottom-left' \| 'top-right' \| 'top-left'` | `'bottom-right'` | Dock corner (until dragged). |
+| `muted` | `boolean` | `false` | Start muted — visual lipsync + captions only. |
+| `collapsed` | `boolean` | `false` | Start as the "Ask a guide" launcher pill. |
+| `picker` | `boolean` | `true` | Show the change-agent affordance + picker. |
+| `controls` | `boolean` | `true` | Show the control bar. |
+| `greeting` | `string` | — | Spoken once on load. Ignored when `autoNarrate` is set. |
+| `autoNarrate` | `boolean \| string` | `false` | `true` tours the whole page; a string is a CSS selector of segments to tour. |
+| `persistAgent` | `boolean` | `true` | Remember the visitor's chosen agent in `localStorage`. |
+| `mount` | `HTMLElement` | — | Reserved; the agent docks itself regardless. |
+
+Initial agent resolution order: `agent` → persisted choice (if `persistAgent`) →
+`DEFAULT_AGENT_ID` → first agent in the roster.
+
+### Properties
+
+| Member | Type | Description |
+|--------|------|-------------|
+| `currentAgent` | `RiggedAgent \| null` | The live agent (read-only). |
+
+### Methods
+
+```ts
+narrate(text: string, opts?: { interrupt?: boolean }): Promise<void>
+```
+Speak a single line. Resolves when it ends, is skipped, or cancelled. Un-collapses
+the agent first. `interrupt: true` cuts off current speech.
+
+```ts
+narratePage(opts?: { selector?: string; greet?: boolean }): Promise<void>
+```
+Walk the page and narrate it segment by segment, highlighting and scrolling to
+each. `selector` scopes the segments; `greet: true` speaks the agent's persona
+line first. See [segment selection](#segment-selection).
+
+```ts
+stop(): void
+```
+Cancel any narration/walk in progress and clear highlights.
+
+```ts
+setAgent(id: AgentId): Promise<void>
+```
+Swap to another rigged agent live — loads its GLB, reframes, adopts its voice and
+accent. Rejects (and emits `error`) if the GLB fails to load.
+
+```ts
+mute(on?: boolean): void
+collapse(on?: boolean): void
+openPicker(): void
+closePicker(): void
+```
+
+```ts
+on(event: PageAgentEvent, cb: (payload) => void): this // chainable
+off(event: PageAgentEvent, cb: (payload) => void): this
+dispose(): void // tear everything down
+```
+
+### Events
+
+| Event | Payload | Fires when |
+|-------|---------|-----------|
+| `ready` | `RiggedAgent` | The initial agent has loaded. |
+| `agentchange` | `RiggedAgent` | An agent's GLB finished loading (initial + each swap). |
+| `state` | `'idle' \| 'speaking'` | Speech starts/stops. |
+| `caption` | `string \| null` | Caption text updates (`null` when cleared). |
+| `segment` | `{ text: string, el: Element }` | A page-walk segment begins. |
+| `error` | `Error` | Load or speech-synthesis failure. |
+
+```js
+guide.on('agentchange', (a) => console.log('now:', a.name))
+ .on('error', (e) => report(e));
+```
+
+### `mount(config?)`
+
+```ts
+import { mount } from '@three-ws/page-agent';
+const guide = mount({ agent: 'nova' }); // === new PageAgent(config)
+```
+
+---
+
+## HTML: `<page-agent>` element
+
+Registered automatically on import (browser only). Invisible itself — the agent
+docks to the corner.
+
+```html
+<script type="module">import '@three-ws/page-agent';</script>
+<page-agent avatar="nova" position="bottom-right" auto-narrate></page-agent>
+```
+
+### Attributes
+
+| Attribute | Maps to | Notes |
+|-----------|---------|-------|
+| `avatar` | `agent` | Initial agent id. |
+| `agents` | `agents` | Comma-separated allow-list. |
+| `position` | `position` | Dock corner. |
+| `asset-base` | `assetBase` | GLB host. |
+| `greeting` | `greeting` | Spoken on load. |
+| `auto-narrate` | `autoNarrate` | Present → tour; value → selector. |
+| `muted` | `muted` | Boolean (presence). |
+| `collapsed` | `collapsed` | Boolean (presence). |
+| `no-picker` | `picker: false` | Boolean (presence). |
+| `no-controls` | `controls: false` | Boolean (presence). |
+
+### Methods & events
+
+The element proxies `narrate`, `narratePage`, `stop`, `setAgent`, `mute`,
+`collapse`, `openPicker`, and exposes `.controller` (the `PageAgent`) and
+`.currentAgent`. Controller events are re-dispatched as bubbling DOM
+`CustomEvent`s, prefixed `page-agent:`:
+
+```js
+const el = document.querySelector('page-agent');
+el.addEventListener('page-agent:segment', (e) => console.log(e.detail.text));
+el.setAgent('vera');
+```
+
+### `registerElement(tag?)`
+
+```ts
+import { registerElement } from '@three-ws/page-agent';
+registerElement('site-guide'); // register under a custom tag → returns the tag
+```
+
+---
+
+## HTML attributes (`data-page-agent` script)
+
+Add `data-page-agent` to a `<script>` loading the global build and it auto-starts
+from its `data-*` attributes (the first such script wins; idempotent).
+
+| Attribute | Effect |
+|-----------|--------|
+| `data-page-agent` | **Required** — enables auto-init. |
+| `data-avatar` | Initial agent id. |
+| `data-agents` | Comma-separated allow-list. |
+| `data-position` | Dock corner. |
+| `data-asset-base` | GLB host. |
+| `data-greeting` | Line spoken on load. |
+| `data-auto-narrate` | Present → tour; `data-auto-narrate=".sel"` → selector. |
+| `data-muted` | Start muted (presence). |
+| `data-collapsed` | Start collapsed (presence). |
+| `data-no-picker` | Hide picker (presence). |
+| `data-no-controls` | Hide control bar (presence). |
+
+The instance is available as `window.__threeWsPageAgent`.
+
+---
+
+## Catalog
+
+```ts
+import {
+ AGENTS, DEFAULT_AGENT_ID, DEFAULT_ASSET_BASE,
+ getAgent, agentUrl, filterAgents,
+} from '@three-ws/page-agent';
+```
+
+| Export | Type | Description |
+|--------|------|-------------|
+| `AGENTS` | `RiggedAgent[]` | The full rigged roster. |
+| `DEFAULT_AGENT_ID` | `string` | `'sol'`. |
+| `DEFAULT_ASSET_BASE` | `string` | `'https://three.ws/avatars/'`. |
+| `getAgent(id)` | `RiggedAgent \| undefined` | Lookup by id. |
+| `agentUrl(agent, assetBase?)` | `string` | Resolve a GLB URL (`agent.url` wins over base+file). |
+| `filterAgents(q?)` | `RiggedAgent[]` | Filter by `{ style, presents, lipsync, ids }`. |
+
+```js
+filterAgents({ style: 'realistic', lipsync: 'viseme' });
+filterAgents({ ids: ['sol', 'nova'] });
+```
+
+### The roster
+
+| id | name | style | presents | lipsync | framing |
+|----|------|-------|----------|---------|---------|
+| `sol` | Sol | realistic | neutral | viseme | bust |
+| `nova` | Nova | stylized | female | viseme | upper |
+| `vera` | Vera | realistic | female | viseme | bust |
+| `atlas` | Atlas | realistic | male | viseme | bust |
+| `echo` | Echo | stylized | neutral | viseme | upper |
+| `lumen` | Lumen | stylized | neutral | jaw | upper |
+| `kai` | Kai | robot | robot | animation | full |
+| `mira` | Mira | stylized | female | animation | full |
+| `pax` | Pax | stylized | neutral | animation | full |
+
+---
+
+## Building blocks
+
+Full walkthrough: [Building blocks guide](./guide-building-blocks.md).
+
+### `AvatarStage`
+
+```ts
+new AvatarStage(container: HTMLElement, opts?: { background?: string })
+ .load(url: string, opts?: { framing?: 'bust'|'upper'|'full' }): Promise<gltf|null>
+ .setSpeaking(on: boolean): void
+ .onFrame(fn: (dt: number, nowMs: number) => void): () => void // returns unsub
+ .morph: { mode:'arkit'|'jaw', map } | null
+ .dispose(): void
+```
+
+### `SpeechNarrator`
+
+```ts
+new SpeechNarrator(stage: AvatarStage, opts?: {
+ muted?: boolean,
+ onState?: (s: 'idle'|'speaking') => void,
+ onCaption?: (text: string|null) => void,
+ onError?: (e: Error) => void,
+})
+ .setAgent(agent: RiggedAgent): void
+ .setMuted(muted: boolean): void
+ .speak(text: string, opts?: { interrupt?: boolean }): Promise<void> // queues
+ .cancel(): void
+ .speaking: boolean
+ .dispose(): void
+```
+
+### `AvatarPicker`
+
+```ts
+new AvatarPicker(agents: RiggedAgent[], opts: {
+ onSelect: (id: string) => void,
+ getCurrent: () => string | undefined,
+ title?: string,
+ subtitle?: string,
+})
+ .mount(parent?: HTMLElement): void
+ .open(): void
+ .close(): void
+ .isOpen: boolean
+ .dispose(): void
+
+AvatarPicker.restore(): string | null // persisted id
+AvatarPicker.persist(id: string): void
+```
+
+---
+
+## Lipsync engine
+
+```ts
+import { createLipsync, buildMorphMap, estimateDurationMs } from '@three-ws/page-agent';
+```
+
+```ts
+buildMorphMap(root: Object3D): { mode: 'arkit'|'jaw', map: Map } | null
+```
+Scan a model for viseme/jaw morph targets. `null` → no mouth morphs.
+
+```ts
+createLipsync(text: string, morph: ReturnType<typeof buildMorphMap> | null, opts?: { rate?: number }): {
+ tick(nowMs: number): void; // call each frame
+ stop(): void; // zero influences, mark done
+ readonly done: boolean;
+ readonly totalMs: number;
+}
+```
+A deterministic text→viseme timeline. With `morph === null` it's a safe no-op
+(`totalMs === 0`). `rate > 1` speeds the mouth to match faster TTS.
+
+```ts
+estimateDurationMs(text: string): number // rough natural duration, ms
+```
+
+---
+
+## Page content extraction
+
+```ts
+import { collectSegments } from '@three-ws/page-agent';
+collectSegments(selector?: string): { el: Element, text: string }[]
+```
+
+The function `narratePage()` uses to build its segment list. Useful if you want
+to compute or preview the tour yourself.
+
+### Segment selection
+
+`narratePage()` / `collectSegments()` pick the **first** non-empty source:
+
+1. Elements matching `selector` (if provided).
+2. `[data-narrate]` elements — text from the attribute, else the element's text;
+ ordered by `data-narrate-order` when present.
+3. Fallback: visible headings (`main`/`article` `h1`–`h3`, then page `h1`/`h2`)
+ each joined with their following lead `<p>`, in document order.
+
+Spoken text is whitespace-collapsed and capped at **600 chars**; the heading
+fallback yields at most **12** segments.
+
+---
+
+## Types
+
+```ts
+type AgentId = string;
+type Position = 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left';
+type LipsyncMode = 'viseme' | 'jaw' | 'animation';
+type Presents = 'female' | 'male' | 'neutral' | 'robot';
+type AvatarStyle = 'realistic' | 'stylized' | 'robot';
+type Framing = 'bust' | 'upper' | 'full';
+type PageAgentEvent = 'ready' | 'agentchange' | 'state' | 'caption' | 'segment' | 'error';
+
+interface VoiceProfile { lang?: string; pitch?: number; rate?: number; match?: string[]; }
+
+interface RiggedAgent {
+ id: AgentId; name: string; tagline: string; persona: string;
+ file: string; url?: string;
+ rig: 'rpm' | 'mixamo' | 'studio';
+ lipsync: LipsyncMode; presents: Presents; style: AvatarStyle; framing: Framing;
+ voice: VoiceProfile; accent: string;
+}
+```
+
+`PageAgentConfig` matches the [config table](#config) above.
+
+---
+
+[← Docs home](./README.md) · [Recipes →](./recipes.md) ·
+[Troubleshooting →](./troubleshooting.md)
diff --git a/page-agent-sdk/docs/guide-building-blocks.md b/page-agent-sdk/docs/guide-building-blocks.md
new file mode 100644
index 000000000..2055aedfb
--- /dev/null
+++ b/page-agent-sdk/docs/guide-building-blocks.md
@@ -0,0 +1,219 @@
+# Building blocks 🔴
+
+`PageAgent` is a convenience shell. Underneath are four independent, exported
+pieces you can compose into something entirely your own — a full-screen kiosk
+guide, an in-app onboarding character, a custom-branded picker, a game NPC.
+
+```
+AvatarStage render + animate a rigged GLB (three.js)
+SpeechNarrator speak text (Web Speech) + drive lipsync on the frame loop
+AvatarPicker accessible "choose your guide" modal
+lipsync text → timed visemes → morph influences (the engine)
+catalog the rigged roster + URL/filter helpers
+```
+
+Each is documented in the [API reference](./api-reference.md). This guide shows
+how they fit together.
+
+---
+
+## Minimal: a stage that talks, with your own UI
+
+No `PageAgent`, no default chrome — just a canvas you place anywhere and a couple
+of buttons you style yourself.
+
+```js
+import { AvatarStage, SpeechNarrator, agentUrl, getAgent } from '@three-ws/page-agent';
+
+const mountEl = document.querySelector('#guide'); // any sized container
+const stage = new AvatarStage(mountEl, { background: 'transparent' });
+
+const agent = getAgent('vera');
+await stage.load(agentUrl(agent), { framing: agent.framing });
+
+const narrator = new SpeechNarrator(stage, {
+ onState: (s) => mountEl.dataset.speaking = s === 'speaking',
+ onCaption: (text) => (myCaptionEl.textContent = text || ''),
+ onError: (e) => console.warn(e),
+});
+narrator.setAgent(agent); // adopt its voice profile
+
+myPlayBtn.onclick = () => narrator.speak('Hello! This is a fully custom guide.', { interrupt: true });
+myStopBtn.onclick = () => narrator.cancel();
+myMuteBtn.onclick = () => narrator.setMuted(true); // visual lipsync only
+
+// Clean up when you're done:
+// narrator.dispose(); stage.dispose();
+```
+
+That's the whole engine. Everything `PageAgent` does is built on exactly this.
+
+---
+
+## `AvatarStage` — the 3D surface
+
+```js
+const stage = new AvatarStage(container, { background: 'transparent' | '#0b0c10' });
+
+await stage.load(url, { framing: 'bust' | 'upper' | 'full' }); // swap models live
+stage.setSpeaking(true); // crossfade in the talk clip / body emphasis
+stage.morph; // the detected morph map (or null) — what lipsync drives
+const off = stage.onFrame((dt, nowMs) => { /* runs every render frame */ });
+off(); // unsubscribe
+stage.dispose(); // free the WebGL context
+```
+
+It auto-frames the model, plays an idle clip (or runs procedural breathing +
+blink when the GLB has no clips), handles resize via `ResizeObserver`, and
+respects `prefers-reduced-motion`.
+
+### The `onFrame` hook is your extension point
+
+Anything that should react to the avatar in real time hangs off `onFrame`. It's
+how `SpeechNarrator` advances lipsync — and you can use it for your own effects:
+
+```js
+// Pulse a ring while the agent speaks.
+stage.onFrame((dt, nowMs) => {
+ ring.style.opacity = stage._speaking ? 0.6 + 0.4 * Math.sin(nowMs / 120) : 0.15;
+});
+```
+
+---
+
+## `SpeechNarrator` — speech + lipsync
+
+```js
+const narrator = new SpeechNarrator(stage, { muted, onState, onCaption, onError });
+
+narrator.setAgent(agent); // voice profile { lang, pitch, rate, match }
+await narrator.speak(text, { interrupt }); // queues; resolves when the line ends
+narrator.cancel(); // stop + clear the queue
+narrator.setMuted(true); // keep lipsync, drop audio
+narrator.speaking; // boolean
+narrator.dispose();
+```
+
+Calls to `speak()` **queue** and play in order, each resolving when its line
+finishes — so you can script multi-line sequences with `await`. It picks the best
+installed system voice from the agent's `voice.match` hints, then `voice.lang`,
+then the first local voice. If TTS is unavailable or muted, it still runs the
+lipsync timeline for the line's estimated duration so the avatar visibly talks.
+
+---
+
+## `AvatarPicker` — your roster, their choice
+
+Build a picker from any list of agents — the full catalog, a filtered subset, or
+your own roster objects:
+
+```js
+import { AvatarPicker, filterAgents } from '@three-ws/page-agent';
+
+const roster = filterAgents({ lipsync: 'viseme' }); // e.g. only the best mouths
+
+const picker = new AvatarPicker(roster, {
+ onSelect: (id) => switchTo(id), // your swap logic
+ getCurrent: () => current.id,
+ title: 'Meet your concierge',
+ subtitle: 'Pick who shows you around.',
+});
+
+picker.mount(); // append to <body> (or pass a parent)
+myChooseBtn.onclick = () => picker.open();
+
+// Remember the choice across pages, like PageAgent does:
+AvatarPicker.persist(id);
+const saved = AvatarPicker.restore(); // string id | null
+```
+
+It's a focus-trapped, keyboard-navigable modal (arrows to move, Tab to cycle, Esc
+to close) with `role="dialog"`/`listbox` semantics — accessibility handled.
+
+---
+
+## The lipsync engine, standalone
+
+Use it on any three.js model, even outside this package:
+
+```js
+import { buildMorphMap, createLipsync, estimateDurationMs } from '@three-ws/page-agent';
+
+const morph = buildMorphMap(model); // { mode:'arkit'|'jaw', map } | null
+const ls = createLipsync('hello world', morph, { rate: 1.0 });
+
+// In your render loop:
+renderer.setAnimationLoop((t) => { ls.tick(performance.now()); /* … */ });
+
+ls.totalMs; // length of the viseme timeline
+ls.done; // true once it has fully played
+ls.stop(); // zero all influences
+
+estimateDurationMs('some text'); // rough natural duration, for pacing
+```
+
+`createLipsync` is deterministic and dependency-free: it tokenizes text into
+timed visemes and lerps the matching morph influences each frame. No audio
+analysis, no microphone, no network.
+
+---
+
+## Putting it together: a branded onboarding guide
+
+A sketch of a self-contained component that uses the blocks with custom UI,
+custom roster, and persisted choice:
+
+```js
+import {
+ AvatarStage, SpeechNarrator, AvatarPicker,
+ filterAgents, getAgent, agentUrl,
+} from '@three-ws/page-agent';
+
+export class Onboarding {
+ constructor(container) {
+ this.stage = new AvatarStage(container, { background: 'transparent' });
+ this.narrator = new SpeechNarrator(this.stage, {
+ onCaption: (t) => this.caption(t),
+ });
+ this.roster = filterAgents({ style: 'stylized' });
+ this.picker = new AvatarPicker(this.roster, {
+ onSelect: (id) => this.use(id),
+ getCurrent: () => this.agent?.id,
+ });
+ this.picker.mount();
+ this.use(AvatarPicker.restore() || this.roster[0].id);
+ }
+
+ async use(id) {
+ this.agent = getAgent(id) || this.roster[0];
+ this.narrator.setAgent(this.agent);
+ AvatarPicker.persist(this.agent.id);
+ await this.stage.load(agentUrl(this.agent), { framing: this.agent.framing });
+ }
+
+ async run() {
+ await this.narrator.speak(`Hi, I'm ${this.agent.name}. Three quick steps…`);
+ await this.narrator.speak('One: connect your account.');
+ await this.narrator.speak('Two: pick a workspace. Three: invite your team.');
+ }
+
+ caption(text) { /* render your own bubble */ }
+ destroy() { this.narrator.dispose(); this.stage.dispose(); this.picker.dispose(); }
+}
+```
+
+---
+
+## Rules of engagement
+
+- **One WebGL context at a time.** Each `AvatarStage` holds a context; dispose
+ before creating another, or you'll exhaust the browser's context budget.
+- **Always `dispose()`.** Stage, narrator, and picker each own resources
+ (WebGL, speech queue, DOM + listeners).
+- **`setAgent` before `speak`.** The narrator needs a voice profile; without one
+ it falls back to a default `en-US` voice.
+
+---
+
+Next: [API reference →](./api-reference.md) ·
+[Contributing →](../CONTRIBUTING.md)
diff --git a/page-agent-sdk/docs/recipes.md b/page-agent-sdk/docs/recipes.md
new file mode 100644
index 000000000..cba94f2f7
--- /dev/null
+++ b/page-agent-sdk/docs/recipes.md
@@ -0,0 +1,185 @@
+# Recipes 🟡
+
+Copy-paste solutions to common needs. Each assumes a `guide` instance:
+
+```js
+import { PageAgent } from '@three-ws/page-agent';
+const guide = new PageAgent({ agent: 'sol' });
+```
+
+---
+
+## Trigger the tour from a button (not on load)
+
+Leave `autoNarrate` off and start it on demand:
+
+```js
+const guide = new PageAgent({ agent: 'nova', collapsed: true });
+document.querySelector('#take-tour').addEventListener('click', () => {
+ guide.narratePage({ greet: true });
+});
+```
+
+## "Explain this" buttons
+
+```js
+function explain(text) {
+ return () => guide.narrate(text, { interrupt: true });
+}
+document.querySelector('#save').addEventListener('click', explain('This saves a draft — it won't publish.'));
+document.querySelector('#publish').addEventListener('click', explain('Publish makes your changes live for everyone.'));
+```
+
+## Only tour first-time visitors
+
+```js
+if (!localStorage.getItem('toured')) {
+ guide.on('ready', () => guide.narratePage({ greet: true }));
+ localStorage.setItem('toured', '1');
+}
+```
+
+## Track which segments visitors actually hear (analytics)
+
+```js
+guide.on('segment', ({ text, el }) => {
+ analytics.track('guide_segment', { id: el.id || el.tagName, text: text.slice(0, 80) });
+});
+guide.on('state', (s) => analytics.track('guide_' + s)); // speaking / idle
+```
+
+## Sync your UI to the speaking state
+
+```js
+guide.on('state', (s) => {
+ document.body.classList.toggle('guide-speaking', s === 'speaking');
+});
+```
+
+```css
+.guide-speaking #hero { filter: brightness(0.9); transition: filter .3s; }
+```
+
+## Route-aware narration in a SPA
+
+Re-tour the new view whenever the route changes:
+
+```js
+function onRouteChange() {
+ guide.stop();
+ guide.narratePage({ selector: '[data-view]:not([hidden]) [data-narrate]' });
+}
+// React Router: useEffect on location. Vue Router: router.afterEach. etc.
+```
+
+## Multi-language narration
+
+Pick the agent's voice via the catalog's voice profile, and feed translated copy.
+The simplest approach is your own strings keyed by `document.documentElement.lang`:
+
+```js
+const COPY = {
+ en: ['Welcome — let me show you around.', 'Start by connecting your wallet.'],
+ es: ['Bienvenido — te muestro el sitio.', 'Empieza conectando tu cartera.'],
+};
+const lines = COPY[document.documentElement.lang] || COPY.en;
+guide.on('ready', async () => { for (const l of lines) await guide.narrate(l); });
+```
+
+> Voice availability is the browser's, not ours — the visitor must have a voice
+> for that language installed. See [Troubleshooting](./troubleshooting.md#speech).
+
+## Pause speech when the tab is hidden
+
+```js
+document.addEventListener('visibilitychange', () => {
+ if (document.hidden) guide.stop();
+});
+```
+
+## Restrict and brand the picker
+
+```js
+const guide = new PageAgent({
+ agent: 'vera',
+ agents: ['vera', 'atlas', 'sol'], // only these appear in the picker
+});
+```
+
+For a custom title/subtitle or a filtered roster, build your own picker — see
+[Building blocks](./guide-building-blocks.md#avatarpicker--your-roster-their-choice).
+
+## Switch guide based on context
+
+```js
+// Match the agent to dark/light mode, locale, persona, A/B bucket, anything.
+const prefersDark = matchMedia('(prefers-color-scheme: dark)').matches;
+guide.setAgent(prefersDark ? 'echo' : 'nova');
+```
+
+## Respect a "reduce/disable" preference
+
+```js
+const wantsQuiet = matchMedia('(prefers-reduced-motion: reduce)').matches
+ || localStorage.getItem('guide-off') === '1';
+
+const guide = new PageAgent({
+ agent: 'sol',
+ muted: wantsQuiet, // visual only, no audio
+ autoNarrate: !wantsQuiet, // don't auto-tour if they opted out
+});
+```
+
+(The avatar already softens its motion under `prefers-reduced-motion`.)
+
+## Lazy-load the agent (defer the 3D cost)
+
+Only construct it when the visitor is likely to want it — on idle, first scroll,
+or a click:
+
+```js
+let guide;
+function ensureGuide() {
+ if (!guide) guide = new PageAgent({ agent: 'nova' });
+ return guide;
+}
+requestIdleCallback(ensureGuide); // or:
+addEventListener('scroll', ensureGuide, { once: true });
+```
+
+With the script tag, the global build is one request; load it `defer` or inject
+the tag on interaction.
+
+## Read a form error aloud
+
+```js
+form.addEventListener('invalid', (e) => {
+ guide.narrate(`Heads up: ${e.target.validationMessage}`, { interrupt: true });
+}, true);
+```
+
+## Clean teardown (SPA / component unmount)
+
+```js
+// React: return () => guide.dispose() from useEffect
+// Vue: onBeforeUnmount(() => guide.dispose())
+// Vanilla:
+window.addEventListener('beforeunload', () => guide.dispose());
+```
+
+## Chain narration with awaits
+
+```js
+guide.on('ready', async () => {
+ await guide.narrate('Three things to know.');
+ await guide.narrate('One: it's all client-side.');
+ await guide.narrate('Two: pick any guide. Three: it speaks your copy.');
+});
+```
+
+---
+
+More patterns welcome — send a PR (see [CONTRIBUTING](../CONTRIBUTING.md)).
+
+[← Docs home](./README.md) · [API reference →](./api-reference.md) ·
+[Troubleshooting →](./troubleshooting.md)
diff --git a/page-agent-sdk/docs/troubleshooting.md b/page-agent-sdk/docs/troubleshooting.md
new file mode 100644
index 000000000..69274d7cb
--- /dev/null
+++ b/page-agent-sdk/docs/troubleshooting.md
@@ -0,0 +1,172 @@
+# Troubleshooting & FAQ 🟢
+
+The usual snags, why they happen, and the fix.
+
+---
+
+## Speech
+
+### I see the avatar mouthing words but hear nothing
+
+Almost always the browser's **autoplay policy**: audio is blocked until the
+visitor interacts with the page. This is by design — not a bug. The avatar
+mouths the words and captions show regardless, so the guide never looks frozen;
+sound starts on the first click/tap (or when they press ▶).
+
+Nothing to fix. If you want to be explicit, prompt for a click before narrating.
+
+### Still silent after interacting
+
+- **Firefox** ships with no speech-synthesis voices by default on many systems,
+ so `speechSynthesis` may produce no audio. The visual lipsync + captions still
+ run. Chrome, Edge, and Safari have built-in voices.
+- **Voices load late.** On some platforms the voice list is empty for a moment
+ after load; the narrator listens for `voiceschanged` and picks a voice when it
+ arrives. The first line may use a default voice.
+- **Muted.** Check you didn't start with `muted` / `data-muted`.
+
+### The wrong voice is used
+
+Browsers expose different voices. Each agent lists preferred voice-name
+substrings (`voice.match`) and a language; the narrator picks the first installed
+match, then any voice for the language, then the first local voice. You can't
+guarantee a specific voice across machines — it depends on what the visitor has
+installed.
+
+### Speech cuts off / overlaps
+
+Use `{ interrupt: true }` to replace current speech, or `guide.stop()` before a
+new line. Multiple `narrate()` calls **queue** by default and play in order.
+
+---
+
+## Avatar / rendering
+
+### The avatar doesn't appear
+
+1. **WebGL.** The page needs a WebGL-capable browser/GPU. Check the console for
+ context-creation errors.
+2. **GLB failed to load.** Listen for it:
+ ```js
+ guide.on('error', (e) => console.error(e));
+ ```
+ A `Failed to load agent "…"` error means the GLB URL 404'd or was blocked.
+3. **`assetBase` / `url`.** If you're self-hosting, confirm the file exists at
+ `assetBase + agent.file` and is reachable.
+
+### CORS errors loading a self-hosted GLB
+
+Serve the model with permissive CORS headers (`Access-Control-Allow-Origin`).
+GLBs are fetched cross-origin by three.js; without CORS the load fails. A CDN or
+same-origin host avoids this.
+
+### Two agents / duplicate canvases
+
+Only run **one** `PageAgent` (or `AvatarStage`) at a time — each holds a WebGL
+context, and browsers cap how many exist. On SPA navigation or hot reload, call
+`guide.dispose()` before constructing a new one. The `<page-agent>` element
+disposes automatically on disconnect.
+
+### The avatar is a frozen statue
+
+You're loading an **unrigged** mesh through the building blocks. The runtime needs
+a skeleton (and ideally morph targets) to animate — see
+[Custom avatars](./guide-custom-avatars.md). The built-in catalog is all rigged.
+
+### Reduced motion
+
+Under `prefers-reduced-motion: reduce` the avatar softens idle motion and blinks,
+and page scrolling during a tour is instant. That's intentional.
+
+---
+
+## Build / bundler
+
+### `Cannot find module 'three'` or `Failed to resolve import "three"`
+
+The ESM build (`dist/page-agent.mjs`) leaves `three` **external** — install it:
+
+```bash
+npm install @three-ws/page-agent three
+```
+
+If you don't want to manage `three`, use the CDN global build instead, which
+inlines it:
+
+```html
+<script src="https://unpkg.com/@three-ws/page-agent/dist/page-agent.global.js"
+ data-page-agent defer></script>
+```
+
+### `[page-agent] requires a browser environment` (SSR)
+
+`PageAgent` was constructed on the server. Build it in a client-only hook
+(`useEffect`, `onMounted`, `onMount`) or behind a dynamic import with SSR
+disabled. See [Framework integration](./guide-frameworks.md).
+
+### Importing `/global` from a CDN 404s
+
+CDNs resolve real file paths, not the package's export aliases. Use the explicit
+dist path:
+
+```
+https://unpkg.com/@three-ws/page-agent/dist/page-agent.global.js
+```
+
+(or the bare `https://unpkg.com/@three-ws/page-agent`, which resolves the
+package's `unpkg` field to the same file).
+
+### Multiple versions of `three`
+
+If your app already bundles `three`, make sure there's a single copy
+(deduped) — two `three` instances can cause "is not an instance of" errors. The
+ESM build's external `three` shares your app's copy, which is what you want.
+
+---
+
+## TypeScript
+
+### `<page-agent>` errors in JSX
+
+Declare the intrinsic element once — see
+[Framework integration → TypeScript](./guide-frameworks.md#typescript).
+
+### Types aren't found
+
+They ship with the package (`types/index.d.ts`, referenced by `package.json`
+`types`). No `@types/...` install needed. If your `tsconfig` uses
+`"moduleResolution": "node"`, switch to `"bundler"` or `"node16"` so the
+`exports`/`types` map resolves.
+
+---
+
+## FAQ
+
+**Does it need a backend or API key?** No. Rendering, speech, and lipsync are all
+client-side. You bring the copy.
+
+**Is the visitor's voice/mic used?** No microphone, no audio capture, no network
+calls for speech. Lipsync is computed from the text.
+
+**How big is it?** The ESM build leaves `three` external and tree-shakes. The
+global CDN build inlines three for a single-tag drop-in (larger, but one request
+and zero setup).
+
+**Can I use my own avatar?** Yes — see [Custom avatars](./guide-custom-avatars.md).
+It must be skeleton-rigged; for lipsync include ARKit visemes or a
+`jawOpen`/`mouthOpen` morph.
+
+**Can visitors turn it off?** They can mute, minimize (collapse), and close the
+control bar's affordances. You can also gate it on a preference — see
+[Recipes](./recipes.md#respect-a-reducedisable-preference).
+
+**Which browsers?** Any modern WebGL browser renders the avatar. Speech audio is
+best in Chrome/Edge/Safari (Firefox often lacks voices). Everything degrades to
+visual lipsync + captions.
+
+---
+
+Still stuck? [Open an issue](https://github.com/nirholas/three.ws/issues) with
+your browser, a repro, and any console output.
+
+[← Docs home](./README.md)
diff --git a/walk-sdk/src/companion.js b/walk-sdk/src/companion.js
index cc0c9fd77..00c9beada 100644
--- a/walk-sdk/src/companion.js
+++ b/walk-sdk/src/companion.js
@@ -24,7 +24,16 @@ import {
} from 'three';
import { reserveWebGLContext, releaseWebGLContext } from './internal/budget.js';
import { log } from './internal/log.js';
-import { lsGet, lsSet, ssGet, ssSet, ssDel, prefersReducedMotion, webglSupported, clamp } from './internal/storage.js';
+import {
+ lsGet,
+ lsSet,
+ ssGet,
+ ssSet,
+ ssDel,
+ prefersReducedMotion,
+ webglSupported,
+ clamp,
+} from './internal/storage.js';
import { loadWalkAvatar } from './internal/load-avatar.js';
import { createAvatarPicker } from './picker.js';
import { resolveConfig, resolveAvatarEntry } from './config.js';
@@ -42,7 +51,8 @@ function isExcludedRoute(config) {
// ── Default page-context greeting (overridable via config.greeting) ───────────
function defaultGreeting(path) {
- if (path === '/pricing' || path === '/x-pricing') return 'Picking a plan? I can point you to the popular one.';
+ if (path === '/pricing' || path === '/x-pricing')
+ return 'Picking a plan? I can point you to the popular one.';
if (path === '/features') return 'Tap any feature card to see it in action.';
if (path.startsWith('/agent') || path.startsWith('/a/') || path.startsWith('/marketplace')) {
const name = pageSubjectName();
@@ -62,7 +72,9 @@ function pageSubjectName() {
function contextTargetEl() {
const path = location.pathname.replace(/\/$/, '') || '/';
if (path === '/pricing' || path === '/x-pricing') {
- return document.querySelector('[data-recommended], .pricing-card.is-featured, .plan.is-popular, .pricing-card--popular');
+ return document.querySelector(
+ '[data-recommended], .pricing-card.is-featured, .plan.is-popular, .pricing-card--popular',
+ );
}
if (path === '/features') return document.querySelector('.feature-card, [data-feature]');
return null;
@@ -205,7 +217,10 @@ class WalkCompanion {
}
_resolveEntry() {
- const param = typeof location !== 'undefined' ? new URLSearchParams(location.search).get('avatar') : null;
+ const param =
+ typeof location !== 'undefined'
+ ? new URLSearchParams(location.search).get('avatar')
+ : null;
if (param) lsSet(this.config.keys.avatar, param);
const id = param || lsGet(this.config.keys.avatar) || this.config.defaultAvatarId;
return resolveAvatarEntry(id, this.config);
@@ -213,7 +228,11 @@ class WalkCompanion {
async _loadInto(entry) {
const fallback = resolveAvatarEntry(this.config.defaultAvatarId, this.config);
- const { model, controller, entry: active } = await loadWalkAvatar(entry, {
+ const {
+ model,
+ controller,
+ entry: active,
+ } = await loadWalkAvatar(entry, {
assetBase: this.config.assetBase,
apiBase: this.config.apiBase,
manifestUrl: this.config.manifestUrl,
@@ -243,7 +262,8 @@ class WalkCompanion {
// ── Live avatar swap (from the picker) ────────────────────────────────────
async setAvatar(idOrEntry) {
- const entry = typeof idOrEntry === 'string' ? resolveAvatarEntry(idOrEntry, this.config) : idOrEntry;
+ const entry =
+ typeof idOrEntry === 'string' ? resolveAvatarEntry(idOrEntry, this.config) : idOrEntry;
if (!entry) return;
lsSet(this.config.keys.avatar, entry.id);
this._picker?.setCurrent(entry.id);
@@ -251,7 +271,11 @@ class WalkCompanion {
this._say('Switching…');
try {
const fallback = resolveAvatarEntry(this.config.defaultAvatarId, this.config);
- const { model, controller, entry: active } = await loadWalkAvatar(entry, {
+ const {
+ model,
+ controller,
+ entry: active,
+ } = await loadWalkAvatar(entry, {
assetBase: this.config.assetBase,
apiBase: this.config.apiBase,
manifestUrl: this.config.manifestUrl,
@@ -513,7 +537,9 @@ export function createWalkCompanion(opts = {}) {
function emitChange() {
try {
- window.dispatchEvent(new CustomEvent('walk-companion:change', { detail: { enabled: isEnabled() } }));
+ window.dispatchEvent(
+ new CustomEvent('walk-companion:change', { detail: { enabled: isEnabled() } }),
+ );
} catch {
/* non-fatal */
}
@@ -588,7 +614,11 @@ export function createWalkCompanion(opts = {}) {
const mod = await import('./playground.js');
if (!mod.consumeDropIn(config)) return false;
control._wirePlaygroundReturn();
- mod.launchPlayground({ avatarId: lsGet(config.keys.avatar) || null, dropIn: true, config });
+ mod.launchPlayground({
+ avatarId: lsGet(config.keys.avatar) || null,
+ dropIn: true,
+ config,
+ });
return true;
} catch (err) {
log.warn('drop-in failed:', err?.message || err);
@@ -609,7 +639,10 @@ export function createWalkCompanion(opts = {}) {
import('./playground.js')
.then((mod) => {
control._wirePlaygroundReturn();
- mod.launchPlayground({ avatarId: lsGet(config.keys.avatar) || null, config });
+ mod.launchPlayground({
+ avatarId: lsGet(config.keys.avatar) || null,
+ config,
+ });
})
.catch((err) => {
log.warn('playground deep-link failed:', err?.message || err);
diff --git a/walk-sdk/src/internal/load-avatar.js b/walk-sdk/src/internal/load-avatar.js
index ccb55bec9..26875f38e 100644
--- a/walk-sdk/src/internal/load-avatar.js
+++ b/walk-sdk/src/internal/load-avatar.js
@@ -60,7 +60,10 @@ export async function loadWalkAvatar(entry, opts = {}) {
gltf = await loader.loadAsync(url);
} catch (err) {
if (fallbackEntry && fallbackEntry.id !== entry.id) {
- log.warn(`avatar "${entry?.id}" failed to load — falling back to "${fallbackEntry.id}"`, err?.message || err);
+ log.warn(
+ `avatar "${entry?.id}" failed to load — falling back to "${fallbackEntry.id}"`,
+ err?.message || err,
+ );
active = fallbackEntry;
gltf = await loader.loadAsync(resolveAvatarUrl(fallbackEntry, { assetBase, apiBase }));
} else {
@@ -80,7 +83,9 @@ export async function loadWalkAvatar(entry, opts = {}) {
waveMs,
});
} else {
- controller = makeEmbeddedController(model, gltf.animations || [], active.clips || {}, { waveMs });
+ controller = makeEmbeddedController(model, gltf.animations || [], active.clips || {}, {
+ waveMs,
+ });
}
return { model, controller, gltf, entry: active };
diff --git a/walk-sdk/src/internal/log.js b/walk-sdk/src/internal/log.js
index 4bea58728..8ac21b257 100644
--- a/walk-sdk/src/internal/log.js
+++ b/walk-sdk/src/internal/log.js
@@ -1,3 +1,4 @@
+/* eslint-disable no-console -- this module IS the console wrapper */
// Minimal namespaced logger. Quiet by default; set `window.__walkDebug = true`
// (or localStorage `walk:debug` = '1') to surface info/debug lines. Warnings
// and errors always pass through so failures are never swallowed silently.
diff --git a/walk-sdk/src/internal/meshopt.js b/walk-sdk/src/internal/meshopt.js
index 7d44f18e3..25a546c0e 100644
--- a/walk-sdk/src/internal/meshopt.js
+++ b/walk-sdk/src/internal/meshopt.js
@@ -10,8 +10,6 @@ let _promise = null;
export function getMeshoptDecoder() {
if (_promise) return _promise;
- _promise = import('three/addons/libs/meshopt_decoder.module.js').then(
- (m) => m.MeshoptDecoder,
- );
+ _promise = import('three/addons/libs/meshopt_decoder.module.js').then((m) => m.MeshoptDecoder);
return _promise;
}
diff --git a/walk-sdk/src/picker.js b/walk-sdk/src/picker.js
index 9506e1e55..529c58c62 100644
--- a/walk-sdk/src/picker.js
+++ b/walk-sdk/src/picker.js
@@ -58,7 +58,13 @@ function ensureStyles() {
*/
export function createAvatarPicker(opts) {
ensureStyles();
- const { avatars = [], onSelect, anchor = { right: 16, bottom: 16 }, assetBase = '', docsUrl } = opts;
+ const {
+ avatars = [],
+ onSelect,
+ anchor = { right: 16, bottom: 16 },
+ assetBase = '',
+ docsUrl,
+ } = opts;
let currentId = opts.currentId || null;
let query = '';
@@ -95,7 +101,9 @@ export function createAvatarPicker(opts) {
btn.dataset.id = entry.id;
btn.title = entry.blurb || entry.name;
if (entry.accent) btn.style.setProperty('--wp-accent', entry.accent);
- const orbStyle = entry.thumb ? ` style="background-image:url('${assetBase}${entry.thumb}')"` : '';
+ const orbStyle = entry.thumb
+ ? ` style="background-image:url('${assetBase}${entry.thumb}')"`
+ : '';
btn.innerHTML = `
<span class="walk-picker-orb"${orbStyle}>${entry.thumb ? '' : entry.emoji || '🧍'}</span>
<span class="walk-picker-name">${entry.name}</span>
diff --git a/walk-sdk/src/playground.js b/walk-sdk/src/playground.js
index 4263e5b64..10c0c27b3 100644
--- a/walk-sdk/src/playground.js
+++ b/walk-sdk/src/playground.js
@@ -31,7 +31,14 @@ import {
} from 'three';
import { reserveWebGLContext, releaseWebGLContext } from './internal/budget.js';
import { log } from './internal/log.js';
-import { ssGet, ssSet, ssDel, prefersReducedMotion, webglSupported, clamp } from './internal/storage.js';
+import {
+ ssGet,
+ ssSet,
+ ssDel,
+ prefersReducedMotion,
+ webglSupported,
+ clamp,
+} from './internal/storage.js';
import { loadWalkAvatar } from './internal/load-avatar.js';
import { resolveConfig, resolveAvatarEntry } from './config.js';
@@ -65,7 +72,20 @@ const FOOT_PAD = 26;
const LAND_TOL = 14;
const LINK_ARM_MS = 850;
-const SOLID_SELECTOR = ['a[href]', 'button', 'h1', 'h2', 'h3', 'h4', 'p', 'li', 'img', 'figure', '.card', '[data-platform]'].join(',');
+const SOLID_SELECTOR = [
+ 'a[href]',
+ 'button',
+ 'h1',
+ 'h2',
+ 'h3',
+ 'h4',
+ 'p',
+ 'li',
+ 'img',
+ 'figure',
+ '.card',
+ '[data-platform]',
+].join(',');
function getMode() {
try {
@@ -282,7 +302,13 @@ class StrollPlayground {
const shadow = new Mesh(
new CircleGeometry(1, 28),
- new MeshBasicMaterial({ color: 0x05070c, transparent: true, opacity: 0.32, side: DoubleSide, depthWrite: false }),
+ new MeshBasicMaterial({
+ color: 0x05070c,
+ transparent: true,
+ opacity: 0.32,
+ side: DoubleSide,
+ depthWrite: false,
+ }),
);
shadow.renderOrder = -1;
scene.add(shadow);
@@ -329,7 +355,11 @@ class StrollPlayground {
this.char.y = clamp(startScreen.y + sy, EDGE_PAD, docHeight() - EDGE_PAD);
} else {
this.char.x = clamp(w * 0.5, EDGE_PAD, w - EDGE_PAD);
- this.char.y = clamp(sy + window.innerHeight * (dropIn ? 0.32 : 0.4), EDGE_PAD, docHeight() - EDGE_PAD);
+ this.char.y = clamp(
+ sy + window.innerHeight * (dropIn ? 0.32 : 0.4),
+ EDGE_PAD,
+ docHeight() - EDGE_PAD,
+ );
}
this.char.vx = 0;
this.char.vy = 0;
@@ -358,7 +388,8 @@ class StrollPlayground {
else if (k === 'ArrowRight' || k === 'd' || k === 'D') this.input.right = true;
else if (k === 'ArrowUp' || k === 'w' || k === 'W') this.input.up = true;
else if (k === 'ArrowDown' || k === 's' || k === 'S') this.input.down = true;
- else if (k === ' ' || k === 'Spacebar' || k === 'Enter' || k === 'e' || k === 'E') this.input.dive = true;
+ else if (k === ' ' || k === 'Spacebar' || k === 'Enter' || k === 'e' || k === 'E')
+ this.input.dive = true;
else handled = false;
if (handled) e.preventDefault();
}
@@ -369,7 +400,8 @@ class StrollPlayground {
else if (k === 'ArrowRight' || k === 'd' || k === 'D') this.input.right = false;
else if (k === 'ArrowUp' || k === 'w' || k === 'W') this.input.up = false;
else if (k === 'ArrowDown' || k === 's' || k === 'S') this.input.down = false;
- else if (k === ' ' || k === 'Spacebar' || k === 'Enter' || k === 'e' || k === 'E') this.input.dive = false;
+ else if (k === ' ' || k === 'Spacebar' || k === 'Enter' || k === 'e' || k === 'E')
+ this.input.dive = false;
}
_onResize() {
@@ -386,7 +418,12 @@ class StrollPlayground {
_hintFor(dropIn) {
const touch = matchMedia('(pointer: coarse)').matches;
const move = touch ? 'Use the d-pad to walk' : 'Arrow keys / WASD to walk anywhere';
- this._say(dropIn ? `You're in! ${move}. Step on a link to dive deeper.` : `${move}. Step on a link to dive in.`, 5200);
+ this._say(
+ dropIn
+ ? `You're in! ${move}. Step on a link to dive deeper.`
+ : `${move}. Step on a link to dive in.`,
+ 5200,
+ );
}
_sayModeIntro() {
@@ -536,7 +573,8 @@ class StrollPlayground {
this.rig.rotation.y += dt * 10;
const s = Math.max(0.04, this.rig.scale.x - dt * 1.6);
this.rig.scale.setScalar(s);
- if (this.shadow) this.shadow.material.opacity = Math.max(0, this.shadow.material.opacity - dt * 0.8);
+ if (this.shadow)
+ this.shadow.material.opacity = Math.max(0, this.shadow.material.opacity - dt * 0.8);
} else {
let d = this.char.facing - this._yaw;
while (d > Math.PI) d -= Math.PI * 2;
@@ -629,7 +667,10 @@ class PlatformerPlayground {
const host = document.createElement('div');
host.className = 'walk-pg walk-pg--plat';
host.setAttribute('role', 'application');
- host.setAttribute('aria-label', 'Page playground — walk and jump the character with arrow keys');
+ host.setAttribute(
+ 'aria-label',
+ 'Page playground — walk and jump the character with arrow keys',
+ );
host.innerHTML = `
<canvas class="walk-pg-canvas"></canvas>
<div class="walk-pg-hint" aria-live="polite"></div>
@@ -694,7 +735,14 @@ class PlatformerPlayground {
sun.position.set(120, 260, 220);
scene.add(sun);
- this.camera = new OrthographicCamera(0, window.innerWidth, 0, -window.innerHeight, -1000, 2000);
+ this.camera = new OrthographicCamera(
+ 0,
+ window.innerWidth,
+ 0,
+ -window.innerHeight,
+ -1000,
+ 2000,
+ );
this.camera.position.z = 600;
const rig = new Group();
@@ -746,7 +794,8 @@ class PlatformerPlayground {
const bottom = r.bottom + sy;
if (bottom < bandTop || top > bandBottom) continue;
const style = el.ownerDocument.defaultView.getComputedStyle(el);
- if (style.visibility === 'hidden' || style.display === 'none' || +style.opacity === 0) continue;
+ if (style.visibility === 'hidden' || style.display === 'none' || +style.opacity === 0)
+ continue;
const left = r.left + sx;
const right = r.right + sx;
const key = `${Math.round(left)},${Math.round(top)},${Math.round(right)}`;
@@ -768,7 +817,14 @@ class PlatformerPlayground {
out.push({ left, right, top, bottom, href, el });
}
const w = docWidth();
- out.push({ left: -40, right: w + 40, top: docHeight() - 3, bottom: docHeight(), href: null, el: null });
+ out.push({
+ left: -40,
+ right: w + 40,
+ top: docHeight() - 3,
+ bottom: docHeight(),
+ href: null,
+ el: null,
+ });
this.platforms = out;
if (this.platform && !out.includes(this.platform)) out.push(this.platform);
}
@@ -799,7 +855,8 @@ class PlatformerPlayground {
let handled = true;
if (k === 'ArrowLeft' || k === 'a' || k === 'A') this.input.left = true;
else if (k === 'ArrowRight' || k === 'd' || k === 'D') this.input.right = true;
- else if (k === ' ' || k === 'ArrowUp' || k === 'w' || k === 'W' || k === 'Spacebar') this.input.jump = true;
+ else if (k === ' ' || k === 'ArrowUp' || k === 'w' || k === 'W' || k === 'Spacebar')
+ this.input.jump = true;
else if (k === 'ArrowDown' || k === 's' || k === 'S') this.input.down = true;
else handled = false;
if (handled) e.preventDefault();
@@ -832,7 +889,12 @@ class PlatformerPlayground {
_hintFor(dropIn) {
const touch = matchMedia('(pointer: coarse)').matches;
const move = touch ? 'Use the buttons' : 'Arrow keys / WASD to move, Space to jump';
- this._say(dropIn ? `You fell in! ${move}. Land on a link to dive deeper.` : `${move}. Land on a link to dive in.`, 5200);
+ this._say(
+ dropIn
+ ? `You fell in! ${move}. Land on a link to dive deeper.`
+ : `${move}. Land on a link to dive in.`,
+ 5200,
+ );
}
_sayModeIntro() {
@@ -1151,7 +1213,13 @@ export function playgroundState() {
diving: _instance._diving,
};
if (_instance.mode === 'platformer') {
- return { ...base, grounded: c.grounded, facing: c.facing, platforms: _instance.platforms.length, onLink: !!_instance.platform?.href };
+ return {
+ ...base,
+ grounded: c.grounded,
+ facing: c.facing,
+ platforms: _instance.platforms.length,
+ onLink: !!_instance.platform?.href,
+ };
}
return { ...base, speed: Math.round(Math.hypot(c.vx, c.vy)), onLink: !!_instance._armHref };
}
diff --git a/walk-sdk/src/roster.js b/walk-sdk/src/roster.js
index f160defc9..1c30726df 100644
--- a/walk-sdk/src/roster.js
+++ b/walk-sdk/src/roster.js
@@ -95,7 +95,13 @@ export const WALK_AVATARS = [
asset: '/avatars/xbot.glb',
source: 'static',
rig: 'shared',
- clips: { idle: 'xbot-idle', walk: 'xbot-walk', run: 'xbot-run', wave: 'wave', jump: 'jump' },
+ clips: {
+ idle: 'xbot-idle',
+ walk: 'xbot-walk',
+ run: 'xbot-run',
+ wave: 'wave',
+ jump: 'jump',
+ },
accent: '#9aa7b5',
tags: ['humanoid', 'robot', 'mixamo'],
},
diff --git a/x402-modal-sdk/build.mjs b/x402-modal-sdk/build.mjs
new file mode 100644
index 000000000..2bb4db226
--- /dev/null
+++ b/x402-modal-sdk/build.mjs
@@ -0,0 +1,53 @@
+#!/usr/bin/env node
+/**
+ * Build @three-ws/x402-modal.
+ *
+ * Two artifacts:
+ * dist/x402-modal.mjs — ESM, side-effect-free. The public API (`pay`,
+ * `configure`, `init`, `CheckoutModal`, …) with no
+ * `window` / auto-bind on import. For bundler + npm
+ * consumers. The dynamic CDN imports (Solana web3.js,
+ * a keccak for EVM SIWX) are left as runtime imports.
+ * dist/x402.global.js — IIFE, minified. Reads `data-x402-*` off its own
+ * <script> tag, auto-binds `[data-x402-endpoint]`,
+ * and exposes `window.X402`. The drop-in CDN <script>.
+ */
+
+import { build } from 'esbuild';
+import { mkdirSync } 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');
+mkdirSync(outDir, { recursive: true });
+
+const common = {
+ bundle: true,
+ sourcemap: true,
+ target: ['es2020'],
+ logLevel: 'info',
+ // The Solana web3.js / @noble/hashes imports are runtime CDN URLs resolved in
+ // the browser — never bundle them.
+ external: ['https://*'],
+};
+
+// 1) ESM core, side-effect-free.
+await build({
+ ...common,
+ entryPoints: [resolve(here, 'src/x402-modal.js')],
+ format: 'esm',
+ outfile: resolve(outDir, 'x402-modal.mjs'),
+});
+
+// 2) Standalone IIFE drop-in <script>, auto-init + window.X402.
+await build({
+ ...common,
+ entryPoints: [resolve(here, 'src/global.js')],
+ format: 'iife',
+ globalName: 'X402Modal',
+ minify: true,
+ outfile: resolve(outDir, 'x402.global.js'),
+});
+
+console.log('[x402-modal] built dist/x402-modal.mjs, dist/x402.global.js');
diff --git a/x402-modal-sdk/src/util.js b/x402-modal-sdk/src/util.js
new file mode 100644
index 000000000..6f7df1148
--- /dev/null
+++ b/x402-modal-sdk/src/util.js
@@ -0,0 +1,147 @@
+// Pure, browser-API-free helpers shared by the modal. Kept in their own module
+// so they can be unit-tested in Node without a DOM, and so the core stays lean.
+
+// USDC EIP-3009 typed-data sig works against Base USDC. The domain `version`
+// must match the on-chain `EIP712_DOMAIN_SEPARATOR_VERSION` — Base USDC is "2".
+export const EVM_NETWORKS = {
+ 'eip155:8453': { chainId: 8453, name: 'Base', explorer: 'https://basescan.org/tx/' },
+ 'eip155:84532': { chainId: 84532, name: 'Base Sepolia', explorer: 'https://sepolia.basescan.org/tx/' },
+ 'eip155:42161': { chainId: 42161, name: 'Arbitrum', explorer: 'https://arbiscan.io/tx/' },
+ 'eip155:10': { chainId: 10, name: 'Optimism', explorer: 'https://optimistic.etherscan.io/tx/' },
+};
+
+// Stablecoins whose atomics are already 6-decimal USD-pegged (used by caps).
+export const STABLE_NAMES = new Set([
+ 'usdc', 'usd coin', 'usdt', 'tether', 'binance-peg usd coin', 'dai',
+]);
+
+// Normalize a single 402 `accept` entry. The x402 spec's canonical atomic-price
+// field is `maxAmountRequired`; some merchants emit `amount`. We read `amount`
+// everywhere downstream, so coerce here once. Without this a spec-compliant
+// merchant yields `accept.amount === undefined` → "NaN USDC".
+export function normalizeAccept(accept) {
+ if (!accept || typeof accept !== 'object') return accept;
+ const amount = accept.amount ?? accept.maxAmountRequired;
+ return amount != null && accept.amount == null ? { ...accept, amount: String(amount) } : accept;
+}
+
+export function isSolanaNetwork(net) {
+ return typeof net === 'string' && (net === 'solana' || net.startsWith('solana:'));
+}
+export function isEvmNetwork(net) {
+ return typeof net === 'string' && net.startsWith('eip155:');
+}
+// The modal only signs EIP-3009 transferWithAuthorization for EVM. When the
+// server publishes both an EIP-3009 entry and a Permit2 sibling (the
+// gas-sponsoring path), pick the EIP-3009 one — the sibling carries
+// `extra.assetTransferMethod === 'permit2'`.
+export function isEip3009Accept(accept) {
+ if (!isEvmNetwork(accept?.network)) return false;
+ const method = accept?.extra?.assetTransferMethod;
+ return !method || method === 'eip3009';
+}
+export function networkLabel(net, accept) {
+ if (isSolanaNetwork(net)) return 'Solana';
+ const meta = EVM_NETWORKS[net];
+ return meta?.name || accept?.extra?.name || net;
+}
+export function explorerUrl(net, tx) {
+ if (!tx) return null;
+ if (isSolanaNetwork(net)) return `https://solscan.io/tx/${tx}`;
+ const meta = EVM_NETWORKS[net];
+ return meta ? `${meta.explorer}${tx}` : null;
+}
+
+export function formatAmount(rawAtomics, decimals = 6) {
+ const n = Number(rawAtomics) / 10 ** decimals;
+ if (n < 0.01) return n.toFixed(6).replace(/0+$/, '').replace(/\.$/, '');
+ if (n < 1) return n.toFixed(4).replace(/0+$/, '').replace(/\.$/, '');
+ return n.toFixed(2);
+}
+
+export function b64encode(obj) {
+ const json = JSON.stringify(obj);
+ if (typeof Buffer !== 'undefined') return Buffer.from(json, 'utf8').toString('base64');
+ return btoa(unescape(encodeURIComponent(json)));
+}
+export function b64decode(str) {
+ if (!str) return null;
+ try {
+ const bin = typeof Buffer !== 'undefined' ? Buffer.from(str, 'base64').toString('utf8') : decodeURIComponent(escape(atob(str)));
+ return JSON.parse(bin);
+ } catch (_) {
+ return null;
+ }
+}
+
+// Base58 (Bitcoin alphabet) — Solana's encoding for addresses and signatures.
+const BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
+export function base58encode(bytes) {
+ if (!bytes || bytes.length === 0) return '';
+ let leadingZeros = 0;
+ while (leadingZeros < bytes.length && bytes[leadingZeros] === 0) leadingZeros++;
+ let n = 0n;
+ for (let i = 0; i < bytes.length; i++) n = (n << 8n) | BigInt(bytes[i]);
+ let out = '';
+ while (n > 0n) {
+ out = BASE58_ALPHABET[Number(n % 58n)] + out;
+ n /= 58n;
+ }
+ for (let i = 0; i < leadingZeros; i++) out = BASE58_ALPHABET[0] + out;
+ return out;
+}
+
+// Convert an asset's atomic amount to micro-USD for cap accounting. Stablecoins
+// pass through (scaled to 6 decimals); non-stable assets pass through atomic and
+// must be capped server-side (the browser modal fetches no prices).
+export function toMicroUsd(amount, accept) {
+ const atomic = BigInt(amount);
+ const decimals = Number(accept?.extra?.decimals ?? 6);
+ const name = String(accept?.extra?.name || '').toLowerCase();
+ if (STABLE_NAMES.has(name)) {
+ if (decimals === 6) return atomic;
+ if (decimals > 6) return atomic / 10n ** BigInt(decimals - 6);
+ return atomic * 10n ** BigInt(6 - decimals);
+ }
+ return atomic;
+}
+
+export function spendBuckets(timestamp = Date.now()) {
+ const hour = Math.floor(timestamp / 3_600_000);
+ const day = Math.floor(timestamp / 86_400_000);
+ return { hour, day };
+}
+
+// Build the CAIP-122 SIWX message string. The server rebuilds the same string
+// from payload fields when verifying — any line-by-line drift makes the
+// recovered signer mismatch payload.address and the signature is rejected.
+export function buildSiwxMessage(info, chain, address) {
+ const isEvm = chain.type === 'eip191';
+ const accountHeader = isEvm
+ ? `${info.domain} wants you to sign in with your Ethereum account:`
+ : `${info.domain} wants you to sign in with your Solana account:`;
+ const [, chainTail = ''] = String(chain.chainId).split(':');
+ const chainRef = isEvm ? String(parseInt(chainTail, 10)) : chainTail;
+
+ const lines = [accountHeader, address, ''];
+ if (info.statement) {
+ lines.push(info.statement, '');
+ } else if (isEvm) {
+ // siwe's prepareMessage() reserves the statement block even when absent,
+ // emitting an extra blank line. SIWS does not.
+ lines.push('');
+ }
+ lines.push(`URI: ${info.uri}`);
+ lines.push(`Version: ${info.version || '1'}`);
+ lines.push(`Chain ID: ${chainRef}`);
+ lines.push(`Nonce: ${info.nonce}`);
+ lines.push(`Issued At: ${info.issuedAt}`);
+ if (info.expirationTime) lines.push(`Expiration Time: ${info.expirationTime}`);
+ if (info.notBefore) lines.push(`Not Before: ${info.notBefore}`);
+ if (info.requestId !== undefined && info.requestId !== null) lines.push(`Request ID: ${info.requestId}`);
+ if (Array.isArray(info.resources) && info.resources.length) {
+ lines.push('Resources:');
+ for (const r of info.resources) lines.push(`- ${r}`);
+ }
+ return lines.join('\n');
+}
diff --git a/x402-modal-sdk/src/x402-modal.js b/x402-modal-sdk/src/x402-modal.js
index 49c356950..5c9bb16bc 100644
--- a/x402-modal-sdk/src/x402-modal.js
+++ b/x402-modal-sdk/src/x402-modal.js
@@ -20,6 +20,22 @@
// response }. Vanilla JS; the only network deps (Solana web3.js, a keccak for
// EVM SIWX) are dynamic-imported from a CDN, and only when that path runs.
+import {
+ EVM_NETWORKS,
+ normalizeAccept,
+ isSolanaNetwork,
+ isEip3009Accept,
+ networkLabel,
+ explorerUrl,
+ formatAmount,
+ b64encode,
+ b64decode,
+ base58encode,
+ toMicroUsd,
+ spendBuckets,
+ buildSiwxMessage,
+} from './util.js';
+
const VERSION = '0.2.0';
// ─────────────────────────────────────────────────────────── configuration ───
diff --git a/x402-modal-sdk/types/index.d.ts b/x402-modal-sdk/types/index.d.ts
new file mode 100644
index 000000000..773b91ae3
--- /dev/null
+++ b/x402-modal-sdk/types/index.d.ts
@@ -0,0 +1,149 @@
+// Type definitions for @three-ws/x402-modal
+
+/** A CAIP-2 network id, e.g. `solana:5eyk…`, `eip155:8453` (Base). */
+export type NetworkId = string;
+
+/** Footer attribution shown at the bottom of the modal. */
+export interface Brand {
+ /** Visible label, e.g. "Powered by Acme". */
+ label?: string;
+ /** Optional link target; renders the label as an anchor when present. */
+ href?: string;
+}
+
+/**
+ * ERC-8021 builder-code self-attribution echoed back when the 402 challenge
+ * declares a builder code. Set the whole field to `null` to disable the echo.
+ */
+export interface BuilderCode {
+ /** Your wallet code (`[a-z0-9_]{1,32}`). */
+ wallet?: string;
+ /** Your integration / service code (`[a-z0-9_]{1,32}`). */
+ service?: string;
+}
+
+/** Per-wallet spending caps, enforced in localStorage. Amounts are µUSD (1e6 = $1). */
+export interface SpendingCaps {
+ /** Max micro-USD a single call may spend. */
+ maxPerCall?: number | string;
+ /** Max micro-USD per rolling UTC hour. */
+ maxPerHour?: number | string;
+ /** Max micro-USD per rolling UTC day. */
+ maxPerDay?: number | string;
+}
+
+/** Global configuration. Defaults reproduce three.ws's hosted behaviour. */
+export interface X402Config {
+ /**
+ * Origin serving the Solana `prepare`/`encode` checkout helpers
+ * (`POST {apiOrigin}/api/x402-checkout?action=prepare|encode`). Only the
+ * Solana path uses it; the EVM/EIP-3009 path needs no backend. `null`
+ * resolves from the script's own origin. `''` means same-origin.
+ */
+ apiOrigin?: string | null;
+ brand?: Brand;
+ /** `null` disables the builder-code echo entirely. */
+ builderCode?: BuilderCode | null;
+ /** CDN URL for `@solana/web3.js`, dynamic-imported on the Solana path. */
+ solanaWeb3Url?: string;
+ /** CDN URL for `@noble/hashes/sha3`, dynamic-imported on the EVM SIWX path. */
+ nobleHashesUrl?: string;
+}
+
+/** Options for a single {@link pay} call. */
+export interface PayOptions {
+ /** The x402-protected endpoint to pay for and call. Required. */
+ endpoint: string;
+ /** HTTP method to use against `endpoint`. Defaults to GET (POST when a body is set). */
+ method?: string;
+ /** Request body forwarded to the endpoint (object → JSON, or a raw string). */
+ body?: unknown;
+ /** Extra request headers merged into the discovery + paid calls. */
+ headers?: Record<string, string>;
+ /** Merchant name shown in the modal header. */
+ merchant?: string;
+ /** Action label shown in the modal header (e.g. "Summarize"). */
+ action?: string;
+ /** Per-wallet spending caps for this call. */
+ caps?: SpendingCaps;
+ /** Skip the wallet picker when exactly one supported wallet is detected. */
+ autoConnect?: boolean;
+ /** Per-call override of the Solana checkout API origin. */
+ apiOrigin?: string;
+ /** Per-call override of the footer brand. */
+ brand?: Brand;
+}
+
+/** Settlement details parsed from the `x-payment-response` header. */
+export interface PaymentReceipt {
+ network?: NetworkId;
+ payer?: string;
+ transaction?: string;
+ [k: string]: unknown;
+}
+
+/** SIWX re-entry details when the wallet signed in instead of paying. */
+export interface SiwxReceipt {
+ address: string;
+ network: NetworkId | string;
+}
+
+/** Resolved value of a successful {@link pay} call. */
+export interface PayResult {
+ ok: true;
+ /** The merchant endpoint's response body (parsed JSON or raw text). */
+ result: unknown;
+ /** Present on a fresh payment. */
+ payment?: PaymentReceipt;
+ /** Present when the user re-entered via SIWX instead of paying. */
+ siwx?: SiwxReceipt;
+ response: { status: number; headers: Record<string, string> };
+}
+
+/** Merge config into the global defaults. Returns the resolved snapshot. */
+export function configure(opts?: X402Config): Required<X402Config>;
+
+/** Read the current resolved global config. */
+export function getConfig(): Required<X402Config>;
+
+/**
+ * Open the payment modal for an x402 endpoint. Resolves after settlement, or
+ * rejects with an `Error` whose `code` is `'cancelled'` if the user closes it.
+ */
+export function pay(opts: PayOptions): Promise<PayResult>;
+
+/** Scan the document and bind every `[data-x402-endpoint]` element. Idempotent. */
+export function init(): void;
+
+/** Bind one element's click to open the modal (sets the `x402:result` event). */
+export function bindElement(el: Element): void;
+
+/** Read {@link PayOptions} from an element's `data-x402-*` attributes. */
+export function readOptsFrom(el: Element): PayOptions;
+
+/** The package version string. */
+export const version: string;
+
+/** The low-level modal controller. Most callers should use {@link pay}. */
+export class CheckoutModal {
+ constructor(opts: PayOptions);
+ mount(): Promise<PayResult>;
+ start(): Promise<void>;
+ close(reason?: string): void;
+}
+
+declare global {
+ interface Window {
+ X402?: {
+ pay: typeof pay;
+ init: typeof init;
+ configure: typeof configure;
+ version: string;
+ };
+ }
+ interface HTMLElementEventMap {
+ 'x402:result': CustomEvent<PayResult>;
+ 'x402:error': CustomEvent<{ error: string }>;
+ 'x402:siwx-signed': CustomEvent<SiwxReceipt>;
+ }
+}
diff --git a/x402-payment-modal/build.mjs b/x402-payment-modal/build.mjs
new file mode 100644
index 000000000..cabc73cb3
--- /dev/null
+++ b/x402-payment-modal/build.mjs
@@ -0,0 +1,47 @@
+#!/usr/bin/env node
+/**
+ * Build script for @three-ws/x402-payment-modal.
+ *
+ * The source (src/index.js) is already a standalone, dependency-free ES module:
+ * the only imports it performs are runtime `import()` of pinned esm.sh URLs, made
+ * lazily and only when a Solana or EVM-sign-in payment is actually attempted. So
+ * there is nothing to *bundle* — we just emit a readable copy and a minified copy
+ * for CDN delivery. We deliberately use esbuild's single-file `transform` (not
+ * `build`) so those `https://…` dynamic imports are left untouched instead of
+ * esbuild trying (and failing) to resolve them at build time.
+ */
+
+import esbuild from '../node_modules/esbuild/lib/main.js';
+import { readFileSync, writeFileSync, copyFileSync, mkdirSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const here = dirname(fileURLToPath(import.meta.url));
+const srcFile = join(here, 'src/index.js');
+const distDir = join(here, 'dist');
+mkdirSync(distDir, { recursive: true });
+
+const pkg = JSON.parse(readFileSync(join(here, 'package.json'), 'utf8'));
+const source = readFileSync(srcFile, 'utf8');
+const banner = `/*! ${pkg.name} v${pkg.version} — ${pkg.license} — ${pkg.homepage} */\n`;
+
+// 1. Readable, unminified copy for CDN debugging and source maps in DevTools.
+writeFileSync(join(distDir, 'x402.js'), banner + source);
+
+// 2. Minified copy for production CDN delivery (unpkg/jsDelivr point here).
+const minified = await esbuild.transform(source, {
+ minify: true,
+ format: 'esm',
+ target: 'es2020',
+ loader: 'js',
+ legalComments: 'none',
+});
+writeFileSync(join(distDir, 'x402.min.js'), banner + minified.code);
+
+// 3. Ship the type definitions next to the dist bundles too.
+copyFileSync(join(here, 'types/index.d.ts'), join(distDir, 'index.d.ts'));
+
+const kb = (s) => `${(Buffer.byteLength(s) / 1024).toFixed(1)} KB`;
+console.log(`[x402-payment-modal] built dist/x402.js ${kb(banner + source)}`);
+console.log(`[x402-payment-modal] built dist/x402.min.js ${kb(banner + minified.code)}`);
+console.log('[x402-payment-modal] copied dist/index.d.ts');
diff --git a/x402-payment-modal/package.json b/x402-payment-modal/package.json
index bdf4712d7..4d85b7fa2 100644
--- a/x402-payment-modal/package.json
+++ b/x402-payment-modal/package.json
@@ -48,7 +48,6 @@
],
"scripts": {
"build": "node build.mjs",
- "sync:public": "node scripts/sync-public.mjs",
"test": "node --test test/",
"prepublishOnly": "npm run build"
},
diff --git a/x402-payment-modal/server/checkout.js b/x402-payment-modal/server/checkout.js
new file mode 100644
index 000000000..51aa18edc
--- /dev/null
+++ b/x402-payment-modal/server/checkout.js
@@ -0,0 +1,293 @@
+// @three-ws/x402-payment-modal/server — Solana checkout helpers.
+//
+// The modal's EVM path signs EIP-3009 typed-data entirely in the browser and
+// never calls your server. The Solana path is different: Phantom only *signs*
+// serialized transactions — it does not build instructions. So the modal needs a
+// tiny server endpoint that (a) builds the SPL transfer the buyer should sign,
+// and (b) wraps the signed transaction into the base64 `X-PAYMENT` envelope the
+// x402 facilitator expects.
+//
+// This module is framework-agnostic. `prepareSolanaCheckout` and
+// `encodeX402Payment` are pure functions; `handleCheckout` routes the two
+// actions and returns `{ status, body }`. Thin adapters for Express and Vercel
+// live in ./express.js and ./vercel.js.
+//
+// Runtime deps: @solana/web3.js and @solana/spl-token (declared as optional peer
+// dependencies — install them in the app that mounts this handler). Nothing here
+// imports anything three.ws-specific.
+
+import {
+ Connection,
+ PublicKey,
+ TransactionMessage,
+ VersionedTransaction,
+ ComputeBudgetProgram,
+} from '@solana/web3.js';
+import {
+ TOKEN_PROGRAM_ID,
+ ASSOCIATED_TOKEN_PROGRAM_ID,
+ getAssociatedTokenAddressSync,
+ createAssociatedTokenAccountIdempotentInstruction,
+ createTransferCheckedInstruction,
+ getMint,
+} from '@solana/spl-token';
+
+export const X402_VERSION = 2;
+
+// CAIP-2 network identifiers for Solana (genesis-hash prefixes).
+export const NETWORK_SOLANA_MAINNET = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';
+export const NETWORK_SOLANA_DEVNET = 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1';
+
+const DEFAULT_MAINNET_RPC = 'https://api.mainnet-beta.solana.com';
+const DEFAULT_DEVNET_RPC = 'https://api.devnet.solana.com';
+
+// Short-lived caches so repeated prepare calls don't re-issue identical RPC
+// round-trips. Mint decimals are effectively immutable; a Solana blockhash stays
+// valid for ~60-90s, so a few seconds of reuse cuts redundant traffic without
+// handing out a blockhash too stale for the buyer's signed tx to land.
+const MINT_DECIMALS_TTL_MS = 5 * 60 * 1000;
+const BLOCKHASH_TTL_MS = 8 * 1000;
+const mintDecimalsCache = new Map(); // `${rpc}:${mint}` -> { decimals, at }
+const blockhashCache = new Map(); // rpc -> { blockhash, at }
+
+/** Thrown for any client-correctable problem; carries an HTTP `status` + `code`. */
+export class CheckoutError extends Error {
+ constructor(status, code, message) {
+ super(message);
+ this.name = 'CheckoutError';
+ this.status = status;
+ this.code = code;
+ }
+}
+
+export function isSolanaNetwork(network) {
+ return (
+ network === NETWORK_SOLANA_MAINNET ||
+ network === NETWORK_SOLANA_DEVNET ||
+ network === 'solana'
+ );
+}
+
+function rpcFor(network, { rpcUrl, devnetRpcUrl } = {}) {
+ if (network === NETWORK_SOLANA_DEVNET) return devnetRpcUrl || DEFAULT_DEVNET_RPC;
+ return rpcUrl || DEFAULT_MAINNET_RPC;
+}
+
+const BASE58 = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+function assertPubkey(value, field) {
+ if (typeof value !== 'string' || !BASE58.test(value)) {
+ throw new CheckoutError(400, 'invalid_request', `${field} must be a base58 Solana address`);
+ }
+ return value;
+}
+
+// Validate the subset of the x402 `accept` entry the Solana path relies on.
+// `extra.feePayer` is required — it is the facilitator's sponsor account that
+// pays the SOL network fee so the buyer needs no SOL, only USDC.
+function validateAccept(accept) {
+ if (!accept || typeof accept !== 'object') {
+ throw new CheckoutError(400, 'invalid_request', 'accept object is required');
+ }
+ if (accept.scheme !== 'exact') {
+ throw new CheckoutError(400, 'invalid_request', `unsupported scheme: ${accept.scheme}`);
+ }
+ if (!isSolanaNetwork(accept.network)) {
+ throw new CheckoutError(
+ 400,
+ 'unsupported_network',
+ `prepare only builds Solana transactions; got network=${accept.network}. EVM clients sign EIP-712 typed data locally and don't need this endpoint.`,
+ );
+ }
+ if (typeof accept.amount !== 'string' || !/^\d+$/.test(accept.amount)) {
+ throw new CheckoutError(400, 'invalid_request', 'accept.amount must be an atomic integer string');
+ }
+ assertPubkey(accept.asset, 'accept.asset');
+ assertPubkey(accept.payTo, 'accept.payTo');
+ const feePayer = accept.extra?.feePayer;
+ assertPubkey(feePayer, 'accept.extra.feePayer');
+ return accept;
+}
+
+async function getMintDecimals(conn, rpc, mint) {
+ const key = `${rpc}:${mint.toBase58()}`;
+ const hit = mintDecimalsCache.get(key);
+ if (hit && Date.now() - hit.at < MINT_DECIMALS_TTL_MS) return hit.decimals;
+ const info = await getMint(conn, mint);
+ mintDecimalsCache.set(key, { decimals: info.decimals, at: Date.now() });
+ return info.decimals;
+}
+
+async function getRecentBlockhash(conn, rpc) {
+ const hit = blockhashCache.get(rpc);
+ if (hit && Date.now() - hit.at < BLOCKHASH_TTL_MS) return hit.blockhash;
+ const { blockhash } = await conn.getLatestBlockhash('confirmed');
+ blockhashCache.set(rpc, { blockhash, at: Date.now() });
+ return blockhash;
+}
+
+/**
+ * Build the partially-signed v0 SPL `transferChecked` the buyer's Phantom wallet
+ * should add its signature to. The fee payer is `accept.extra.feePayer` (the
+ * facilitator's sponsor), so the buyer pays only USDC.
+ *
+ * @param {object} args
+ * @param {object} args.accept one x402 `accept` entry (scheme=exact, Solana)
+ * @param {string} args.buyer buyer's base58 Solana address
+ * @param {string} [args.rpcUrl] mainnet RPC URL override
+ * @param {string} [args.devnetRpcUrl] devnet RPC URL override
+ * @returns {Promise<{ network: string, tx_base64: string, recent_blockhash: string }>}
+ */
+export async function prepareSolanaCheckout({ accept, buyer, rpcUrl, devnetRpcUrl }) {
+ validateAccept(accept);
+ assertPubkey(buyer, 'buyer');
+
+ const rpc = rpcFor(accept.network, { rpcUrl, devnetRpcUrl });
+ const conn = new Connection(rpc, 'confirmed');
+
+ const mint = new PublicKey(accept.asset);
+ const payTo = new PublicKey(accept.payTo);
+ const feePayer = new PublicKey(accept.extra.feePayer);
+ const buyerPubkey = new PublicKey(buyer);
+ const amount = BigInt(accept.amount);
+
+ const senderAta = getAssociatedTokenAddressSync(
+ mint, buyerPubkey, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
+ );
+ const receiverAta = getAssociatedTokenAddressSync(
+ mint, payTo, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
+ );
+ const mintDecimals = await getMintDecimals(conn, rpc, mint);
+
+ const ixs = [
+ ComputeBudgetProgram.setComputeUnitLimit({ units: 60_000 }),
+ ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 1 }),
+ ];
+ // Create the recipient's token account if it doesn't exist yet — idempotent,
+ // paid for by the fee payer so the buyer is never charged extra SOL.
+ const receiverInfo = await conn.getAccountInfo(receiverAta);
+ if (!receiverInfo) {
+ ixs.push(
+ createAssociatedTokenAccountIdempotentInstruction(
+ feePayer, receiverAta, payTo, mint, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
+ ),
+ );
+ }
+ ixs.push(
+ createTransferCheckedInstruction(
+ senderAta, mint, receiverAta, buyerPubkey, amount, mintDecimals, [], TOKEN_PROGRAM_ID,
+ ),
+ );
+
+ const blockhash = await getRecentBlockhash(conn, rpc);
+ const message = new TransactionMessage({
+ payerKey: feePayer,
+ recentBlockhash: blockhash,
+ instructions: ixs,
+ }).compileToV0Message();
+ const vtx = new VersionedTransaction(message);
+
+ return {
+ network: accept.network,
+ tx_base64: Buffer.from(vtx.serialize()).toString('base64'),
+ recent_blockhash: blockhash,
+ };
+}
+
+const BUILDER_CODE_PATTERN = /^[a-z0-9_]{1,32}$/;
+function sanitizeBuilderCode(builderCode) {
+ if (!builderCode || typeof builderCode !== 'object') return null;
+ const a = builderCode.a;
+ if (typeof a !== 'string' || !BUILDER_CODE_PATTERN.test(a)) return null;
+ const out = { a };
+ if (typeof builderCode.w === 'string' && BUILDER_CODE_PATTERN.test(builderCode.w)) out.w = builderCode.w;
+ if (Array.isArray(builderCode.s)) {
+ const s = builderCode.s.filter((x) => typeof x === 'string' && BUILDER_CODE_PATTERN.test(x)).slice(0, 32);
+ if (s.length) out.s = s;
+ }
+ return out;
+}
+
+/**
+ * Wrap a buyer-signed Solana transaction into the base64 `X-PAYMENT` envelope.
+ *
+ * @param {object} args
+ * @param {object} args.accept the same accept entry used in prepare
+ * @param {string} args.signedTxBase64 base64 of the fully buyer-signed v0 tx
+ * @param {string} args.resourceUrl absolute URL of the paid resource
+ * @param {object} [args.builderCode] optional ERC-8021 builder-code echo
+ * @returns {{ x_payment: string }}
+ */
+export function encodeX402Payment({ accept, signedTxBase64, resourceUrl, builderCode }) {
+ validateAccept(accept);
+ if (typeof signedTxBase64 !== 'string' || signedTxBase64.length < 40) {
+ throw new CheckoutError(400, 'invalid_request', 'signedTxBase64 is required');
+ }
+ let url;
+ try {
+ url = new URL(resourceUrl).href;
+ } catch {
+ throw new CheckoutError(400, 'invalid_request', 'resourceUrl must be an absolute URL');
+ }
+
+ const payload = {
+ x402Version: X402_VERSION,
+ scheme: 'exact',
+ network: accept.network,
+ resource: { url, mimeType: 'application/json' },
+ accepted: accept,
+ payload: { transaction: signedTxBase64 },
+ };
+ const echo = sanitizeBuilderCode(builderCode);
+ if (echo) payload.extensions = { 'builder-code': echo };
+
+ return { x_payment: Buffer.from(JSON.stringify(payload), 'utf8').toString('base64') };
+}
+
+/**
+ * Route an action ('prepare' | 'encode') to its handler and return a plain
+ * `{ status, body }` pair the framework adapters serialize as JSON. Accepts the
+ * camelCase fields the helpers use *and* the snake_case fields the browser modal
+ * POSTs (`signed_tx_base64`, `resource_url`, `builder_code`).
+ *
+ * @param {object} args
+ * @param {'prepare'|'encode'} args.action
+ * @param {object} args.body parsed JSON request body
+ * @param {object} [args.options] { rpcUrl, devnetRpcUrl }
+ * @returns {Promise<{ status: number, body: object }>}
+ */
+export async function handleCheckout({ action, body = {}, options = {} }) {
+ try {
+ if (action === 'prepare') {
+ const data = await prepareSolanaCheckout({
+ accept: body.accept,
+ buyer: body.buyer,
+ rpcUrl: options.rpcUrl,
+ devnetRpcUrl: options.devnetRpcUrl,
+ });
+ return { status: 200, body: data };
+ }
+ if (action === 'encode') {
+ const data = encodeX402Payment({
+ accept: body.accept,
+ signedTxBase64: body.signedTxBase64 ?? body.signed_tx_base64,
+ resourceUrl: body.resourceUrl ?? body.resource_url,
+ builderCode: body.builderCode ?? body.builder_code,
+ });
+ return { status: 200, body: data };
+ }
+ return {
+ status: 404,
+ body: { error: 'not_found', error_description: `unknown action: ${action ?? '(none)'}` },
+ };
+ } catch (err) {
+ if (err instanceof CheckoutError) {
+ return { status: err.status, body: { error: err.code, error_description: err.message } };
+ }
+ // Unexpected (RPC down, malformed tx). Surface a generic 502 — the caller
+ // shows "try again"; the real cause is in your server logs.
+ return {
+ status: 502,
+ body: { error: 'checkout_failed', error_description: 'Could not build the Solana payment. Try again.' },
+ };
+ }
+}
diff --git a/x402-payment-modal/server/express.js b/x402-payment-modal/server/express.js
new file mode 100644
index 000000000..f87c0caff
--- /dev/null
+++ b/x402-payment-modal/server/express.js
@@ -0,0 +1,44 @@
+// Express adapter for the Solana checkout endpoints.
+//
+// import express from 'express';
+// import { x402CheckoutRouter } from '@three-ws/x402-payment-modal/server/express';
+//
+// const app = express();
+// app.use(express.json());
+// app.use('/api/x402-checkout', x402CheckoutRouter({ rpcUrl: process.env.SOLANA_RPC_URL }));
+//
+// The modal POSTs to `/api/x402-checkout?action=prepare` and `?action=encode`.
+// CORS is permissive (the drop-in modal runs on any origin); tighten `origin`
+// via the option if you only serve your own pages.
+
+import { handleCheckout } from './checkout.js';
+
+/**
+ * @param {object} [options]
+ * @param {string} [options.rpcUrl] Solana mainnet RPC URL
+ * @param {string} [options.devnetRpcUrl] Solana devnet RPC URL
+ * @param {string} [options.origin] Access-Control-Allow-Origin (default '*')
+ * @returns {import('express').RequestHandler}
+ */
+export function x402CheckoutRouter(options = {}) {
+ const allowOrigin = options.origin || '*';
+ return async function x402CheckoutHandler(req, res) {
+ res.setHeader('Access-Control-Allow-Origin', allowOrigin);
+ res.setHeader('Access-Control-Allow-Methods', 'POST,OPTIONS');
+ res.setHeader('Access-Control-Allow-Headers', 'content-type');
+ if (req.method === 'OPTIONS') {
+ res.status(204).end();
+ return;
+ }
+ if (req.method !== 'POST') {
+ res.status(405).json({ error: 'method_not_allowed', error_description: 'use POST' });
+ return;
+ }
+ const action = req.query?.action;
+ const body = req.body && typeof req.body === 'object' ? req.body : {};
+ const { status, body: out } = await handleCheckout({ action, body, options });
+ res.status(status).json(out);
+ };
+}
+
+export default x402CheckoutRouter;
diff --git a/x402-payment-modal/server/vercel.js b/x402-payment-modal/server/vercel.js
new file mode 100644
index 000000000..9590719df
--- /dev/null
+++ b/x402-payment-modal/server/vercel.js
@@ -0,0 +1,54 @@
+// Vercel / Next.js (pages API) adapter for the Solana checkout endpoints.
+//
+// Save as `api/x402-checkout.js`:
+//
+// export { default } from '@three-ws/x402-payment-modal/server/vercel';
+//
+// or with options:
+//
+// import { createVercelCheckoutHandler } from '@three-ws/x402-payment-modal/server/vercel';
+// export default createVercelCheckoutHandler({ rpcUrl: process.env.SOLANA_RPC_URL });
+//
+// The modal POSTs to this route with `?action=prepare` and `?action=encode`.
+
+import { handleCheckout } from './checkout.js';
+
+async function readJsonBody(req) {
+ // Next.js pages API and Vercel Node functions usually pre-parse JSON into
+ // req.body. When they don't (raw runtime), read the stream ourselves.
+ if (req.body && typeof req.body === 'object') return req.body;
+ if (typeof req.body === 'string' && req.body) {
+ try { return JSON.parse(req.body); } catch { return {}; }
+ }
+ const chunks = [];
+ for await (const chunk of req) chunks.push(chunk);
+ if (!chunks.length) return {};
+ try { return JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { return {}; }
+}
+
+/**
+ * @param {object} [options] { rpcUrl, devnetRpcUrl, origin }
+ * @returns {(req: any, res: any) => Promise<void>}
+ */
+export function createVercelCheckoutHandler(options = {}) {
+ const allowOrigin = options.origin || '*';
+ return async function handler(req, res) {
+ res.setHeader('Access-Control-Allow-Origin', allowOrigin);
+ res.setHeader('Access-Control-Allow-Methods', 'POST,OPTIONS');
+ res.setHeader('Access-Control-Allow-Headers', 'content-type');
+ if (req.method === 'OPTIONS') {
+ res.status(204).end();
+ return;
+ }
+ if (req.method !== 'POST') {
+ res.status(405).json({ error: 'method_not_allowed', error_description: 'use POST' });
+ return;
+ }
+ const action = req.query?.action;
+ const body = await readJsonBody(req);
+ const { status, body: out } = await handleCheckout({ action, body, options });
+ res.status(status).json(out);
+ };
+}
+
+export default createVercelCheckoutHandler();