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 + page-agent SDK packages, walk-sdk playground/companion, rig inspect

nirholascedc4cb0ae39
diff --git a/CHANGELOG.md b/CHANGELOG.md
index eee012ed4..447c3a8ad 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -57,6 +57,8 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Platform-wide API security hardening** — We completed a full security audit of the API and tightened it across the board. Server errors no longer echo internal details back to callers — they return a short reference code you can quote to support, while the real diagnostics stay server-side (this also closes a path where a backend service key could surface in an error message). Account-changing actions made from the website — updating preferences, managing webhooks and payout wallets, marking notifications read, scheduling posts, setting skill prices — now carry cross-site request-forgery protection, so a malicious page can't act on your behalf. Sign-in, wallet-linking, GitHub connect and sensitive admin actions gained rate limits, and image-analysis requests are now screened so a supplied URL can't be used to probe internal systems. API access via developer keys is unaffected. `[security]`
- **Pole Club music opens up as you walk inside** — The soundtrack at the Pole Club now follows you in. Out in the alley it plays muffled and bass-heavy, like the room heard through the door. Pay the cover and the same track — never restarted, just picked up from wherever it is — gets a little clearer with every threshold you cross: a step more open when the rope drops, more again through the gallery and the clubhouse, then wide open the moment you step onto the floor. The walk in now sounds like a walk in. (`/club`) `[improvement]`
- **Premium avatar cosmetics are now buyable right in the character creator** — Locked premium headwear, eyewear, dyes and auras in the character creator no longer dead-end on a placeholder — clicking one now opens the real wallet checkout and unlocks it the moment the USDC payment settles, then equips it on your live preview. Anything you already own loads pre-unlocked, and the price you see is the true checkout amount pulled from the catalog. (`/create`) `[feature, fix]`
+- **Put a talking 3D guide on any website — new @three-ws/page-agent SDK** — Drop one tag onto any site and a rigged 3D agent appears in the corner, greets visitors, and talks them through the page out loud — mouth moving in time with the words, all in the browser with no backend or API key. Visitors pick who guides them from a diverse roster of rigged agents (realistic, stylized, and a robot), and the choice is remembered as they move between pages. Only skeleton-rigged avatars ship in the catalog, so every guide actually breathes, blinks, and lip-syncs instead of standing frozen. Install @three-ws/page-agent from npm, or paste the one-line embed. `[sdk, feature]`
+- **Rigged-or-not filter across your Agents and Avatars** — The rigged-or-not category now reaches everything you own, not just the public gallery. Your Avatars page (both My avatars and the Community tab) and your Agents page each get a Rigged / Static filter and a badge on every card, so you can tell at a glance which models carry a skeleton and can play the animation library — and narrow the list to just the animation-ready ones. An agent's badge reflects the rig state of its 3D body. (`/dashboard/avatars`) `[feature]`
- **Saved avatar now shows the real model on the "what's next" screen** — After saving an avatar you'd made — including ones built from a template — the post-save "your agent is ready" screen showed a blank white mannequin instead of the avatar you just created, even though the name was correct. The page was looking for the model under a field name the agent record doesn't use, and never fell back to the avatar itself. It now loads your actual avatar — and works even for private avatars you've just made. `[fix]`
- **See your net take when you price a skill** — The Skill Pricing panel on the Monetize dashboard now shows exactly what you keep on every payment. As you type a per-call price, a line below the field updates live — "You receive $X.XX after 2.5% fee" — so the platform's cut is never a surprise at payout time. The same net figure appears in the Add Pricing dialog, and the panel header states the current platform fee rate, which is read from the live billing config rather than hardcoded. (`/dashboard/monetize`) `[feature, improvement]`
- **Shared agent links now unfurl with the agent's own avatar** — When you paste a link to an agent on X, Discord, Slack, Telegram or iMessage, the preview card now shows that agent's actual avatar, name and description instead of a generic three.ws image — so every shared link is visual proof of the collectible. Bots that don't run JavaScript get the right image and text rendered on the server, and agents without an avatar yet fall back to a clean branded card with their initial. We also fixed the canonical and share URLs on agent pages to point at the real /agents/<id> address. `[feature, improvement]`
diff --git a/api/_lib/glb-inspect.js b/api/_lib/glb-inspect.js
index 0c6949fad..83543a3ab 100644
--- a/api/_lib/glb-inspect.js
+++ b/api/_lib/glb-inspect.js
@@ -37,7 +37,7 @@ const CHUNK_BIN = 0x004E4942; // 'BIN\0' little-endian
* binChunkBytes: number,
* }}
*/
-export function inspectGlb(buf) {
+export function inspectGlb(buf, { allowPartial = false } = {}) {
if (!isBufferLike(buf) || buf.length < 12 + 8) return null;
const view = bufToDataView(buf);
if (view.getUint32(0, true) !== GLB_MAGIC) return null;
@@ -46,7 +46,14 @@ export function inspectGlb(buf) {
// Reject if declared length is inconsistent with the buffer or absurdly large.
// 512 MB is a hard ceiling — no realistic avatar exceeds this; a corrupted
// header could otherwise allocate enormous slices during JSON chunk reads.
- if (declaredLen > buf.length || declaredLen < 20) return null;
+ //
+ // allowPartial: the caller deliberately fetched only a leading prefix (a
+ // ranged read covering the JSON chunk), so declaredLen — the FULL file size —
+ // legitimately exceeds buf.length. Skip that consistency check; the JSON
+ // chunk's own bounds are still validated below, so a truncated/short prefix
+ // (chunk not fully present) returns null and the caller can refetch.
+ if (!allowPartial && declaredLen > buf.length) return null;
+ if (declaredLen < 20) return null;
if (declaredLen > 512 * 1024 * 1024) return null;
// First chunk header at byte 12.
@@ -112,6 +119,20 @@ export function inspectGlb(buf) {
};
}
+/**
+ * Byte offset at which the glTF JSON chunk ends (i.e. the minimum prefix length
+ * needed to parse it): 12-byte file header + 8-byte chunk header + chunk body.
+ * Returns 0 when the buffer is too short or isn't a JSON-first binary glTF.
+ * Lets a ranged-read caller fetch exactly enough on a second pass.
+ */
+export function glbJsonChunkEnd(buf) {
+ if (!isBufferLike(buf) || buf.length < 20) return 0;
+ const view = bufToDataView(buf);
+ if (view.getUint32(0, true) !== GLB_MAGIC) return 0;
+ if (view.getUint32(16, true) !== CHUNK_JSON) return 0;
+ return 20 + view.getUint32(12, true);
+}
+
/**
* Strict header check used by upload boundaries — does not parse JSON.
* Returns true iff the 12-byte header + first chunk header look valid.
diff --git a/api/_lib/r2.js b/api/_lib/r2.js
index 951763890..58b89b5f6 100644
--- a/api/_lib/r2.js
+++ b/api/_lib/r2.js
@@ -116,6 +116,18 @@ export async function getObjectBuffer(key) {
return Buffer.concat(chunks);
}
+// Read just the leading `length` bytes of an object via an HTTP Range request.
+// Used by the rig classifier to read a GLB's glTF JSON chunk (which lives at
+// the file head) without downloading the whole — potentially large — mesh.
+export async function getObjectRange(key, length) {
+ const { Body } = await r2.send(
+ new GetObjectCommand({ Bucket: env.S3_BUCKET, Key: key, Range: `bytes=0-${length - 1}` }),
+ );
+ const chunks = [];
+ for await (const chunk of Body) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
+ return Buffer.concat(chunks);
+}
+
// Public CDN URL for objects served via R2 custom domain / r2.dev.
//
// First-party / externally-hosted avatars store an absolute URL in their
diff --git a/api/_lib/rig-inspect.js b/api/_lib/rig-inspect.js
new file mode 100644
index 000000000..1b4a16189
--- /dev/null
+++ b/api/_lib/rig-inspect.js
@@ -0,0 +1,63 @@
+// Server-side rig inspection for stored GLBs.
+//
+// The rig classifier needs to know whether an avatar carries a skeleton
+// (glTF skins[] + joints). That signal lives entirely in the glTF JSON chunk,
+// which sits at the head of the file — so we read only a leading prefix via a
+// ranged request and never download the (potentially large) mesh binary.
+//
+// Used at upload time (api/avatars/index.js → handleCreate) so every new avatar
+// self-classifies, and by scripts/backfill-rig-meta.mjs to populate avatars
+// that predate the classifier.
+
+import { getObjectRange } from './r2.js';
+import { inspectGlb, glbJsonChunkEnd } from './glb-inspect.js';
+
+// 256 KB covers the JSON chunk of essentially every real avatar in one read.
+const INITIAL_PREFIX = 256 * 1024;
+// Refetch ceiling — a JSON chunk larger than this is pathological; leave it
+// "unknown" rather than pull megabytes hunting for joints.
+const MAX_PREFIX = 8 * 1024 * 1024;
+
+async function readGlbPrefix(storageKey, length) {
+ if (/^https?:\/\//i.test(storageKey)) {
+ // Externally-hosted / first-party absolute URLs (e.g. the built-in sample
+ // avatars at three.ws/avatars/*.glb) aren't bucket objects — range-fetch.
+ const r = await fetch(storageKey, { headers: { Range: `bytes=0-${length - 1}` } });
+ if (!r.ok) throw new Error(`http ${r.status}`);
+ return Buffer.from(await r.arrayBuffer());
+ }
+ return getObjectRange(storageKey, length);
+}
+
+/**
+ * Inspect a stored GLB's rig signal from its JSON chunk only.
+ * @param {string} storageKey — R2 object key or absolute URL.
+ * @returns {Promise<null | {
+ * is_rigged: boolean, skin_count: number, skeleton_joint_count: number,
+ * node_count: number, mesh_count: number, animation_count: number,
+ * glb_generator: string | null,
+ * }>} null when the object isn't a parseable GLB (caller treats as "unknown").
+ */
+export async function inspectStorageKeyRig(storageKey) {
+ if (!storageKey) return null;
+ let buf = await readGlbPrefix(storageKey, INITIAL_PREFIX);
+ let info = inspectGlb(buf, { allowPartial: true });
+ if (!info) {
+ // JSON chunk didn't fit in the first prefix — refetch exactly enough.
+ const need = glbJsonChunkEnd(buf);
+ if (need > buf.length && need <= MAX_PREFIX) {
+ buf = await readGlbPrefix(storageKey, need);
+ info = inspectGlb(buf, { allowPartial: true });
+ }
+ }
+ if (!info) return null;
+ return {
+ is_rigged: info.isRigged,
+ skin_count: info.skinCount,
+ skeleton_joint_count: info.skeletonJointCount,
+ node_count: info.nodeCount,
+ mesh_count: info.meshCount,
+ animation_count: info.animationCount,
+ glb_generator: info.generator,
+ };
+}
diff --git a/api/avatars/index.js b/api/avatars/index.js
index 14d61db7c..e000ac020 100644
--- a/api/avatars/index.js
+++ b/api/avatars/index.js
@@ -4,6 +4,7 @@
import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
import { listAvatars, createAvatar } from '../_lib/avatars.js';
import { headObject, r2 } from '../_lib/r2.js';
+import { inspectStorageKeyRig } from '../_lib/rig-inspect.js';
import { HeadObjectCommand } from '@aws-sdk/client-s3';
import { env } from '../_lib/env.js';
import { sql } from '../_lib/db.js';
@@ -92,6 +93,22 @@ async function handleCreate(req, res) {
if (!rows[0]) return error(res, 404, 'not_found', 'parent_avatar_id not found');
}
+ // Skeleton-inspect the uploaded GLB so the rig classifier (gallery filter,
+ // per-card badge, "Rigged first" sort) knows whether it can animate. Only the
+ // glTF JSON chunk is read via a ranged request — never the mesh binary — so
+ // this is one small round trip. Best-effort: any failure leaves the rig fields
+ // absent and the avatar reads as "unknown", exactly as before. Paths that
+ // already stamp the signal (reconstruct, forge, studio) pass their own
+ // source_meta; we only fill what inspection found and never clobber it.
+ if (!body.source_meta || body.source_meta.is_rigged == null) {
+ try {
+ const rig = await inspectStorageKeyRig(body.storage_key);
+ if (rig) body.source_meta = { ...rig, ...(body.source_meta || {}) };
+ } catch {
+ // non-fatal — classifier degrades to "unknown" for this avatar
+ }
+ }
+
const avatar = await createAvatar({
userId: auth.userId,
input: body,
diff --git a/data/changelog.json b/data/changelog.json
index 103aba8a1..3e9924575 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-19",
+ "title": "Put a talking 3D guide on any website — new @three-ws/page-agent SDK",
+ "summary": "Drop one tag onto any site and a rigged 3D agent appears in the corner, greets visitors, and talks them through the page out loud — mouth moving in time with the words, all in the browser with no backend or API key. Visitors pick who guides them from a diverse roster of rigged agents (realistic, stylized, and a robot), and the choice is remembered as they move between pages. Only skeleton-rigged avatars ship in the catalog, so every guide actually breathes, blinks, and lip-syncs instead of standing frozen. Install @three-ws/page-agent from npm, or paste the one-line embed.",
+ "tags": [
+ "sdk",
+ "feature"
+ ]
+ },
+ {
+ "date": "2026-06-19",
+ "title": "Rigged-or-not filter across your Agents and Avatars",
+ "summary": "The rigged-or-not category now reaches everything you own, not just the public gallery. Your Avatars page (both My avatars and the Community tab) and your Agents page each get a Rigged / Static filter and a badge on every card, so you can tell at a glance which models carry a skeleton and can play the animation library — and narrow the list to just the animation-ready ones. An agent's badge reflects the rig state of its 3D body.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/dashboard/avatars"
+ },
{
"date": "2026-06-19",
"title": "Filter the avatar gallery by rigged vs static",
diff --git a/package.json b/package.json
index daf55000b..31d8bd0b5 100644
--- a/package.json
+++ b/package.json
@@ -39,6 +39,7 @@
"agent-payments-sdk",
"agent-ui-sdk",
"avatar-sdk",
+ "page-agent-sdk",
"character-studio",
"mcp-bridge",
"mcp-server",
diff --git a/page-agent-sdk/LICENSE b/page-agent-sdk/LICENSE
new file mode 100644
index 000000000..8e2251ab4
--- /dev/null
+++ b/page-agent-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/page-agent-sdk/README.md b/page-agent-sdk/README.md
new file mode 100644
index 000000000..252e9b8dc
--- /dev/null
+++ b/page-agent-sdk/README.md
@@ -0,0 +1,190 @@
+<div align="center">
+
+# @three-ws/page-agent
+
+**A rigged 3D AI agent that talks your visitors through any web page.**
+
+One tag. A skeleton-rigged, lipsync-capable avatar docks in the corner, greets
+visitors, narrates your page out loud, and lets each visitor pick the guide they
+want — from a diverse roster of rigged agents.
+
+[![npm](https://img.shields.io/npm/v/@three-ws/page-agent?logo=npm&color=cb3837)](https://www.npmjs.com/package/@three-ws/page-agent)
+[![downloads](https://img.shields.io/npm/dm/@three-ws/page-agent?color=cb3837)](https://www.npmjs.com/package/@three-ws/page-agent)
+![license](https://img.shields.io/npm/l/@three-ws/page-agent?color=3b82f6)
+![node](https://img.shields.io/node/v/@three-ws/page-agent?color=339933&logo=node.js)
+
+[Quick start](#quick-start) · [The catalog](#the-rigged-catalog) · [API](#api) · [How it works](#how-it-works) · [FAQ](#faq)
+
+</div>
+
+---
+
+## Why
+
+Most "AI widget" embeds are a text bubble. This is a **3D presence**: a rigged
+character that looks at the visitor, breathes, blinks, and moves its mouth to the
+words it speaks — synthesized in the browser, no backend, no API key, no audio
+files.
+
+**Only rigged agents, by design.** Every avatar in the catalog ships a verified
+skinned mesh + armature. That's a hard rule, not a preference: the runtime drives
+skeletal idle motion and viseme lipsync, so an unrigged mesh would render a
+frozen, dead-faced statue. Those are excluded.
+
+## Quick start
+
+### 1 — One script tag (zero JS)
+
+```html
+<script type="module"
+ src="https://unpkg.com/@three-ws/page-agent/global"
+ data-page-agent
+ data-avatar="nova"
+ data-auto-narrate></script>
+```
+
+That's it. `Nova` appears bottom-right and tours the page. The visitor can change
+guides from the control bar.
+
+### 2 — HTML element
+
+```html
+<script type="module">import '@three-ws/page-agent';</script>
+
+<page-agent avatar="sol" position="bottom-right" auto-narrate></page-agent>
+```
+
+### 3 — Imperative (full control)
+
+```js
+import { PageAgent } from '@three-ws/page-agent';
+
+const guide = new PageAgent({ agent: 'atlas', autoNarrate: true });
+
+guide.narrate('Welcome — let me show you the new dashboard.');
+guide.on('segment', ({ text, el }) => highlight(el));
+```
+
+> **Peer dependency:** `three` (>= 0.150). Bundler users get tree-shaking and a
+> small ESM build with `three` left external. The `/global` build inlines three
+> for a plain CDN `<script>`.
+
+## The rigged catalog
+
+A deliberately diverse roster — realistic, stylized, and robot guides, with
+different presentations and lipsync capabilities. Every one is rigged.
+
+| id | name | style | presents | lipsync |
+|---------|-------|------------|----------|-----------|
+| `sol` | Sol | realistic | neutral | viseme |
+| `nova` | Nova | stylized | female | viseme |
+| `vera` | Vera | realistic | female | viseme |
+| `atlas` | Atlas | realistic | male | viseme |
+| `echo` | Echo | stylized | neutral | viseme |
+| `lumen` | Lumen | stylized | neutral | jaw |
+| `kai` | Kai | robot | robot | full-body |
+| `mira` | Mira | stylized | female | full-body |
+| `pax` | Pax | stylized | neutral | full-body |
+
+- **viseme** — full Oculus/ARKit viseme morphs; phoneme-accurate mouth shapes.
+- **jaw** — a single jaw/mouthOpen morph driven on a speech envelope.
+- **full-body** — no face morphs; the agent carries speech with a talk body
+ animation + head motion (Mixamo rigs).
+
+```js
+import { AGENTS, filterAgents } from '@three-ws/page-agent';
+
+filterAgents({ style: 'realistic' }); // just the realistic guides
+filterAgents({ lipsync: 'viseme' }); // best-in-class mouth sync
+```
+
+Self-host the GLBs by pointing `assetBase` (or any agent's `url`) at your own CDN.
+
+## API
+
+### `new PageAgent(config)`
+
+| option | type | default | notes |
+|----------------|----------------------------------------|----------------|-------|
+| `agent` | `string` | saved / `sol` | initial rigged agent id |
+| `agents` | `string[]` | all | allow-list shown in the picker |
+| `position` | `bottom-right \| bottom-left \| top-right \| top-left` | `bottom-right` | dock corner |
+| `assetBase` | `string` | three.ws CDN | GLB host |
+| `autoNarrate` | `boolean \| string` | `false` | `true` tours the page; a string is a CSS selector of segments |
+| `greeting` | `string` | — | spoken on load (ignored if `autoNarrate`) |
+| `muted` | `boolean` | `false` | start muted (visual lipsync only) |
+| `collapsed` | `boolean` | `false` | start as the launcher pill |
+| `picker` | `boolean` | `true` | show the "change agent" affordance |
+| `controls` | `boolean` | `true` | show the control bar |
+| `persistAgent` | `boolean` | `true` | remember the visitor's choice |
+
+### Methods
+
+```ts
+guide.narrate(text, { interrupt? }) // speak one line → Promise
+guide.narratePage({ selector?, greet? }) // walk + narrate the page → Promise
+guide.stop() // cancel narration
+guide.setAgent('vera') // swap rigged avatar live → Promise
+guide.mute(true) / guide.collapse(true)
+guide.openPicker() / guide.closePicker()
+guide.on(event, cb) / guide.off(event, cb)
+guide.dispose()
+```
+
+### Events
+
+`ready` · `agentchange` · `state` (`idle`/`speaking`) · `caption` · `segment` ·
+`error`. On the `<page-agent>` element these are DOM `CustomEvent`s prefixed
+`page-agent:` (e.g. `page-agent:agentchange`).
+
+### Marking up a guided page
+
+The page walk reads, in order of preference:
+
+1. elements matching your `selector`,
+2. `[data-narrate]` elements (optionally ordered with `data-narrate-order`),
+3. a heading + lead-paragraph fallback.
+
+```html
+<h1 data-narrate="Welcome — here's what's new this week.">Changelog</h1>
+<section data-narrate data-narrate-order="2">…read verbatim…</section>
+```
+
+## How it works
+
+```
+PageAgent ─┬─ AvatarStage three.js scene · loads the rigged GLB · frames
+ │ bust/upper/full · idle clip or procedural
+ │ breathing+blink · talk animation
+ ├─ SpeechNarrator Web Speech TTS queue · picks a voice per agent ·
+ │ drives the lipsync timeline on the render loop
+ ├─ AvatarPicker accessible modal grid · persists the choice
+ └─ lipsync text → timed visemes → morph influences
+```
+
+No microphone, no network calls for speech, no API keys. Speech is `SpeechSynthesis`;
+lipsync is a deterministic text-to-viseme heuristic advanced on three.js's frame
+loop so mouth shapes track the spoken words. Where TTS is unavailable or muted,
+the avatar still "talks" visually and captions render — narration never silently
+stalls.
+
+Accessibility: keyboard-navigable picker with focus trap and `Esc`, `aria-live`
+captions, focus-visible rings, and full `prefers-reduced-motion` /
+`prefers-color-scheme` support.
+
+## FAQ
+
+**Can I use my own avatar?** Yes — give an agent an absolute `url` to your rigged
+GLB, or override `assetBase`. It must be skeleton-rigged; for lipsync include
+Oculus visemes (`viseme_aa` …) or at least a `jawOpen` / `mouthOpen` morph.
+
+**Does it need a server?** No. It's fully client-side. Bring your own copy/text;
+narrate it with `narrate()` / `[data-narrate]`.
+
+**Bundle size?** The ESM build leaves `three` external and tree-shakes. The
+`/global` CDN build inlines three for a single-tag drop-in.
+
+## License
+
+[Apache-2.0](./LICENSE) © three.ws. Part of the [three.ws](https://three.ws)
+platform for building, animating, rigging, and monetizing 3D AI agents.
diff --git a/page-agent-sdk/build.mjs b/page-agent-sdk/build.mjs
new file mode 100644
index 000000000..6d2bdd4d3
--- /dev/null
+++ b/page-agent-sdk/build.mjs
@@ -0,0 +1,54 @@
+#!/usr/bin/env node
+/**
+ * Build @three-ws/page-agent.
+ *
+ * Two artifacts:
+ * dist/page-agent.mjs — ESM, `three` left external. For bundler /
+ * npm consumers who already depend on three.
+ * dist/page-agent.global.js — IIFE with three + addons inlined, self-
+ * registers <page-agent> and exposes
+ * window.ThreeWsPageAgent. For a CDN <script>.
+ * dist/page-agent.css — the injected stylesheet, materialised for the
+ * "@three-ws/page-agent/style.css" subpath.
+ */
+
+import { build } from 'esbuild';
+import { mkdirSync, writeFileSync } from 'node:fs';
+import { dirname, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { CSS } from './src/styles.js';
+
+const here = dirname(fileURLToPath(import.meta.url));
+const outDir = resolve(here, 'dist');
+mkdirSync(outDir, { recursive: true });
+
+const common = {
+ entryPoints: [resolve(here, 'src/index.js')],
+ bundle: true,
+ sourcemap: true,
+ target: ['es2020'],
+ logLevel: 'info',
+};
+
+// 1) ESM, three external (peer dependency).
+await build({
+ ...common,
+ format: 'esm',
+ external: ['three', 'three/addons/*'],
+ outfile: resolve(outDir, 'page-agent.mjs'),
+});
+
+// 2) Standalone IIFE, three inlined, for a plain CDN <script>.
+await build({
+ ...common,
+ format: 'iife',
+ globalName: 'ThreeWsPageAgent',
+ minify: true,
+ outfile: resolve(outDir, 'page-agent.global.js'),
+ footer: { js: 'if(typeof window!=="undefined"){window.PageAgent=ThreeWsPageAgent.PageAgent;}' },
+});
+
+// 3) Stylesheet for the ./style.css subpath import.
+writeFileSync(resolve(outDir, 'page-agent.css'), CSS.trimStart());
+
+console.log('[page-agent] built dist/page-agent.mjs, dist/page-agent.global.js, dist/page-agent.css');
diff --git a/page-agent-sdk/examples/index.html b/page-agent-sdk/examples/index.html
new file mode 100644
index 000000000..f5e1960c3
--- /dev/null
+++ b/page-agent-sdk/examples/index.html
@@ -0,0 +1,89 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>@three-ws/page-agent — rigged 3D guide demo</title>
+ <style>
+ :root { color-scheme: dark; }
+ * { box-sizing: border-box; }
+ body {
+ margin: 0; font: 16px/1.6 -apple-system, system-ui, sans-serif;
+ background: #0b0c10; color: #e9eaf0;
+ }
+ main { max-width: 720px; margin: 0 auto; padding: 80px 24px 200px; }
+ h1 { font-size: 40px; line-height: 1.1; margin: 0 0 12px; }
+ h2 { font-size: 26px; margin: 48px 0 8px; }
+ .lede { font-size: 19px; color: #aab; }
+ p { color: #c7c9d6; }
+ .row { display: flex; gap: 10px; flex-wrap: wrap; margin: 24px 0; }
+ button {
+ cursor: pointer; border: 1px solid #2a2c38; background: #15161e; color: #e9eaf0;
+ padding: 10px 16px; border-radius: 12px; font: inherit; font-weight: 600;
+ }
+ button:hover { background: #1d1f29; }
+ code { background: #15161e; padding: 2px 6px; border-radius: 6px; font-size: 14px; }
+ </style>
+</head>
+<body>
+ <main>
+ <h1 data-narrate="Welcome to three.ws page agent — I'm your rigged 3D guide, and I'll walk you through this demo.">
+ The rigged 3D guide for any page
+ </h1>
+ <p class="lede" data-narrate="Drop one script tag, and a skeleton-rigged avatar appears in the corner and talks visitors through your site. Visitors pick which agent they want.">
+ Drop in one tag. A rigged, lipsync-capable avatar greets your visitors,
+ narrates the page, and lets them choose their own guide.
+ </p>
+
+ <div class="row">
+ <button id="tour">▶ Take the tour</button>
+ <button id="say">💬 Say something</button>
+ <button id="pick">🔀 Choose a guide</button>
+ <button id="stop">⏹ Stop</button>
+ </div>
+
+ <h2 data-narrate="Every avatar in the catalog is skeleton-rigged. That's a hard rule — unrigged meshes are excluded, because the runtime drives skeletal idle motion and viseme lipsync.">Only rigged agents</h2>
+ <p>Each agent ships a verified skinned mesh and armature. The runtime picks a
+ viseme, jaw, or full-body lipsync driver based on what the rig exposes.</p>
+
+ <h2 data-narrate="Visitors choose. Click change agent any time to swap between a diverse roster — realistic, stylized, and robot guides — and your choice is remembered.">Visitors choose their guide</h2>
+ <p>The picker is built in. The selection persists across pages via
+ <code>localStorage</code>.</p>
+
+ <h2 data-narrate="Speech is synthesized in the browser with the Web Speech API. No backend, no API key, no audio files — and the mouth shapes track the words.">Talks out loud, in-browser</h2>
+ <p>Web Speech API drives the voice; the text-to-viseme driver drives the mouth.</p>
+ </main>
+
+ <!-- Local dev: map the bare `three` specifier so the unbundled ESM source runs
+ straight from disk. In production you'd use the bundled global build or a
+ bundler that resolves `three` for you. -->
+ <script type="importmap">
+ {
+ "imports": {
+ "three": "https://unpkg.com/[email protected]/build/three.module.js",
+ "three/addons/": "https://unpkg.com/[email protected]/examples/jsm/"
+ }
+ }
+ </script>
+ <script type="module">
+ import { PageAgent } from '../src/index.js';
+
+ const guide = new PageAgent({
+ agent: 'sol',
+ position: 'bottom-right',
+ // Local assets so the demo works offline against this repo's public/ dir.
+ assetBase: 'https://three.ws/avatars/',
+ });
+ window.guide = guide;
+
+ document.getElementById('tour').onclick = () => guide.narratePage({ greet: true });
+ document.getElementById('say').onclick = () =>
+ guide.narrate("Hi! I'm a rigged 3D agent. Try the tour, or pick a different guide.", { interrupt: true });
+ document.getElementById('pick').onclick = () => guide.openPicker();
+ document.getElementById('stop').onclick = () => guide.stop();
+
+ guide.on('agentchange', (a) => console.log('now guided by', a.name));
+ guide.on('error', (e) => console.warn('page-agent error', e));
+ </script>
+</body>
+</html>
diff --git a/page-agent-sdk/package.json b/page-agent-sdk/package.json
index 1c50e04bc..782f3f779 100644
--- a/page-agent-sdk/package.json
+++ b/page-agent-sdk/package.json
@@ -59,7 +59,7 @@
"scripts": {
"build": "node build.mjs",
"prepublishOnly": "node build.mjs",
- "test": "node --test test/"
+ "test": "node --test 'test/*.test.js'"
},
"peerDependencies": {
"three": ">=0.150.0"
diff --git a/page-agent-sdk/src/element.js b/page-agent-sdk/src/element.js
new file mode 100644
index 000000000..b1e712055
--- /dev/null
+++ b/page-agent-sdk/src/element.js
@@ -0,0 +1,82 @@
+/**
+ * <page-agent> custom element — @three-ws/page-agent
+ * ==================================================
+ *
+ * Declarative wrapper around PageAgent. The element itself is invisible (the
+ * agent docks itself to the page corner); it exists so a site can drop the
+ * companion in with pure HTML and no script:
+ *
+ * <page-agent avatar="nova" position="bottom-right" auto-narrate controls></page-agent>
+ *
+ * Attributes (all optional):
+ * avatar initial rigged agent id (default: visitor's saved choice / "sol")
+ * agents comma-separated allow-list of agent ids for the picker
+ * position bottom-right | bottom-left | top-right | top-left
+ * asset-base override GLB host
+ * greeting line spoken on load (ignored when auto-narrate is set)
+ * auto-narrate present → tour the page; value → CSS selector of segments
+ * muted present → start muted (visual lipsync only)
+ * collapsed present → start as the launcher pill
+ * no-picker present → hide the "change agent" affordance
+ * no-controls present → hide the control bar
+ *
+ * Methods mirror PageAgent: narrate, narratePage, stop, setAgent, mute,
+ * collapse, openPicker. Events re-dispatched as DOM CustomEvents:
+ * page-agent:ready | :agentchange | :state | :caption | :segment | :error
+ */
+
+import { PageAgent } from './page-agent.js';
+
+const bool = (el, name) => el.hasAttribute(name);
+
+export class PageAgentElement extends HTMLElement {
+ connectedCallback() {
+ if (this._agent) return;
+ this.style.display = 'none';
+
+ const autoAttr = this.getAttribute('auto-narrate');
+ const autoNarrate = this.hasAttribute('auto-narrate') ? (autoAttr || true) : false;
+
+ this._agent = new PageAgent({
+ agent: this.getAttribute('avatar') || undefined,
+ agents: this.getAttribute('agents')?.split(',').map((s) => s.trim()).filter(Boolean),
+ position: this.getAttribute('position') || undefined,
+ assetBase: this.getAttribute('asset-base') || undefined,
+ greeting: this.getAttribute('greeting') || undefined,
+ autoNarrate,
+ muted: bool(this, 'muted'),
+ collapsed: bool(this, 'collapsed'),
+ picker: !bool(this, 'no-picker'),
+ controls: !bool(this, 'no-controls'),
+ });
+
+ for (const ev of ['ready', 'agentchange', 'state', 'caption', 'segment', 'error']) {
+ this._agent.on(ev, (detail) => {
+ this.dispatchEvent(new CustomEvent(`page-agent:${ev}`, { detail, bubbles: true, composed: true }));
+ });
+ }
+ }
+
+ disconnectedCallback() {
+ this._agent?.dispose();
+ this._agent = null;
+ }
+
+ // ── Imperative API proxy ──────────────────────────────────────────────────
+ narrate(text, opts) { return this._agent?.narrate(text, opts); }
+ narratePage(opts) { return this._agent?.narratePage(opts); }
+ stop() { this._agent?.stop(); }
+ setAgent(id) { return this._agent?.setAgent(id); }
+ mute(on = true) { this._agent?.mute(on); }
+ collapse(on = true) { this._agent?.collapse(on); }
+ openPicker() { this._agent?.openPicker(); }
+ get controller() { return this._agent; }
+ get currentAgent() { return this._agent?.currentAgent; }
+}
+
+export function registerElement(tag = 'page-agent') {
+ if (typeof customElements !== 'undefined' && !customElements.get(tag)) {
+ customElements.define(tag, PageAgentElement);
+ }
+ return tag;
+}
diff --git a/page-agent-sdk/src/index.js b/page-agent-sdk/src/index.js
new file mode 100644
index 000000000..bb832e4ca
--- /dev/null
+++ b/page-agent-sdk/src/index.js
@@ -0,0 +1,82 @@
+/**
+ * @three-ws/page-agent — public entry
+ * ===================================
+ *
+ * A rigged 3D AI agent that talks visitors through any web page. Three ways in:
+ *
+ * 1. Zero-JS: <script type="module" src=".../page-agent.global.js" data-page-agent
+ * data-avatar="nova" data-auto-narrate></script>
+ * 2. HTML tag: import '@three-ws/page-agent'; then <page-agent auto-narrate></page-agent>
+ * 3. Imperative:
+ * import { PageAgent } from '@three-ws/page-agent';
+ * const guide = new PageAgent({ agent: 'sol', autoNarrate: true });
+ * guide.narrate('Welcome — let me show you around.');
+ *
+ * Every agent in the catalog is skeleton-rigged and lipsync-capable; unrigged
+ * meshes are intentionally excluded.
+ */
+
+import { PageAgent } from './page-agent.js';
+import { registerElement } from './element.js';
+
+export { PageAgent, collectSegments } from './page-agent.js';
+export { PageAgentElement, registerElement } from './element.js';
+export { AvatarStage } from './stage.js';
+export { SpeechNarrator } from './narrator.js';
+export { AvatarPicker } from './picker.js';
+export { createLipsync, buildMorphMap, estimateDurationMs } from './lipsync.js';
+export {
+ AGENTS, DEFAULT_AGENT_ID, DEFAULT_ASSET_BASE,
+ getAgent, agentUrl, filterAgents,
+} from './catalog.js';
+
+// Register the <page-agent> element on import (browser only).
+if (typeof window !== 'undefined') {
+ registerElement();
+}
+
+/**
+ * Convenience factory — mount a page agent and return the controller.
+ * @param {ConstructorParameters<typeof PageAgent>[0]} [config]
+ * @returns {PageAgent}
+ */
+export function mount(config) {
+ return new PageAgent(config);
+}
+
+/**
+ * Auto-init from a `<script data-page-agent>` tag. Lets a site drop the agent
+ * in with no JS at all — the script's `data-*` attributes become the config.
+ * Idempotent: only the first tagged script mounts an instance.
+ */
+function autoInit() {
+ if (typeof document === 'undefined' || window.__threeWsPageAgent) return;
+ const tag = document.currentScript
+ || document.querySelector('script[data-page-agent]');
+ if (!tag || !tag.hasAttribute('data-page-agent')) return;
+
+ const d = tag.dataset;
+ const autoNarrate = 'autoNarrate' in d ? (d.autoNarrate || true) : false;
+ window.__threeWsPageAgent = new PageAgent({
+ agent: d.avatar || undefined,
+ agents: d.agents?.split(',').map((s) => s.trim()).filter(Boolean),
+ position: d.position || undefined,
+ assetBase: d.assetBase || undefined,
+ greeting: d.greeting || undefined,
+ autoNarrate,
+ muted: 'muted' in d,
+ collapsed: 'collapsed' in d,
+ picker: !('noPicker' in d),
+ controls: !('noControls' in d),
+ });
+}
+
+if (typeof window !== 'undefined') {
+ if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', autoInit, { once: true });
+ } else {
+ autoInit();
+ }
+}
+
+export default PageAgent;
diff --git a/page-agent-sdk/test/catalog.test.js b/page-agent-sdk/test/catalog.test.js
new file mode 100644
index 000000000..83db81e94
--- /dev/null
+++ b/page-agent-sdk/test/catalog.test.js
@@ -0,0 +1,62 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import {
+ AGENTS, DEFAULT_AGENT_ID, DEFAULT_ASSET_BASE,
+ getAgent, agentUrl, filterAgents,
+} from '../src/catalog.js';
+import { estimateDurationMs, createLipsync } from '../src/lipsync.js';
+
+test('catalog is non-empty and ids are unique', () => {
+ assert.ok(AGENTS.length >= 8, 'expected a diverse roster');
+ const ids = AGENTS.map((a) => a.id);
+ assert.equal(new Set(ids).size, ids.length, 'agent ids must be unique');
+});
+
+test('every catalog agent is rigged and lipsync-classified', () => {
+ const rigs = new Set(['rpm', 'mixamo', 'studio']);
+ const lips = new Set(['viseme', 'jaw', 'animation']);
+ for (const a of AGENTS) {
+ assert.ok(rigs.has(a.rig), `${a.id} has a known rig`);
+ assert.ok(lips.has(a.lipsync), `${a.id} declares a lipsync mode`);
+ assert.ok(a.file.endsWith('.glb'), `${a.id} points at a GLB`);
+ assert.ok(a.voice && (a.voice.lang || a.voice.match), `${a.id} has a voice profile`);
+ assert.match(a.accent, /^#[0-9a-f]{6}$/i, `${a.id} has a hex accent`);
+ }
+});
+
+test('roster is diverse across style and presentation', () => {
+ assert.ok(new Set(AGENTS.map((a) => a.style)).size >= 3, 'multiple styles');
+ assert.ok(new Set(AGENTS.map((a) => a.presents)).size >= 3, 'multiple presentations');
+ assert.ok(AGENTS.some((a) => a.lipsync === 'viseme'), 'at least one viseme agent');
+});
+
+test('default agent exists', () => {
+ assert.ok(getAgent(DEFAULT_AGENT_ID), 'default agent id resolves');
+});
+
+test('agentUrl resolves against the asset base and honors overrides', () => {
+ const a = getAgent(DEFAULT_AGENT_ID);
+ assert.equal(agentUrl(a), DEFAULT_ASSET_BASE + a.file);
+ assert.equal(agentUrl(a, 'https://cdn.example/'), 'https://cdn.example/' + a.file);
+ assert.equal(agentUrl({ ...a, url: 'https://x/y.glb' }), 'https://x/y.glb');
+});
+
+test('filterAgents narrows by id, style and lipsync', () => {
+ assert.equal(filterAgents({ ids: [DEFAULT_AGENT_ID] }).length, 1);
+ const viseme = filterAgents({ lipsync: 'viseme' });
+ assert.ok(viseme.length && viseme.every((a) => a.lipsync === 'viseme'));
+ assert.equal(filterAgents({ ids: ['does-not-exist'] }).length, 0);
+});
+
+test('lipsync duration grows with text length', () => {
+ const short = estimateDurationMs('hi');
+ const long = estimateDurationMs('the quick brown fox jumps over the lazy dog');
+ assert.ok(long > short, 'longer text → longer timeline');
+ assert.equal(estimateDurationMs(''), 0);
+});
+
+test('createLipsync with no morph map is a safe no-op', () => {
+ const ls = createLipsync('hello there', null);
+ assert.equal(ls.totalMs, 0);
+ assert.doesNotThrow(() => { ls.tick(0); ls.tick(100); ls.stop(); });
+});
diff --git a/page-agent-sdk/types/index.d.ts b/page-agent-sdk/types/index.d.ts
new file mode 100644
index 000000000..6f4a25c01
--- /dev/null
+++ b/page-agent-sdk/types/index.d.ts
@@ -0,0 +1,151 @@
+// Type definitions for @three-ws/page-agent
+
+export type AgentId = string;
+export type Position = 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left';
+export type LipsyncMode = 'viseme' | 'jaw' | 'animation';
+export type Presents = 'female' | 'male' | 'neutral' | 'robot';
+export type AvatarStyle = 'realistic' | 'stylized' | 'robot';
+export type Framing = 'bust' | 'upper' | 'full';
+
+export interface VoiceProfile {
+ lang?: string;
+ pitch?: number;
+ rate?: number;
+ match?: string[];
+}
+
+/** A skeleton-rigged, lipsync-capable agent in the catalog. */
+export 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;
+}
+
+export const AGENTS: RiggedAgent[];
+export const DEFAULT_AGENT_ID: AgentId;
+export const DEFAULT_ASSET_BASE: string;
+export function getAgent(id: AgentId): RiggedAgent | undefined;
+export function agentUrl(agent: RiggedAgent, assetBase?: string): string;
+export function filterAgents(q?: {
+ style?: AvatarStyle;
+ presents?: Presents;
+ lipsync?: LipsyncMode;
+ ids?: AgentId[];
+}): RiggedAgent[];
+
+export interface PageAgentConfig {
+ /** Element is not used as a mount; the agent docks itself to the page. */
+ mount?: HTMLElement;
+ agent?: AgentId;
+ /** Allow-list of agent ids shown in the picker. */
+ agents?: AgentId[];
+ assetBase?: string;
+ position?: Position;
+ muted?: boolean;
+ collapsed?: boolean;
+ /** Hide the "change agent" affordance + picker. Default true (shown). */
+ picker?: boolean;
+ /** Show the control bar. Default true. */
+ controls?: boolean;
+ /** Spoken once on load (ignored when autoNarrate is set). */
+ greeting?: string;
+ /** true → tour the page; string → CSS selector of segments to narrate. */
+ autoNarrate?: boolean | string;
+ /** Persist the visitor's chosen agent in localStorage. Default true. */
+ persistAgent?: boolean;
+}
+
+export type PageAgentEvent =
+ | 'ready' | 'agentchange' | 'state' | 'caption' | 'segment' | 'error';
+
+export class PageAgent {
+ constructor(config?: PageAgentConfig);
+ readonly currentAgent: RiggedAgent | null;
+ narrate(text: string, opts?: { interrupt?: boolean }): Promise<void>;
+ narratePage(opts?: { selector?: string; greet?: boolean }): Promise<void>;
+ stop(): void;
+ setAgent(id: AgentId): Promise<void>;
+ mute(on?: boolean): void;
+ collapse(on?: boolean): void;
+ openPicker(): void;
+ closePicker(): void;
+ on(event: PageAgentEvent, cb: (payload: any) => void): this;
+ off(event: PageAgentEvent, cb: (payload: any) => void): this;
+ dispose(): void;
+}
+
+export function mount(config?: PageAgentConfig): PageAgent;
+export function collectSegments(selector?: string): { el: Element; text: string }[];
+
+export class PageAgentElement extends HTMLElement {
+ readonly controller: PageAgent | null;
+ readonly currentAgent: RiggedAgent | null;
+ narrate(text: string, opts?: { interrupt?: boolean }): Promise<void> | undefined;
+ narratePage(opts?: { selector?: string; greet?: boolean }): Promise<void> | undefined;
+ stop(): void;
+ setAgent(id: AgentId): Promise<void> | undefined;
+ mute(on?: boolean): void;
+ collapse(on?: boolean): void;
+ openPicker(): void;
+}
+export function registerElement(tag?: string): string;
+
+export class AvatarStage {
+ constructor(container: HTMLElement, opts?: { background?: string });
+ morph: unknown;
+ onFrame(fn: (dt: number, nowMs: number) => void): () => void;
+ load(url: string, opts?: { framing?: Framing }): Promise<unknown>;
+ setSpeaking(on: boolean): void;
+ dispose(): void;
+}
+
+export class SpeechNarrator {
+ constructor(stage: AvatarStage, opts?: {
+ muted?: boolean;
+ onState?: (s: 'idle' | 'speaking') => void;
+ onCaption?: (text: string | null) => void;
+ onError?: (e: Error) => void;
+ });
+ readonly speaking: boolean;
+ setAgent(agent: RiggedAgent): void;
+ setMuted(muted: boolean): void;
+ speak(text: string, opts?: { interrupt?: boolean }): Promise<void>;
+ cancel(): void;
+ dispose(): void;
+}
+
+export class AvatarPicker {
+ constructor(agents: RiggedAgent[], opts: {
+ onSelect: (id: AgentId) => void;
+ getCurrent: () => AgentId | undefined;
+ title?: string;
+ subtitle?: string;
+ });
+ static restore(): AgentId | null;
+ static persist(id: AgentId): void;
+ readonly isOpen: boolean;
+ mount(parent?: HTMLElement): void;
+ open(): void;
+ close(): void;
+ dispose(): void;
+}
+
+export function createLipsync(
+ text: string,
+ morph: unknown,
+ opts?: { rate?: number },
+): { tick(nowMs: number): void; stop(): void; readonly done: boolean; readonly totalMs: number };
+export function buildMorphMap(root: unknown): { mode: 'arkit' | 'jaw'; map: Map<string, any[]> } | null;
+export function estimateDurationMs(text: string): number;
+
+export default PageAgent;
diff --git a/pages/club.html b/pages/club.html
index 9ab53f846..594b3efcb 100644
--- a/pages/club.html
+++ b/pages/club.html
@@ -2052,7 +2052,7 @@
<span class="tagline">tip in USDC · she dances</span>
<span class="spacer"></span>
<span class="club-pill">$0.001 / dance</span>
- <span class="club-pill club-pill-blue">x402 · Base &amp; Solana</span>
+ <span class="club-pill club-pill-blue">x402 · Solana</span>
<button
id="club-audio-toggle"
type="button"
diff --git a/pages/ibm/x402-demo.html b/pages/ibm/x402-demo.html
index bbc89460e..135a4eabf 100644
--- a/pages/ibm/x402-demo.html
+++ b/pages/ibm/x402-demo.html
@@ -274,6 +274,44 @@ a:focus-visible{outline-offset:3px}
.forge-foot{font-size:13px;color:var(--ibm-muted);margin-top:18px;font-weight:300}
.forge-foot a{font-weight:500}
+/* Free text→3D widget — the no-wallet companion to the paid Forge */
+.g3d{margin-top:32px;border:1px solid var(--ibm-border);background:var(--ibm-field);padding:24px}
+.g3d-tag{font-size:12px;letter-spacing:.08em;text-transform:uppercase;color:var(--ibm-blue);font-weight:500;margin-bottom:8px}
+.g3d h4{font-size:20px;font-weight:300;margin:0 0 8px;color:var(--ibm-ink);max-width:none}
+.g3d h4 strong{font-weight:600}
+.g3d-sub{font-size:14px;color:var(--ibm-muted);line-height:1.6;margin:0 0 20px;max-width:640px}
+.g3d-field{display:flex;gap:1px;flex-wrap:wrap;background:var(--ibm-border)}
+.g3d-input{flex:1 1 280px;min-width:0;font-family:var(--font-sans);font-size:15px;color:var(--ibm-ink);background:var(--ibm-page);border:none;padding:0 16px;height:48px;outline:none}
+.g3d-input:focus-visible{outline:2px solid var(--ibm-blue);outline-offset:-2px}
+.g3d-btn{display:inline-flex;align-items:center;gap:10px;background:var(--ibm-blue);color:#fff;border:none;cursor:pointer;font-family:var(--font-sans);font-size:15px;font-weight:500;padding:0 24px;height:48px;transition:background .12s,transform .04s}
+.g3d-btn:hover:not(:disabled){background:var(--ibm-blue-hover)}
+.g3d-btn:active:not(:disabled){transform:translateY(1px)}
+.g3d-btn:disabled{opacity:.7;cursor:not-allowed}
+.g3d-btn:focus-visible{outline:2px solid var(--ibm-blue);outline-offset:2px}
+.g3d-spin{width:15px;height:15px;border:2px solid rgba(255,255,255,.4);border-top-color:#fff;border-radius:50%;animation:spin .7s linear infinite;display:none}
+.g3d-btn.loading .g3d-spin{display:inline-block}
+.g3d-suggest{display:flex;flex-wrap:wrap;gap:8px;margin-top:14px}
+.g3d-suggest button{font-family:inherit;font-size:13px;color:var(--ibm-muted);background:transparent;border:1px solid var(--ibm-border);padding:6px 12px;cursor:pointer;transition:border-color .12s,color .12s}
+.g3d-suggest button:hover{border-color:var(--ibm-blue);color:var(--ibm-blue)}
+.g3d-result{margin-top:20px;border:1px solid var(--ibm-border);background:var(--ibm-page)}
+.g3d-result.is-empty{padding:28px 20px;text-align:center;font-size:14px;color:var(--ibm-subtle)}
+.g3d-load{padding:28px 20px}
+.g3d-bar{display:block;height:3px;background:var(--ibm-border);overflow:hidden;margin-bottom:16px}
+.g3d-bar span{display:block;height:100%;width:40%;background:var(--ibm-blue);animation:g3dslide 1.3s ease-in-out infinite}
+@keyframes g3dslide{0%{transform:translateX(-110%)}100%{transform:translateX(360%)}}
+.g3d-loadmsg{font-size:14px;color:var(--ibm-muted);text-align:center}
+.g3d-err{padding:24px 20px;text-align:center}
+.g3d-err p{font-size:14px;color:var(--ibm-muted);margin:0 auto 16px;max-width:440px;line-height:1.6}
+.g3d-retry{font-family:inherit;font-size:14px;font-weight:500;color:#fff;background:var(--ibm-blue);border:none;padding:10px 20px;cursor:pointer;transition:background .12s}
+.g3d-retry:hover{background:var(--ibm-blue-hover)}
+.g3d-actions{display:flex;align-items:center;gap:8px;flex-wrap:wrap;padding:14px 16px;border-top:1px solid var(--ibm-border)}
+.g3d-act{display:inline-flex;align-items:center;font-family:inherit;font-size:14px;font-weight:500;text-decoration:none;padding:9px 16px;border:1px solid var(--ibm-blue);color:var(--ibm-blue);cursor:pointer;transition:background .12s}
+.g3d-act:hover{background:rgba(15,98,254,.08);text-decoration:none}
+.g3d-act.primary{background:var(--ibm-blue);color:#fff;border-color:var(--ibm-blue)}
+.g3d-act.primary:hover{background:var(--ibm-blue-hover)}
+.g3d-engine{font-size:12px;color:var(--ibm-subtle);margin-left:auto}
+@media(max-width:560px){.g3d-btn{width:100%}.g3d-engine{margin-left:0;width:100%}}
+
@media(pointer:coarse){.tier,.r-btn{min-height:44px}}
/* embed snippet */
@@ -518,6 +556,31 @@ agent-3d:defined ~ .agent-skel{display:none}
</div>
</div>
</div>
+
+ <!-- Free, no-wallet companion to the paid Forge above. Same text→3D
+ pipeline (Microsoft TRELLIS on NVIDIA NIM), on the house — no wallet,
+ no key, no payment. POSTs the free /api/forge lane and polls it. -->
+ <div class="g3d">
+ <div class="g3d-tag">Live · Free · No wallet</div>
+ <h4 id="g3d-h">Or forge one <strong>free</strong> — no wallet needed</h4>
+ <p class="g3d-sub">The same pipeline, on the house. No wallet, no API key, no payment — it runs Microsoft TRELLIS on NVIDIA NIM with automatic fallback across generation lanes, so a textured GLB always comes back to orbit and download.</p>
+ <div class="g3d-field">
+ <label for="g3dPrompt" class="sr-only">Describe an object to generate for free</label>
+ <input id="g3dPrompt" class="g3d-input" value="a brass steampunk owl, full body" maxlength="600" autocomplete="off" spellcheck="true" inputmode="text" aria-describedby="g3d-h">
+ <button id="g3dBtn" class="g3d-btn" type="button"><span class="g3d-spin" aria-hidden="true"></span><span class="g3d-label">Generate free</span> <span aria-hidden="true">→</span></button>
+ </div>
+ <div class="g3d-suggest" id="g3dSuggest" aria-label="Example prompts">
+ <button type="button" data-p="a low-poly red fox, sitting">low-poly fox</button>
+ <button type="button" data-p="a glossy ceramic teapot with gold trim">ceramic teapot</button>
+ <button type="button" data-p="a futuristic delivery drone">delivery drone</button>
+ <button type="button" data-p="a worn leather hiking boot">hiking boot</button>
+ </div>
+ <div id="g3dResult" class="g3d-result is-empty">
+ Describe an object and generate — your model appears here to orbit and download.
+ </div>
+ <p id="g3dStatus" class="sr-only" role="status" aria-live="polite"></p>
+ </div>
+
<p class="forge-foot">Want image→3D, auto-rigging, AR preview and the full gallery? <a href="https://three.ws/forge" target="_blank" rel="noopener">Open the full Forge tool ↗</a></p>
</div>
</section>
@@ -1655,5 +1718,215 @@ agent-3d:defined ~ .agent-skel{display:none}
loadChallengePreview();
})();
</script>
+
+<!-- Free, no-wallet text→3D companion to the paid Forge. POSTs the free
+ /api/forge NVIDIA NIM (Microsoft TRELLIS) lane, walks a fallback ladder, and
+ polls GET /api/forge?job=<id>. No wallet, no key, no payment. -->
+<script type="module">
+(function () {
+ 'use strict';
+
+ var API = 'https://three.ws/api/forge';
+ var $ = function (id) { return document.getElementById(id); };
+ var btn = $('g3dBtn');
+ if (!btn) return; // panel not present — nothing to wire
+
+ var input = $('g3dPrompt');
+ var result = $('g3dResult');
+ var statusEl = $('g3dStatus');
+ var suggest = $('g3dSuggest');
+
+ var inFlight = false;
+ var runSeq = 0;
+ var loadTimer = null;
+
+ var CID = (function () {
+ var fresh = function () { return 'c-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 10); };
+ try {
+ var KEY = 'forge:cid';
+ var v = localStorage.getItem(KEY);
+ if (!v) { v = (window.crypto && crypto.randomUUID) ? crypto.randomUUID() : fresh(); localStorage.setItem(KEY, v); }
+ return v;
+ } catch (e) { return fresh(); }
+ })();
+ var HEADERS = { 'x-forge-client': CID };
+
+ var _mv = null;
+ function ensureModelViewer() {
+ if (_mv) return _mv;
+ _mv = new Promise(function (resolve) {
+ if (window.customElements && customElements.get('model-viewer')) { resolve(); return; }
+ var s = document.createElement('script');
+ s.type = 'module';
+ s.src = './vendor/model-viewer.min.js';
+ s.addEventListener('error', resolve);
+ document.head.appendChild(s);
+ if (window.customElements) customElements.whenDefined('model-viewer').then(resolve, resolve);
+ else resolve();
+ });
+ return _mv;
+ }
+
+ function esc(s) {
+ return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) {
+ return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c];
+ });
+ }
+ function sleep(ms) { return new Promise(function (r) { setTimeout(r, ms); }); }
+
+ // Fallback ladder — first rung that yields a GLB wins. The free NVIDIA NIM lane
+ // degrades internally too, but walking distinct backends + a second pass makes
+ // a transient outage on any one engine invisible to the user.
+ var LADDER = [
+ { aspect_ratio: '1:1', path: 'image', tier: 'draft', backend: 'nvidia' },
+ { aspect_ratio: '1:1', path: 'image', tier: 'draft', backend: 'trellis' },
+ { aspect_ratio: '1:1', path: 'image', tier: 'standard', backend: 'trellis' }
+ ];
+
+ async function startJob(body) {
+ var res = await fetch(API, {
+ method: 'POST',
+ headers: Object.assign({ 'content-type': 'application/json' }, HEADERS),
+ body: JSON.stringify(body)
+ });
+ var data = await res.json().catch(function () { return {}; });
+ if (!res.ok) throw new Error(data.message || data.error || ('HTTP ' + res.status));
+ return data;
+ }
+
+ async function pollJob(jobId, seq) {
+ var deadline = Date.now() + 240000;
+ while (seq === runSeq && Date.now() < deadline) {
+ await sleep(2500);
+ if (seq !== runSeq) return null;
+ var res = await fetch(API + '?job=' + encodeURIComponent(jobId), { headers: HEADERS });
+ var data = await res.json().catch(function () { return {}; });
+ if (data.status === 'done' && data.glb_url) return data;
+ if (data.status === 'failed') throw new Error(data.error || 'generation failed');
+ }
+ if (seq !== runSeq) return null;
+ throw new Error('timed out');
+ }
+
+ async function generate(prompt, seq) {
+ var lastErr = null;
+ for (var pass = 0; pass < 2; pass++) {
+ for (var i = 0; i < LADDER.length; i++) {
+ if (seq !== runSeq) return null;
+ try {
+ var job = await startJob(Object.assign({ prompt: prompt }, LADDER[i]));
+ if (job.status === 'done' && job.glb_url) return job; // synchronous (NVIDIA sync)
+ if (job.job_id) {
+ var done = await pollJob(job.job_id, seq);
+ if (done) return done;
+ if (seq !== runSeq) return null;
+ }
+ lastErr = new Error('no model returned');
+ } catch (e) { lastErr = e; }
+ if (seq !== runSeq) return null;
+ }
+ await sleep(1500);
+ }
+ throw lastErr || new Error('generation unavailable');
+ }
+
+ function setLoading() {
+ var msgs = [
+ 'Reading your prompt…',
+ 'Generating geometry on NVIDIA NIM…',
+ 'Texturing the mesh…',
+ 'Finalizing the GLB…'
+ ];
+ var i = 0;
+ result.className = 'g3d-result is-loading';
+ result.innerHTML =
+ '<div class="g3d-load"><span class="g3d-bar"><span></span></span>' +
+ '<span class="g3d-loadmsg" id="g3dLoadMsg">' + esc(msgs[0]) + '</span></div>';
+ statusEl.textContent = 'Generating your 3D model.';
+ clearInterval(loadTimer);
+ loadTimer = setInterval(function () {
+ i = (i + 1) % msgs.length;
+ var el = $('g3dLoadMsg');
+ if (el) el.textContent = msgs[i];
+ }, 4000);
+ }
+
+ function setError() {
+ clearInterval(loadTimer);
+ result.className = 'g3d-result is-error';
+ result.innerHTML =
+ '<div class="g3d-err"><p>The free generator is briefly unreachable. It auto-retries across NVIDIA NIM and TRELLIS — give it another try.</p>' +
+ '<button type="button" class="g3d-retry" id="g3dRetry">Try again</button></div>';
+ var rb = $('g3dRetry');
+ if (rb) rb.addEventListener('click', run);
+ statusEl.textContent = 'Generation failed. Press try again.';
+ }
+
+ function engineLabel(backend) {
+ if (backend === 'nvidia') return 'Microsoft TRELLIS · NVIDIA NIM';
+ if (backend === 'trellis') return 'Microsoft TRELLIS';
+ if (backend === 'huggingface') return 'TRELLIS · Hugging Face';
+ return 'three.ws Forge';
+ }
+
+ async function renderModel(job, prompt) {
+ clearInterval(loadTimer);
+ await ensureModelViewer();
+ var glb = job.glb_url;
+ var scene = 'https://three.ws/scene?model=' + encodeURIComponent(glb) +
+ '&name=' + encodeURIComponent(prompt.slice(0, 80));
+ result.className = 'g3d-result is-done';
+ result.innerHTML =
+ '<div class="mv-wrap"><model-viewer src="' + esc(glb) + '" alt="3D model generated from your prompt" ' +
+ 'camera-controls auto-rotate rotation-per-second="18deg" interaction-prompt="none" ' +
+ 'shadow-intensity="0.7" shadow-softness="0.8" environment-image="neutral" exposure="1" ' +
+ 'camera-orbit="0deg 80deg auto" loading="eager"></model-viewer></div>' +
+ '<div class="g3d-actions">' +
+ '<a class="g3d-act primary" href="' + esc(glb) + '" download>Download GLB</a>' +
+ '<a class="g3d-act" href="' + esc(scene) + '" target="_blank" rel="noopener">Open in 3D scene ↗</a>' +
+ '<span class="g3d-engine">Generated free · ' + esc(engineLabel(job.backend)) + '</span>' +
+ '</div>';
+ statusEl.textContent = 'Your 3D model is ready. Orbit it, or download the GLB.';
+ }
+
+ async function run() {
+ var prompt = (input.value || '').trim();
+ if (!prompt) { try { input.focus(); } catch (_) {} return; }
+ var seq = ++runSeq;
+ inFlight = true;
+ btn.classList.add('loading');
+ btn.disabled = true;
+ setLoading();
+ try {
+ var job = await generate(prompt, seq);
+ if (seq !== runSeq) return;
+ if (!job || !job.glb_url) throw new Error('no model');
+ await renderModel(job, prompt);
+ } catch (e) {
+ if (seq !== runSeq) return;
+ setError();
+ } finally {
+ if (seq === runSeq) {
+ inFlight = false;
+ btn.classList.remove('loading');
+ btn.disabled = false;
+ }
+ }
+ }
+
+ btn.addEventListener('click', function () { if (!inFlight) run(); });
+ input.addEventListener('keydown', function (e) {
+ if (e.key === 'Enter') { e.preventDefault(); if (!inFlight) run(); }
+ });
+ if (suggest) {
+ suggest.addEventListener('click', function (e) {
+ var b = e.target.closest('button[data-p]');
+ if (!b) return;
+ input.value = b.getAttribute('data-p');
+ if (!inFlight) run();
+ });
+ }
+})();
+</script>
</body>
</html>
diff --git a/public/changelog.json b/public/changelog.json
index 9430d182c..92e067077 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-19T22:02:31.198Z",
+ "generated_at": "2026-06-19T22:11:07.149Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -526,6 +526,27 @@
"fix"
]
},
+ {
+ "date": "2026-06-19",
+ "type": "update",
+ "title": "Put a talking 3D guide on any website — new @three-ws/page-agent SDK",
+ "summary": "Drop one tag onto any site and a rigged 3D agent appears in the corner, greets visitors, and talks them through the page out loud — mouth moving in time with the words, all in the browser with no backend or API key. Visitors pick who guides them from a diverse roster of rigged agents (realistic, stylized, and a robot), and the choice is remembered as they move between pages. Only skeleton-rigged avatars ship in the catalog, so every guide actually breathes, blinks, and lip-syncs instead of standing frozen. Install @three-ws/page-agent from npm, or paste the one-line embed.",
+ "link": null,
+ "tags": [
+ "sdk",
+ "feature"
+ ]
+ },
+ {
+ "date": "2026-06-19",
+ "type": "update",
+ "title": "Rigged-or-not filter across your Agents and Avatars",
+ "summary": "The rigged-or-not category now reaches everything you own, not just the public gallery. Your Avatars page (both My avatars and the Community tab) and your Agents page each get a Rigged / Static filter and a badge on every card, so you can tell at a glance which models carry a skeleton and can play the animation library — and narrow the list to just the animation-ready ones. An agent's badge reflects the rig state of its 3D body.",
+ "link": "/dashboard/avatars",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-19",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 4a6854a01..c14a96c80 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -414,6 +414,22 @@
<category>feature</category>
<description>Locked premium headwear, eyewear, dyes and auras in the character creator no longer dead-end on a placeholder — clicking one now opens the real wallet checkout and unlocks it the moment the USDC payment settles, then equips it on your live preview. Anything you already own loads pre-unlocked, and the price you see is the true checkout amount pulled from the catalog.</description>
</item>
+ <item>
+ <title>Put a talking 3D guide on any website — new @three-ws/page-agent SDK</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-19:Put a talking 3D guide on any website — new @three-ws/page-agent SDK</guid>
+ <pubDate>Fri, 19 Jun 2026 12:00:00 GMT</pubDate>
+ <category>sdk</category>
+ <description>Drop one tag onto any site and a rigged 3D agent appears in the corner, greets visitors, and talks them through the page out loud — mouth moving in time with the words, all in the browser with no backend or API key. Visitors pick who guides them from a diverse roster of rigged agents (realistic, stylized, and a robot), and the choice is remembered as they move between pages. Only skeleton-rigged avatars ship in the catalog, so every guide actually breathes, blinks, and lip-syncs instead of standing frozen. Install @three-ws/page-agent from npm, or paste the one-line embed.</description>
+ </item>
+ <item>
+ <title>Rigged-or-not filter across your Agents and Avatars</title>
+ <link>https://three.ws/dashboard/avatars</link>
+ <guid isPermaLink="false">2026-06-19:Rigged-or-not filter across your Agents and Avatars</guid>
+ <pubDate>Fri, 19 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>The rigged-or-not category now reaches everything you own, not just the public gallery. Your Avatars page (both My avatars and the Community tab) and your Agents page each get a Rigged / Static filter and a badge on every card, so you can tell at a glance which models carry a skeleton and can play the animation library — and narrow the list to just the animation-ready ones. An agent's badge reflects the rig state of its 3D body.</description>
+ </item>
<item>
<title>Saved avatar now shows the real model on the &quot;what's next&quot; screen</title>
<link>https://three.ws/changelog</link>
diff --git a/public/features.json b/public/features.json
index c37ceb12e..bf1670d28 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-19T22:02:31.187Z",
+ "generated_at": "2026-06-19T22:11:07.110Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/src/dashboard-next/pages/agents.js b/src/dashboard-next/pages/agents.js
index 4d79bb623..43730a07f 100644
--- a/src/dashboard-next/pages/agents.js
+++ b/src/dashboard-next/pages/agents.js
@@ -20,6 +20,7 @@ import { onchainBadgeHTML } from '../../shared/onchain-badge.js';
import { coinChipHTML } from '../../shared/agent-coin.js';
import { walletChipHTML, wireWalletChips } from '../../shared/agent-wallet-chip.js';
import { skeletonHTML, emptyStateHTML, ensureStateKitStyles } from '../../shared/state-kit.js';
+import { rigBadgeHTML, matchesRigFilter, RIG_FILTERS } from '../../shared/rig-status.js';
ensureStateKitStyles();
const MONO = `'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace`;
@@ -79,6 +80,9 @@ function toast(msg) {
<option value="name-desc">Name Z-A</option>
</select>
</div>
+ <div class="dn-agents-rig-chips" role="tablist" aria-label="Rig filter">
+ ${RIG_FILTERS.map((f) => `<button type="button" class="dn-agents-rig-chip${f.key === 'all' ? ' active' : ''}" data-action="rig-chip" data-rig="${f.key}" role="tab" aria-selected="${f.key === 'all'}">${f.label}</button>`).join('')}
+ </div>
<span class="dn-agents-count" data-slot="agents-count"></span>
</div>
@@ -99,6 +103,8 @@ function toast(msg) {
let currentFilter = '';
let currentSort = 'created-desc';
+ let currentRig = 'all';
+ const avatarById = new Map(avatars.map((av) => [av.id, av]));
function getFilteredAgents() {
let filtered = agents;
@@ -111,6 +117,9 @@ function toast(msg) {
return name.includes(q) || wallet.includes(q) || tagline.includes(q);
});
}
+ if (currentRig !== 'all') {
+ filtered = filtered.filter((a) => matchesRigFilter(avatarById.get(a.avatar_id), currentRig));
+ }
filtered = [...filtered].sort((a, b) => {
switch (currentSort) {
case 'created-asc':
@@ -163,6 +172,20 @@ function toast(msg) {
rerender();
});
+ main.querySelectorAll('[data-action="rig-chip"]').forEach((chip) => {
+ chip.addEventListener('click', () => {
+ const v = chip.getAttribute('data-rig');
+ if (currentRig === v) return;
+ currentRig = v;
+ main.querySelectorAll('[data-action="rig-chip"]').forEach((x) => {
+ const on = x === chip;
+ x.classList.toggle('active', on);
+ x.setAttribute('aria-selected', on ? 'true' : 'false');
+ });
+ rerender();
+ });
+ });
+
main.querySelector('[data-action="create-agent"]').addEventListener('click', () => {
openCreateModal(host, agents, avatars);
});
@@ -453,6 +476,7 @@ function agentCard(a, avatars) {
<div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-bottom:4px">
<span style="font-size:15px;font-weight:600;color:var(--nxt-ink)">${name}</span>
${onchainBadge || `<span class="dn-tag" style="font-size:11px">off-chain</span>`}
+ ${a.avatar_id ? rigBadgeHTML(avatar, { size: 'sm' }) : ''}
${coinChipHTML(a, { launchable: false })}
</div>
<div style="margin-bottom:6px">${walletChipHTML(a, { isOwner: true, showPending: false })}</div>
@@ -1169,6 +1193,20 @@ function injectStyles() {
}
.dn-agents-sort:focus { border-color: var(--nxt-stroke-strong); }
.dn-agents-sort option { background: #14151c; color: var(--nxt-ink); }
+ .dn-agents-rig-chips { display: flex; gap: 4px; flex-wrap: wrap; }
+ .dn-agents-rig-chip {
+ padding: 7px 11px;
+ background: rgba(255,255,255,0.04);
+ border: 1px solid var(--nxt-stroke);
+ border-radius: 8px;
+ color: var(--nxt-ink-dim);
+ font-size: 12.5px;
+ font-family: inherit;
+ cursor: pointer;
+ transition: color 0.14s ease, background 0.14s ease, border-color 0.14s ease;
+ }
+ .dn-agents-rig-chip:hover { color: var(--nxt-ink); background: rgba(255,255,255,0.06); }
+ .dn-agents-rig-chip.active { color: var(--nxt-ink); border-color: var(--nxt-stroke-strong); background: rgba(255,255,255,0.08); }
.dn-agents-count {
font-size: 12px;
color: var(--nxt-ink-fade);
diff --git a/vite.config.js b/vite.config.js
index 6a7f01f45..289083711 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -262,6 +262,7 @@ const appConfig = {
entryFileNames: (chunk) =>
chunk.name === 'footer-bot' ||
chunk.name === 'walk-companion' ||
+ chunk.name === 'walk-playground' ||
chunk.name === 'notifications' ||
chunk.name === 'nav-tier-badge'
? `${chunk.name}.js`
@@ -270,6 +271,7 @@ const appConfig = {
input: {
'footer-bot': resolve(__dirname, 'src/footer-bot.js'),
'walk-companion': resolve(__dirname, 'src/walk-companion.js'),
+ 'walk-playground': resolve(__dirname, 'src/walk-playground.js'),
notifications: resolve(__dirname, 'src/notifications.js'),
'nav-tier-badge': resolve(__dirname, 'src/nav-tier-badge.js'),
app: resolve(__dirname, 'pages/app.html'),
@@ -1197,6 +1199,12 @@ support: resolve(__dirname, 'pages/support.html'),
req.url = '/src/walk-companion.js';
return next();
}
+ // /walk-playground.js — stable URL so any page (not just the nav
+ // companion) can launch the full-page walk playground on demand.
+ if (path === '/walk-playground.js') {
+ req.url = '/src/walk-playground.js';
+ return next();
+ }
// /notifications.js — nav.js loads this module for the per-user inbox.
if (path === '/notifications.js') {
req.url = '/src/notifications.js';
diff --git a/walk-sdk/src/companion.js b/walk-sdk/src/companion.js
new file mode 100644
index 000000000..cc0c9fd77
--- /dev/null
+++ b/walk-sdk/src/companion.js
@@ -0,0 +1,627 @@
+// Walk Companion — a persistent 3D avatar that walks and talks over your pages.
+// =============================================================================
+// A small avatar idles in the corner of every page, turns to follow the cursor,
+// waves when you navigate, and greets you with a page-aware line. Click it and
+// it detaches into the full-page Playground. An avatar picker lets each visitor
+// choose who walks with them, from a diverse roster, and hot-swaps the rig live.
+//
+// This module is side-effect free on import: call `createWalkCompanion(config)`
+// to get a controller, then `.bootstrap()` (or `.enable()`) to mount. That keeps
+// it safe to `import` from a bundler while still supporting the app's
+// inject-on-demand delivery.
+
+import {
+ AmbientLight,
+ Box3,
+ Timer,
+ DirectionalLight,
+ Group,
+ HemisphereLight,
+ PerspectiveCamera,
+ Scene,
+ Vector3,
+ WebGLRenderer,
+} 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 { loadWalkAvatar } from './internal/load-avatar.js';
+import { createAvatarPicker } from './picker.js';
+import { resolveConfig, resolveAvatarEntry } from './config.js';
+
+const CANVAS_W = 200;
+const CANVAS_H = 280;
+const CURSOR_IDLE_MS = 450; // cursor still longer than this → stop walking
+
+function isExcludedRoute(config) {
+ if (typeof window === 'undefined') return true;
+ if (window.top !== window.self) return true; // never inside an iframe/embed
+ const path = location.pathname.replace(/\/$/, '') || '/';
+ return config.excludedRoutes.some((p) => path === p || path.startsWith(p + '/'));
+}
+
+// ── 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 === '/features') return 'Tap any feature card to see it in action.';
+ if (path.startsWith('/agent') || path.startsWith('/a/') || path.startsWith('/marketplace')) {
+ const name = pageSubjectName();
+ return name ? `Say hi to ${name}!` : 'Browse agents — I’ll tag along.';
+ }
+ if (path === '/' || path.startsWith('/home')) return 'Hey! I’m your guide. I’ll walk with you.';
+ return 'I’ll walk along while you explore.';
+}
+
+function pageSubjectName() {
+ const el = document.querySelector('[data-agent-name], .agent-name, h1');
+ const txt = el?.textContent?.trim();
+ if (!txt || txt.length > 40) return null;
+ return txt;
+}
+
+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');
+ }
+ if (path === '/features') return document.querySelector('.feature-card, [data-feature]');
+ return null;
+}
+
+// ── The companion instance ───────────────────────────────────────────────────
+class WalkCompanion {
+ constructor(config, owner) {
+ this.config = config;
+ this.owner = owner; // the factory control object (for playground hand-off)
+ this.mounted = false;
+ 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._reduced = prefersReducedMotion();
+ this._currentEntry = null;
+ this._picker = null;
+
+ this._cursorX = window.innerWidth * 0.5;
+ this._cursorMovedAt = 0;
+ this._yaw = 0;
+ this._targetYaw = 0;
+ this._onPointerMove = this._onPointerMove.bind(this);
+ this._onLinkClick = this._onLinkClick.bind(this);
+ this._onVisibility = this._onVisibility.bind(this);
+ this._onPageHide = this._onPageHide.bind(this);
+ this._tick = this._tick.bind(this);
+ }
+
+ async mount() {
+ if (this.mounted || isExcludedRoute(this.config)) return;
+ if (!webglSupported()) return;
+ this.mounted = true;
+
+ this._buildDom();
+ try {
+ await this._buildScene();
+ } catch (err) {
+ log.warn('companion failed to load avatar:', err?.message || err);
+ this._teardownScene();
+ this._showError();
+ return;
+ }
+
+ this._restoreState();
+ this._bindEvents();
+ this._greetForRoute();
+ this.clock = new Timer();
+ this._raf = requestAnimationFrame(this._tick);
+ }
+
+ unmount() {
+ if (!this.mounted) return;
+ this.mounted = false;
+ cancelAnimationFrame(this._raf);
+ this._raf = 0;
+ window.removeEventListener('pointermove', this._onPointerMove);
+ document.removeEventListener('click', this._onLinkClick, true);
+ document.removeEventListener('visibilitychange', this._onVisibility);
+ window.removeEventListener('pagehide', this._onPageHide);
+ this._picker?.destroy();
+ this._picker = null;
+ this._teardownScene();
+ if (this.host && this.host.parentNode) this.host.parentNode.removeChild(this.host);
+ this.host = null;
+ }
+
+ // ── DOM / styles ──────────────────────────────────────────────────────────
+ _buildDom() {
+ ensureStyles();
+ const host = document.createElement('div');
+ host.className = 'walk-companion';
+ host.setAttribute('role', 'complementary');
+ host.setAttribute('aria-label', 'Walk companion');
+ const pickerBtn = this.config.enablePicker
+ ? `<button type="button" class="walk-companion-swap" data-walk-picker-toggle aria-label="Choose a different avatar" title="Choose avatar">⇄</button>`
+ : '';
+ host.innerHTML = `
+ <button type="button" class="walk-companion-close" aria-label="Dismiss walk companion" title="Dismiss">×</button>
+ ${pickerBtn}
+ <div class="walk-companion-bubble" hidden></div>
+ <canvas class="walk-companion-canvas" width="${CANVAS_W}" height="${CANVAS_H}"></canvas>
+ `;
+ document.body.appendChild(host);
+ this.host = host;
+ this.canvas = host.querySelector('.walk-companion-canvas');
+ this.bubble = host.querySelector('.walk-companion-bubble');
+ host.querySelector('.walk-companion-close').addEventListener('click', (e) => {
+ e.stopPropagation();
+ this.owner.disable();
+ });
+ host.querySelector('.walk-companion-swap')?.addEventListener('click', (e) => {
+ e.stopPropagation();
+ this.openPicker();
+ });
+ // Clicking the avatar detaches it into Playground mode.
+ this.canvas.addEventListener('click', () => this.owner._detachToPlayground(this));
+ requestAnimationFrame(() => host.classList.add('is-in'));
+ }
+
+ _showError() {
+ if (this.host && this.host.parentNode) this.host.parentNode.removeChild(this.host);
+ this.host = null;
+ this.mounted = false;
+ }
+
+ // ── Three.js scene ────────────────────────────────────────────────────────
+ 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;
+ reserveWebGLContext();
+
+ const scene = new Scene();
+ this.scene = scene;
+ scene.add(new AmbientLight(0xffffff, 0.85));
+ 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);
+
+ const camera = new PerspectiveCamera(40, CANVAS_W / CANVAS_H, 0.05, 100);
+ this.camera = camera;
+
+ const rig = new Group();
+ scene.add(rig);
+ this.rig = rig;
+
+ const entry = this._resolveEntry();
+ await this._loadInto(entry);
+ }
+
+ _resolveEntry() {
+ 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);
+ }
+
+ async _loadInto(entry) {
+ const fallback = resolveAvatarEntry(this.config.defaultAvatarId, this.config);
+ const { model, controller, entry: active } = await loadWalkAvatar(entry, {
+ assetBase: this.config.assetBase,
+ apiBase: this.config.apiBase,
+ manifestUrl: this.config.manifestUrl,
+ fallbackEntry: fallback,
+ });
+ this.model = model;
+ this.controller = controller;
+ this._currentEntry = active;
+ this._frame(model, this.rig, this.camera);
+ }
+
+ // Center on X/Z, drop feet to the floor, frame the camera on the full body.
+ _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.25);
+ camera.lookAt(0, height * 0.52, 0);
+ this._height = height;
+ }
+
+ // ── Live avatar swap (from the picker) ────────────────────────────────────
+ async setAvatar(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);
+ if (!this.mounted || !this.rig) return; // will apply on next mount
+ this._say('Switching…');
+ try {
+ const fallback = resolveAvatarEntry(this.config.defaultAvatarId, this.config);
+ const { model, controller, entry: active } = await loadWalkAvatar(entry, {
+ assetBase: this.config.assetBase,
+ apiBase: this.config.apiBase,
+ manifestUrl: this.config.manifestUrl,
+ fallbackEntry: fallback,
+ });
+ if (!this.mounted) {
+ disposeObject(model);
+ controller.dispose?.();
+ return;
+ }
+ if (this.model) {
+ this.rig.remove(this.model);
+ disposeObject(this.model);
+ }
+ this.controller?.dispose();
+ this._yaw = 0;
+ this._targetYaw = 0;
+ this.rig.rotation.y = 0;
+ this.model = model;
+ this.controller = controller;
+ this._currentEntry = active;
+ this._frame(model, this.rig, this.camera);
+ this._say(`Say hi to ${active.name}!`);
+ } catch (err) {
+ log.warn('avatar swap failed:', err?.message || err);
+ this._say('Couldn’t load that one — try another.');
+ }
+ }
+
+ openPicker() {
+ if (!this.config.enablePicker) return;
+ if (!this._picker) {
+ this._picker = createAvatarPicker({
+ avatars: this.config.avatars,
+ currentId: this._currentEntry?.id || this.config.defaultAvatarId,
+ assetBase: this.config.assetBase,
+ docsUrl: this.config.docsUrl,
+ anchor: { right: 16, bottom: CANVAS_H + 28 },
+ onSelect: (entry) => this.setAvatar(entry),
+ });
+ }
+ this._picker.toggle();
+ }
+
+ _teardownScene() {
+ try {
+ this.controller?.dispose();
+ } catch {
+ /* non-fatal */
+ }
+ this.controller = null;
+ this.model = null;
+ if (this.scene) {
+ this.scene.traverse((n) => {
+ if (n.isMesh) disposeMesh(n);
+ });
+ }
+ this.scene = null;
+ if (this.renderer) {
+ this.renderer.dispose();
+ this.renderer.forceContextLoss?.();
+ this.renderer = null;
+ releaseWebGLContext();
+ }
+ }
+
+ // ── Events ────────────────────────────────────────────────────────────────
+ _bindEvents() {
+ window.addEventListener('pointermove', this._onPointerMove, { passive: true });
+ document.addEventListener('click', this._onLinkClick, true);
+ document.addEventListener('visibilitychange', this._onVisibility);
+ window.addEventListener('pagehide', this._onPageHide);
+ }
+
+ _onPointerMove(e) {
+ this._cursorX = e.clientX;
+ this._cursorMovedAt = performance.now();
+ }
+
+ _onLinkClick(e) {
+ const a = e.target.closest?.('a[href]');
+ if (!a) return;
+ if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey) return;
+ const href = a.getAttribute('href');
+ if (!href || href.startsWith('#')) return;
+ if (a.target && a.target !== '_self') return;
+ let url;
+ try {
+ url = new URL(href, location.href);
+ } catch {
+ return;
+ }
+ if (url.origin !== location.origin) return;
+ if (url.pathname === location.pathname) return;
+ this.controller?.playWave();
+ ssSet(this.config.keys.greet, '1');
+ }
+
+ _onVisibility() {
+ if (document.hidden) {
+ cancelAnimationFrame(this._raf);
+ this._raf = 0;
+ } else if (this.mounted && !this._raf) {
+ this.clock?.update();
+ this._raf = requestAnimationFrame(this._tick);
+ }
+ }
+
+ _onPageHide() {
+ this._persistState();
+ }
+
+ // ── Greeting / speech bubble ──────────────────────────────────────────────
+ _greetForRoute() {
+ const arrivedByNav = ssGet(this.config.keys.greet) === '1';
+ ssDel(this.config.keys.greet);
+ if (arrivedByNav) this.controller?.playWave();
+ this._orientToContext();
+ const path = location.pathname.replace(/\/$/, '') || '/';
+ const greet = (this.config.greeting && this.config.greeting(path)) ?? defaultGreeting(path);
+ this._say(greet);
+ if (ssGet(this.config.keys.invited) !== '1') {
+ ssSet(this.config.keys.invited, '1');
+ clearTimeout(this._inviteTimer);
+ this._inviteTimer = setTimeout(() => {
+ if (this.mounted) this._say('Click me to walk the whole page →');
+ }, 5600);
+ }
+ }
+
+ _orientToContext() {
+ const el = contextTargetEl();
+ if (!el) return;
+ const rect = el.getBoundingClientRect();
+ const elCenterX = rect.left + rect.width / 2;
+ const hostRect = this.host.getBoundingClientRect();
+ const hostCenterX = hostRect.left + hostRect.width / 2;
+ this._targetYaw = clamp((elCenterX - hostCenterX) / window.innerWidth, -0.6, 0.6);
+ this._orientLock = true;
+ clearTimeout(this._orientTimer);
+ this._orientTimer = setTimeout(() => {
+ this._orientLock = false;
+ }, 4000);
+ }
+
+ _say(text) {
+ if (!this.bubble || !text) return;
+ this.bubble.textContent = text;
+ this.bubble.hidden = false;
+ this.bubble.classList.add('is-in');
+ clearTimeout(this._bubbleTimer);
+ this._bubbleTimer = setTimeout(() => {
+ this.bubble.classList.remove('is-in');
+ setTimeout(() => {
+ if (this.bubble) this.bubble.hidden = true;
+ }, 300);
+ }, 5200);
+ }
+
+ // ── Persistence ───────────────────────────────────────────────────────────
+ _persistState() {
+ if (!this.controller) return;
+ lsSet(this.config.keys.state, JSON.stringify({ yaw: this._yaw }));
+ }
+
+ _restoreState() {
+ try {
+ const raw = lsGet(this.config.keys.state);
+ if (!raw) return;
+ const s = JSON.parse(raw);
+ if (typeof s.yaw === 'number') {
+ this._yaw = s.yaw;
+ this._targetYaw = s.yaw;
+ }
+ } catch {
+ /* corrupt state — ignore */
+ }
+ }
+
+ // ── Render loop ───────────────────────────────────────────────────────────
+ _tick() {
+ if (!this.mounted) return;
+ this.clock.update();
+ const dt = Math.min(this.clock.getDelta(), 0.05);
+
+ const movingRecently = performance.now() - this._cursorMovedAt < CURSOR_IDLE_MS;
+ if (!this._reduced && !this._orientLock) {
+ const rel = (this._cursorX - window.innerWidth / 2) / (window.innerWidth / 2);
+ this._targetYaw = clamp(rel * 0.7, -0.7, 0.7);
+ }
+ const turning = Math.abs(this._targetYaw - this._yaw) > 0.04;
+ const shouldWalk = !this._reduced && (movingRecently || turning);
+ this.controller?.setState(shouldWalk ? 'walk' : 'idle');
+
+ this._yaw += (this._targetYaw - this._yaw) * 0.12;
+ if (this.rig) this.rig.rotation.y = this._yaw;
+
+ this.controller?.update(dt);
+ this.renderer.render(this.scene, this.camera);
+ this._raf = requestAnimationFrame(this._tick);
+ }
+}
+
+// ── Shared disposal helpers ───────────────────────────────────────────────────
+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?.();
+ });
+}
+function disposeObject(obj) {
+ obj?.traverse?.((n) => {
+ if (n.isMesh) disposeMesh(n);
+ });
+}
+
+// ── Scoped styles (injected once) ─────────────────────────────────────────────
+let _stylesInjected = false;
+function ensureStyles() {
+ if (_stylesInjected) return;
+ _stylesInjected = true;
+ const style = document.createElement('style');
+ style.id = 'walk-companion-style';
+ style.textContent = `
+.walk-companion{position:fixed;right:16px;bottom:16px;width:${CANVAS_W}px;height:${CANVAS_H}px;z-index:2147483000;pointer-events:none;opacity:0;transform:translateY(12px);transition:opacity .35s ease,transform .35s ease;-webkit-user-select:none;user-select:none}
+.walk-companion.is-in{opacity:1;transform:translateY(0)}
+.walk-companion-canvas{position:absolute;inset:0;width:100%;height:100%;z-index:1;pointer-events:auto;cursor:pointer;filter:drop-shadow(0 18px 22px rgba(0,0,0,.32))}
+.walk-companion-close,.walk-companion-swap{position:absolute;top:2px;z-index:3;width:22px;height:22px;border:none;border-radius:50%;background:rgba(12,14,20,.55);color:#fff;font-size:14px;line-height:1;cursor:pointer;pointer-events:auto;opacity:0;transition:opacity .2s ease,background .2s ease;display:grid;place-items:center;padding:0}
+.walk-companion-close{right:2px;font-size:15px}
+.walk-companion-swap{right:28px}
+.walk-companion:hover .walk-companion-close,.walk-companion:focus-within .walk-companion-close,.walk-companion:hover .walk-companion-swap,.walk-companion:focus-within .walk-companion-swap{opacity:1}
+.walk-companion-close:hover{background:rgba(220,60,60,.85)}
+.walk-companion-swap:hover{background:rgba(122,162,255,.85)}
+.walk-companion-close:focus-visible,.walk-companion-swap:focus-visible{outline:2px solid #7aa2ff;outline-offset:2px;opacity:1}
+.walk-companion-bubble{position:absolute;left:50%;bottom:calc(100% - 38px);z-index:2;transform:translateX(-50%) translateY(6px);max-width:230px;width:max-content;background:rgba(18,20,28,.94);color:#f2f4f8;font:500 12.5px/1.4 system-ui,-apple-system,'Segoe UI',sans-serif;padding:8px 11px;border-radius:12px;border:1px solid rgba(255,255,255,.1);box-shadow:0 10px 28px rgba(0,0,0,.35);pointer-events:none;opacity:0;transition:opacity .3s ease,transform .3s ease;text-align:center}
+.walk-companion-bubble.is-in{opacity:1;transform:translateX(-50%) translateY(0)}
+.walk-companion-bubble::after{content:'';position:absolute;left:50%;top:100%;transform:translateX(-50%);border:6px solid transparent;border-top-color:rgba(18,20,28,.94)}
+@media (max-width:520px){.walk-companion{width:148px;height:208px;right:10px;bottom:10px}.walk-companion-bubble{font-size:11.5px;max-width:170px}}
+@media (prefers-reduced-motion:reduce){.walk-companion,.walk-companion-bubble{transition:none}}
+`;
+ document.head.appendChild(style);
+}
+
+// ── Factory + control object ──────────────────────────────────────────────────
+/**
+ * Create a Walk Companion controller. Side-effect free: nothing mounts until
+ * `enable()` or `bootstrap()` is called.
+ * @param {object} [opts] see config.js / README for the full option set
+ */
+export function createWalkCompanion(opts = {}) {
+ const config = resolveConfig(opts);
+ let instance = null;
+ let pgWired = false;
+
+ const isEnabled = () => lsGet(config.keys.enabled) === '1';
+
+ function emitChange() {
+ try {
+ window.dispatchEvent(new CustomEvent('walk-companion:change', { detail: { enabled: isEnabled() } }));
+ } catch {
+ /* non-fatal */
+ }
+ }
+
+ const control = {
+ config,
+ get instance() {
+ return instance;
+ },
+ isEnabled,
+ enable() {
+ lsSet(config.keys.enabled, '1');
+ if (!instance) instance = new WalkCompanion(config, control);
+ instance.mount();
+ emitChange();
+ },
+ disable() {
+ lsSet(config.keys.enabled, '0');
+ if (instance) instance.unmount();
+ emitChange();
+ },
+ toggle() {
+ if (isEnabled() && instance && instance.mounted) control.disable();
+ else control.enable();
+ },
+ setAvatar(idOrEntry) {
+ lsSet(config.keys.avatar, typeof idOrEntry === 'string' ? idOrEntry : idOrEntry?.id);
+ if (instance) instance.setAvatar(idOrEntry);
+ },
+ openPicker() {
+ instance?.openPicker();
+ },
+
+ // Re-mount the corner companion when the playground exits.
+ _wirePlaygroundReturn() {
+ if (pgWired) return;
+ pgWired = true;
+ window.addEventListener('walk-playground:exit', () => {
+ if (isEnabled()) {
+ if (!instance) instance = new WalkCompanion(config, control);
+ instance.mount();
+ }
+ });
+ },
+
+ async _detachToPlayground(companion) {
+ control._wirePlaygroundReturn();
+ let startScreen = null;
+ try {
+ const r = companion.host.getBoundingClientRect();
+ startScreen = { x: r.left + r.width / 2, y: r.top + r.height * 0.86 };
+ } catch {
+ /* fall back to centered spawn */
+ }
+ const avatarId = companion._currentEntry?.id || lsGet(config.keys.avatar) || null;
+ if (instance) instance.unmount(); // free the corner WebGL context first
+ try {
+ const mod = await import('./playground.js');
+ mod.launchPlayground({ avatarId, startScreen, config });
+ } catch (err) {
+ log.warn('playground failed to load:', err?.message || err);
+ if (isEnabled()) {
+ if (!instance) instance = new WalkCompanion(config, control);
+ instance.mount();
+ }
+ }
+ },
+
+ async _tryDropIn() {
+ try {
+ 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 });
+ return true;
+ } catch (err) {
+ log.warn('drop-in failed:', err?.message || err);
+ return false;
+ }
+ },
+
+ // Replicates the app's auto-mount + deep-link behaviour. Safe to call once
+ // on load; reads ?walk= and the saved enabled flag.
+ bootstrap() {
+ if (typeof window === 'undefined') return;
+ const params = new URLSearchParams(location.search);
+ const walk = params.get('walk');
+ if (walk === '0') {
+ control.disable();
+ } else if (walk === 'play') {
+ lsSet(config.keys.enabled, '1');
+ import('./playground.js')
+ .then((mod) => {
+ control._wirePlaygroundReturn();
+ mod.launchPlayground({ avatarId: lsGet(config.keys.avatar) || null, config });
+ })
+ .catch((err) => {
+ log.warn('playground deep-link failed:', err?.message || err);
+ control.enable();
+ });
+ } else if (walk === '1' || isEnabled()) {
+ control._tryDropIn().then((dropped) => {
+ if (!dropped) control.enable();
+ });
+ }
+ },
+ };
+
+ return control;
+}
diff --git a/walk-sdk/src/index.js b/walk-sdk/src/index.js
new file mode 100644
index 000000000..44c7ba5c4
--- /dev/null
+++ b/walk-sdk/src/index.js
@@ -0,0 +1,56 @@
+// @three-ws/walk — a 3D avatar that walks and talks over your web pages.
+// =====================================================================
+// Drop a diverse, animated character into any site. It idles in the corner,
+// follows the cursor, waves on navigation, and greets each page. Click it and
+// it detaches into a full-page playground (stroll or platformer). Visitors pick
+// who walks with them from a roster of avatars — or you supply your own.
+//
+// Quick start (the whole thing, app-style auto-mount):
+//
+// import { createWalkCompanion } from '@three-ws/walk';
+// createWalkCompanion().bootstrap();
+//
+// Or drive it yourself:
+//
+// const walk = createWalkCompanion({ defaultAvatarId: 'fox' });
+// walk.enable(); // mount the corner companion
+// walk.openPicker(); // let the visitor choose
+// walk.setAvatar('michelle'); // swap live
+//
+// `three` is a peer dependency — bring your own copy.
+
+export const VERSION = '0.1.0';
+
+// Companion (corner mascot) — the main entry point.
+export { createWalkCompanion } from './companion.js';
+
+// Playground (full-page stroll / platformer). The companion drives these for
+// you, but they're exported for direct/standalone use.
+export {
+ launchPlayground,
+ exitPlayground,
+ switchPlaygroundMode,
+ getPlaygroundMode,
+ shouldDropIn,
+ consumeDropIn,
+ playgroundState,
+} from './playground.js';
+
+// Avatar roster + helpers.
+export {
+ WALK_AVATARS,
+ DEFAULT_AVATAR_ID,
+ DEFAULT_SHARED_CLIPS,
+ getAvatar,
+ defaultAvatar,
+ listCategories,
+ makeApiAvatarEntry,
+ resolveAvatarUrl,
+} from './roster.js';
+
+// The picker UI, for hosts that want to place it themselves.
+export { createAvatarPicker } from './picker.js';
+
+// Low-level building blocks for advanced integrations.
+export { loadWalkAvatar } from './internal/load-avatar.js';
+export { resolveConfig, resolveAvatarEntry, DEFAULT_EXCLUDED_PREFIXES } from './config.js';
diff --git a/walk-sdk/src/playground.js b/walk-sdk/src/playground.js
new file mode 100644
index 000000000..58c2324e1
--- /dev/null
+++ b/walk-sdk/src/playground.js
@@ -0,0 +1,1157 @@
+// Walk Playground — the page becomes a place your avatar can roam.
+// ================================================================
+// Hands off from the corner companion: click it and the avatar "detaches" into
+// a full-page character you steer around the site. Two movement models, switched
+// live (the mode button, top-right, or the M key) and remembered across pages:
+//
+// • Stroll — a gentle top-down aerial view. No gravity, nothing to fall off:
+// walk anywhere across the page; step on a link to dive into it.
+// • Platformer — the page's real DOM (headings, cards, buttons, links) becomes
+// solid ground. Gravity, jumping, falling; land on a link to dive in.
+//
+// Whatever avatar the visitor chose in the companion picker walks here too:
+// loading goes through the shared unified loader, so a retarget-only humanoid
+// (which would otherwise stand in a bind pose) animates exactly like the robot.
+
+import {
+ AmbientLight,
+ Box3,
+ CircleGeometry,
+ DirectionalLight,
+ DoubleSide,
+ Group,
+ HemisphereLight,
+ Mesh,
+ MeshBasicMaterial,
+ OrthographicCamera,
+ Scene,
+ Timer,
+ Vector3,
+ WebGLRenderer,
+} 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 { loadWalkAvatar } from './internal/load-avatar.js';
+import { resolveConfig, resolveAvatarEntry } from './config.js';
+
+// Active config — set by launchPlayground. Defaults keep the module usable if a
+// caller forgets to pass one (e.g. console-driven `__walkPlayground.launch()`).
+let _config = resolveConfig();
+
+// ── Stroll tuning (CSS-pixel units, seconds) ─────────────────────────────────
+const CHAR_PX = 150;
+const MOVE_ACCEL = 3600;
+const MAX_SPEED = 360;
+const RUN_SPEED = 250;
+const FRICTION = 3200;
+const EDGE_PAD = 30;
+const CAM_PITCH = 0.5;
+const LINK_DWELL_MS = 700;
+const SPAWN_GUARD_MS = 1100;
+const ELEM_PROBE_MS = 90;
+
+// ── Platformer tuning ────────────────────────────────────────────────────────
+const PLAT_CHAR_PX = 138;
+const GRAVITY = 2600;
+const TERMINAL = 2400;
+const MOVE_SPEED = 330;
+const PLAT_RUN_SPEED = 250;
+const JUMP_V = 1000;
+const GROUND_ACCEL = 2600;
+const AIR_ACCEL = 1400;
+const PLAT_FRICTION = 2400;
+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(',');
+
+function getMode() {
+ try {
+ return localStorage.getItem(_config.keys.mode) === 'platformer' ? 'platformer' : 'stroll';
+ } catch {
+ return 'stroll';
+ }
+}
+function setMode(m) {
+ try {
+ localStorage.setItem(_config.keys.mode, m === 'platformer' ? 'platformer' : 'stroll');
+ } catch {
+ /* non-fatal */
+ }
+}
+
+function docWidth() {
+ return Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
+}
+function docHeight() {
+ const el = document.scrollingElement || document.documentElement;
+ return Math.max(el.scrollHeight, window.innerHeight || 0);
+}
+function maxScroll() {
+ return Math.max(0, docHeight() - window.innerHeight);
+}
+
+function linkHrefAtPoint(sx, sy) {
+ let el = document.elementFromPoint(sx, sy);
+ if (!el) return null;
+ const a = el.closest?.('a[href]');
+ if (!a) return null;
+ if (a.target && a.target !== '_self') return null;
+ const raw = a.getAttribute('href') || '';
+ if (!raw || raw.startsWith('#') || raw.startsWith('javascript:')) return null;
+ try {
+ const u = new URL(raw, location.href);
+ if (u.origin !== location.origin) return null;
+ return { href: u.href, el: a };
+ } catch {
+ return null;
+ }
+}
+
+function modeButtonHTML(mode) {
+ const label = mode === 'platformer' ? 'Platformer' : 'Stroll';
+ const icon = mode === 'platformer' ? '🎮' : '🚶';
+ return `<button type="button" class="walk-pg-mode" aria-label="Switch movement mode (currently ${label})" title="Switch mode (M)"><span class="walk-pg-mode-ic" aria-hidden="true">${icon}</span><span class="walk-pg-mode-tx">${label}</span></button>`;
+}
+
+// Load + scale the chosen avatar to a fixed pixel height, feet at the rig
+// origin. Goes through the shared unified loader so any roster avatar animates.
+async function loadCharacter(avatarId, charPx) {
+ const entry = resolveAvatarEntry(avatarId, _config);
+ const fallback = resolveAvatarEntry(_config.defaultAvatarId, _config);
+ const { model, controller } = await loadWalkAvatar(entry, {
+ assetBase: _config.assetBase,
+ apiBase: _config.apiBase,
+ manifestUrl: _config.manifestUrl,
+ fallbackEntry: fallback,
+ });
+ const box = new Box3().setFromObject(model);
+ const size = box.getSize(new Vector3());
+ const scale = charPx / Math.max(0.001, size.y);
+ model.scale.setScalar(scale);
+ const box2 = new Box3().setFromObject(model);
+ const center = box2.getCenter(new Vector3());
+ model.position.x -= center.x;
+ model.position.z -= center.z;
+ model.position.y -= box2.min.y;
+ return { model, controller, halfW: (size.x * scale) / 2 };
+}
+
+// ═════════════════════════════════════════════════════════════════════════════
+// Stroll mode — gentle top-down aerial view, no gravity, roam anywhere.
+// ═════════════════════════════════════════════════════════════════════════════
+class StrollPlayground {
+ constructor() {
+ this.mode = 'stroll';
+ this.mounted = false;
+ this._reduced = prefersReducedMotion();
+ this._raf = 0;
+ this._tick = this._tick.bind(this);
+ this._onKeyDown = this._onKeyDown.bind(this);
+ this._onKeyUp = this._onKeyUp.bind(this);
+ this._onResize = this._onResize.bind(this);
+ this.char = { x: 0, y: 0, vx: 0, vy: 0, facing: 0 };
+ this._yaw = 0;
+ this.input = { up: false, down: false, left: false, right: false, dive: false };
+ this._armEl = null;
+ this._armAt = 0;
+ this._armHref = null;
+ this._lastProbe = 0;
+ this._diving = false;
+ this._spawnGuardUntil = 0;
+ this._v0 = new Vector3();
+ this._v1 = new Vector3();
+ }
+
+ async mount({ avatarId = null, startScreen = null, dropIn = false, switched = false } = {}) {
+ if (this.mounted) return;
+ if (!webglSupported()) {
+ log.warn('playground: WebGL unavailable');
+ return;
+ }
+ this.mounted = true;
+ this._avatarId = avatarId;
+ this._buildDom();
+ try {
+ await this._buildScene();
+ } catch (err) {
+ log.warn('playground failed to load avatar:', err?.message || err);
+ this._teardown();
+ return;
+ }
+ this._placeStart(startScreen, dropIn);
+ this._spawnGuardUntil = performance.now() + SPAWN_GUARD_MS;
+ this._bindEvents();
+ if (switched) this._sayModeIntro();
+ else this._hintFor(dropIn);
+ this.clock = new Timer();
+ this._raf = requestAnimationFrame(this._tick);
+ }
+
+ unmount() {
+ if (!this.mounted) return;
+ this.mounted = false;
+ cancelAnimationFrame(this._raf);
+ this._raf = 0;
+ window.removeEventListener('keydown', this._onKeyDown, true);
+ window.removeEventListener('keyup', this._onKeyUp, true);
+ window.removeEventListener('resize', this._onResize);
+ this._clearArm();
+ this._teardown();
+ }
+
+ currentScreenPos() {
+ return { x: this.char.x - (window.scrollX || 0), y: this.char.y - (window.scrollY || 0) };
+ }
+
+ _buildDom() {
+ ensureStyles();
+ const host = document.createElement('div');
+ host.className = 'walk-pg walk-pg--stroll';
+ host.setAttribute('role', 'application');
+ host.setAttribute('aria-label', 'Page playground — walk the character with the arrow keys');
+ host.innerHTML = `
+ <canvas class="walk-pg-canvas"></canvas>
+ <div class="walk-pg-hint" aria-live="polite"></div>
+ ${modeButtonHTML(this.mode)}
+ <button type="button" class="walk-pg-exit" aria-label="Exit playground" title="Exit (Esc)">Exit ✕</button>
+ <div class="walk-pg-pad" aria-hidden="true">
+ <button type="button" class="walk-pg-btn" data-act="up" aria-label="Walk up">▲</button>
+ <div class="walk-pg-pad-row">
+ <button type="button" class="walk-pg-btn" data-act="left" aria-label="Walk left">◀</button>
+ <button type="button" class="walk-pg-btn walk-pg-dive" data-act="dive" aria-label="Dive into link">⬇</button>
+ <button type="button" class="walk-pg-btn" data-act="right" aria-label="Walk right">▶</button>
+ </div>
+ <button type="button" class="walk-pg-btn" data-act="down" aria-label="Walk down">▼</button>
+ </div>
+ <div class="walk-pg-flash" aria-hidden="true"></div>
+ `;
+ document.body.appendChild(host);
+ this.host = host;
+ this.canvas = host.querySelector('.walk-pg-canvas');
+ this.hintEl = host.querySelector('.walk-pg-hint');
+ this.flashEl = host.querySelector('.walk-pg-flash');
+ host.querySelector('.walk-pg-exit').addEventListener('click', () => exitPlayground());
+ host.querySelector('.walk-pg-mode').addEventListener('click', () => switchPlaygroundMode());
+ host.querySelectorAll('.walk-pg-btn').forEach((btn) => {
+ const act = btn.getAttribute('data-act');
+ const on = (e) => {
+ e.preventDefault();
+ this._setAct(act, true);
+ };
+ const off = (e) => {
+ e.preventDefault();
+ this._setAct(act, false);
+ };
+ btn.addEventListener('pointerdown', on);
+ btn.addEventListener('pointerup', off);
+ btn.addEventListener('pointerleave', off);
+ btn.addEventListener('pointercancel', off);
+ });
+ requestAnimationFrame(() => host.classList.add('is-in'));
+ }
+
+ _setAct(act, val) {
+ if (act in this.input) this.input[act] = val;
+ }
+
+ async _buildScene() {
+ const renderer = new WebGLRenderer({ canvas: this.canvas, alpha: true, antialias: true });
+ renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
+ this.renderer = renderer;
+ reserveWebGLContext();
+ this._resizeRenderer();
+
+ const scene = new Scene();
+ this.scene = scene;
+ scene.add(new AmbientLight(0xffffff, 0.9));
+ const hemi = new HemisphereLight(0xbcd6ff, 0x1a2230, 0.75);
+ hemi.position.set(0, 300, 0);
+ scene.add(hemi);
+ const sun = new DirectionalLight(0xffffff, 1.7);
+ sun.position.set(80, 320, 260);
+ scene.add(sun);
+
+ this._setupCamera();
+
+ const rig = new Group();
+ scene.add(rig);
+ this.rig = rig;
+
+ const shadow = new Mesh(
+ new CircleGeometry(1, 28),
+ new MeshBasicMaterial({ color: 0x05070c, transparent: true, opacity: 0.32, side: DoubleSide, depthWrite: false }),
+ );
+ shadow.renderOrder = -1;
+ scene.add(shadow);
+ this.shadow = shadow;
+
+ const { model, controller, halfW } = await loadCharacter(this._avatarId, CHAR_PX);
+ this.modelHalfW = halfW;
+ this._shadowR = Math.max(22, halfW * 1.15);
+ rig.add(model);
+ this.controller = controller;
+ }
+
+ _setupCamera() {
+ const W = window.innerWidth;
+ const H = window.innerHeight;
+ const cam = new OrthographicCamera(-W / 2, W / 2, H / 2, -H / 2, -4000, 8000);
+ const D = 3000;
+ cam.position.set(0, Math.sin(CAM_PITCH) * D, Math.cos(CAM_PITCH) * D);
+ cam.up.set(0, 1, 0);
+ cam.lookAt(0, 0, 0);
+ cam.updateProjectionMatrix();
+ cam.updateMatrixWorld(true);
+ this.camera = cam;
+ }
+
+ _pagePointAtScreen(sx, sy, out) {
+ const W = window.innerWidth;
+ const H = window.innerHeight;
+ const ndcX = (sx / W) * 2 - 1;
+ const ndcY = -((sy / H) * 2 - 1);
+ const p0 = this._v0.set(ndcX, ndcY, -1).unproject(this.camera);
+ const p1 = this._v1.set(ndcX, ndcY, 1).unproject(this.camera);
+ const dz = p1.z - p0.z;
+ const t = Math.abs(dz) < 1e-6 ? 0 : -p0.z / dz;
+ return out.set(p0.x + (p1.x - p0.x) * t, p0.y + (p1.y - p0.y) * t, 0);
+ }
+
+ _placeStart(startScreen, dropIn) {
+ const sx = window.scrollX || 0;
+ const sy = window.scrollY || 0;
+ const w = docWidth();
+ if (startScreen) {
+ this.char.x = clamp(startScreen.x + sx, EDGE_PAD, w - EDGE_PAD);
+ 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.vx = 0;
+ this.char.vy = 0;
+ this._dropIn = dropIn;
+ }
+
+ _bindEvents() {
+ window.addEventListener('keydown', this._onKeyDown, true);
+ window.addEventListener('keyup', this._onKeyUp, true);
+ window.addEventListener('resize', this._onResize);
+ }
+
+ _onKeyDown(e) {
+ const k = e.key;
+ if (k === 'Escape') {
+ exitPlayground();
+ return;
+ }
+ if (k === 'm' || k === 'M') {
+ e.preventDefault();
+ switchPlaygroundMode();
+ return;
+ }
+ 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 === '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 handled = false;
+ if (handled) e.preventDefault();
+ }
+
+ _onKeyUp(e) {
+ const k = e.key;
+ if (k === 'ArrowLeft' || k === 'a' || k === 'A') this.input.left = false;
+ 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;
+ }
+
+ _onResize() {
+ this._resizeRenderer();
+ this._setupCamera();
+ this.char.x = clamp(this.char.x, EDGE_PAD, docWidth() - EDGE_PAD);
+ this.char.y = clamp(this.char.y, EDGE_PAD, docHeight() - EDGE_PAD);
+ }
+
+ _resizeRenderer() {
+ this.renderer.setSize(window.innerWidth, window.innerHeight, false);
+ }
+
+ _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);
+ }
+
+ _sayModeIntro() {
+ this._say('Stroll mode — free roam, no falling. M to switch back.', 3800);
+ }
+
+ _say(text, ms = 3200) {
+ if (!this.hintEl || !text) return;
+ this.hintEl.textContent = text;
+ this.hintEl.classList.add('is-in');
+ clearTimeout(this._hintTimer);
+ this._hintTimer = setTimeout(() => this.hintEl?.classList.remove('is-in'), ms);
+ }
+
+ _armLink(el, href) {
+ if (this._armEl === el) return;
+ this._clearArm();
+ this._armEl = el;
+ this._armHref = href;
+ this._armAt = performance.now();
+ el.classList.add('walk-pg-portal');
+ this._say('Pause here or press Space to dive in', 2400);
+ }
+
+ _clearArm() {
+ if (this._armEl) this._armEl.classList.remove('walk-pg-portal');
+ this._armEl = null;
+ this._armHref = null;
+ }
+
+ _dive(href) {
+ if (this._diving || !href) return;
+ this._diving = true;
+ this.controller?.setState('jump');
+ if (this._armEl) this._armEl.classList.add('is-open');
+ ssSet(_config.keys.resume, '1');
+ this.flashEl?.classList.add('is-on');
+ const go = () => {
+ location.href = href;
+ };
+ if (this._reduced) {
+ go();
+ return;
+ }
+ this.char.vx = 0;
+ this.char.vy = 0;
+ setTimeout(go, 560);
+ }
+
+ _tick() {
+ if (!this.mounted) return;
+ this.clock.update();
+ const dt = Math.min(this.clock.getDelta(), 0.033);
+ if (!this._diving) this._step(dt);
+ this._follow();
+ this._render(dt);
+ this._raf = requestAnimationFrame(this._tick);
+ }
+
+ _step(dt) {
+ const c = this.char;
+ let ix = (this.input.right ? 1 : 0) - (this.input.left ? 1 : 0);
+ let iy = (this.input.down ? 1 : 0) - (this.input.up ? 1 : 0);
+ if (ix !== 0 && iy !== 0) {
+ const inv = 1 / Math.SQRT2;
+ ix *= inv;
+ iy *= inv;
+ }
+ if (ix !== 0 || iy !== 0) {
+ c.vx += ix * MOVE_ACCEL * dt;
+ c.vy += iy * MOVE_ACCEL * dt;
+ const sp = Math.hypot(c.vx, c.vy);
+ if (sp > MAX_SPEED) {
+ const k = MAX_SPEED / sp;
+ c.vx *= k;
+ c.vy *= k;
+ }
+ } else {
+ const f = FRICTION * dt;
+ const sp = Math.hypot(c.vx, c.vy);
+ if (sp <= f) {
+ c.vx = 0;
+ c.vy = 0;
+ } else {
+ const k = (sp - f) / sp;
+ c.vx *= k;
+ c.vy *= k;
+ }
+ }
+ c.x = clamp(c.x + c.vx * dt, EDGE_PAD, docWidth() - EDGE_PAD);
+ c.y = clamp(c.y + c.vy * dt, EDGE_PAD, docHeight() - EDGE_PAD);
+ const speed = Math.hypot(c.vx, c.vy);
+ if (speed > 12) this.char.facing = Math.atan2(c.vx, c.vy);
+
+ const now = performance.now();
+ if (now - this._lastProbe > ELEM_PROBE_MS) {
+ this._lastProbe = now;
+ const feetX = c.x - (window.scrollX || 0);
+ const feetY = c.y - (window.scrollY || 0);
+ const hit = linkHrefAtPoint(feetX, feetY);
+ if (hit) this._armLink(hit.el, hit.href);
+ else if (this._armEl) this._clearArm();
+ }
+
+ if (this._armHref) {
+ if (this.input.dive) {
+ this._dive(this._armHref);
+ return;
+ }
+ const pastGuard = now > this._spawnGuardUntil;
+ if (pastGuard && speed < 24 && now - this._armAt > LINK_DWELL_MS) {
+ this._dive(this._armHref);
+ return;
+ }
+ }
+
+ let state = 'idle';
+ if (speed > RUN_SPEED) state = 'run';
+ else if (speed > 12) state = 'walk';
+ this.controller?.setState(state);
+ }
+
+ _follow() {
+ const vh = window.innerHeight;
+ const cur = window.scrollY || 0;
+ const screenY = this.char.y - cur;
+ const top = vh * 0.3;
+ const bottom = vh * 0.7;
+ let next = cur;
+ if (screenY < top) next = this.char.y - top;
+ else if (screenY > bottom) next = this.char.y - bottom;
+ next = clamp(next, 0, maxScroll());
+ if (Math.abs(next - cur) > 0.5) window.scrollTo(0, next);
+ }
+
+ _render(dt) {
+ const c = this.char;
+ const feetX = c.x - (window.scrollX || 0);
+ const feetY = c.y - (window.scrollY || 0);
+ this._pagePointAtScreen(feetX, feetY, this._v0);
+ this.rig.position.copy(this._v0);
+ if (this.shadow) {
+ this.shadow.position.set(this._v0.x, this._v0.y, this._v0.z + 0.5);
+ this.shadow.scale.set(this._shadowR, this._shadowR * 0.5, 1);
+ }
+ if (this._diving) {
+ 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);
+ } else {
+ let d = this.char.facing - this._yaw;
+ while (d > Math.PI) d -= Math.PI * 2;
+ while (d < -Math.PI) d += Math.PI * 2;
+ this._yaw += d * Math.min(1, dt * 11);
+ this.rig.rotation.y = this._yaw;
+ }
+ this.controller?.update(dt);
+ this.renderer.render(this.scene, this.camera);
+ }
+
+ _teardown() {
+ teardownScene(this);
+ }
+}
+
+// ═════════════════════════════════════════════════════════════════════════════
+// Platformer mode — the page's DOM is solid ground; gravity, jumping, falling.
+// ═════════════════════════════════════════════════════════════════════════════
+class PlatformerPlayground {
+ constructor() {
+ this.mode = 'platformer';
+ this.mounted = false;
+ this._reduced = prefersReducedMotion();
+ this._raf = 0;
+ this._tick = this._tick.bind(this);
+ this._onKeyDown = this._onKeyDown.bind(this);
+ this._onKeyUp = this._onKeyUp.bind(this);
+ this._onResize = this._onResize.bind(this);
+ this._scheduleRescan = this._scheduleRescan.bind(this);
+ this.char = { x: 0, y: 0, vx: 0, vy: 0, grounded: false, facing: 1 };
+ this.platform = null;
+ this.platforms = [];
+ this._lastScan = 0;
+ this._scrollY = 0;
+ this.input = { left: false, right: false, jump: false, down: false };
+ this._jumpEdge = false;
+ this._armEl = null;
+ this._armAt = 0;
+ this._armHref = null;
+ this._diving = false;
+ }
+
+ async mount({ avatarId = null, startScreen = null, dropIn = false, switched = false } = {}) {
+ if (this.mounted) return;
+ if (!webglSupported()) {
+ log.warn('playground: WebGL unavailable');
+ return;
+ }
+ this.mounted = true;
+ this._avatarId = avatarId;
+ this._buildDom();
+ try {
+ await this._buildScene();
+ } catch (err) {
+ log.warn('playground failed to load avatar:', err?.message || err);
+ this._teardown();
+ return;
+ }
+ this._scrollY = window.scrollY || 0;
+ this._scan(true);
+ this._placeStart(startScreen, dropIn);
+ this._spawnGuardUntil = performance.now() + 1500;
+ this._bindEvents();
+ if (switched) this._sayModeIntro();
+ else this._hintFor(dropIn);
+ this.clock = new Timer();
+ this._raf = requestAnimationFrame(this._tick);
+ }
+
+ unmount() {
+ if (!this.mounted) return;
+ this.mounted = false;
+ cancelAnimationFrame(this._raf);
+ this._raf = 0;
+ window.removeEventListener('keydown', this._onKeyDown, true);
+ window.removeEventListener('keyup', this._onKeyUp, true);
+ window.removeEventListener('resize', this._onResize);
+ window.removeEventListener('scroll', this._scheduleRescan, true);
+ this._clearArm();
+ this._teardown();
+ }
+
+ currentScreenPos() {
+ return { x: this.char.x - (window.scrollX || 0), y: this.char.y - (window.scrollY || 0) };
+ }
+
+ _buildDom() {
+ ensureStyles();
+ 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.innerHTML = `
+ <canvas class="walk-pg-canvas"></canvas>
+ <div class="walk-pg-hint" aria-live="polite"></div>
+ ${modeButtonHTML(this.mode)}
+ <button type="button" class="walk-pg-exit" aria-label="Exit playground" title="Exit (Esc)">Exit ✕</button>
+ <div class="walk-pg-pad" aria-hidden="true">
+ <button type="button" class="walk-pg-btn" data-act="left" aria-label="Walk left">◀</button>
+ <button type="button" class="walk-pg-btn" data-act="right" aria-label="Walk right">▶</button>
+ <button type="button" class="walk-pg-btn walk-pg-jump" data-act="jump" aria-label="Jump">⤒</button>
+ <button type="button" class="walk-pg-btn" data-act="down" aria-label="Dive into link">⤓</button>
+ </div>
+ <div class="walk-pg-flash" aria-hidden="true"></div>
+ `;
+ document.body.appendChild(host);
+ this.host = host;
+ this.canvas = host.querySelector('.walk-pg-canvas');
+ this.hintEl = host.querySelector('.walk-pg-hint');
+ this.flashEl = host.querySelector('.walk-pg-flash');
+ host.querySelector('.walk-pg-exit').addEventListener('click', () => exitPlayground());
+ host.querySelector('.walk-pg-mode').addEventListener('click', () => switchPlaygroundMode());
+ host.querySelectorAll('.walk-pg-btn').forEach((btn) => {
+ const act = btn.getAttribute('data-act');
+ const on = (e) => {
+ e.preventDefault();
+ this._setAct(act, true);
+ };
+ const off = (e) => {
+ e.preventDefault();
+ this._setAct(act, false);
+ };
+ btn.addEventListener('pointerdown', on);
+ btn.addEventListener('pointerup', off);
+ btn.addEventListener('pointerleave', off);
+ btn.addEventListener('pointercancel', off);
+ });
+ requestAnimationFrame(() => host.classList.add('is-in'));
+ }
+
+ _setAct(act, val) {
+ if (act === 'left') this.input.left = val;
+ else if (act === 'right') this.input.right = val;
+ else if (act === 'jump') {
+ this.input.jump = val;
+ if (!val) this._jumpEdge = false;
+ } else if (act === 'down') this.input.down = val;
+ }
+
+ async _buildScene() {
+ const renderer = new WebGLRenderer({ canvas: this.canvas, alpha: true, antialias: true });
+ renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
+ this.renderer = renderer;
+ reserveWebGLContext();
+ this._resizeRenderer();
+
+ const scene = new Scene();
+ this.scene = scene;
+ scene.add(new AmbientLight(0xffffff, 0.9));
+ const hemi = new HemisphereLight(0xbcd6ff, 0x1a2230, 0.75);
+ hemi.position.set(0, 200, 0);
+ scene.add(hemi);
+ const sun = new DirectionalLight(0xffffff, 1.7);
+ sun.position.set(120, 260, 220);
+ scene.add(sun);
+
+ this.camera = new OrthographicCamera(0, window.innerWidth, 0, -window.innerHeight, -1000, 2000);
+ this.camera.position.z = 600;
+
+ const rig = new Group();
+ scene.add(rig);
+ this.rig = rig;
+
+ const { model, controller, halfW } = await loadCharacter(this._avatarId, PLAT_CHAR_PX);
+ this.modelHalfW = halfW;
+ rig.add(model);
+ this.controller = controller;
+ }
+
+ _placeStart(startScreen, dropIn) {
+ const sy = window.scrollY || 0;
+ if (dropIn) {
+ this.char.x = clamp(docWidth() * 0.5, 40, docWidth() - 40);
+ this.char.y = sy - PLAT_CHAR_PX;
+ this.char.vy = 60;
+ this.char.grounded = false;
+ } else if (startScreen) {
+ this.char.x = clamp(startScreen.x + (window.scrollX || 0), 40, docWidth() - 40);
+ this.char.y = startScreen.y + sy;
+ this.char.vy = 40;
+ this.char.grounded = false;
+ } else {
+ this.char.x = clamp(docWidth() * 0.5, 40, docWidth() - 40);
+ this.char.y = sy + window.innerHeight * 0.3;
+ this.char.vy = 0;
+ }
+ }
+
+ _scan(force = false) {
+ const now = performance.now();
+ if (!force && now - this._lastScan < 180) return;
+ this._lastScan = now;
+ const sx = window.scrollX || 0;
+ const sy = window.scrollY || 0;
+ const bandTop = sy - 1100;
+ const bandBottom = sy + window.innerHeight + 1100;
+ const out = [];
+ const seen = new Set();
+ const els = document.querySelectorAll(SOLID_SELECTOR);
+ for (const el of els) {
+ if (out.length >= 360) break;
+ if (this.host.contains(el)) continue;
+ const r = el.getBoundingClientRect();
+ if (r.width < 38 || r.height < 14 || r.height > 520) continue;
+ const top = r.top + sy;
+ 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;
+ const left = r.left + sx;
+ const right = r.right + sx;
+ const key = `${Math.round(left)},${Math.round(top)},${Math.round(right)}`;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ const link = el.closest('a[href]');
+ let href = null;
+ if (link) {
+ const raw = link.getAttribute('href') || '';
+ if (raw && !raw.startsWith('#') && (!link.target || link.target === '_self')) {
+ try {
+ const u = new URL(raw, location.href);
+ if (u.origin === location.origin) href = u.href;
+ } catch {
+ /* unparseable href — treat as plain platform */
+ }
+ }
+ }
+ 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 });
+ this.platforms = out;
+ if (this.platform && !out.includes(this.platform)) out.push(this.platform);
+ }
+
+ _scheduleRescan() {
+ this._scrollY = window.scrollY || 0;
+ this._scan();
+ }
+
+ _bindEvents() {
+ window.addEventListener('keydown', this._onKeyDown, true);
+ window.addEventListener('keyup', this._onKeyUp, true);
+ window.addEventListener('resize', this._onResize);
+ window.addEventListener('scroll', this._scheduleRescan, true);
+ }
+
+ _onKeyDown(e) {
+ const k = e.key;
+ if (k === 'Escape') {
+ exitPlayground();
+ return;
+ }
+ if (k === 'm' || k === 'M') {
+ e.preventDefault();
+ switchPlaygroundMode();
+ return;
+ }
+ 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 === 'ArrowDown' || k === 's' || k === 'S') this.input.down = true;
+ else handled = false;
+ if (handled) e.preventDefault();
+ }
+
+ _onKeyUp(e) {
+ const k = e.key;
+ if (k === 'ArrowLeft' || k === 'a' || k === 'A') this.input.left = false;
+ else if (k === 'ArrowRight' || k === 'd' || k === 'D') this.input.right = false;
+ else if (k === ' ' || k === 'ArrowUp' || k === 'w' || k === 'W' || k === 'Spacebar') {
+ this.input.jump = false;
+ this._jumpEdge = false;
+ } else if (k === 'ArrowDown' || k === 's' || k === 'S') this.input.down = false;
+ }
+
+ _onResize() {
+ this._resizeRenderer();
+ if (this.camera) {
+ this.camera.right = window.innerWidth;
+ this.camera.bottom = -window.innerHeight;
+ this.camera.updateProjectionMatrix();
+ }
+ this._scan(true);
+ }
+
+ _resizeRenderer() {
+ this.renderer.setSize(window.innerWidth, window.innerHeight, false);
+ }
+
+ _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);
+ }
+
+ _sayModeIntro() {
+ const touch = matchMedia('(pointer: coarse)').matches;
+ const jump = touch ? 'tap ⤒ to jump' : 'Space to jump';
+ this._say(`Platformer mode — gravity on, ${jump}. M to switch back.`, 3800);
+ }
+
+ _say(text, ms = 3200) {
+ if (!this.hintEl || !text) return;
+ this.hintEl.textContent = text;
+ this.hintEl.classList.add('is-in');
+ clearTimeout(this._hintTimer);
+ this._hintTimer = setTimeout(() => this.hintEl?.classList.remove('is-in'), ms);
+ }
+
+ _armLink(p) {
+ if (this._armEl === p.el) return;
+ this._clearArm();
+ this._armEl = p.el;
+ this._armAt = performance.now();
+ this._armHref = p.href;
+ p.el.classList.add('walk-pg-portal');
+ this._say('↓ to dive in', 2200);
+ }
+
+ _clearArm() {
+ if (this._armEl) this._armEl.classList.remove('walk-pg-portal');
+ this._armEl = null;
+ this._armHref = null;
+ }
+
+ _dive(href) {
+ if (this._diving || !href) return;
+ this._diving = true;
+ this.controller?.setState('jump');
+ if (this._armEl) this._armEl.classList.add('is-open');
+ ssSet(_config.keys.resume, '1');
+ this.flashEl?.classList.add('is-on');
+ const go = () => {
+ location.href = href;
+ };
+ if (this._reduced) {
+ go();
+ return;
+ }
+ this.char.vx = 0;
+ this.char.vy = TERMINAL;
+ this.char.grounded = false;
+ setTimeout(go, 620);
+ }
+
+ _tick() {
+ if (!this.mounted) return;
+ this.clock.update();
+ const dt = Math.min(this.clock.getDelta(), 0.033);
+ if (!this._diving) this._step(dt);
+ this._follow(dt);
+ this._render(dt);
+ this._raf = requestAnimationFrame(this._tick);
+ }
+
+ _step(dt) {
+ const c = this.char;
+ const dir = (this.input.right ? 1 : 0) - (this.input.left ? 1 : 0);
+ const accel = c.grounded ? GROUND_ACCEL : AIR_ACCEL;
+ if (dir !== 0) {
+ c.vx += dir * accel * dt;
+ c.vx = clamp(c.vx, -MOVE_SPEED, MOVE_SPEED);
+ c.facing = dir;
+ } else if (c.grounded) {
+ const f = PLAT_FRICTION * dt;
+ if (Math.abs(c.vx) <= f) c.vx = 0;
+ else c.vx -= Math.sign(c.vx) * f;
+ }
+ if (this.input.jump && c.grounded && !this._jumpEdge) {
+ c.vy = -JUMP_V;
+ c.grounded = false;
+ this.platform = null;
+ this._jumpEdge = true;
+ this._clearArm();
+ }
+ if (this.input.down && c.grounded) {
+ if (this.platform?.href) {
+ this._dive(this.platform.href);
+ return;
+ }
+ c.y += 4;
+ c.grounded = false;
+ const dropped = this.platform;
+ this.platform = null;
+ this._dropIgnore = dropped;
+ }
+ c.vy = Math.min(c.vy + GRAVITY * dt, TERMINAL);
+ const prevY = c.y;
+ c.x = clamp(c.x + c.vx * dt, this.modelHalfW, docWidth() - this.modelHalfW);
+ c.y = c.y + c.vy * dt;
+ if (c.vy >= 0) {
+ let best = null;
+ for (const p of this.platforms) {
+ if (p === this._dropIgnore) continue;
+ if (c.x < p.left - FOOT_PAD || c.x > p.right + FOOT_PAD) continue;
+ if (prevY <= p.top + LAND_TOL && c.y >= p.top) {
+ if (!best || p.top < best.top) best = p;
+ }
+ }
+ if (best) {
+ c.y = best.top;
+ c.vy = 0;
+ c.grounded = true;
+ this.platform = best;
+ this._dropIgnore = null;
+ } else if (c.grounded && this.platform) {
+ const p = this.platform;
+ if (c.x < p.left - FOOT_PAD || c.x > p.right + FOOT_PAD) {
+ c.grounded = false;
+ this.platform = null;
+ } else {
+ c.y = p.top;
+ }
+ } else {
+ c.grounded = false;
+ }
+ }
+ const pastGuard = performance.now() > this._spawnGuardUntil;
+ if (pastGuard && c.grounded && this.platform?.href && Math.abs(c.vx) < 30 && dir === 0) {
+ this._armLink(this.platform);
+ if (performance.now() - this._armAt > LINK_ARM_MS) {
+ this._dive(this.platform.href);
+ return;
+ }
+ } else if (this._armEl && (!c.grounded || this.platform?.el !== this._armEl || dir !== 0)) {
+ this._clearArm();
+ }
+ let state = 'idle';
+ if (!c.grounded) state = 'jump';
+ else if (Math.abs(c.vx) > PLAT_RUN_SPEED) state = 'run';
+ else if (Math.abs(c.vx) > 6) state = 'walk';
+ this.controller?.setState(state);
+ }
+
+ _follow(dt) {
+ const want = clamp(this.char.y - window.innerHeight * 0.55, 0, maxScroll());
+ const cur = window.scrollY || 0;
+ const next = this._reduced ? want : cur + (want - cur) * Math.min(1, dt * 6);
+ if (Math.abs(next - cur) > 0.5) window.scrollTo(0, next);
+ this._scrollY = window.scrollY || 0;
+ this._scan();
+ }
+
+ _render(dt) {
+ const c = this.char;
+ const sx = window.scrollX || 0;
+ const sy = window.scrollY || 0;
+ const screenX = c.x - sx;
+ const screenY = c.y - sy;
+ this.rig.position.set(screenX, -screenY, 0);
+ if (this._diving) {
+ this.rig.rotation.y += dt * 9;
+ const s = Math.max(0.05, this.rig.scale.x - dt * 1.4);
+ this.rig.scale.setScalar(s);
+ } else {
+ const targetYaw = c.facing >= 0 ? 0.6 : -0.6;
+ this.rig.rotation.y += (targetYaw - this.rig.rotation.y) * Math.min(1, dt * 10);
+ }
+ this.controller?.update(dt);
+ this.renderer.render(this.scene, this.camera);
+ }
+
+ _teardown() {
+ teardownScene(this);
+ }
+}
+
+// ── Shared scene teardown ─────────────────────────────────────────────────────
+function teardownScene(pg) {
+ try {
+ pg.controller?.dispose();
+ } catch {
+ /* non-fatal */
+ }
+ pg.controller = null;
+ if (pg.scene) {
+ pg.scene.traverse((n) => {
+ if (n.isMesh) {
+ 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?.();
+ });
+ }
+ });
+ }
+ pg.scene = null;
+ if (pg.renderer) {
+ pg.renderer.dispose();
+ pg.renderer.forceContextLoss?.();
+ pg.renderer = null;
+ releaseWebGLContext();
+ }
+ if (pg.host?.parentNode) pg.host.parentNode.removeChild(pg.host);
+ pg.host = null;
+}
+
+// ── Scoped styles ─────────────────────────────────────────────────────────────
+let _stylesInjected = false;
+function ensureStyles() {
+ if (_stylesInjected) return;
+ _stylesInjected = true;
+ const style = document.createElement('style');
+ style.id = 'walk-pg-style';
+ style.textContent = `
+.walk-pg{position:fixed;inset:0;z-index:2147483100;pointer-events:none;opacity:0;transition:opacity .3s ease}
+.walk-pg.is-in{opacity:1}
+.walk-pg-canvas{position:absolute;inset:0;width:100%;height:100%;pointer-events:none;filter:drop-shadow(0 18px 22px rgba(0,0,0,.3))}
+.walk-pg-exit{position:fixed;top:14px;right:14px;z-index:3;pointer-events:auto;border:1px solid rgba(255,255,255,.16);background:rgba(14,16,22,.72);color:#f2f4f8;font:600 12.5px/1 system-ui,sans-serif;padding:9px 13px;border-radius:999px;cursor:pointer;backdrop-filter:blur(6px);transition:background .2s ease,transform .15s ease}
+.walk-pg-exit:hover{background:rgba(220,60,60,.85)}
+.walk-pg-exit:active{transform:scale(.96)}
+.walk-pg-exit:focus-visible{outline:2px solid #7aa2ff;outline-offset:2px}
+.walk-pg-mode{position:fixed;top:14px;right:92px;z-index:3;pointer-events:auto;display:inline-flex;align-items:center;gap:6px;border:1px solid rgba(255,255,255,.16);background:rgba(14,16,22,.72);color:#f2f4f8;font:600 12.5px/1 system-ui,sans-serif;padding:9px 13px;border-radius:999px;cursor:pointer;backdrop-filter:blur(6px);transition:background .2s ease,transform .15s ease}
+.walk-pg-mode:hover{background:rgba(122,162,255,.55)}
+.walk-pg-mode:active{transform:scale(.96)}
+.walk-pg-mode:focus-visible{outline:2px solid #7aa2ff;outline-offset:2px}
+.walk-pg-mode-ic{font-size:14px;line-height:1}
+.walk-pg-hint{position:fixed;left:50%;bottom:22px;transform:translateX(-50%) translateY(8px);z-index:3;pointer-events:none;max-width:88vw;width:max-content;background:rgba(18,20,28,.92);color:#f2f4f8;font:500 13px/1.4 system-ui,sans-serif;padding:9px 14px;border-radius:12px;border:1px solid rgba(255,255,255,.1);box-shadow:0 10px 28px rgba(0,0,0,.35);opacity:0;transition:opacity .3s ease,transform .3s ease;text-align:center}
+.walk-pg-hint.is-in{opacity:1;transform:translateX(-50%) translateY(0)}
+.walk-pg-btn{pointer-events:auto;border:1px solid rgba(255,255,255,.18);background:rgba(16,18,26,.78);color:#fff;display:grid;place-items:center;backdrop-filter:blur(6px);-webkit-user-select:none;user-select:none;touch-action:none}
+.walk-pg-btn:active{background:rgba(122,162,255,.5)}
+.walk-pg--stroll .walk-pg-pad{position:fixed;left:18px;bottom:18px;z-index:3;display:none;flex-direction:column;align-items:center;gap:8px;pointer-events:none}
+.walk-pg--stroll .walk-pg-pad-row{display:flex;gap:8px;align-items:center}
+.walk-pg--stroll .walk-pg-btn{width:54px;height:54px;border-radius:14px;font-size:20px}
+.walk-pg-dive{border-radius:50%!important;background:rgba(122,162,255,.32)}
+.walk-pg--plat .walk-pg-pad{position:fixed;left:0;right:0;bottom:18px;z-index:3;display:none;justify-content:center;gap:12px;pointer-events:none}
+.walk-pg--plat .walk-pg-btn{width:60px;height:60px;border-radius:50%;font-size:22px}
+.walk-pg-jump{background:rgba(122,162,255,.32)}
+.walk-pg-flash{position:fixed;inset:0;z-index:2;pointer-events:none;background:radial-gradient(circle at 50% 50%,rgba(122,162,255,0) 0%,rgba(8,10,16,0) 60%);opacity:0;transition:opacity .5s ease}
+.walk-pg-flash.is-on{background:radial-gradient(circle at 50% 50%,rgba(122,162,255,.25) 0%,rgba(6,8,14,.96) 70%);opacity:1}
+.walk-pg-portal{outline:2px solid rgba(122,162,255,.9)!important;outline-offset:3px;border-radius:6px;box-shadow:0 0 0 4px rgba(122,162,255,.18),0 0 28px rgba(122,162,255,.45)!important;transition:box-shadow .2s ease,transform .25s ease;animation:walk-pg-pulse 1.1s ease-in-out infinite}
+.walk-pg-portal.is-open{transform:scale(.94);box-shadow:0 0 0 6px rgba(122,162,255,.3),0 0 48px rgba(122,162,255,.7)!important}
+@keyframes walk-pg-pulse{0%,100%{box-shadow:0 0 0 4px rgba(122,162,255,.16),0 0 22px rgba(122,162,255,.35)}50%{box-shadow:0 0 0 6px rgba(122,162,255,.3),0 0 36px rgba(122,162,255,.6)}}
+@media (pointer: coarse){.walk-pg--stroll .walk-pg-pad,.walk-pg--plat .walk-pg-pad{display:flex}.walk-pg--stroll .walk-pg-hint{bottom:200px}.walk-pg--plat .walk-pg-hint{bottom:110px}.walk-pg-mode .walk-pg-mode-tx{display:none}.walk-pg-mode{right:84px}}
+@media (prefers-reduced-motion:reduce){.walk-pg,.walk-pg-hint,.walk-pg-flash{transition:none}.walk-pg-portal{animation:none}}
+`;
+ document.head.appendChild(style);
+}
+
+// ── Public API ────────────────────────────────────────────────────────────────
+let _instance = null;
+
+function modeClass(mode) {
+ return mode === 'platformer' ? PlatformerPlayground : StrollPlayground;
+}
+
+export function launchPlayground(opts = {}) {
+ if (opts.config) _config = opts.config;
+ if (_instance) return _instance;
+ const mode = opts.mode || getMode();
+ _instance = new (modeClass(mode))();
+ _instance.mount({ ...opts, mode });
+ return _instance;
+}
+
+export function exitPlayground() {
+ if (_instance) {
+ _instance.unmount();
+ _instance = null;
+ }
+ try {
+ window.dispatchEvent(new CustomEvent('walk-playground:exit'));
+ } catch {
+ /* non-fatal */
+ }
+}
+
+export function switchPlaygroundMode(forceMode = null) {
+ if (!_instance || !_instance.mounted) return null;
+ const cur = _instance.mode;
+ const next = forceMode || (cur === 'platformer' ? 'stroll' : 'platformer');
+ if (next === cur) return _instance;
+ setMode(next);
+ const startScreen = _instance.currentScreenPos();
+ const avatarId = _instance._avatarId || null;
+ _instance.unmount();
+ _instance = new (modeClass(next))();
+ _instance.mount({ avatarId, startScreen, switched: true, mode: next });
+ return _instance;
+}
+
+export function getPlaygroundMode() {
+ return _instance?.mode || getMode();
+}
+
+export function shouldDropIn(config) {
+ if (config) _config = config;
+ return ssGet(_config.keys.resume) === '1';
+}
+
+export function consumeDropIn(config) {
+ if (config) _config = config;
+ const v = ssGet(_config.keys.resume) === '1';
+ if (v) ssDel(_config.keys.resume);
+ return v;
+}
+
+export function playgroundState() {
+ if (!_instance || !_instance.mounted) return null;
+ const c = _instance.char;
+ const base = {
+ mode: _instance.mode,
+ x: Math.round(c.x),
+ y: Math.round(c.y),
+ vx: Math.round(c.vx),
+ vy: Math.round(c.vy),
+ 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, speed: Math.round(Math.hypot(c.vx, c.vy)), onLink: !!_instance._armHref };
+}
diff --git a/x402-modal-sdk/.gitignore b/x402-modal-sdk/.gitignore
new file mode 100644
index 000000000..672434e70
--- /dev/null
+++ b/x402-modal-sdk/.gitignore
@@ -0,0 +1,4 @@
+node_modules/
+*.log
+.DS_Store
+*.tmp.*
diff --git a/x402-modal-sdk/LICENSE b/x402-modal-sdk/LICENSE
new file mode 100644
index 000000000..8e2251ab4
--- /dev/null
+++ b/x402-modal-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/x402-modal-sdk/package.json b/x402-modal-sdk/package.json
new file mode 100644
index 000000000..66d2fc784
--- /dev/null
+++ b/x402-modal-sdk/package.json
@@ -0,0 +1,75 @@
+{
+ "name": "@three-ws/x402-modal",
+ "version": "0.2.0",
+ "description": "A drop-in, dependency-free payment modal for any x402 paid endpoint. One script tag turns a 402 challenge into a polished checkout: wallet connect (Phantom on Solana, MetaMask/EVM via EIP-3009), the 402 → sign → settle flow, SIWX re-entry, spending caps, and a receipt — vanilla JS, no bundler required. Powered by three.ws.",
+ "keywords": [
+ "x402",
+ "payments",
+ "micropayments",
+ "usdc",
+ "stablecoin",
+ "solana",
+ "base",
+ "evm",
+ "eip-3009",
+ "eip3009",
+ "phantom",
+ "metamask",
+ "paywall",
+ "pay-per-call",
+ "checkout",
+ "web3",
+ "siwx",
+ "agent-payments",
+ "402"
+ ],
+ "author": "three.ws <[email protected]> (https://three.ws)",
+ "license": "Apache-2.0",
+ "homepage": "https://three.ws",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/nirholas/three.ws.git",
+ "directory": "x402-modal-sdk"
+ },
+ "bugs": {
+ "url": "https://github.com/nirholas/three.ws/issues"
+ },
+ "type": "module",
+ "main": "./dist/x402-modal.mjs",
+ "module": "./dist/x402-modal.mjs",
+ "unpkg": "./dist/x402.global.js",
+ "jsdelivr": "./dist/x402.global.js",
+ "types": "./types/index.d.ts",
+ "exports": {
+ ".": {
+ "types": "./types/index.d.ts",
+ "import": "./dist/x402-modal.mjs",
+ "default": "./dist/x402-modal.mjs"
+ },
+ "./global": "./dist/x402.global.js",
+ "./src": "./src/x402-modal.js"
+ },
+ "files": [
+ "dist",
+ "src",
+ "types",
+ "docs",
+ "README.md",
+ "TUTORIAL.md",
+ "LICENSE"
+ ],
+ "scripts": {
+ "build": "node build.mjs",
+ "prepublishOnly": "node build.mjs",
+ "test": "node --test \"test/*.test.js\""
+ },
+ "devDependencies": {
+ "esbuild": "^0.21.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "publishConfig": {
+ "access": "public"
+ }
+}
diff --git a/x402-modal-sdk/src/index.js b/x402-modal-sdk/src/index.js
new file mode 100644
index 000000000..78fc66419
--- /dev/null
+++ b/x402-modal-sdk/src/index.js
@@ -0,0 +1,1615 @@
+// @three-ws/x402-modal — drop-in payment modal for any x402 paid endpoint.
+//
+// A single, dependency-free ES module. Drop it on any page and any element with
+// `data-x402-endpoint` opens a payment modal on click:
+//
+// <script type="module" src="https://unpkg.com/@three-ws/x402-modal"></script>
+//
+// <button
+// data-x402-endpoint="https://example.com/api/paid/summarize"
+// data-x402-method="POST"
+// data-x402-body='{"text":"hello"}'
+// data-x402-merchant="Acme"
+// data-x402-action="Summarize"
+// >Pay & Run</button>
+//
+// On completion the element receives an `x402:result` CustomEvent whose detail
+// is { ok, result, payment, response }. On error: `x402:error` with { error }.
+//
+// You can also call programmatically:
+//
+// import { pay, configure } from '@three-ws/x402-modal';
+// const out = await pay({
+// endpoint: '/api/paid/summarize',
+// body: { text: 'hello' },
+// merchant: 'Acme',
+// action: 'Summarize',
+// });
+//
+// The modal handles wallet connect (Phantom for Solana, window.ethereum for
+// Base/EVM USDC via EIP-3009), drives the 402 → sign → retry flow, optional
+// SIWX (Sign-In-With-X) re-entry, client-side spending caps, and shows the
+// result. Vanilla JS, no bundler required.
+//
+// Everything host-specific (the Solana checkout origin, branding, builder-code
+// attribution, and the esm.sh CDN URLs used for the Solana/EVM crypto helpers)
+// is configurable via `configure({...})` or `data-*` attributes on the script
+// tag — see CONFIG / configure() below and docs/api-reference.md.
+
+const VERSION = '1.0.0';
+
+// ─────────────────────────────────────────────────────────── configuration ───
+// All host-specific knobs live here so the modal runs unchanged on any site.
+// Defaults match the three.ws hosted instance; override with configure() or via
+// `data-*` attributes on the <script> tag (read once at load by readScriptConfig).
+const CONFIG = {
+ // Origin that serves the Solana checkout endpoints
+ // (`/api/x402-checkout?action=prepare|encode`). `null` → resolve from this
+ // script's own src, falling back to the current page origin. EVM payments
+ // never touch this — the wallet signs EIP-3009 typed-data locally.
+ checkoutOrigin: null,
+ // Path of the checkout endpoint on `checkoutOrigin`. Override if you mount
+ // the server handler somewhere other than /api/x402-checkout.
+ checkoutPath: '/api/x402-checkout',
+ // Footer attribution shown in the modal.
+ brand: { name: 'three.ws', url: 'https://three.ws' },
+ // Small text on the left of the footer.
+ footerNote: 'x402 · onchain settled',
+ // ERC-8021 builder-code self-attribution echoed back when the 402 challenge
+ // declares a builder-code extension. Set either field to '' to disable it.
+ builderCode: { wallet: '3d_agent', service: '3d_agent_modal' },
+ // CDN URLs for the crypto helpers loaded on demand (only when a Solana or an
+ // EVM sign-in payment is actually attempted). Repoint these at a self-hosted
+ // mirror to satisfy a strict Content-Security-Policy.
+ esm: {
+ solanaWeb3: 'https://esm.sh/@solana/[email protected]?bundle',
+ nobleHashesSha3: 'https://esm.sh/@noble/[email protected]/sha3?bundle',
+ },
+};
+
+/**
+ * Merge caller overrides into CONFIG. Shallow-merges the nested `brand`,
+ * `builderCode`, and `esm` objects so you can override a single field. Call
+ * before the first `pay()` (or before the auto-bound buttons are clicked).
+ * @param {Partial<typeof CONFIG>} opts
+ * @returns {typeof CONFIG} the resolved config
+ */
+export function configure(opts = {}) {
+ if (!opts || typeof opts !== 'object') return CONFIG;
+ for (const key of ['checkoutOrigin', 'checkoutPath', 'footerNote']) {
+ if (opts[key] !== undefined) CONFIG[key] = opts[key];
+ }
+ if (opts.brand && typeof opts.brand === 'object') Object.assign(CONFIG.brand, opts.brand);
+ if (opts.builderCode && typeof opts.builderCode === 'object') Object.assign(CONFIG.builderCode, opts.builderCode);
+ if (opts.esm && typeof opts.esm === 'object') Object.assign(CONFIG.esm, opts.esm);
+ return CONFIG;
+}
+
+// Resolved base URL for the Solana checkout endpoints.
+function checkoutBase() {
+ return `${CONFIG.checkoutOrigin || ORIGIN}${CONFIG.checkoutPath}`;
+}
+
+// SIWX ("Sign-In-With-X" / CAIP-122) lets a wallet that has already paid for
+// an endpoint re-enter it by signing a challenge instead of paying again. The
+// server advertises support by including `extensions['sign-in-with-x']` in the
+// 402 body; clients submit signed proofs via the `SIGN-IN-WITH-X` header. See
+// prompts/siwx/PLAN.md for the full architecture.
+const SIWX_HEADER = 'SIGN-IN-WITH-X';
+const SIWX_EXTENSION_KEY = 'sign-in-with-x';
+
+const ORIGIN = (() => {
+ // Resolve the origin that hosts this script — used as the API origin for
+ // the prepare/encode helpers. Falls back to the merchant origin in same-
+ // origin mode.
+ try {
+ const script = document.currentScript;
+ if (script?.src) return new URL(script.src).origin;
+ const found = document.querySelector('script[src*="/x402.js"]');
+ if (found?.src) return new URL(found.src).origin;
+ } catch (_) {}
+ return location.origin;
+})();
+
+// USDC EIP-3009 typed-data sig works against Base USDC at this address. The
+// domain `version` must match the on-chain `EIP712_DOMAIN_SEPARATOR_VERSION`
+// of the deployed USDC implementation — Base USDC is at version "2".
+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/' },
+};
+
+// Normalize a single 402 `accept` entry to the shape the modal speaks
+// internally. The x402 spec's canonical atomic-price field is
+// `maxAmountRequired`; some merchants (and our own server) emit `amount`. We
+// read `amount` everywhere downstream (price display, cap check, prepare/encode
+// POST body, EIP-3009 signing), so coerce here once at ingestion. Without this,
+// a spec-compliant merchant yields `accept.amount === undefined` → "NaN USDC"
+// in the modal and an `accept.amount: Required` 400 from /api/x402-checkout.
+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;
+}
+
+function isSolanaNetwork(net) {
+ return typeof net === 'string' && (net === 'solana' || net.startsWith('solana:'));
+}
+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 used by @x402/evm SDK clients), we must pick the
+// EIP-3009 one — signing typed-data against the Permit2 entry would build a
+// payload the facilitator rejects. The sibling carries
+// `extra.assetTransferMethod === 'permit2'`; the legacy entry omits it.
+function isEip3009Accept(accept) {
+ if (!isEvmNetwork(accept?.network)) return false;
+ const method = accept?.extra?.assetTransferMethod;
+ return !method || method === 'eip3009';
+}
+function networkLabel(net, accept) {
+ if (isSolanaNetwork(net)) return 'Solana';
+ const meta = EVM_NETWORKS[net];
+ return meta?.name || accept?.extra?.name || net;
+}
+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;
+}
+
+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);
+}
+
+function b64encode(obj) {
+ const json = JSON.stringify(obj);
+ if (typeof Buffer !== 'undefined') return Buffer.from(json, 'utf8').toString('base64');
+ return btoa(unescape(encodeURIComponent(json)));
+}
+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;
+ }
+}
+
+// ──────────────────────────────────────────── Spending caps (USE-22) ────────
+// Persists per-wallet spend in localStorage so reload-survivable caps work
+// in a pure-browser context. Keys are bucketed by UTC hour and UTC day so
+// the sliding windows reset cleanly at midnight UTC for the daily case.
+// All amounts are stored as base-10 BigInt strings of micro-USD; stablecoin
+// payments (USDC, USDT, DAI) flow through as-is since their atomics are
+// already 6-decimal USD-pegged.
+
+const SPEND_LS_PREFIX = 'x402.spend.';
+const STABLE_NAMES = new Set([
+ 'usdc', 'usd coin', 'usdt', 'tether', 'binance-peg usd coin', 'dai',
+]);
+
+function spendBuckets(timestamp = Date.now()) {
+ const hour = Math.floor(timestamp / 3_600_000);
+ const day = Math.floor(timestamp / 86_400_000);
+ return { hour, day };
+}
+
+function spendKey(address, kind, bucket) {
+ return `${SPEND_LS_PREFIX}${kind}.${address.toLowerCase()}.${bucket}`;
+}
+
+function readSpend(address, kind, bucket) {
+ try {
+ const raw = localStorage.getItem(spendKey(address, kind, bucket));
+ if (!raw) return 0n;
+ return BigInt(raw);
+ } catch {
+ return 0n;
+ }
+}
+
+function writeSpend(address, kind, bucket, value) {
+ try {
+ localStorage.setItem(spendKey(address, kind, bucket), value.toString());
+ } catch {
+ // localStorage full / disabled — caps degrade to per-call only.
+ }
+}
+
+function toMicroUsdBrowser(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);
+ }
+ // Non-stable in the browser modal: we don't fetch live prices to keep the
+ // drop-in script dependency-free. Cap enforcement for non-stable assets
+ // must be done server-side via x402-spending-cap.js.
+ return atomic;
+}
+
+// Check the configured caps and, if admitted, reserve the spend in
+// localStorage. Returns { abort: boolean, reason?, reservation? }.
+// Reservation has { address, microUsd, buckets } so rollback can undo.
+function browserEnforceCap({ accept, caps, address }) {
+ if (!caps || !address) return { abort: false };
+ const microUsd = toMicroUsdBrowser(accept.amount, accept);
+ const maxPerCall = caps.maxPerCall != null ? BigInt(caps.maxPerCall) : null;
+ const maxPerHour = caps.maxPerHour != null ? BigInt(caps.maxPerHour) : null;
+ const maxPerDay = caps.maxPerDay != null ? BigInt(caps.maxPerDay) : null;
+ if (maxPerCall != null && microUsd > maxPerCall) {
+ return {
+ abort: true,
+ reason: `Per-call cap exceeded (${microUsd} > ${maxPerCall} µUSD)`,
+ };
+ }
+ const buckets = spendBuckets();
+ const hourTotal = readSpend(address, 'hr', buckets.hour) + microUsd;
+ const dayTotal = readSpend(address, 'day', buckets.day) + microUsd;
+ if (maxPerHour != null && hourTotal > maxPerHour) {
+ return { abort: true, reason: `Hourly cap exceeded (${hourTotal} > ${maxPerHour} µUSD)` };
+ }
+ if (maxPerDay != null && dayTotal > maxPerDay) {
+ return { abort: true, reason: `Daily cap exceeded (${dayTotal} > ${maxPerDay} µUSD)` };
+ }
+ writeSpend(address, 'hr', buckets.hour, hourTotal);
+ writeSpend(address, 'day', buckets.day, dayTotal);
+ return { abort: false, reservation: { address, microUsd, buckets } };
+}
+
+function browserRollbackReservation(reservation) {
+ if (!reservation) return;
+ const { address, microUsd, buckets } = reservation;
+ const hourCurrent = readSpend(address, 'hr', buckets.hour);
+ const dayCurrent = readSpend(address, 'day', buckets.day);
+ const hourNext = hourCurrent - microUsd;
+ const dayNext = dayCurrent - microUsd;
+ writeSpend(address, 'hr', buckets.hour, hourNext < 0n ? 0n : hourNext);
+ writeSpend(address, 'day', buckets.day, dayNext < 0n ? 0n : dayNext);
+}
+
+// ──────────────────────────────────────────── ERC-8021 builder-code echo ────
+// The server-side x402-spec.js enforces that any client-echoed builder-code
+// `a` matches what the 402 challenge declared (anti-tamper). Builders/wallets
+// can append their own service code in `s` and set their wallet code `w`
+// — for our own demo modal we self-attribute `w: "3d_agent"` and `s: ["3d_agent_modal"]`.
+
+const BUILDER_CODE_KEY = 'builder-code';
+const BUILDER_CODE_PATTERN = /^[a-z0-9_]{1,32}$/;
+
+function buildBuilderCodeEcho(challenge) {
+ const ext = challenge?.extensions?.[BUILDER_CODE_KEY];
+ const declaredA = ext?.info?.a;
+ if (!declaredA || !BUILDER_CODE_PATTERN.test(declaredA)) return null;
+ const out = { a: declaredA };
+ const serviceCode = CONFIG.builderCode.service;
+ const walletCode = CONFIG.builderCode.wallet;
+ if (serviceCode && BUILDER_CODE_PATTERN.test(serviceCode)) out.s = [serviceCode];
+ if (walletCode && BUILDER_CODE_PATTERN.test(walletCode)) out.w = walletCode;
+ return out;
+}
+
+// ─────────────────────────────────────────────────────────── SIWX helpers ────
+
+function extractSiwxExtension(body) {
+ const ext = body?.extensions?.[SIWX_EXTENSION_KEY];
+ if (!ext || !ext.info || !Array.isArray(ext.supportedChains) || !ext.supportedChains.length) return null;
+ return ext;
+}
+
+// Returns { chain, kind: 'evm' | 'solana' } or null. `chain` is the matching
+// entry from `ext.supportedChains` whose signature type matches the wallet kind.
+function pickSiwxChain(ext, walletKind) {
+ for (const chain of ext.supportedChains) {
+ if (walletKind === 'evm' && chain.type === 'eip191') return { chain, kind: 'evm' };
+ if (walletKind === 'solana' && chain.type === 'ed25519') return { chain, kind: 'solana' };
+ }
+ return null;
+}
+
+// Build the CAIP-122 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.
+//
+// EVM path mirrors EIP-4361 / siwe library's prepareMessage (chain ref =
+// numeric chainId extracted from "eip155:<n>"). Solana path mirrors SIWS
+// (chain ref = genesis hash extracted from "solana:<ref>"). Optional fields
+// are omitted entirely when absent from server info.
+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 the
+ // statement is absent, emitting an extra blank line (header, address,
+ // "", "", URI). SIWS's formatter does not. The server rebuilds the EVM
+ // message via siwe before recovering the signer, so omit-statement EVM
+ // must carry the same extra blank or the recovered address mismatches.
+ 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');
+}
+
+// Base64-encoded JSON per x402 v2 spec (CHANGELOG-v2.md line 335). CAIP-122
+// fields are all ASCII/Latin-1, so the unescape+encodeURIComponent dance
+// matches what btoa expects without garbling unicode (none is sent anyway).
+function encodeSiwxHeaderValue(payload) {
+ const json = JSON.stringify(payload);
+ if (typeof Buffer !== 'undefined') return Buffer.from(json, 'utf8').toString('base64');
+ return btoa(unescape(encodeURIComponent(json)));
+}
+
+// Base58 (Bitcoin alphabet) — Solana's encoding for both addresses and
+// signatures. Inlined here to avoid pulling in a bundler dependency; this
+// matches what `bs58` does on the server side (api/_lib/siws.js).
+const BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
+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;
+}
+
+// EIP-55 checksum the address before signing. MetaMask returns addresses in
+// lowercase via eth_requestAccounts, but the server rebuilds the SIWE message
+// with a checksummed address (siwe library's prepareMessage always upgrades
+// case via getAddress). If we sign a lowercase-address message and send the
+// lowercase address in the payload, the server's recovered signer (from the
+// checksummed-address message it builds) differs from payload.address and
+// verification fails. So checksum here, then use the same string everywhere.
+//
+// Keccak-256 lives in @noble/hashes which the server already uses
+// (api/_lib/siws.js → @noble/curves). Pulled in dynamically via esm.sh only
+// when SIWX EVM sign-in is actually attempted, mirroring loadSolanaWeb3.
+let _evmChecksum = null;
+async function loadEvmChecksum() {
+ if (_evmChecksum) return _evmChecksum;
+ const sha3 = await import(/* @vite-ignore */ CONFIG.esm.nobleHashesSha3);
+ const keccak = sha3.keccak_256;
+ _evmChecksum = (addr) => {
+ const a = String(addr).toLowerCase().replace(/^0x/, '');
+ if (!/^[0-9a-f]{40}$/.test(a)) throw new Error(`invalid EVM address: ${addr}`);
+ const hashBytes = keccak(new TextEncoder().encode(a));
+ let hex = '';
+ for (let i = 0; i < hashBytes.length; i++) hex += hashBytes[i].toString(16).padStart(2, '0');
+ let out = '0x';
+ for (let i = 0; i < 40; i++) {
+ out += parseInt(hex[i], 16) >= 8 ? a[i].toUpperCase() : a[i];
+ }
+ return out;
+ };
+ return _evmChecksum;
+}
+
+// ───────────────────────────────────────────────────────────────── styles ────
+
+const STYLE_ID = 'x402-styles';
+const STYLES = `
+:root {
+ --x402-z: 2147483600;
+}
+.x402-overlay {
+ position: fixed; inset: 0;
+ background: rgba(8, 10, 18, 0.55);
+ backdrop-filter: blur(10px);
+ -webkit-backdrop-filter: blur(10px);
+ display: flex; align-items: center; justify-content: center;
+ z-index: var(--x402-z);
+ opacity: 0; transition: opacity 0.16s ease-out;
+ font-family: -apple-system, BlinkMacSystemFont, "Inter", "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
+ -webkit-font-smoothing: antialiased;
+ color: #0f0f0f;
+}
+.x402-overlay.x402-open { opacity: 1; }
+.x402-overlay * { box-sizing: border-box; }
+.x402-modal {
+ width: calc(100% - 32px); max-width: 420px;
+ background: #ffffff;
+ border-radius: 18px;
+ box-shadow: 0 24px 80px rgba(8, 10, 18, 0.28), 0 4px 16px rgba(8, 10, 18, 0.12);
+ overflow: hidden;
+ transform: translateY(8px) scale(0.985);
+ transition: transform 0.18s ease-out;
+ display: flex; flex-direction: column;
+ max-height: calc(100dvh - 32px);
+}
+.x402-overlay.x402-open .x402-modal { transform: translateY(0) scale(1); }
+.x402-head {
+ padding: 18px 20px 14px;
+ border-bottom: 1px solid #eef0f4;
+ display: flex; align-items: center; gap: 12px;
+}
+.x402-head .x402-merchant {
+ flex: 1; min-width: 0;
+}
+.x402-merchant .x402-name {
+ font-size: 12px; color: #5a6378; font-weight: 600; letter-spacing: 0.02em; text-transform: uppercase;
+ margin-bottom: 2px;
+}
+.x402-merchant .x402-action {
+ font-size: 17px; font-weight: 700; color: #0f0f0f;
+ white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
+ letter-spacing: -0.01em;
+}
+.x402-close {
+ width: 32px; height: 32px;
+ border-radius: 8px; border: none; background: #f3f4f7;
+ font-size: 16px; color: #5a6378; cursor: pointer;
+ display: flex; align-items: center; justify-content: center;
+ transition: background 0.12s;
+}
+.x402-close:hover { background: #e7e9ee; color: #0f0f0f; }
+
+.x402-price-row {
+ padding: 18px 20px;
+ display: flex; align-items: baseline; justify-content: space-between;
+ background: linear-gradient(180deg, #fafbfc 0%, #ffffff 100%);
+ border-bottom: 1px solid #eef0f4;
+}
+.x402-price {
+ font-size: 32px; font-weight: 700; letter-spacing: -0.02em; color: #0f0f0f;
+ font-variant-numeric: tabular-nums;
+}
+.x402-price .x402-currency { font-size: 14px; color: #5a6378; font-weight: 600; margin-left: 6px; letter-spacing: 0; }
+.x402-network {
+ font-size: 12px; color: #5a6378; font-weight: 500;
+ background: #f3f4f7; padding: 5px 10px; border-radius: 99px;
+ display: inline-flex; align-items: center; gap: 6px;
+}
+.x402-network::before {
+ content: ''; width: 6px; height: 6px; border-radius: 50%;
+ background: #22c55e;
+}
+
+.x402-body {
+ padding: 16px 20px 18px;
+ flex: 1 1 auto; overflow-y: auto;
+ display: flex; flex-direction: column; gap: 10px;
+}
+.x402-step {
+ display: flex; gap: 12px; align-items: flex-start;
+ padding: 10px 0;
+}
+.x402-step + .x402-step { border-top: 1px solid #f3f4f7; }
+.x402-step-num {
+ width: 22px; height: 22px; flex: 0 0 auto;
+ border-radius: 50%; border: 1.5px solid #d0d4dd; background: #fff;
+ color: #5a6378;
+ font-size: 11px; font-weight: 700;
+ display: flex; align-items: center; justify-content: center;
+}
+.x402-step.x402-active .x402-step-num {
+ border-color: #0a84ff; background: #0a84ff; color: #fff;
+ animation: x402-spin 1.2s linear infinite;
+}
+.x402-step.x402-done .x402-step-num {
+ border-color: #22c55e; background: #22c55e; color: #fff;
+}
+.x402-step.x402-error .x402-step-num {
+ border-color: #ef4444; background: #ef4444; color: #fff;
+}
+@keyframes x402-spin {
+ from { box-shadow: 0 0 0 0 rgba(10, 132, 255, 0.4); }
+ to { box-shadow: 0 0 0 8px rgba(10, 132, 255, 0); }
+}
+.x402-step-body { flex: 1; min-width: 0; }
+.x402-step-label { font-size: 14px; font-weight: 600; color: #0f0f0f; line-height: 1.35; }
+.x402-step-meta { font-size: 12px; color: #5a6378; margin-top: 2px; font-feature-settings: 'tnum' 1; }
+.x402-step.x402-error .x402-step-meta { color: #ef4444; }
+
+.x402-wallet-buttons {
+ display: flex; flex-direction: column; gap: 8px;
+ margin-top: 4px;
+}
+.x402-wallet-btn {
+ width: 100%; padding: 13px 14px;
+ background: #ffffff; border: 1.5px solid #e2e5ec; border-radius: 11px;
+ font-size: 14px; font-weight: 600; color: #0f0f0f;
+ cursor: pointer; font-family: inherit;
+ display: flex; align-items: center; gap: 12px;
+ transition: border-color 0.12s, background 0.12s, transform 0.05s;
+}
+.x402-wallet-btn:hover:not(:disabled) { border-color: #0a84ff; background: #f7faff; }
+.x402-wallet-btn:active:not(:disabled) { transform: translateY(1px); }
+.x402-wallet-btn:disabled { opacity: 0.45; cursor: not-allowed; }
+.x402-wallet-icon {
+ width: 28px; height: 28px; flex: 0 0 auto;
+ border-radius: 7px;
+ display: flex; align-items: center; justify-content: center;
+ font-size: 16px;
+ background: #f3f4f7;
+}
+.x402-wallet-icon.x402-phantom { background: linear-gradient(135deg, #ab9ff2, #534bb1); color: #fff; }
+.x402-wallet-icon.x402-metamask { background: linear-gradient(135deg, #f6851b, #e2761b); color: #fff; }
+.x402-wallet-name { flex: 1; text-align: left; }
+.x402-wallet-meta { font-size: 11px; color: #8a90a8; font-weight: 500; }
+
+.x402-pay-btn {
+ width: 100%; padding: 14px 16px;
+ background: #0f0f0f; color: #fff; border: none;
+ border-radius: 12px;
+ font-size: 15px; font-weight: 700; font-family: inherit;
+ cursor: pointer; letter-spacing: -0.005em;
+ transition: background 0.12s, transform 0.05s;
+ margin-top: 4px;
+ display: flex; align-items: center; justify-content: center; gap: 8px;
+}
+.x402-pay-btn:hover:not(:disabled) { background: #1d1d1d; }
+.x402-pay-btn:active:not(:disabled) { transform: translateY(1px); }
+.x402-pay-btn:disabled { background: #c8ccd4; cursor: not-allowed; }
+
+.x402-pay-secondary {
+ width: 100%; padding: 12px 14px;
+ background: #ffffff; color: #0f0f0f;
+ border: 1.5px solid #e2e5ec; border-radius: 11px;
+ font-size: 14px; font-weight: 600; font-family: inherit;
+ cursor: pointer; letter-spacing: -0.005em;
+ margin-top: 6px;
+ transition: border-color 0.12s, background 0.12s, transform 0.05s;
+}
+.x402-pay-secondary:hover:not(:disabled) { border-color: #0a84ff; background: #f7faff; }
+.x402-pay-secondary:active:not(:disabled) { transform: translateY(1px); }
+
+.x402-siwx-hint {
+ font-size: 11px; color: #5a6378; text-align: center;
+ margin-top: 8px; line-height: 1.4;
+}
+.x402-siwx-fallback {
+ font-size: 12px; color: #b45309; line-height: 1.45;
+ padding: 8px 10px; border-radius: 8px;
+ background: #fffbeb; border: 1px solid #fde68a;
+ margin-bottom: 6px;
+}
+
+.x402-error-box {
+ padding: 12px 14px; border-radius: 10px;
+ background: #fef2f2; border: 1px solid #fecaca; color: #b91c1c;
+ font-size: 13px; line-height: 1.45;
+ font-family: ui-monospace, "JetBrains Mono", Menlo, monospace;
+ word-break: break-word;
+}
+.x402-error-box strong { font-weight: 700; }
+
+.x402-receipt {
+ padding: 14px 16px; border-radius: 12px;
+ background: linear-gradient(180deg, #f0fdf4 0%, #ffffff 100%);
+ border: 1px solid #bbf7d0;
+}
+.x402-receipt-title {
+ font-size: 11px; font-weight: 700; color: #15803d;
+ text-transform: uppercase; letter-spacing: 0.06em;
+ margin-bottom: 8px;
+ display: flex; align-items: center; gap: 6px;
+}
+.x402-receipt-title::before { content: '✓'; font-size: 14px; }
+.x402-receipt-row {
+ display: flex; justify-content: space-between; gap: 12px;
+ font-size: 12px; padding: 2px 0;
+ font-family: ui-monospace, "JetBrains Mono", Menlo, monospace;
+}
+.x402-receipt-row .x402-k { color: #5a6378; }
+.x402-receipt-row .x402-v { color: #0f0f0f; text-align: right; word-break: break-all; }
+.x402-receipt-row a { color: #0a84ff; text-decoration: none; }
+.x402-receipt-row a:hover { text-decoration: underline; }
+
+.x402-result {
+ padding: 12px 14px; border-radius: 10px;
+ background: #fafbfc; border: 1px solid #e2e5ec;
+ max-height: 240px; overflow: auto;
+ font-family: ui-monospace, "JetBrains Mono", Menlo, monospace;
+ font-size: 12px; line-height: 1.5; color: #0f0f0f;
+ white-space: pre-wrap; word-break: break-word;
+}
+
+.x402-foot {
+ padding: 10px 20px 14px;
+ border-top: 1px solid #eef0f4;
+ display: flex; align-items: center; justify-content: space-between;
+ font-size: 11px; color: #8a90a8;
+}
+.x402-foot a { color: #5a6378; text-decoration: none; font-weight: 600; }
+.x402-foot a:hover { color: #0f0f0f; }
+.x402-foot .x402-secure { display: flex; align-items: center; gap: 5px; }
+.x402-foot .x402-secure::before { content: '🔒'; font-size: 10px; }
+
+@media (max-width: 480px) {
+ .x402-modal { max-width: none; width: calc(100% - 16px); border-radius: 16px; }
+ .x402-price { font-size: 26px; }
+}
+
+@media (prefers-color-scheme: dark) {
+ .x402-overlay { color: #e6e8f0; }
+ .x402-modal { background: #161616; box-shadow: 0 24px 80px rgba(0, 0, 0, 0.6); }
+ .x402-head, .x402-price-row, .x402-foot { border-color: #272727; }
+ .x402-step + .x402-step { border-top-color: #272727; }
+ .x402-merchant .x402-name { color: #8a90a8; }
+ .x402-merchant .x402-action, .x402-price, .x402-step-label { color: #e6e8f0; }
+ .x402-step-meta { color: #8a90a8; }
+ .x402-close { background: #222222; color: #8a90a8; }
+ .x402-close:hover { background: #2e2e2e; color: #e6e8f0; }
+ .x402-price-row { background: linear-gradient(180deg, #1d1d1d 0%, #161616 100%); }
+ .x402-network { background: #222222; color: #b0b6cc; }
+ .x402-wallet-btn { background: #1d1d1d; border-color: #2e2e2e; color: #e6e8f0; }
+ .x402-wallet-btn:hover:not(:disabled) { background: #252525; border-color: #0a84ff; }
+ .x402-wallet-icon { background: #2e2e2e; }
+ .x402-wallet-meta { color: #6b7088; }
+ .x402-pay-btn { background: #ffffff; color: #0f0f0f; }
+ .x402-pay-btn:hover:not(:disabled) { background: #e7e9ee; }
+ .x402-pay-btn:disabled { background: #2e2e2e; color: #5a6378; }
+ .x402-pay-secondary { background: #1d1d1d; border-color: #2e2e2e; color: #e6e8f0; }
+ .x402-pay-secondary:hover:not(:disabled) { background: #252525; border-color: #0a84ff; }
+ .x402-siwx-hint { color: #8a90a8; }
+ .x402-siwx-fallback { background: #2a1d10; border-color: #78350f; color: #fcd34d; }
+ .x402-step-num { background: #161616; border-color: #2e2e2e; color: #8a90a8; }
+ .x402-result { background: #1d1d1d; border-color: #2e2e2e; color: #e6e8f0; }
+ .x402-receipt { background: linear-gradient(180deg, #0b1f17 0%, #161616 100%); border-color: #14532d; }
+ .x402-receipt-title { color: #4ade80; }
+ .x402-receipt-row .x402-k { color: #8a90a8; }
+ .x402-receipt-row .x402-v { color: #e6e8f0; }
+ .x402-receipt-row a { color: #60a5fa; }
+ .x402-error-box { background: #1f1416; border-color: #7f1d1d; color: #fca5a5; }
+ .x402-foot a { color: #b0b6cc; }
+ .x402-foot a:hover { color: #ffffff; }
+}
+`;
+
+function injectStyles() {
+ if (document.getElementById(STYLE_ID)) return;
+ const el = document.createElement('style');
+ el.id = STYLE_ID;
+ el.textContent = STYLES;
+ document.head.appendChild(el);
+}
+
+// ───────────────────────────────────────────────────────────── modal class ───
+
+class CheckoutModal {
+ constructor(opts) {
+ this.opts = opts;
+ this.steps = [
+ { id: 'discover', label: 'Confirming price' },
+ { id: 'connect', label: 'Connect wallet' },
+ { id: 'authorize', label: 'Authorize payment' },
+ { id: 'verify', label: 'Verify & complete' },
+ ];
+ this.activeNetwork = null;
+ this.payerAddress = null;
+ this.accept = null;
+ this.challenge = null;
+ this.disposed = false;
+ // One-shot guard for opts.autoConnect: we only auto-open the wallet on the
+ // first connect render, so an error that drops the user back to this step
+ // shows the manual picker instead of re-launching the wallet in a loop.
+ this.autoConnectTried = false;
+ }
+
+ mount() {
+ injectStyles();
+ const overlay = document.createElement('div');
+ overlay.className = 'x402-overlay';
+ overlay.innerHTML = `
+ <div class="x402-modal" role="dialog" aria-modal="true" aria-label="x402 payment">
+ <div class="x402-head">
+ <div class="x402-merchant">
+ <div class="x402-name" data-merchant>${escapeHtml(this.opts.merchant || 'Payment')}</div>
+ <div class="x402-action" data-action>${escapeHtml(this.opts.action || 'Pay-per-call')}</div>
+ </div>
+ <button class="x402-close" data-close aria-label="Close">✕</button>
+ </div>
+ <div class="x402-price-row">
+ <div class="x402-price" data-price>—<span class="x402-currency"> USDC</span></div>
+ <div class="x402-network" data-network>resolving…</div>
+ </div>
+ <div class="x402-body" data-body></div>
+ <div class="x402-foot">
+ <span class="x402-secure">x402 · onchain settled</span>
+ <a href="https://three.ws" target="_blank" rel="noopener">Powered by three.ws</a>
+ </div>
+ </div>
+ `;
+ document.body.appendChild(overlay);
+ this.overlay = overlay;
+ this.bodyEl = overlay.querySelector('[data-body]');
+ this.priceEl = overlay.querySelector('[data-price]');
+ this.networkEl = overlay.querySelector('[data-network]');
+ overlay.querySelector('[data-close]').addEventListener('click', () => this.close('cancelled'));
+ overlay.addEventListener('click', (e) => { if (e.target === overlay) this.close('cancelled'); });
+ this.onKey = (e) => { if (e.key === 'Escape') this.close('cancelled'); };
+ document.addEventListener('keydown', this.onKey);
+ requestAnimationFrame(() => overlay.classList.add('x402-open'));
+ return new Promise((resolve, reject) => {
+ this.resolve = resolve;
+ this.reject = reject;
+ });
+ }
+
+ close(reason) {
+ if (this.disposed) return;
+ this.disposed = true;
+ document.removeEventListener('keydown', this.onKey);
+ this.overlay.classList.remove('x402-open');
+ setTimeout(() => this.overlay.remove(), 180);
+ if (reason === 'cancelled' && this.reject) {
+ const err = new Error('cancelled');
+ err.code = 'cancelled';
+ this.reject(err);
+ }
+ }
+
+ renderSteps(activeId, status = {}) {
+ const html = this.steps
+ .map((s) => {
+ const state = status[s.id] || (s.id === activeId ? 'active' : 'idle');
+ const cls = state === 'active' ? 'x402-active' : state === 'done' ? 'x402-done' : state === 'error' ? 'x402-error' : '';
+ const meta = status[`${s.id}_meta`] || '';
+ const sym = state === 'done' ? '✓' : state === 'error' ? '!' : s.id === activeId && state === 'active' ? ' ' : (this.steps.findIndex((x) => x.id === s.id) + 1);
+ return `<div class="x402-step ${cls}">
+ <div class="x402-step-num">${sym}</div>
+ <div class="x402-step-body">
+ <div class="x402-step-label">${s.label}</div>
+ ${meta ? `<div class="x402-step-meta">${escapeHtml(meta)}</div>` : ''}
+ </div>
+ </div>`;
+ })
+ .join('');
+ return html;
+ }
+
+ setPrice(accept) {
+ const decimals = accept.extra?.decimals ?? 6;
+ const amount = formatAmount(accept.amount, decimals);
+ const sym = (accept.extra?.name || 'USDC').replace(/^USD Coin$/, 'USDC');
+ this.priceEl.innerHTML = `${amount}<span class="x402-currency"> ${sym}</span>`;
+ this.networkEl.textContent = networkLabel(accept.network, accept);
+ }
+
+ renderConnect() {
+ const phantomDetected = typeof window !== 'undefined' && (window.solana?.isPhantom || window.phantom?.solana);
+ const evmDetected = typeof window !== 'undefined' && window.ethereum;
+ const solanaAccept = this.challenge?.accepts.find((a) => isSolanaNetwork(a.network));
+ const evmAccept = this.challenge?.accepts.find(isEip3009Accept);
+
+ // SIWX-first path: when the 402 advertises sign-in-with-x AND we have a
+ // compatible wallet, lead with "Sign in with wallet" (primary) and
+ // demote pay to a secondary action. payFlowOverride is set true when
+ // the user explicitly chooses to pay (either by clicking the secondary
+ // button, or after a 401/402 siwx_not_paid retry told us this wallet
+ // hasn't actually paid for this resource yet).
+ if (this.siwx && !this.payFlowOverride) {
+ const siwxSolana = phantomDetected ? pickSiwxChain(this.siwx, 'solana') : null;
+ const siwxEvm = evmDetected ? pickSiwxChain(this.siwx, 'evm') : null;
+ if (siwxSolana || siwxEvm) {
+ this.renderSiwxChoice({ siwxSolana, siwxEvm });
+ return;
+ }
+ }
+
+ // autoConnect (opt-in via opts.autoConnect): when the caller knows the
+ // user is wallet-ready and shouldn't have to pick, skip the picker and go
+ // straight to the signature — but only when exactly one supported wallet
+ // is actually detected. Zero wallets (must install) or two (must choose)
+ // still fall through to the picker, as does the SIWX "you haven't paid"
+ // fallback, which needs to explain itself. One-shot via autoConnectTried.
+ if (this.opts.autoConnect && !this.autoConnectTried && !this.siwxFallbackNotice) {
+ this.autoConnectTried = true;
+ const solanaViable = !!(solanaAccept && phantomDetected);
+ const evmViable = !!(evmAccept && evmDetected);
+ if (solanaViable && !evmViable) { this.runSolana(solanaAccept); return; }
+ if (evmViable && !solanaViable) { this.runEvm(evmAccept); return; }
+ }
+
+ const buttons = [];
+ if (solanaAccept) {
+ buttons.push(`
+ <button class="x402-wallet-btn" data-wallet="phantom" ${phantomDetected ? '' : 'disabled'}>
+ <div class="x402-wallet-icon x402-phantom">P</div>
+ <span class="x402-wallet-name">${phantomDetected ? 'Phantom' : 'Phantom (not detected)'}</span>
+ <span class="x402-wallet-meta">${networkLabel(solanaAccept.network, solanaAccept)}</span>
+ </button>
+ `);
+ }
+ if (evmAccept) {
+ buttons.push(`
+ <button class="x402-wallet-btn" data-wallet="evm" ${evmDetected ? '' : 'disabled'}>
+ <div class="x402-wallet-icon x402-metamask">M</div>
+ <span class="x402-wallet-name">${evmDetected ? 'Browser wallet' : 'No EVM wallet detected'}</span>
+ <span class="x402-wallet-meta">${networkLabel(evmAccept.network, evmAccept)}</span>
+ </button>
+ `);
+ }
+ const fallbackBox = this.siwxFallbackNotice
+ ? `<div class="x402-siwx-fallback">${escapeHtml(this.siwxFallbackNotice)}</div>`
+ : '';
+ this.bodyEl.innerHTML = `
+ ${this.renderSteps('connect', { discover: 'done' })}
+ ${fallbackBox}
+ <div class="x402-wallet-buttons">${buttons.join('')}</div>
+ `;
+ const onClick = (e) => {
+ const btn = e.target.closest('[data-wallet]');
+ if (!btn || btn.disabled) return;
+ const wallet = btn.dataset.wallet;
+ if (wallet === 'phantom') this.runSolana(solanaAccept);
+ else if (wallet === 'evm') this.runEvm(evmAccept);
+ };
+ this.bodyEl.querySelectorAll('[data-wallet]').forEach((b) => b.addEventListener('click', onClick));
+ }
+
+ renderSiwxChoice({ siwxSolana, siwxEvm }) {
+ const priceText = formatAmount(this.accept.amount, this.accept.extra?.decimals ?? 6);
+ // One primary button — internally we pick the wallet kind that matches
+ // the supported SIWX chains AND the detected wallets. Phantom wins ties
+ // to match the existing modal's default preference.
+ const siwxTarget = siwxSolana
+ ? { kind: 'solana', chain: siwxSolana.chain }
+ : { kind: 'evm', chain: siwxEvm.chain };
+ const siwxLabel = siwxTarget.kind === 'solana' ? 'Sign in with Phantom' : 'Sign in with wallet';
+ this.bodyEl.innerHTML = `
+ ${this.renderSteps('connect', { discover: 'done' })}
+ <button class="x402-pay-btn" data-action="siwx">${siwxLabel}</button>
+ <button class="x402-pay-secondary" data-action="pay">Pay ${priceText} USDC instead</button>
+ <div class="x402-siwx-hint">Already paid for this once? Sign in to re-enter without paying again.</div>
+ `;
+ const siwxBtn = this.bodyEl.querySelector('[data-action="siwx"]');
+ const payBtn = this.bodyEl.querySelector('[data-action="pay"]');
+ siwxBtn.addEventListener('click', () => {
+ if (siwxTarget.kind === 'solana') this.runSiwxSolana(siwxTarget.chain);
+ else this.runSiwxEvm(siwxTarget.chain);
+ });
+ payBtn.addEventListener('click', () => {
+ this.payFlowOverride = true;
+ this.renderConnect();
+ });
+ // Focus the primary SIWX button for keyboard accessibility.
+ requestAnimationFrame(() => siwxBtn.focus());
+ }
+
+ renderProgress(activeId, meta = {}) {
+ this.bodyEl.innerHTML = this.renderSteps(activeId, {
+ discover: 'done',
+ connect: 'done',
+ ...(activeId === 'verify' ? { authorize: 'done' } : {}),
+ [`${activeId}_meta`]: meta.text || '',
+ ...meta.statuses,
+ });
+ }
+
+ renderError(stepId, message) {
+ this.bodyEl.innerHTML = `
+ ${this.renderSteps(stepId, {
+ ...(stepId !== 'discover' ? { discover: 'done' } : {}),
+ ...(stepId === 'authorize' || stepId === 'verify' ? { connect: 'done' } : {}),
+ ...(stepId === 'verify' ? { authorize: 'done' } : {}),
+ [stepId]: 'error',
+ [`${stepId}_meta`]: 'failed',
+ })}
+ <div class="x402-error-box"><strong>${escapeHtml(stepId)}:</strong> ${escapeHtml(message)}</div>
+ <button class="x402-pay-btn" data-retry>Try again</button>
+ `;
+ this.bodyEl.querySelector('[data-retry]').addEventListener('click', () => this.start());
+ }
+
+ renderDone({ result, payment, siwx }) {
+ const resultStr = typeof result === 'string' ? result : JSON.stringify(result, null, 2);
+ let receiptHtml;
+ if (siwx) {
+ const addrShort = siwx.address ? `${siwx.address.slice(0, 8)}…${siwx.address.slice(-6)}` : '—';
+ receiptHtml = `
+ <div class="x402-receipt">
+ <div class="x402-receipt-title">Welcome back!</div>
+ <div class="x402-receipt-row">
+ <span class="x402-k">network</span>
+ <span class="x402-v">${escapeHtml(networkLabel(siwx.network) || siwx.network || '—')}</span>
+ </div>
+ <div class="x402-receipt-row">
+ <span class="x402-k">wallet</span>
+ <span class="x402-v">${escapeHtml(addrShort)}</span>
+ </div>
+ <div class="x402-receipt-row">
+ <span class="x402-k">paid</span>
+ <span class="x402-v">previously · re-entered free</span>
+ </div>
+ </div>
+ `;
+ } else {
+ const explorer = explorerUrl(payment?.network, payment?.transaction);
+ const txShort = payment?.transaction ? `${payment.transaction.slice(0, 8)}…${payment.transaction.slice(-6)}` : '—';
+ receiptHtml = `
+ <div class="x402-receipt">
+ <div class="x402-receipt-title">Payment confirmed!</div>
+ <div class="x402-receipt-row">
+ <span class="x402-k">network</span>
+ <span class="x402-v">${escapeHtml(networkLabel(payment?.network) || '—')}</span>
+ </div>
+ <div class="x402-receipt-row">
+ <span class="x402-k">payer</span>
+ <span class="x402-v">${escapeHtml(payment?.payer ? `${payment.payer.slice(0, 8)}…${payment.payer.slice(-6)}` : '—')}</span>
+ </div>
+ ${
+ payment?.transaction
+ ? `<div class="x402-receipt-row"><span class="x402-k">tx</span><span class="x402-v">${
+ explorer ? `<a href="${explorer}" target="_blank" rel="noopener">${txShort} ↗</a>` : txShort
+ }</span></div>`
+ : ''
+ }
+ </div>
+ `;
+ }
+ this.bodyEl.innerHTML = `
+ ${receiptHtml}
+ <div class="x402-result">${escapeHtml(resultStr).slice(0, 4000)}</div>
+ <button class="x402-pay-btn" data-done>Done</button>
+ `;
+ this.bodyEl.querySelector('[data-done]').addEventListener('click', () => {
+ this.disposed = true;
+ document.removeEventListener('keydown', this.onKey);
+ this.overlay.classList.remove('x402-open');
+ setTimeout(() => this.overlay.remove(), 180);
+ });
+ }
+
+ async start() {
+ this.bodyEl.innerHTML = this.renderSteps('discover');
+ try {
+ const challenge = await discoverChallenge(this.opts);
+ this.challenge = challenge;
+ this.siwx = extractSiwxExtension(challenge);
+ this.payFlowOverride = false;
+ this.siwxFallbackNotice = null;
+ // Prefer Solana when Phantom is present, else first EIP-3009 EVM
+ // entry (skipping Permit2 siblings the modal can't sign for), else
+ // first accept.
+ const solana = challenge.accepts.find((a) => isSolanaNetwork(a.network));
+ const evm = challenge.accepts.find(isEip3009Accept);
+ const phantomDetected = typeof window !== 'undefined' && (window.solana?.isPhantom || window.phantom?.solana);
+ this.accept = (phantomDetected && solana) || evm || challenge.accepts[0];
+ this.setPrice(this.accept);
+ this.renderConnect();
+ } catch (err) {
+ this.renderError('discover', err.message || String(err));
+ }
+ }
+
+ async runSolana(accept) {
+ this.accept = accept;
+ this.setPrice(accept);
+ this.renderProgress('connect', { text: 'Opening Phantom…' });
+ try {
+ const provider = window.phantom?.solana || window.solana;
+ if (!provider) throw new Error('Phantom wallet not detected');
+ const conn = await provider.connect();
+ const payerAddress = (conn?.publicKey || provider.publicKey)?.toString();
+ if (!payerAddress) throw new Error('Phantom did not return a public key');
+ this.payerAddress = payerAddress;
+ const capCheck = browserEnforceCap({
+ accept,
+ caps: this.opts.caps,
+ address: payerAddress,
+ });
+ if (capCheck.abort) {
+ this.renderError('authorize', capCheck.reason);
+ return;
+ }
+ this.spendReservation = capCheck.reservation || null;
+ this.renderProgress('authorize', { text: `Building Solana payment for ${payerAddress.slice(0, 6)}…${payerAddress.slice(-4)}` });
+
+ const prep = await postJson(`${checkoutBase()}?action=prepare`, {
+ accept,
+ buyer: payerAddress,
+ });
+ this.renderProgress('authorize', { text: 'Confirm in Phantom…' });
+ const txBytes = base64ToUint8Array(prep.tx_base64);
+ // Phantom returns a fully-signed VersionedTransaction with the buyer's
+ // signature added. The facilitator's fee-payer signature is added by
+ // PayAI during /settle.
+ const SolanaWeb3 = await loadSolanaWeb3();
+ const tx = SolanaWeb3.VersionedTransaction.deserialize(txBytes);
+ const signed = await provider.signTransaction(tx);
+ const signedB64 = uint8ArrayToBase64(signed.serialize());
+
+ const builderCodeBlock = buildBuilderCodeEcho(this.challenge);
+ const enc = await postJson(`${checkoutBase()}?action=encode`, {
+ accept,
+ signed_tx_base64: signedB64,
+ resource_url: new URL(this.opts.endpoint, location.href).href,
+ ...(builderCodeBlock ? { builder_code: builderCodeBlock } : {}),
+ });
+
+ await this.executePaid(enc.x_payment);
+ } catch (err) {
+ if (this.spendReservation) {
+ browserRollbackReservation(this.spendReservation);
+ this.spendReservation = null;
+ }
+ this.renderError(this.payerAddress ? 'authorize' : 'connect', friendlyError(err));
+ }
+ }
+
+ async runEvm(accept) {
+ this.accept = accept;
+ this.setPrice(accept);
+ this.renderProgress('connect', { text: 'Opening browser wallet…' });
+ try {
+ const eth = window.ethereum;
+ if (!eth) throw new Error('No EVM wallet detected');
+ const accounts = await eth.request({ method: 'eth_requestAccounts' });
+ const payerAddress = accounts?.[0];
+ if (!payerAddress) throw new Error('Wallet did not return an account');
+ this.payerAddress = payerAddress;
+ const capCheck = browserEnforceCap({
+ accept,
+ caps: this.opts.caps,
+ address: payerAddress,
+ });
+ if (capCheck.abort) {
+ this.renderError('authorize', capCheck.reason);
+ return;
+ }
+ this.spendReservation = capCheck.reservation || null;
+
+ const meta = EVM_NETWORKS[accept.network];
+ if (!meta) throw new Error(`Unknown EVM network ${accept.network}`);
+ // Switch chain if needed.
+ const currentChainHex = await eth.request({ method: 'eth_chainId' });
+ const desiredChainHex = '0x' + meta.chainId.toString(16);
+ if (currentChainHex !== desiredChainHex) {
+ this.renderProgress('connect', { text: `Switch wallet to ${meta.name}…` });
+ try {
+ await eth.request({ method: 'wallet_switchEthereumChain', params: [{ chainId: desiredChainHex }] });
+ } catch (e) {
+ throw new Error(`Wallet is on ${currentChainHex}; please switch to ${meta.name} (${desiredChainHex}) and retry`);
+ }
+ }
+
+ this.renderProgress('authorize', { text: `Authorize ${formatAmount(accept.amount)} USDC…` });
+
+ // EIP-3009 transferWithAuthorization typed-data signature.
+ // validAfter / validBefore use unix seconds; nonce is a random 32-byte hex.
+ const validAfter = 0;
+ const validBefore = Math.floor(Date.now() / 1000) + (accept.maxTimeoutSeconds || 600);
+ const nonce = '0x' + randomHex(32);
+ const domain = {
+ name: accept.extra?.name || 'USD Coin',
+ version: accept.extra?.version || '2',
+ chainId: meta.chainId,
+ verifyingContract: accept.asset,
+ };
+ const types = {
+ EIP712Domain: [
+ { name: 'name', type: 'string' },
+ { name: 'version', type: 'string' },
+ { name: 'chainId', type: 'uint256' },
+ { name: 'verifyingContract', type: 'address' },
+ ],
+ TransferWithAuthorization: [
+ { name: 'from', type: 'address' },
+ { name: 'to', type: 'address' },
+ { name: 'value', type: 'uint256' },
+ { name: 'validAfter', type: 'uint256' },
+ { name: 'validBefore', type: 'uint256' },
+ { name: 'nonce', type: 'bytes32' },
+ ],
+ };
+ const message = {
+ from: payerAddress,
+ to: accept.payTo,
+ value: accept.amount,
+ validAfter,
+ validBefore,
+ nonce,
+ };
+ const typedData = {
+ primaryType: 'TransferWithAuthorization',
+ types,
+ domain,
+ message,
+ };
+ const signature = await eth.request({
+ method: 'eth_signTypedData_v4',
+ params: [payerAddress, JSON.stringify(typedData)],
+ });
+
+ const paymentPayload = {
+ x402Version: 2,
+ scheme: 'exact',
+ network: accept.network,
+ resource: { url: this.opts.endpoint, mimeType: 'application/json' },
+ accepted: accept,
+ payload: {
+ signature,
+ // CDP facilitator /verify requires the EIP-3009 time bounds as
+ // decimal strings, not JSON numbers — a numeric validAfter/
+ // validBefore is rejected with "'paymentPayload' is invalid".
+ // The signature is unaffected: uint256 0 and "0" encode identically.
+ authorization: { from: payerAddress, to: accept.payTo, value: accept.amount, validAfter: String(validAfter), validBefore: String(validBefore), nonce },
+ },
+ };
+ const builderCodeBlock = buildBuilderCodeEcho(this.challenge);
+ if (builderCodeBlock) {
+ paymentPayload.extensions = { 'builder-code': builderCodeBlock };
+ }
+ const xPayment = b64encode(paymentPayload);
+ await this.executePaid(xPayment);
+ } catch (err) {
+ if (this.spendReservation) {
+ browserRollbackReservation(this.spendReservation);
+ this.spendReservation = null;
+ }
+ this.renderError(this.payerAddress ? 'authorize' : 'connect', friendlyError(err));
+ }
+ }
+
+ async executePaid(xPayment, attempt = 0) {
+ this.renderProgress('verify', {
+ text: attempt ? 'Retrying after upstream throttle…' : 'Calling merchant endpoint…',
+ });
+ try {
+ const res = await fetch(this.opts.endpoint, {
+ method: this.opts.method || 'GET',
+ headers: {
+ ...(this.opts.headers || {}),
+ ...(this.opts.body && !this.opts.headers?.['content-type'] ? { 'content-type': 'application/json' } : {}),
+ 'X-PAYMENT': xPayment,
+ },
+ body: this.opts.body ? (typeof this.opts.body === 'string' ? this.opts.body : JSON.stringify(this.opts.body)) : undefined,
+ });
+ const ct = res.headers.get('content-type') || '';
+ const text = await res.text();
+ let result;
+ if (ct.includes('json')) {
+ try {
+ result = JSON.parse(text);
+ } catch {
+ result = text;
+ }
+ } else {
+ result = text;
+ }
+ if (!res.ok) {
+ // A 429 here is a transient upstream throttle (e.g. the generator's
+ // create-prediction rate limit). The payment is signed but NOT yet
+ // settled — the merchant runs the work before settling — so the same
+ // X-PAYMENT can be safely re-sent once the window resets, with no risk
+ // of a double charge. Auto-retry a couple of times, respecting the
+ // server's Retry-After, before surfacing the manual "Try again".
+ if (res.status === 429 && attempt < MAX_THROTTLE_RETRIES) {
+ await this.waitForThrottle(retryAfterSeconds(res, result));
+ return this.executePaid(xPayment, attempt + 1);
+ }
+ const msg = (result && typeof result === 'object' && (result.error_description || result.error)) || `HTTP ${res.status}`;
+ throw new Error(msg);
+ }
+ const settleHeader = res.headers.get('x-payment-response');
+ const payment = b64decode(settleHeader) || {};
+ this.spendReservation = null;
+ this.renderDone({ result, payment });
+ this.resolve?.({ ok: true, result, payment, response: { status: res.status, headers: headersToObject(res.headers) } });
+ } catch (err) {
+ if (this.spendReservation) {
+ browserRollbackReservation(this.spendReservation);
+ this.spendReservation = null;
+ }
+ this.renderError('verify', friendlyError(err));
+ }
+ }
+
+ // Hold the verify step on a live countdown while an upstream throttle resets,
+ // then return so the caller re-sends the same signed payment. The reservation
+ // is deliberately left intact — this is the same payment, not a new one — so
+ // no rollback runs between attempts.
+ async waitForThrottle(seconds) {
+ const total = Math.max(1, Math.min(30, Math.round(seconds) || 6));
+ for (let left = total; left > 0; left--) {
+ this.renderProgress('verify', { text: `Generator is busy — retrying in ${left}s…` });
+ await new Promise((r) => setTimeout(r, 1000));
+ }
+ this.renderProgress('verify', { text: 'Retrying…' });
+ }
+
+ async runSiwxEvm(chain) {
+ this.renderProgress('connect', { text: 'Opening browser wallet…' });
+ try {
+ const eth = window.ethereum;
+ if (!eth) throw new Error('No EVM wallet detected');
+ const accounts = await eth.request({ method: 'eth_requestAccounts' });
+ const rawAddress = accounts?.[0];
+ if (!rawAddress) throw new Error('Wallet did not return an account');
+ const checksum = await loadEvmChecksum();
+ const address = checksum(rawAddress);
+ this.payerAddress = address;
+ this.renderProgress('authorize', { text: `Sign sign-in message as ${address.slice(0, 6)}…${address.slice(-4)}` });
+
+ const message = buildSiwxMessage(this.siwx.info, chain, address);
+ const signature = await eth.request({
+ method: 'personal_sign',
+ params: [message, address],
+ });
+
+ const info = this.siwx.info;
+ const payload = {
+ domain: info.domain,
+ address,
+ ...(info.statement ? { statement: info.statement } : {}),
+ uri: info.uri,
+ version: info.version || '1',
+ chainId: chain.chainId,
+ type: 'eip191',
+ nonce: info.nonce,
+ issuedAt: info.issuedAt,
+ ...(info.expirationTime ? { expirationTime: info.expirationTime } : {}),
+ ...(info.notBefore ? { notBefore: info.notBefore } : {}),
+ ...(info.requestId !== undefined && info.requestId !== null ? { requestId: info.requestId } : {}),
+ ...(Array.isArray(info.resources) ? { resources: info.resources } : {}),
+ signatureScheme: 'eip191',
+ signature,
+ };
+ await this.executeSiwx(payload, chain.chainId);
+ } catch (err) {
+ this.renderError(this.payerAddress ? 'authorize' : 'connect', friendlyError(err));
+ }
+ }
+
+ async runSiwxSolana(chain) {
+ this.renderProgress('connect', { text: 'Opening Phantom…' });
+ try {
+ const provider = window.phantom?.solana || window.solana;
+ if (!provider) throw new Error('Phantom wallet not detected');
+ const conn = await provider.connect();
+ const pubkey = conn?.publicKey || provider.publicKey;
+ const address = pubkey?.toString();
+ if (!address) throw new Error('Phantom did not return a public key');
+ this.payerAddress = address;
+ this.renderProgress('authorize', { text: `Sign sign-in message as ${address.slice(0, 6)}…${address.slice(-4)}` });
+
+ const message = buildSiwxMessage(this.siwx.info, chain, address);
+ const encoded = new TextEncoder().encode(message);
+ const signed = await provider.signMessage(encoded, 'utf8');
+ const sigBytes = signed?.signature instanceof Uint8Array ? signed.signature : new Uint8Array(signed?.signature || signed);
+ if (!sigBytes || !sigBytes.length) throw new Error('Phantom did not return a signature');
+ const signature = base58encode(sigBytes);
+
+ const info = this.siwx.info;
+ const payload = {
+ domain: info.domain,
+ address,
+ ...(info.statement ? { statement: info.statement } : {}),
+ uri: info.uri,
+ version: info.version || '1',
+ chainId: chain.chainId,
+ type: 'ed25519',
+ nonce: info.nonce,
+ issuedAt: info.issuedAt,
+ ...(info.expirationTime ? { expirationTime: info.expirationTime } : {}),
+ ...(info.notBefore ? { notBefore: info.notBefore } : {}),
+ ...(info.requestId !== undefined && info.requestId !== null ? { requestId: info.requestId } : {}),
+ ...(Array.isArray(info.resources) ? { resources: info.resources } : {}),
+ signatureScheme: 'siws',
+ signature,
+ };
+ await this.executeSiwx(payload, chain.chainId);
+ } catch (err) {
+ this.renderError(this.payerAddress ? 'authorize' : 'connect', friendlyError(err));
+ }
+ }
+
+ async executeSiwx(payload, chainId) {
+ this.renderProgress('verify', { text: 'Verifying sign-in…' });
+ const headerValue = encodeSiwxHeaderValue(payload);
+ let res;
+ try {
+ res = await fetch(this.opts.endpoint, {
+ method: this.opts.method || 'GET',
+ headers: {
+ ...(this.opts.headers || {}),
+ ...(this.opts.body && !this.opts.headers?.['content-type'] ? { 'content-type': 'application/json' } : {}),
+ [SIWX_HEADER]: headerValue,
+ },
+ body: this.opts.body ? (typeof this.opts.body === 'string' ? this.opts.body : JSON.stringify(this.opts.body)) : undefined,
+ });
+ } catch (err) {
+ this.renderError('verify', friendlyError(err));
+ return;
+ }
+
+ if (res.status === 200) {
+ const ct = res.headers.get('content-type') || '';
+ const text = await res.text();
+ let result;
+ if (ct.includes('json')) {
+ try { result = JSON.parse(text); } catch { result = text; }
+ } else {
+ result = text;
+ }
+ const siwx = { address: payload.address, network: chainId };
+ this.renderDone({ result, siwx });
+ this.resolve?.({
+ ok: true,
+ result,
+ siwx,
+ response: { status: res.status, headers: headersToObject(res.headers) },
+ });
+ return;
+ }
+
+ if (res.status === 401 || res.status === 402) {
+ // Most likely: signature verified but this wallet hasn't actually
+ // paid for the resource yet. Drop the SIWX offering and fall back
+ // to the normal payment flow with a one-line notice.
+ let parsed = null;
+ try { parsed = await res.clone().json(); } catch (_) {}
+ const code = parsed?.code || parsed?.error;
+ this.siwx = null;
+ this.payerAddress = null;
+ this.payFlowOverride = false;
+ this.siwxFallbackNotice = code === 'siwx_not_paid' || res.status === 402
+ ? "You haven't paid for this yet — pay now to unlock re-entry."
+ : 'Sign-in not accepted — please pay to continue.';
+ // Re-render the wallet picker. If we had collected the 402 challenge
+ // already, this just re-runs renderConnect; otherwise we re-discover.
+ if (!this.challenge || !Array.isArray(this.challenge.accepts) || !this.challenge.accepts.length) {
+ this.start();
+ } else {
+ this.renderConnect();
+ }
+ return;
+ }
+
+ const text = await res.text().catch(() => '');
+ this.renderError('verify', `SIWX retry failed: HTTP ${res.status}${text ? ` · ${text.slice(0, 120)}` : ''}`);
+ }
+}
+
+// ───────────────────────────────────────────────────────── helpers ──────────
+
+function escapeHtml(s) {
+ return String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+}
+
+function headersToObject(headers) {
+ const out = {};
+ headers.forEach((v, k) => (out[k] = v));
+ return out;
+}
+
+// How many times executePaid silently re-sends a signed payment after a 429
+// throttle before falling back to the manual "Try again". The payment isn't
+// settled until the merchant call succeeds, so re-sending can't double-charge.
+const MAX_THROTTLE_RETRIES = 2;
+
+// Seconds to wait before re-sending after a 429. Prefers the standard
+// Retry-After header, then the body's `retry_after` hint, then a sane default.
+function retryAfterSeconds(res, result, fallback = 6) {
+ const header = Number.parseInt(res.headers.get('retry-after') || '', 10);
+ if (Number.isFinite(header) && header > 0) return header;
+ const body = result && typeof result === 'object' ? Number(result.retry_after) : NaN;
+ if (Number.isFinite(body) && body > 0) return body;
+ return fallback;
+}
+
+function friendlyError(err) {
+ const msg = err?.shortMessage || err?.message || String(err);
+ // Trim ethers/viem long stacks, Phantom's RPC-error verbosity.
+ if (/user rejected|user denied|reject/i.test(msg)) return 'cancelled in wallet';
+ // Upstream throttles (e.g. a generator's create-prediction rate limit) often
+ // arrive as raw provider text that names the merchant's internal billing or
+ // credit state. Never relay that to the buyer: the payment isn't settled until
+ // the merchant call succeeds, so a clean, retryable message is both safer and
+ // more accurate than echoing the upstream's account internals.
+ if (/throttl|rate.?limit|too many requests|less than \$|in credit|\b429\b/i.test(msg)) {
+ return 'The service is briefly busy and your payment was not taken — retry in a few seconds.';
+ }
+ // The Solana and EVM-sign-in paths dynamic-import a library from esm.sh. A strict
+ // host Content-Security-Policy (or esm.sh being unreachable) blocks that import and
+ // the raw "Failed to fetch dynamically imported module" is opaque. The Base/EIP-3009
+ // payment path has no such dependency, so steer the buyer there.
+ if (/dynamically imported module|esm\.sh|module script failed/i.test(msg)) {
+ return 'A component this wallet path needs (loaded from esm.sh) was blocked — often by a strict host security policy. Pay with MetaMask on Base instead; it needs no third-party code.';
+ }
+ return msg.slice(0, 240);
+}
+
+function base64ToUint8Array(b64) {
+ if (typeof Buffer !== 'undefined') return new Uint8Array(Buffer.from(b64, 'base64'));
+ const bin = atob(b64);
+ const arr = new Uint8Array(bin.length);
+ for (let i = 0; i < bin.length; i++) arr[i] = bin.charCodeAt(i);
+ return arr;
+}
+function uint8ArrayToBase64(arr) {
+ if (typeof Buffer !== 'undefined') return Buffer.from(arr).toString('base64');
+ let bin = '';
+ for (let i = 0; i < arr.length; i++) bin += String.fromCharCode(arr[i]);
+ return btoa(bin);
+}
+function randomHex(bytes) {
+ const arr = new Uint8Array(bytes);
+ crypto.getRandomValues(arr);
+ return Array.from(arr).map((b) => b.toString(16).padStart(2, '0')).join('');
+}
+
+let _solanaWeb3 = null;
+async function loadSolanaWeb3() {
+ if (_solanaWeb3) return _solanaWeb3;
+ // Dynamic import from esm.sh keeps the drop-in script tiny — Solana web3.js
+ // is only fetched when a Solana payment is actually attempted.
+ _solanaWeb3 = await import(/* @vite-ignore */ CONFIG.esm.solanaWeb3);
+ return _solanaWeb3;
+}
+
+async function postJson(url, body) {
+ const res = await fetch(url, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify(body),
+ });
+ const text = await res.text();
+ let data;
+ try {
+ data = JSON.parse(text);
+ } catch {
+ data = { error: 'parse_error', error_description: text.slice(0, 200) };
+ }
+ if (!res.ok) {
+ const err = new Error(data.error_description || data.error || `HTTP ${res.status}`);
+ err.status = res.status;
+ err.data = data;
+ throw err;
+ }
+ return data;
+}
+
+// Probe the merchant endpoint with a benign request to extract the 402 challenge.
+// Accepts HTTP 402 (standard x402) or HTTP 401 with a `payment-required` header
+// (MCP 2025-06-18 spec, which uses 401 for resource-server authorization challenges).
+async function discoverChallenge(opts) {
+ const headers = { ...(opts.headers || {}) };
+ const init = {
+ method: opts.method || 'GET',
+ headers,
+ body: opts.body ? (typeof opts.body === 'string' ? opts.body : JSON.stringify(opts.body)) : undefined,
+ };
+ if (init.body && !headers['content-type']) headers['content-type'] = 'application/json';
+ const res = await fetch(opts.endpoint, init);
+
+ // MCP 2025-06-18 endpoints return 401 with the full x402 challenge in the
+ // `payment-required` header (base64-JSON). Accept that alongside standard 402.
+ const prHeader = res.headers.get('payment-required');
+ const is401WithChallenge = res.status === 401 && !!prHeader;
+
+ if (res.status !== 402 && !is401WithChallenge) {
+ // Endpoint isn't paid (200) or isn't an x402 endpoint at all. In either
+ // case, surface a clear error — accidentally pointing the modal at a
+ // free endpoint should not silently succeed.
+ const txt = await res.text();
+ throw new Error(`Endpoint did not return 402 (got ${res.status}). Body: ${txt.slice(0, 120)}`);
+ }
+
+ // For 401+header, decode directly — the full envelope is in the header.
+ // For 402, read body first and fall back to header if body is minimal.
+ let body = is401WithChallenge ? b64decode(prHeader) : await res.json().catch(() => null);
+ if (!body || !Array.isArray(body.accepts) || !body.accepts.length) {
+ // send402 (api/_lib/x402-spec.js) only emits `{error}` in the body and
+ // puts the full v2 PaymentRequired envelope (accepts + extensions) in
+ // the base64-JSON PAYMENT-REQUIRED header. b64decode returns already-
+ // parsed JSON, so use its result directly.
+ const decoded = b64decode(prHeader);
+ if (decoded && Array.isArray(decoded.accepts) && decoded.accepts.length) {
+ body = decoded;
+ }
+ }
+ if (!body || !Array.isArray(body.accepts) || !body.accepts.length) {
+ throw new Error('Endpoint returned 402 but no `accepts` array could be found in body or header');
+ }
+ return body;
+}
+
+// ───────────────────────────────────────────────────────── public api ───────
+
+export async function pay(opts) {
+ if (!opts?.endpoint) throw new Error('X402.pay: endpoint is required');
+ const modal = new CheckoutModal(opts);
+ const result = modal.mount();
+ // kick off the discovery on next tick so the modal animates in first.
+ queueMicrotask(() => modal.start());
+ return result;
+}
+
+function bindElement(el) {
+ if (el.dataset.x402Bound === '1') return;
+ el.dataset.x402Bound = '1';
+ el.addEventListener('click', async (e) => {
+ e.preventDefault();
+ const opts = readOptsFrom(el);
+ try {
+ const out = await pay(opts);
+ if (out?.siwx) {
+ el.dispatchEvent(new CustomEvent('x402:siwx-signed', { detail: out.siwx, bubbles: true }));
+ }
+ el.dispatchEvent(new CustomEvent('x402:result', { detail: out, bubbles: true }));
+ } catch (err) {
+ if (err?.code === 'cancelled') return;
+ el.dispatchEvent(new CustomEvent('x402:error', { detail: { error: err?.message || String(err) }, bubbles: true }));
+ }
+ });
+}
+
+function readOptsFrom(el) {
+ const ds = el.dataset;
+ let body = ds.x402Body;
+ if (body) {
+ try { body = JSON.parse(body); } catch { /* keep as string */ }
+ }
+ let headers = ds.x402Headers;
+ if (headers) {
+ try { headers = JSON.parse(headers); } catch { headers = undefined; }
+ }
+ return {
+ endpoint: ds.x402Endpoint,
+ method: ds.x402Method || (body ? 'POST' : 'GET'),
+ body,
+ headers,
+ merchant: ds.x402Merchant,
+ action: ds.x402Action || el.textContent?.trim().slice(0, 60),
+ };
+}
+
+export function init() {
+ document.querySelectorAll('[data-x402-endpoint]').forEach(bindElement);
+}
+
+// Auto-init on DOMContentLoaded, plus on demand.
+if (typeof document !== 'undefined') {
+ if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', init, { once: true });
+ } else {
+ init();
+ }
+ // Re-scan when merchants dynamically inject buttons.
+ const mo = new MutationObserver(() => init());
+ mo.observe(document.documentElement, { childList: true, subtree: true });
+}
+
+// Expose to merchants' inline scripts.
+if (typeof window !== 'undefined') {
+ window.X402 = Object.freeze({ pay, init, version: VERSION });
+}