Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
Add economy and hero demo pages, vscode-x402 package, and studio updates
nirholas1ee6538c67a9
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d65a8cb8e..2f8a17309 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,7 +10,9 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Credits** (`/credits`) — Top up with SOL or $THREE and spend credits on 3D generation, agents, and compute. Hold $THREE for up to 30% off every spend.- **Docs · Walk Avatar** (`/docs/walk`) — Developer and user documentation for the three.ws walking-avatar system: the /walk page, iframe embeds, the JavaScript SDK, the postMessage event contract, companion mode, analytics, and the Chrome extension.- **Feed** (`/feed`) — Recent activity from the people and agents you follow on three.ws.+- **Hero Stage** (`/hero-demo`) — A cinematic 3D hero stage for three.ws agents — a lit avatar centered in deep space over concentric glowing rings, a drifting starfield, and soft bloom, with pointer parallax and a live avatar switcher. Motion-safe.- **Studio — Object + Avatar from text** (`/forge-studio`) — One canvas for both text-to-3D pipelines: forge a textured object (GLB) in the Object tab, or describe a character and get a rigged avatar in the Avatar tab.+- **The Agent Economy — Live** (`/economy`) — The live three.ws agent economy: agents earning real money ranked by buyers and ratings, and the pay-per-call (x402) services they expose across Solana and Base.- **Walk** (`/walk`) — Your 3D avatar walks anywhere on the web. Live demos across six environments, a Chrome extension, one-tag embeds, and a global distance leaderboard.- **Walk Leaderboard** (`/walk-leaderboard`) — Global leaderboard for the walking avatar — distance walked, sites visited, and time, ranked daily, weekly, and all-time.- **"Fresh from the Forge" thumbnails now show your models** — The community strip on the Forge page shows the newest models people make. Half the tiles were rendering as blank dark squares: for models generated without a reference image, the page builds a thumbnail by snapshotting the 3D model itself — but it was doing that on a one-pixel-wide canvas, so the snapshot came out as a solid block. The snapshot now renders at full thumbnail resolution, and a snapshot that comes back empty cleanly falls back to a labeled prompt card instead of an empty tile. Every card in the strip now shows real artwork. (`/forge`) `[fix]`@@ -21,11 +23,13 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Affiliate dashboard now shows who you referred** — The referrals dashboard lists each person you referred with their signup date, the revenue they generated, and the commission you earned — not just totals. (`/dashboard/referrals`) `[improvement]`- **Agent payments now produce a signed receipt of exactly what was bought** — Autonomous agent-to-agent payments already run under a signed Intent Mandate (your standing authorization with budget and per-call caps). They now also issue a Cart Mandate for each transaction — a tamper-evident, signed record of the exact endpoint paid, the amount, currency, network, and line items, bound to the authorizing mandate. It comes back with every paid call and can be checked by anyone via a new verification endpoint, so a paid service has cryptographic proof of what its caller agreed to. This completes our alignment with Google's Agent Payments Protocol (AP2), layered cleanly on top of x402 settlement. `[feature, sdk]`- **Agent Studio: fixed an invisible overlay that blocked the Brain tab** — The Brain tab of Agent Studio could become unclickable — a full-screen dialog layer that's meant to stay hidden until you open Templates or the behavior view was rendering invisibly on top of the whole studio, swallowing every click. It now stays properly hidden until you actually open it, so the Brain tab is usable again. (`/agent-studio`) `[fix]`+- **Agent Studio: save a draft or step away without losing work** — Agent Studio now carries a persistent header on every tab with Save draft and Exit. Your agent already saves automatically as you edit — Save draft commits your progress on demand with a clear confirmation, and Exit saves first, then opens your live agent. Move freely between Brain, Memory, Body, Money and Skills from the tab row at any time, so no single section is a dead end. (`/agent-studio`) `[improvement]`- **Agent Studio: save your Brain and flow straight into Memory** — Building your agent's reasoning graph in the Brain tab now has a clear finish line. A new Save button writes the graph to the server on demand (or press ⌘/Ctrl+S), the header's save indicator finally lights up for Brain edits the way it does for the name and tagline, and a Done button saves and carries you on to the Memory tab so designing a mind flows naturally into the next step instead of dead-ending on the canvas. Pressing Escape now also closes the Templates and behavior dialogs so they can never trap you. (`/agent-studio`) `[improvement]`- **Arm your agent gets its own setup page** — Configuring your 3D agent to trade Oracle conviction now has a dedicated page at /oracle/arm — a clean, focused setup laid out the way trading bots do it: a live status bar with a big arm switch, a stats strip, and step-by-step cards for entry rules, position sizing and caps, alerts, and simulate-vs-live mode. The Oracle tab now shows your agent's configuration at a glance and links straight to the full editor. (`/oracle/arm`) `[feature, improvement]`- **Authorize $THREE once, then pay with no wallet popups** — The $THREE page now lets you set a spending allowance: approve a cap once, and paid actions across the platform — forge, skills, names, cosmetics — debit it automatically without asking you to sign every time. It's non-custodial and built on Solana's native, audited Subscriptions & Allowances program: your tokens stay in your own wallet until a charge pulls them, never more than the cap you set. You can see what your remaining cap covers, get a heads-up when it runs low, top it up, or revoke it in one click anytime. Prefer to sign each payment? Just leave it off. (`/three-token`) `[feature]`- **Authorize $THREE once, then pay with no wallet popups** — The $THREE page now lets you set a spending allowance: approve a cap once, and paid actions across the platform — forge, skills, names, cosmetics — debit it automatically without asking you to sign every time. It's non-custodial and built on Solana's native, audited Subscriptions & Allowances program: your tokens stay in your own wallet until a charge pulls them, never more than the cap you set, and you can let it expire or revoke it anytime. Set a cap, top it up, or leave it off and keep signing each payment — your choice. (`/three-token`) `[feature]`- **Avatar Studio: full-spectrum color picker and one-tap Looks** — The Color tab in Avatar Studio is no longer limited to a fixed row of swatches. Tap the rainbow chip on any of skin, hair, or outfit and a real color wheel opens — drag for any hue, slide for brightness, type or paste an exact hex code, or use the eyedropper to sample any color on your screen (where your browser supports it). Every color you pick is remembered in a 'Recent' strip so a palette carries from one part of the avatar to the next, and between sessions. New 'Looks' sit above the colors too: one tap themes skin, hair, and outfit together — Noir, Sunset, Arctic, Cyber, Rosé, Forest, Mono, Ember — and a whole picking session counts as a single undo. The wheel loads only when you open it, so the studio stays fast. (`/avatar-studio`) `[feature, improvement]`+- **Bring your creations to life — talk to them** — Made an avatar from a prompt, or a model in the Lab? A new Talk button drops you into a live voice conversation with it: speak, and it answers out loud with an AI brain and real-time lip-sync. Avatars take on a first-person persona; objects play along. Same voice + reasoning stack the rest of three.ws uses. (`/forge-studio`) `[feature]`- **Clearer empty state on the $THREE live-trades feed** — Before the next trade lands, the live-trades panel on the $THREE token page now reads in plain language — 'Live trades will appear here' — with a short note on what it shows, and the technical detail tucked behind an info tooltip. Screen readers announce new trades as they stream in. (`/three-token`) `[improvement]`- **Club: silenced a spurious audio error on every visit** — The club's walk-in anthem only ships as an MP3, but the audio mixer always probed for an Ogg version first — so every visit logged a failed file request in the browser console before falling back to the MP3 that was there all along. The mixer now knows which tracks are MP3-only and loads them directly, so the anthem still plays and the console stays clean. (`/club`) `[fix]`- **Club: walk-in can no longer trap you on a frozen loading screen** — The club's alley walk-in lays a full-screen loading screen and 3D canvas over the stage, and a single script was responsible for clearing them once you arrive. If that script failed to load or a venue asset stalled, the loading screen stayed up and swallowed every click — the club looked frozen and nothing was clickable. A new independent watchdog now watches the load: if the walk-in stalls with no progress, it clears the overlays and opens the cover-charge card so you can always pay in and reach the stage. (`/club`) `[fix]`@@ -83,6 +87,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Solana reads and the club door survive a degraded RPC provider** — When a Solana node answers with a 200 but an unusable body — an empty payload, an HTML error page, or a quota-exhausted reply — our network layer had one weak spot: if every node was momentarily cooling off at once, it forwarded that garbage response straight through. In the browser that showed up as broken balance and blockhash reads on the marketplace, staking, and payment screens; at the club door it could fail the cover charge with an opaque error even though nothing was charged. The network layer now validates every reply on every path and fails over to a healthy node instead of passing a bad one along, returning a clean, honest error only when every provider is genuinely down. The club door also keeps a recent blockhash on hand and reuses it through a brief blip, so paying to enter and reading on-chain balances stay reliable through provider hiccups. `[fix, infra]`- **Solana stays online even if our paid RPC goes dark** — Everything onchain — paying, minting, balances, name lookups — depends on a Solana RPC node answering. When our primary paid node was throttled or its plan lapsed, some of those reads could error out. The platform now falls through a deeper chain: the paid node first, then several backup providers, then five independent public nodes (each verified live), so a request only fails if every one of them is down at the same moment. The embeddable payment widget and Solana name registration were moved onto the same resilient connection. `[fix, infra]`- **Studio Lab: six free 3D generators, right in your browser** — The new Lab tab in Studio turns text and parameters into real 3D — no API key, no cost, nothing leaves your machine. Build math-driven parametric solids and supershapes, extrude 3D lettering from any string, turn an SVG icon or logo into a solid model, generate a lithophane relief from a photo, or grow a procedural landscape from a seed — each one previews live and downloads as a real GLB. Plus a Gaussian-splat viewer for the photoreal radiance-field format (.splat / .ply). Powered by three.js and GaussianSplats3D. (`/forge-studio`) `[feature]`+- **Studio Lab: turn any model into a Gaussian splat** — The Lab in Studio now owns the splat format both ways. A new Mesh → Splats tool resamples any model — a Lab generator or a GLB you upload — into a Gaussian-splat radiance field entirely in your browser, viewable live and downloadable as a real .splat file. The Splat Viewer also gained a download button, so you can pull down whatever you load. No API key, no upload, no cost. (`/forge-studio`) `[feature]`- **The $THREE page now shows live market cap, holders & real trades** — Because $THREE has graduated to a DEX, the token page's main panel had broken: it read "100% graduated" but then showed a $0 market cap, no price, a blank holder count, and a "live trades" feed that never filled — even though the header above it showed a real $3.5M market cap. All four are fixed. The bonding-curve panel now reads the live DEX price and market cap for the graduated coin, the holder count comes from our own on-chain holder snapshot (so it shows even when the market-data provider omits it), and the live-trades tape now streams real on-chain swaps from the $THREE pool, refreshed every few seconds with buy/sell side, size, and a link to each transaction. (`/three-token`) `[fix]`- **The $THREE page now spells out why to hold — four real utility pillars** — The $THREE page leads with a clear "Why hold $THREE" section: revenue buybacks (a fixed, live share of platform revenue buys $THREE on the open market), holder rewards (every paid action reflects $THREE back to holders pro-rata), hold-to-access (discounts, higher quotas, and pro perks), and real usage (deploying agents, forging avatars, and trading the marketplace all run on $THREE). Each pillar maps to a mechanism that actually exists on the platform, and the buyback figure is wired to the live commitment. The page's market data also now rides a shared cache, so it stays fast and reliable under heavy traffic. (`/three-token`) `[feature, improvement]`- **The Forge now fills the whole screen** — The Forge — where you turn text or photos into a textured 3D model — used to sit in a narrow column down the middle of the page, leaving big empty margins on wide monitors and a cramped preview. It now stretches edge to edge with comfortable side gutters, so the 3D preview gets far more room to show off your model while the controls stay put on the left. (`/forge`) `[improvement]`diff --git a/data/changelog.json b/data/changelog.jsonindex d1031cebf..283493baa 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,27 @@{"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-06-21",+ "title": "Agent Studio: save a draft or step away without losing work",+ "summary": "Agent Studio now carries a persistent header on every tab with Save draft and Exit. Your agent already saves automatically as you edit — Save draft commits your progress on demand with a clear confirmation, and Exit saves first, then opens your live agent. Move freely between Brain, Memory, Body, Money and Skills from the tab row at any time, so no single section is a dead end.",+ "tags": ["improvement"],+ "link": "/agent-studio"+ },+ {+ "date": "2026-06-21",+ "title": "Studio Lab: turn any model into a Gaussian splat",+ "summary": "The Lab in Studio now owns the splat format both ways. A new Mesh → Splats tool resamples any model — a Lab generator or a GLB you upload — into a Gaussian-splat radiance field entirely in your browser, viewable live and downloadable as a real .splat file. The Splat Viewer also gained a download button, so you can pull down whatever you load. No API key, no upload, no cost.",+ "tags": ["feature"],+ "link": "/forge-studio"+ },+ {+ "date": "2026-06-21",+ "title": "Bring your creations to life — talk to them",+ "summary": "Made an avatar from a prompt, or a model in the Lab? A new Talk button drops you into a live voice conversation with it: speak, and it answers out loud with an AI brain and real-time lip-sync. Avatars take on a first-person persona; objects play along. Same voice + reasoning stack the rest of three.ws uses.",+ "tags": ["feature"],+ "link": "/forge-studio"+ },{"date": "2026-06-21","title": "Membership tiers: see your mode on your member card",diff --git a/data/pages.json b/data/pages.jsonindex 781984b27..06b5ae917 100644--- a/data/pages.json+++ b/data/pages.json@@ -875,6 +875,14 @@"changefreq": "weekly","added": "2026-06-03"},+ {+ "path": "/economy",+ "title": "The Agent Economy — Live",+ "description": "The live three.ws agent economy: agents earning real money ranked by buyers and ratings, and the pay-per-call (x402) services they expose across Solana and Base.",+ "priority": 0.7,+ "changefreq": "daily",+ "added": "2026-06-21"+ },{"path": "/agent-trade","title": "Agent Commerce",@@ -915,6 +923,14 @@"changefreq": "weekly","added": "2026-06-02"},+ {+ "path": "/hero-demo",+ "title": "Hero Stage",+ "description": "A cinematic 3D hero stage for three.ws agents — a lit avatar centered in deep space over concentric glowing rings, a drifting starfield, and soft bloom, with pointer parallax and a live avatar switcher. Motion-safe.",+ "priority": 0.5,+ "changefreq": "monthly",+ "added": "2026-06-21"+ },{"path": "/evm-wallet","title": "EVM Vanity Wallet",diff --git a/packages/vscode-x402/.gitignore b/packages/vscode-x402/.gitignorenew file mode 100644index 000000000..49cdee350--- /dev/null+++ b/packages/vscode-x402/.gitignore@@ -0,0 +1,3 @@+dist/+node_modules/+*.vsixdiff --git a/packages/vscode-x402/.vscodeignore b/packages/vscode-x402/.vscodeignorenew file mode 100644index 000000000..8c68d97f0--- /dev/null+++ b/packages/vscode-x402/.vscodeignore@@ -0,0 +1,8 @@+.vscode/**+src/**+build.mjs+**/*.map+**/tsconfig.json+.gitignore+.eslintrc*+node_modules/**diff --git a/packages/vscode-x402/build.mjs b/packages/vscode-x402/build.mjsnew file mode 100644index 000000000..5ed24465b--- /dev/null+++ b/packages/vscode-x402/build.mjs@@ -0,0 +1,29 @@+// Bundle the extension (and the bundled @three-ws/x402-fetch source) into a+// single CJS file VS Code can require. `vscode` is provided by the host and must+// stay external.+import esbuild from 'esbuild';++const production = process.argv.includes('--production');+const watch = process.argv.includes('--watch');++/** @type {import('esbuild').BuildOptions} */+const options = {+ entryPoints: ['src/extension.js'],+ bundle: true,+ outfile: 'dist/extension.js',+ platform: 'node',+ format: 'cjs',+ target: 'node18',+ external: ['vscode'],+ sourcemap: !production,+ minify: production,+ logLevel: 'info',+};++if (watch) {+ const ctx = await esbuild.context(options);+ await ctx.watch();+ console.log('[vscode-x402] watching…');+} else {+ await esbuild.build(options);+}diff --git a/packages/vscode-x402/package.json b/packages/vscode-x402/package.jsonnew file mode 100644index 000000000..1ce25a35d--- /dev/null+++ b/packages/vscode-x402/package.json@@ -0,0 +1,169 @@+{+ "name": "@three-ws/vscode-x402",+ "displayName": "three.ws — x402",+ "description": "Browse the x402 bazaar, decode 402 payment challenges, and pay-per-call paid APIs with USDC — without leaving VS Code. Powered by three.ws.",+ "version": "0.1.0",+ "publisher": "three-ws",+ "license": "Apache-2.0",+ "homepage": "https://three.ws",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/nirholas/three.ws.git",+ "directory": "packages/vscode-x402"+ },+ "bugs": {+ "url": "https://github.com/nirholas/three.ws/issues"+ },+ "engines": {+ "vscode": "^1.85.0"+ },+ "categories": [+ "Other"+ ],+ "keywords": [+ "x402",+ "payments",+ "usdc",+ "micropayments",+ "agent",+ "bazaar",+ "web3"+ ],+ "main": "./dist/extension.js",+ "icon": "media/icon.png",+ "activationEvents": [],+ "contributes": {+ "viewsContainers": {+ "activitybar": [+ {+ "id": "threewsX402",+ "title": "x402 Bazaar",+ "icon": "media/x402.svg"+ }+ ]+ },+ "views": {+ "threewsX402": [+ {+ "id": "threewsX402.bazaar",+ "name": "Services",+ "icon": "media/x402.svg"+ }+ ]+ },+ "viewsWelcome": [+ {+ "view": "threewsX402.bazaar",+ "contents": "Browse paid x402 APIs and MCP tools from across the bazaar.\n[Refresh services](command:threewsX402.refresh)\n[Set filters](command:threewsX402.setFilters)\n\nTo pay for a service you'll need an EVM wallet key.\n[Set wallet key](command:threewsX402.setWalletKey)"+ }+ ],+ "commands": [+ {+ "command": "threewsX402.refresh",+ "title": "x402: Refresh Bazaar",+ "icon": "$(refresh)"+ },+ {+ "command": "threewsX402.search",+ "title": "x402: Search Bazaar",+ "icon": "$(search)"+ },+ {+ "command": "threewsX402.setFilters",+ "title": "x402: Set Bazaar Filters",+ "icon": "$(filter)"+ },+ {+ "command": "threewsX402.inspect",+ "title": "x402: Inspect Endpoint (decode 402 challenge)"+ },+ {+ "command": "threewsX402.openService",+ "title": "x402: Open Service Details"+ },+ {+ "command": "threewsX402.pay",+ "title": "x402: Pay & Call Endpoint"+ },+ {+ "command": "threewsX402.setWalletKey",+ "title": "x402: Set Wallet Key"+ },+ {+ "command": "threewsX402.clearWalletKey",+ "title": "x402: Clear Wallet Key"+ },+ {+ "command": "threewsX402.scaffoldEndpoint",+ "title": "x402: Scaffold a Paid Endpoint"+ }+ ],+ "menus": {+ "view/title": [+ {+ "command": "threewsX402.search",+ "when": "view == threewsX402.bazaar",+ "group": "navigation@1"+ },+ {+ "command": "threewsX402.setFilters",+ "when": "view == threewsX402.bazaar",+ "group": "navigation@2"+ },+ {+ "command": "threewsX402.refresh",+ "when": "view == threewsX402.bazaar",+ "group": "navigation@3"+ }+ ],+ "view/item/context": [+ {+ "command": "threewsX402.pay",+ "when": "view == threewsX402.bazaar && viewItem == x402service",+ "group": "inline"+ }+ ]+ },+ "configuration": {+ "title": "three.ws x402",+ "properties": {+ "threewsX402.origin": {+ "type": "string",+ "default": "https://three.ws",+ "description": "Origin that hosts the bazaar discovery API (/api/bazaar/list, /api/bazaar/search)."+ },+ "threewsX402.maxPaymentUsd": {+ "type": "number",+ "default": 0.1,+ "description": "Spending cap per request, in USD. Any auto-payment above this is refused before signing."+ },+ "threewsX402.confirmEachPayment": {+ "type": "boolean",+ "default": true,+ "description": "Show a confirmation dialog with the exact USD amount before signing each payment."+ },+ "threewsX402.network": {+ "type": "string",+ "default": "eip155:8453",+ "description": "Preferred CAIP-2 network for payment when an endpoint accepts several (default: Base mainnet)."+ },+ "threewsX402.filters": {+ "type": "object",+ "default": {+ "type": "http"+ },+ "description": "Default bazaar filters (type, network, maxPrice, tag, sort)."+ }+ }+ }+ },+ "scripts": {+ "build": "node build.mjs",+ "watch": "node build.mjs --watch",+ "vscode:prepublish": "node build.mjs --production"+ },+ "devDependencies": {+ "@types/vscode": "^1.85.0",+ "esbuild": "^0.21.0"+ }+}diff --git a/packages/vscode-x402/src/bazaar.js b/packages/vscode-x402/src/bazaar.jsnew file mode 100644index 000000000..974e187bb--- /dev/null+++ b/packages/vscode-x402/src/bazaar.js@@ -0,0 +1,50 @@+// Buyer-side discovery client. Talks to the three.ws bazaar proxy+// (/api/bazaar/list, /api/bazaar/search), which merges + normalises results+// across every configured x402 facilitator. Mirrors public/x402-discover.js but+// runs in the extension host (Node global fetch).++import * as vscode from 'vscode';++function origin() {+ return vscode.workspace+ .getConfiguration('threewsX402')+ .get('origin', 'https://three.ws')+ .replace(/\/+$/, '');+}++function applyFilters(url, filters = {}) {+ const set = (k, v) => v != null && v !== '' && url.searchParams.set(k, String(v));+ set('type', filters.type || 'http');+ set('network', filters.network);+ set('maxPrice', filters.maxPrice);+ set('asset', filters.asset);+ set('extension', filters.extension);+ set('tag', filters.tag);+ set('sort', filters.sort);+ set('maxItems', filters.maxItems);+ set('limit', filters.limit);+}++async function call(url) {+ const res = await fetch(url.toString(), { headers: { accept: 'application/json' } });+ const body = await res.json().catch(() => ({}));+ if (!res.ok) {+ throw new Error(body?.error_description || body?.error || `discovery HTTP ${res.status}`);+ }+ return body;+}++/** List bazaar services. Returns { type, count, items[], sources, errors }. */+export async function list(filters = {}) {+ const url = new URL(`${origin()}/api/bazaar/list`);+ applyFilters(url, filters);+ return call(url);+}++/** Full-text search across the bazaar. Same envelope as list(). */+export async function search(query, filters = {}) {+ const url = new URL(`${origin()}/api/bazaar/search`);+ if (query) url.searchParams.set('query', query);+ applyFilters(url, filters);+ return call(url);+}diff --git a/packages/vscode-x402/src/inspect.js b/packages/vscode-x402/src/inspect.jsnew file mode 100644index 000000000..42426582e--- /dev/null+++ b/packages/vscode-x402/src/inspect.js@@ -0,0 +1,74 @@+// Inspect any endpoint: do an unpaid request, and if it answers 402, decode the+// payment challenge into a readable summary using the same parser the payer+// uses. Reachable as a standalone command (paste a URL) or from a bazaar item.++import {+ parseChallenge,+ selectRequirement,+ amountToUsd,+} from '../../x402-fetch/src/index.js';++/**+ * @returns {Promise<{ status:number, paid:boolean, accepts:any[], chosen:any|null, resource:any, raw:any }>}+ */+export async function inspectEndpoint(url, { method = 'GET', preferNetwork } = {}) {+ const res = await fetch(url, {+ method,+ headers: { accept: 'application/json' },+ // MCP endpoints expect a body; for inspection a HEAD-ish GET is enough to+ // trigger the 402 on three.ws + CDP merchants.+ });++ if (res.status !== 402) {+ return {+ status: res.status,+ paid: res.status >= 200 && res.status < 300,+ accepts: [],+ chosen: null,+ resource: null,+ raw: null,+ };+ }++ const parsed = await parseChallenge(res);+ const accepts = parsed?.accepts || [];+ const chosen = selectRequirement(accepts, { preferNetwork });+ return {+ status: 402,+ paid: false,+ accepts,+ chosen,+ resource: parsed?.resource || null,+ raw: parsed?.raw || null,+ };+}++/** Human summary lines for a parsed challenge. */+export function summarize(result) {+ if (result.status !== 402) {+ return [+ `Status: ${result.status}`,+ result.paid+ ? 'No payment required — this endpoint answered without a 402.'+ : 'Endpoint did not return a 402 payment challenge.',+ ];+ }+ const lines = ['Status: 402 Payment Required', ''];+ result.accepts.forEach((a, i) => {+ const usd = amountToUsd(a);+ const mark = a === result.chosen ? ' ← payable by this wallet' : '';+ lines.push(+ `#${i + 1} ${a.network || '?'} · ${a.scheme || 'exact'} · $${usd.toFixed(6)} ${shortAsset(a.asset)}${mark}`,+ );+ if (a.payTo) lines.push(` payTo: ${a.payTo}`);+ });+ if (!result.chosen) {+ lines.push('', '⚠ No requirement this wallet can satisfy (needs an EVM EIP-3009 USDC accept).');+ }+ return lines;+}++function shortAsset(asset) {+ if (!asset) return '';+ return asset.length > 12 ? `${asset.slice(0, 6)}…${asset.slice(-4)}` : asset;+}diff --git a/packages/vscode-x402/src/panel.js b/packages/vscode-x402/src/panel.jsnew file mode 100644index 000000000..24888942b--- /dev/null+++ b/packages/vscode-x402/src/panel.js@@ -0,0 +1,207 @@+// Service detail webview. Shows the normalised bazaar item, its payment+// requirements, and a "Pay & call" action that runs the real x402 flow and+// renders the response body + settlement receipt. One reusable panel.++import * as vscode from 'vscode';+import { payAndCall } from './pay.js';++let panel = null;++export function showService(context, item) {+ if (!panel) {+ panel = vscode.window.createWebviewPanel(+ 'threewsX402.service',+ 'x402 Service',+ vscode.ViewColumn.Active,+ { enableScripts: true, retainContextWhenHidden: true },+ );+ panel.onDidDispose(() => {+ panel = null;+ });+ panel.webview.onDidReceiveMessage(async (msg) => {+ if (msg?.type === 'pay') {+ await runPay(context, msg);+ } else if (msg?.type === 'openExternal' && msg.url) {+ vscode.env.openExternal(vscode.Uri.parse(msg.url));+ }+ });+ }+ panel.title = `x402 · ${item.serviceName || hostOf(item.resource)}`;+ panel.webview.html = render(item);+ panel.reveal();+}++async function runPay(context, msg) {+ panel?.webview.postMessage({ type: 'status', state: 'running' });+ try {+ const result = await payAndCall(context, {+ url: msg.url,+ method: msg.method,+ body: msg.body,+ serviceName: msg.serviceName,+ });+ if (!result) {+ panel?.webview.postMessage({ type: 'status', state: 'cancelled' });+ return;+ }+ panel?.webview.postMessage({ type: 'result', result });+ if (result.ok) {+ vscode.window.showInformationMessage(+ `x402: ${msg.serviceName || msg.url} → ${result.status}` ++ (result.receipt?.transaction ? ` · tx ${short(result.receipt.transaction)}` : ''),+ );+ }+ } catch (e) {+ panel?.webview.postMessage({ type: 'error', message: e?.message || String(e) });+ vscode.window.showErrorMessage(`x402 payment failed: ${e?.message || e}`);+ }+}++function render(item) {+ const accepts = item.accepts || [];+ const isMcp = item.type === 'mcp';+ const defaultMethod = isMcp ? 'POST' : item.method && item.method !== 'MCP' ? item.method : 'GET';+ const defaultBody = isMcp+ ? JSON.stringify(+ {+ jsonrpc: '2.0',+ id: 1,+ method: 'tools/call',+ params: { name: item.toolName || 'tool', arguments: {} },+ },+ null,+ 2,+ )+ : '';+ const rows = accepts+ .map(+ (a) => `<tr>+ <td>${esc(a.network || '?')}</td>+ <td>${esc(a.priceLabel || a.amount || '?')}</td>+ <td>${esc(a.scheme || 'exact')}</td>+ <td class="mono">${esc(a.payTo || '')}</td>+ </tr>`,+ )+ .join('');++ return `<!DOCTYPE html><html><head><meta charset="utf-8">+<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline';">+<style>${STYLE}</style></head><body>+ <h1>${esc(item.serviceName || hostOf(item.resource))}</h1>+ <p class="desc">${esc(item.description || 'No description provided.')}</p>+ <div class="meta">+ <span class="pill">${esc(item.type || 'http')}</span>+ <span class="pill">${esc(item.minPriceLabel || 'free')}</span>+ ${(item.tags || []).map((t) => `<span class="tag">${esc(t)}</span>`).join('')}+ </div>+ <p class="resource"><a href="#" onclick="ext('${esc(item.resource)}')">${esc(item.resource)}</a>${item.toolName ? ` · tool <code>${esc(item.toolName)}</code>` : ''}</p>+ ${item.facilitator ? `<p class="muted">via ${esc(item.facilitator)}</p>` : ''}++ <h2>Payment requirements</h2>+ <table><thead><tr><th>Network</th><th>Price</th><th>Scheme</th><th>payTo</th></tr></thead><tbody>${rows || '<tr><td colspan="4">none</td></tr>'}</tbody></table>++ <h2>Call</h2>+ <label>Method+ <select id="method"><option${defaultMethod === 'GET' ? ' selected' : ''}>GET</option><option${defaultMethod === 'POST' ? ' selected' : ''}>POST</option></select>+ </label>+ <label>Request body (JSON, for POST/MCP)+ <textarea id="body" rows="7" spellcheck="false">${esc(defaultBody)}</textarea>+ </label>+ <button id="pay">Pay & call</button>+ <span id="state" class="state"></span>++ <div id="out" class="out hidden">+ <h2>Response</h2>+ <div id="receipt"></div>+ <pre id="resp"></pre>+ </div>++<script>+ const vscode = acquireVsCodeApi();+ const D = {+ url: ${JSON.stringify(item.resource)},+ serviceName: ${JSON.stringify(item.serviceName || hostOf(item.resource))},+ };+ function ext(url){ vscode.postMessage({ type:'openExternal', url }); }+ document.getElementById('pay').addEventListener('click', () => {+ vscode.postMessage({+ type:'pay',+ url: D.url,+ serviceName: D.serviceName,+ method: document.getElementById('method').value,+ body: document.getElementById('body').value,+ });+ });+ window.addEventListener('message', (e) => {+ const m = e.data;+ const state = document.getElementById('state');+ const out = document.getElementById('out');+ const btn = document.getElementById('pay');+ if (m.type === 'status') {+ btn.disabled = m.state === 'running';+ state.textContent = m.state === 'running' ? 'Working…' : m.state === 'cancelled' ? 'Cancelled.' : '';+ state.className = 'state';+ } else if (m.type === 'error') {+ btn.disabled = false;+ state.textContent = m.message;+ state.className = 'state err';+ } else if (m.type === 'result') {+ btn.disabled = false;+ state.textContent = '';+ out.classList.remove('hidden');+ const r = m.result;+ const rc = document.getElementById('receipt');+ const paid = r.amountUsd ? '\$' + Number(r.amountUsd).toFixed(6) : 'free';+ let receipt = '<div class="kv"><b>Status</b> ' + r.status + ' · <b>Paid</b> ' + paid + ' · <b>From</b> <code>' + r.address + '</code></div>';+ if (r.receipt) {+ const tx = r.receipt.transaction || r.receipt.txHash;+ if (tx) receipt += '<div class="kv"><b>Tx</b> <code>' + tx + '</code> ' + (r.receipt.network ? '('+r.receipt.network+')' : '') + '</div>';+ }+ rc.innerHTML = receipt;+ let body = r.bodyText || '';+ try { body = JSON.stringify(JSON.parse(body), null, 2); } catch(_) {}+ document.getElementById('resp').textContent = body;+ }+ });+</script>+</body></html>`;+}++const STYLE = `+ body { font-family: var(--vscode-font-family); color: var(--vscode-foreground); padding: 0 4px 24px; }+ h1 { font-size: 1.4em; margin-bottom: 4px; }+ h2 { font-size: 1em; text-transform: uppercase; letter-spacing: .04em; opacity: .7; margin-top: 24px; }+ .desc { opacity: .9; }+ .muted, .resource { opacity: .7; font-size: .9em; }+ .meta { display:flex; gap:6px; flex-wrap:wrap; margin: 8px 0; }+ .pill { background: var(--vscode-badge-background); color: var(--vscode-badge-foreground); padding: 1px 8px; border-radius: 10px; font-size:.8em; }+ .tag { border:1px solid var(--vscode-panel-border); padding:1px 7px; border-radius:10px; font-size:.8em; opacity:.8; }+ a { color: var(--vscode-textLink-foreground); }+ table { width:100%; border-collapse: collapse; font-size:.9em; }+ th, td { text-align:left; padding:4px 8px; border-bottom:1px solid var(--vscode-panel-border); }+ .mono, code { font-family: var(--vscode-editor-font-family); font-size:.85em; word-break: break-all; }+ label { display:block; margin:10px 0 2px; font-size:.85em; opacity:.85; }+ select, textarea { width:100%; background: var(--vscode-input-background); color: var(--vscode-input-foreground); border:1px solid var(--vscode-input-border); border-radius:4px; padding:6px; font-family: var(--vscode-editor-font-family); }+ button { margin-top:12px; background: var(--vscode-button-background); color: var(--vscode-button-foreground); border:none; padding:8px 16px; border-radius:4px; cursor:pointer; }+ button:hover { background: var(--vscode-button-hoverBackground); }+ button:disabled { opacity:.5; cursor:default; }+ .state { margin-left:10px; font-size:.85em; opacity:.8; }+ .state.err { color: var(--vscode-errorForeground); opacity:1; }+ .out.hidden { display:none; }+ .kv { font-size:.85em; margin:4px 0; }+ pre { background: var(--vscode-textCodeBlock-background); padding:10px; border-radius:6px; overflow:auto; max-height:420px; }+`;++function esc(s) {+ return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);+}+function hostOf(url) {+ try {+ return new URL(url).host;+ } catch {+ return url || 'service';+ }+}+function short(s) {+ return s ? `${s.slice(0, 6)}…${s.slice(-4)}` : '';+}diff --git a/packages/vscode-x402/src/pay.js b/packages/vscode-x402/src/pay.jsnew file mode 100644index 000000000..269b26b63--- /dev/null+++ b/packages/vscode-x402/src/pay.js@@ -0,0 +1,114 @@+// Pay-per-call flow. Pre-checks the 402 to show the exact USD amount, asks for+// confirmation (honouring the spend cap), then performs the real paid request+// with @three-ws/x402-fetch and surfaces the settlement receipt.++import * as vscode from 'vscode';+import { withX402, privateKeyToWallet } from '../../x402-fetch/src/index.js';+import { amountToUsd } from '../../x402-fetch/src/parse-challenge.js';+import { getKey, setKey } from './wallet.js';+import { inspectEndpoint } from './inspect.js';++function config() {+ const c = vscode.workspace.getConfiguration('threewsX402');+ return {+ maxPaymentUsd: c.get('maxPaymentUsd', 0.1),+ confirmEachPayment: c.get('confirmEachPayment', true),+ network: c.get('network', 'eip155:8453'),+ };+}++function decodeReceipt(res) {+ const raw = res.headers.get('x-payment-response') || res.headers.get('payment-response');+ if (!raw) return null;+ try {+ return JSON.parse(Buffer.from(raw, 'base64').toString('utf8'));+ } catch {+ return null;+ }+}++/**+ * @param {{ url:string, method?:string, body?:string, serviceName?:string }} req+ * @returns {Promise<{ ok:boolean, status:number, amountUsd:number|null, address:string, receipt:any, bodyText:string }|null>}+ */+export async function payAndCall(context, req) {+ const cfg = config();++ let pk = await getKey(context);+ if (!pk) {+ const choice = await vscode.window.showWarningMessage(+ 'No wallet key set. Set one to pay for x402 endpoints?',+ 'Set Wallet Key',+ 'Cancel',+ );+ if (choice !== 'Set Wallet Key') return null;+ await setKey(context);+ pk = await getKey(context);+ if (!pk) return null;+ }++ const { address } = privateKeyToWallet(pk);+ const method = (req.method || 'GET').toUpperCase();+ const init = { method, headers: { accept: 'application/json' } };+ if (req.body != null && method !== 'GET' && method !== 'HEAD') {+ init.headers['content-type'] = 'application/json';+ init.body = req.body;+ }++ // Pre-check the challenge so the confirmation shows a real amount.+ const probe = await inspectEndpoint(req.url, { method, preferNetwork: cfg.network });+ if (probe.status !== 402) {+ // Free or non-paid endpoint — just run it, no signing.+ const res = await fetch(req.url, init);+ return finalize(res, { amountUsd: 0, address });+ }+ if (!probe.chosen) {+ throw new Error(+ 'This endpoint requires payment but offers no requirement this wallet can satisfy (needs USDC EIP-3009 on an EVM network).',+ );+ }++ const amountUsd = amountToUsd(probe.chosen);+ if (amountUsd > cfg.maxPaymentUsd) {+ const raise = await vscode.window.showWarningMessage(+ `This call costs $${amountUsd.toFixed(4)}, above your cap of $${cfg.maxPaymentUsd.toFixed(4)}.`,+ 'Raise cap & pay',+ 'Cancel',+ );+ if (raise !== 'Raise cap & pay') return null;+ } else if (cfg.confirmEachPayment) {+ const go = await vscode.window.showInformationMessage(+ `Pay $${amountUsd.toFixed(6)} from ${short(address)} to call ${req.serviceName || req.url}?`,+ { modal: true },+ 'Pay & call',+ );+ if (go !== 'Pay & call') return null;+ }++ const paidFetch = withX402(pk, {+ maxPaymentUsd: Math.max(cfg.maxPaymentUsd, amountUsd),+ network: cfg.network,+ });++ const res = await vscode.window.withProgress(+ { location: vscode.ProgressLocation.Notification, title: `Paying $${amountUsd.toFixed(6)} & calling…` },+ () => paidFetch(req.url, init),+ );+ return finalize(res, { amountUsd, address });+}++async function finalize(res, { amountUsd, address }) {+ const bodyText = await res.text();+ return {+ ok: res.ok,+ status: res.status,+ amountUsd,+ address,+ receipt: decodeReceipt(res),+ bodyText,+ };+}++function short(addr) {+ return addr ? `${addr.slice(0, 6)}…${addr.slice(-4)}` : '';+}diff --git a/packages/vscode-x402/src/scaffold.js b/packages/vscode-x402/src/scaffold.jsnew file mode 100644index 000000000..f09cb2d30--- /dev/null+++ b/packages/vscode-x402/src/scaffold.js@@ -0,0 +1,124 @@+// Scaffold a new paid x402 endpoint that follows the repo's canonical+// paidEndpoint() pattern (api/_lib/x402-paid-endpoint.js). Generates a working+// handler file in the open workspace and opens it.++import * as vscode from 'vscode';++function template({ slug, fnName, priceUsd, description }) {+ const priceAtomics = Math.round(Number(priceUsd) * 1e6);+ return `// ${slug} — paid x402 endpoint. Buyers pay USDC; the call runs only after+// settlement. Wired to the shared paidEndpoint() x402 dance.+//+// GET|POST /api/x402/${slug}++import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';+import { buildBazaarSchema } from '../_lib/x402-spec.js';+import { withService } from '../_lib/x402/bazaar-helpers.js';++const RESOURCE_URL = 'https://three.ws/api/x402/${slug}';++const paid = paidEndpoint({+ route: '/api/x402/${slug}',+ method: 'POST',+ // $${Number(priceUsd).toFixed(6)} in USDC atomics (6 decimals).+ priceAtomics: ${priceAtomics},+ networks: ['base'],+ description: ${JSON.stringify(description)},+ service: withService({+ serviceName: ${JSON.stringify(slug)},+ tags: ['x402', 'paid'],+ }),+ bazaar: {+ description: ${JSON.stringify(description)},+ useCases: ['x402 paid api'],+ input: { type: 'json', example: {}, schema: { type: 'object', additionalProperties: true } },+ output: { type: 'json', example: {} },+ schema: buildBazaarSchema({ method: 'POST', bodySchema: { type: 'object', additionalProperties: true } }),+ resource: RESOURCE_URL,+ },+ resourceUrlBuilder: () => RESOURCE_URL,++ // Runs ONLY after the buyer's USDC settles. Return JSON; throw an Error with+ // a .status for handled failures.+ async handler({ req }) {+ const body = await readJson(req);+ // Replace this echo with the real work. It returns the validated request+ // so the endpoint is wired end-to-end from the first deploy.+ return {+ ok: true,+ service: ${JSON.stringify(slug)},+ received: body,+ };+ },+});++async function readJson(req) {+ const chunks = [];+ for await (const c of req) chunks.push(c);+ const raw = Buffer.concat(chunks).toString('utf8');+ return raw ? JSON.parse(raw) : {};+}++export default paid;+export const config = { api: { bodyParser: false } };+`;+}++export async function scaffoldEndpoint() {+ const folders = vscode.workspace.workspaceFolders;+ if (!folders?.length) {+ vscode.window.showErrorMessage('Open a workspace folder to scaffold an endpoint into.');+ return;+ }++ const slug = await vscode.window.showInputBox({+ title: 'Scaffold paid endpoint — slug',+ prompt: 'URL slug, e.g. "summarize" → /api/x402/summarize',+ validateInput: (v) =>+ /^[a-z0-9][a-z0-9-]*$/.test((v || '').trim()) ? null : 'lowercase letters, digits, hyphens',+ });+ if (!slug) return;++ const priceUsd = await vscode.window.showInputBox({+ title: 'Price per call (USD)',+ value: '0.01',+ validateInput: (v) => (Number(v) > 0 ? null : 'must be a positive number'),+ });+ if (!priceUsd) return;++ const description = await vscode.window.showInputBox({+ title: 'Description',+ prompt: 'What does this endpoint do? (shown in the bazaar)',+ value: `${slug} service`,+ });+ if (description == null) return;++ const cleanSlug = slug.trim();+ const content = template({+ slug: cleanSlug,+ fnName: cleanSlug.replace(/-([a-z])/g, (_, c) => c.toUpperCase()),+ priceUsd,+ description,+ });++ const root = folders[0].uri;+ const target = vscode.Uri.joinPath(root, 'api', 'x402', `${cleanSlug}.js`);+ try {+ await vscode.workspace.fs.stat(target);+ const ow = await vscode.window.showWarningMessage(+ `api/x402/${cleanSlug}.js already exists. Overwrite?`,+ 'Overwrite',+ 'Cancel',+ );+ if (ow !== 'Overwrite') return;+ } catch {+ /* doesn't exist — good */+ }++ await vscode.workspace.fs.writeFile(target, Buffer.from(content, 'utf8'));+ const doc = await vscode.workspace.openTextDocument(target);+ await vscode.window.showTextDocument(doc);+ vscode.window.showInformationMessage(+ `Scaffolded /api/x402/${cleanSlug} — it returns a wired echo response; replace the handler body with real work.`,+ );+}diff --git a/packages/vscode-x402/src/tree.js b/packages/vscode-x402/src/tree.jsnew file mode 100644index 000000000..081496af4--- /dev/null+++ b/packages/vscode-x402/src/tree.js@@ -0,0 +1,116 @@+// Sidebar tree of live bazaar services. Top level groups by facilitator source;+// children are services. Each leaf carries the normalised bazaar item so the+// detail/pay commands can act on it without re-fetching.++import * as vscode from 'vscode';+import * as bazaar from './bazaar.js';++const STATE = { loading: 'loading', error: 'error', ready: 'ready' };++export class BazaarProvider {+ constructor() {+ this._emitter = new vscode.EventEmitter();+ this.onDidChangeTreeData = this._emitter.event;+ this._items = [];+ this._state = STATE.ready;+ this._message = '';+ this._query = '';+ }++ filters() {+ return vscode.workspace.getConfiguration('threewsX402').get('filters', { type: 'http' });+ }++ setQuery(query) {+ this._query = query || '';+ this.refresh();+ }++ async refresh() {+ this._state = STATE.loading;+ this._emitter.fire();+ try {+ const res = this._query+ ? await bazaar.search(this._query, this.filters())+ : await bazaar.list(this.filters());+ this._items = Array.isArray(res.items) ? res.items : [];+ this._errors = Array.isArray(res.errors) ? res.errors : [];+ this._state = STATE.ready;+ } catch (e) {+ this._state = STATE.error;+ this._message = e?.message || String(e);+ this._items = [];+ }+ this._emitter.fire();+ }++ getTreeItem(node) {+ return node;+ }++ getChildren(node) {+ if (this._state === STATE.loading) {+ return [infoNode('Loading services…', new vscode.ThemeIcon('loading~spin'))];+ }+ if (this._state === STATE.error) {+ return [infoNode(`Error: ${this._message}`, new vscode.ThemeIcon('error'))];+ }+ if (!node) {+ if (!this._items.length) {+ const label = this._query+ ? `No matches for "${this._query}"`+ : 'No services found';+ return [infoNode(label, new vscode.ThemeIcon('info'))];+ }+ return this._items.map((item) => serviceNode(item));+ }+ return [];+ }+}++function infoNode(label, icon) {+ const node = new vscode.TreeItem(label, vscode.TreeItemCollapsibleState.None);+ node.iconPath = icon;+ node.contextValue = 'x402info';+ return node;+}++function serviceNode(item) {+ const title = item.serviceName || labelFromUrl(item.resource) || item.resource;+ const node = new vscode.TreeItem(title, vscode.TreeItemCollapsibleState.None);+ const price = item.minPriceLabel || 'free';+ const nets = (item.networks || []).join(', ');+ node.description = [price, item.type, nets].filter(Boolean).join(' · ');+ node.tooltip = new vscode.MarkdownString(+ [+ `**${title}**`,+ '',+ item.description || '_no description_',+ '',+ `- **Resource:** \`${item.resource}\`${item.toolName ? ` · tool \`${item.toolName}\`` : ''}`,+ `- **Price:** ${price}`,+ `- **Networks:** ${nets || 'n/a'}`,+ `- **Facilitator:** ${item.facilitator || 'n/a'}`,+ item.tags?.length ? `- **Tags:** ${item.tags.join(', ')}` : '',+ ]+ .filter(Boolean)+ .join('\n'),+ );+ node.iconPath = new vscode.ThemeIcon(item.type === 'mcp' ? 'plug' : 'globe');+ node.contextValue = 'x402service';+ node.command = {+ command: 'threewsX402.openService',+ title: 'Open Service Details',+ arguments: [item],+ };+ return node;+}++function labelFromUrl(url) {+ try {+ const u = new URL(url);+ return `${u.host}${u.pathname}`.replace(/\/$/, '');+ } catch {+ return null;+ }+}diff --git a/packages/vscode-x402/src/wallet.js b/packages/vscode-x402/src/wallet.jsnew file mode 100644index 000000000..04c081269--- /dev/null+++ b/packages/vscode-x402/src/wallet.js@@ -0,0 +1,60 @@+// Wallet key handling. The EVM private key lives ONLY in VS Code SecretStorage+// (OS keychain) — never in settings.json, never on disk in plaintext. From the+// key we derive the public address with the bundled, zero-dep signer so we can+// show the user which account they're paying from.++import * as vscode from 'vscode';+import { privateKeyToWallet } from '../../x402-fetch/src/index.js';++const SECRET_KEY = 'threewsX402.walletPrivateKey';++function normalizePk(raw) {+ const pk = raw.trim();+ if (!/^0x[0-9a-fA-F]{64}$/.test(pk)) {+ throw new Error('Expected a 0x-prefixed 32-byte (64 hex char) EVM private key.');+ }+ return pk;+}++/** Prompt for and store an EVM private key. Returns the derived address. */+export async function setKey(context) {+ const raw = await vscode.window.showInputBox({+ title: 'x402 — Set Wallet Key',+ prompt: 'EVM private key (0x + 64 hex). Stored in the OS keychain, never in settings or files.',+ password: true,+ ignoreFocusOut: true,+ validateInput(value) {+ if (!value) return 'Required';+ return /^0x[0-9a-fA-F]{64}$/.test(value.trim())+ ? null+ : 'Must be 0x followed by 64 hex characters';+ },+ });+ if (!raw) return null;+ const pk = normalizePk(raw);+ // Validate it derives a real address before persisting.+ const { address } = privateKeyToWallet(pk);+ await context.secrets.store(SECRET_KEY, pk);+ return address;+}++/** Remove the stored key. */+export async function clearKey(context) {+ await context.secrets.delete(SECRET_KEY);+}++/** The stored private key, or null. */+export async function getKey(context) {+ return (await context.secrets.get(SECRET_KEY)) || null;+}++/** Derived address for the stored key, or null if none set. */+export async function getAddress(context) {+ const pk = await getKey(context);+ if (!pk) return null;+ try {+ return privateKeyToWallet(pk).address;+ } catch {+ return null;+ }+}diff --git a/pages/agent-studio.html b/pages/agent-studio.htmlindex b748b3661..a156ab8c2 100644--- a/pages/agent-studio.html+++ b/pages/agent-studio.html@@ -121,11 +121,20 @@.studio-identity {display: grid;grid-template-columns: 1fr auto;- grid-template-areas: 'name save' 'tag tag';+ grid-template-areas: 'name actions' 'tag actions';gap: 4px var(--space-sm, 0.618rem);padding: var(--space-md, 1rem) var(--space-lg, 1.618rem);border-bottom: 1px solid var(--stroke);}+ .studio-actions {+ grid-area: actions;+ align-self: center;+ display: flex;+ align-items: center;+ flex-wrap: wrap;+ justify-content: flex-end;+ gap: var(--space-sm, 0.618rem);+ }.studio-name {grid-area: name;font-family: var(--font-display);@@ -160,12 +169,12 @@background: var(--surface-2);}.studio-save {- grid-area: save;align-self: center;font-size: var(--text-2xs, 0.6875rem);font-weight: var(--weight-semibold, 600);color: var(--ink-faint);transition: color var(--duration-fast) var(--ease-standard);+ white-space: nowrap;}.studio-save[data-state='pending'] { color: var(--warn, #fbbf24); }.studio-save[data-state='saved'] { color: var(--success, #4ade80); }@@ -302,6 +311,14 @@margin-top: 8px;}.studio-btn-ghost:hover { background: var(--surface-3); }+ /* Compact header actions (Save draft / Exit) — sit inline beside the save+ indicator without the ghost button's stacking margin. */+ .studio-action {+ margin-top: 0;+ padding: 6px 13px;+ font-size: var(--text-md, 0.8125rem);+ white-space: nowrap;+ }/* Gate / error / empty-agent */.studio-gate {diff --git a/pages/economy.html b/pages/economy.htmlnew file mode 100644index 000000000..93483e4a3--- /dev/null+++ b/pages/economy.html@@ -0,0 +1,185 @@+<!doctype html>+<html lang="en">+ <head>+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>The Agent Economy · Live · three.ws</title>+ <meta+ name="description"+ content="The live three.ws agent economy: agents earning real money, ranked by buyers and ratings, and the pay-per-call (x402) services they expose across Solana and Base."+ />+ <meta property="og:title" content="The Agent Economy — Live · three.ws" />+ <meta property="og:description" content="Agents earning on three.ws and the x402 services they sell — live across the network." />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:url" content="https://three.ws/economy" />+ <meta property="og:image" content="https://three.ws/api/page-og?s=trade&t=The+Agent+Economy&d=Agents+earning+on+three.ws+and+the+x402+services+they+sell+%E2%80%94+live+across+the+network.&p=%2Feconomy" />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="twitter:title" content="The Agent Economy — Live · three.ws" />+ <meta name="twitter:description" content="Agents earning on three.ws and the x402 services they sell — live across the network." />+ <meta name="theme-color" content="#080814" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/site.webmanifest" />+ <link rel="stylesheet" href="/style.css" />+ <link rel="canonical" href="https://three.ws/economy" />+ <style>+ .ae-main {+ max-width: 1180px;+ margin: 0 auto;+ padding: var(--space-lg, 24px) clamp(16px, 4vw, 40px) var(--space-2xl, 64px);+ }+ .ae-hero h1 {+ font-size: clamp(28px, 5vw, 44px);+ letter-spacing: -0.02em;+ margin: 0 0 8px;+ }+ .ae-hero p {+ color: var(--text-muted, #888);+ margin: 0 0 4px;+ max-width: 62ch;+ }+ .ae-hero .ae-demo-link {+ color: var(--text, #e8e8e8);+ text-decoration: underline;+ text-underline-offset: 2px;+ }+ .ae-stats {+ display: flex;+ flex-wrap: wrap;+ gap: 12px;+ margin: 22px 0 8px;+ }+ .ae-stat {+ border: 1px solid var(--border, #1a1a1a);+ background: var(--surface-1, #0a0a0a);+ border-radius: 14px;+ padding: 14px 18px;+ min-width: 120px;+ }+ .ae-stat-num { font-size: 26px; font-weight: 700; letter-spacing: -0.01em; }+ .ae-stat-label { font-size: 12px; color: var(--text-muted, #888); margin-top: 2px; }+ .ae-section { margin-top: 40px; }+ .ae-section-head { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; margin-bottom: 16px; }+ .ae-section-head h2 { font-size: 19px; margin: 0; letter-spacing: -0.01em; }+ .ae-section-head a { font-size: 13px; color: var(--text-muted, #888); text-decoration: none; }+ .ae-section-head a:hover { color: var(--text, #e8e8e8); }+ .ae-muted { color: var(--text-muted, #888); }++ /* Agent grid */+ .ae-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 14px; }+ .ae-card {+ display: flex;+ flex-direction: column;+ gap: 10px;+ border: 1px solid var(--border, #1a1a1a);+ background: var(--surface-1, #0a0a0a);+ border-radius: 16px;+ padding: 16px;+ text-decoration: none;+ color: var(--text, #e8e8e8);+ transition: border-color 0.15s, transform 0.12s, background 0.15s;+ }+ .ae-card:hover { border-color: #3a3a3a; background: var(--surface-2, #111); transform: translateY(-2px); }+ .ae-card-top { display: flex; align-items: center; gap: 12px; }+ .ae-avatar {+ width: 46px; height: 46px; border-radius: 12px; overflow: hidden; flex: none;+ background: linear-gradient(135deg, #1c1c28, #0c0c12);+ display: flex; align-items: center; justify-content: center;+ border: 1px solid var(--border, #1a1a1a);+ }+ .ae-avatar img { width: 100%; height: 100%; object-fit: cover; }+ .ae-avatar-fallback { font-weight: 700; color: #777; font-size: 18px; }+ .ae-card-head { display: flex; flex-direction: column; min-width: 0; }+ .ae-card-name { font-weight: 600; font-size: 15px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+ .ae-card-cat { font-size: 12px; text-transform: capitalize; }+ .ae-card-desc { font-size: 13px; line-height: 1.45; color: #aaa; margin: 0; min-height: 2.6em; }+ .ae-card-foot { display: flex; align-items: center; justify-content: space-between; gap: 8px; }+ .ae-stars { color: #ffd166; font-size: 13px; }+ .ae-card-metrics { display: flex; gap: 12px; font-size: 12px; color: var(--text-muted, #888); border-top: 1px solid var(--border, #1a1a1a); padding-top: 10px; }+ .ae-card-metrics strong { color: var(--text, #e8e8e8); }+ .ae-up { color: #6ee7a8; }+ .ae-chip { font-size: 12px; border: 1px solid var(--border-strong, #2a2a2a); border-radius: 999px; padding: 3px 10px; color: #ccc; white-space: nowrap; }+ .ae-chip-price { color: #6ee7a8; border-color: #1f3a2a; }+ .ae-chip-free { color: #888; }++ /* Services list */+ .ae-list { display: flex; flex-direction: column; gap: 10px; }+ .ae-svc {+ display: flex; align-items: center; justify-content: space-between; gap: 16px;+ border: 1px solid var(--border, #1a1a1a); background: var(--surface-1, #0a0a0a);+ border-radius: 14px; padding: 14px 16px; text-decoration: none; color: var(--text, #e8e8e8);+ transition: border-color 0.15s, background 0.15s;+ }+ .ae-svc:hover { border-color: #3a3a3a; background: var(--surface-2, #111); }+ .ae-svc-main { display: flex; flex-direction: column; gap: 4px; min-width: 0; }+ .ae-svc-name { font-weight: 600; font-size: 14.5px; display: flex; align-items: center; gap: 8px; }+ .ae-svc-method { font-size: 10.5px; font-weight: 700; color: #8be9fd; border: 1px solid #1d3a44; border-radius: 5px; padding: 1px 5px; }+ .ae-svc-desc { font-size: 12.5px; }+ .ae-svc-tags { display: flex; gap: 6px; flex-wrap: wrap; margin-top: 2px; }+ .ae-tag { font-size: 11px; color: #888; border: 1px solid var(--border, #1a1a1a); border-radius: 999px; padding: 1px 8px; }+ .ae-svc-price { display: flex; flex-direction: column; align-items: flex-end; gap: 4px; flex: none; }+ .ae-svc-net { font-size: 11px; }++ /* States */+ .ae-skel { border-radius: 14px; background: linear-gradient(90deg, #0e0e16 25%, #16161f 37%, #0e0e16 63%); background-size: 400% 100%; animation: ae-shimmer 1.4s ease infinite; }+ .ae-skel-card { height: 168px; }+ .ae-skel-row { height: 64px; }+ @keyframes ae-shimmer { 0% { background-position: 100% 0; } 100% { background-position: -100% 0; } }+ .ae-empty, .ae-error { border: 1px dashed var(--border-strong, #2a2a2a); border-radius: 14px; padding: 28px; text-align: center; }+ .ae-empty-title { font-weight: 600; margin: 0 0 6px; }+ .ae-error p { margin: 0 0 12px; color: #f3b4b4; }+ .ae-retry { border: 1px solid var(--border-strong, #2a2a2a); background: var(--surface-1, #0a0a0a); color: var(--text, #e8e8e8); border-radius: 10px; padding: 8px 16px; cursor: pointer; font: inherit; }+ .ae-retry:hover { border-color: #444; }+ .ae-grid.ae-skelwrap, .ae-list.ae-skelwrap { /* skeletons reuse the same containers */ }+ </style>+ </head>+ <body>+ <div id="nav-container"></div>+ <main class="ae-main">+ <header class="ae-hero">+ <h1>The Agent Economy</h1>+ <p>+ Agents on three.ws don't just exist — they earn. Below: the agents people are+ actually paying, and the pay-per-call services agents expose to each other over x402.+ </p>+ <p class="ae-muted">+ Want to see a single trade up close?+ <a class="ae-demo-link" href="/agent-economy">Watch two agents transact on-chain →</a>+ </p>+ <div class="ae-stats">+ <div class="ae-stat"><div class="ae-stat-num" id="ae-stat-agents">—</div><div class="ae-stat-label">Agents listed</div></div>+ <div class="ae-stat"><div class="ae-stat-num" id="ae-stat-earning">—</div><div class="ae-stat-label">With paying buyers</div></div>+ <div class="ae-stat"><div class="ae-stat-num" id="ae-stat-services">—</div><div class="ae-stat-label">Live x402 services</div></div>+ </div>+ </header>++ <section class="ae-section">+ <div class="ae-section-head">+ <h2>Agents earning on three.ws</h2>+ <a href="/marketplace">Open marketplace →</a>+ </div>+ <div class="ae-grid" id="ae-agents"></div>+ </section>++ <section class="ae-section">+ <div class="ae-section-head">+ <h2>Live x402 services</h2>+ <a href="/docs">How x402 works →</a>+ </div>+ <div class="ae-list" id="ae-services"></div>+ </section>+ </main>+ <div id="footer-container"></div>++ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"The Agent Economy — Live","description":"Agents earning on three.ws and the x402 services they sell, live across the network.","url":"https://three.ws/economy","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>+ <script src="/nav.js" defer></script>+ <script type="module" src="/src/economy-live.js"></script>+ <script src="/footer.js"></script>+ </body>+</html>diff --git a/pages/forge-studio.html b/pages/forge-studio.htmlindex 749797c86..7e865ad04 100644--- a/pages/forge-studio.html+++ b/pages/forge-studio.html@@ -3906,7 +3906,13 @@</div><div class="done-tags" id="cp-done-tags"></div><div class="done-actions">- <a class="btn-primary" id="cp-open-editor" href="#">+ <button class="btn-primary" id="cp-talk" type="button">+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">+ <path d="M21 11.5a8.38 8.38 0 0 1-8.5 8.5 9 9 0 0 1-3.9-.9L3 21l1.9-5.6A8.38 8.38 0 0 1 4 11.5 8.5 8.5 0 0 1 12.5 3 8.38 8.38 0 0 1 21 11.5z" />+ </svg>+ Talk to it+ </button>+ <a class="btn-ghost" id="cp-open-editor" href="#">Open in editor<svgwidth="14"@@ -3951,12 +3957,18 @@</div><div class="lab-actions"><button class="btn-primary" id="lab-generate" type="button">Generate model</button>- <a class="btn-ghost is-disabled" id="lab-download" href="#" download>- Download GLB+ <a class="btn-ghost is-disabled" id="lab-download" download>+ <span class="lab-dl-label">Download</span><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 3v12" /><polyline points="7 11 12 16 17 11" /><line x1="5" y1="20" x2="19" y2="20" /></svg></a>+ <button class="btn-ghost is-hidden" id="lab-talk" type="button" title="Talk to your creation with voice + an AI brain">+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">+ <path d="M21 11.5a8.38 8.38 0 0 1-8.5 8.5 9 9 0 0 1-3.9-.9L3 21l1.9-5.6A8.38 8.38 0 0 1 4 11.5 8.5 8.5 0 0 1 12.5 3 8.38 8.38 0 0 1 21 11.5z" />+ </svg>+ Bring it alive+ </button><span class="lab-status" id="lab-status" role="status" aria-live="polite"></span></div><p class="lab-foot">diff --git a/pages/hero-demo.html b/pages/hero-demo.htmlnew file mode 100644index 000000000..5f0dc56ac--- /dev/null+++ b/pages/hero-demo.html@@ -0,0 +1,495 @@+<!doctype html>+<html lang="en">+ <head>+ <style>/* three.ws hidden-guard — make the `hidden` attribute authoritative; see scripts/lib/hidden-guard.mjs */[hidden]{display:none!important}</style>+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/site.webmanifest" />+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />+ <title>Hero Stage · three.ws</title>+ <meta+ name="description"+ content="A cinematic 3D hero stage for three.ws agents — a lit avatar centered in deep space over concentric glowing rings, a drifting starfield, and soft bloom. Pointer parallax, motion-safe."+ />+ <meta property="og:title" content="Hero Stage · three.ws" />+ <meta property="og:description" content="A cinematic 3D hero stage — a lit agent over concentric glowing rings, starfield, and bloom." />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:url" content="https://three.ws/hero-demo" />+ <meta property="og:image" content="https://three.ws/api/page-og?s=default&t=Hero+Stage&d=A+cinematic+3D+hero+stage+%E2%80%94+a+lit+agent+over+concentric+glowing+rings%2C+starfield%2C+and+bloom.&p=%2Fhero-demo" />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="twitter:title" content="Hero Stage · three.ws" />+ <meta name="twitter:description" content="A cinematic 3D hero stage for three.ws agents — lit avatar, glowing rings, starfield, bloom." />+ <link rel="canonical" href="https://three.ws/hero-demo" />+ <style>+ :root {+ --bg-0: #04040a;+ --bg-1: #0c0c1c;+ --fg: #eef1ff;+ --muted: #98a0c8;+ --accent: #7c6cff;+ --accent-2: #36e0ff;+ --card: rgba(16, 18, 38, 0.62);+ --border: rgba(124, 108, 255, 0.22);+ --radius: 16px;+ }+ * { box-sizing: border-box; }+ html, body { margin: 0; }+ body {+ font-family: Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif;+ color: var(--fg);+ background:+ radial-gradient(120% 90% at 50% -10%, #1a1640 0%, var(--bg-1) 38%, var(--bg-0) 75%);+ -webkit-font-smoothing: antialiased;+ overflow-x: hidden;+ }++ /* ── Hero ───────────────────────────────────────────────── */+ .hero {+ position: relative;+ min-height: 100svh;+ display: grid;+ place-items: center;+ isolation: isolate;+ overflow: hidden;+ }+ /* Backdrop WebGL canvas — fills the hero, sits behind everything. */+ #stage {+ position: absolute;+ inset: 0;+ width: 100%;+ height: 100%;+ display: block;+ z-index: 0;+ }+ /* Subtle radial vignette to seat the subject. */+ .hero::after {+ content: '';+ position: absolute;+ inset: 0;+ z-index: 1;+ pointer-events: none;+ background: radial-gradient(60% 60% at 50% 52%, transparent 40%, rgba(4, 4, 10, 0.55) 100%);+ }++ /* The lit subject: a real <agent-3d>, transparent bg, dead center. */+ .subject {+ position: relative;+ z-index: 2;+ width: min(82vw, 460px);+ height: min(64svh, 560px);+ display: grid;+ place-items: center;+ }+ .subject agent-3d {+ width: 100%;+ height: 100%;+ display: block;+ opacity: 0;+ transition: opacity 0.8s ease;+ filter: drop-shadow(0 24px 60px rgba(124, 108, 255, 0.35));+ }+ .subject agent-3d.ready { opacity: 1; }++ /* Avatar loading skeleton — a breathing silhouette, not a spinner. */+ .subject-skel {+ position: absolute;+ inset: 0;+ display: grid;+ place-items: center;+ pointer-events: none;+ }+ .subject-skel[hidden] { display: none; }+ .skel-orb {+ width: 120px;+ height: 120px;+ border-radius: 50%;+ background: radial-gradient(circle at 50% 40%, rgba(124,108,255,0.35), rgba(54,224,255,0.06) 70%, transparent);+ animation: breathe 2.2s ease-in-out infinite;+ }+ @keyframes breathe {+ 0%, 100% { transform: scale(0.92); opacity: 0.55; }+ 50% { transform: scale(1.08); opacity: 1; }+ }++ /* Avatar failed → actionable retry. */+ .subject-error {+ position: absolute;+ inset: 0;+ display: grid;+ place-items: center;+ text-align: center;+ padding: 20px;+ }+ .subject-error p { color: var(--muted); font-size: 14px; margin: 0 0 14px; }++ /* Copy overlay — pinned to the lower third, fomo-style. */+ .hero-copy {+ position: absolute;+ left: 50%;+ bottom: clamp(28px, 8svh, 88px);+ transform: translateX(-50%);+ z-index: 3;+ width: min(92vw, 760px);+ text-align: center;+ animation: rise 0.7s cubic-bezier(0.2, 0.8, 0.2, 1) both;+ }+ @keyframes rise {+ from { opacity: 0; transform: translate(-50%, 18px); }+ to { opacity: 1; transform: translate(-50%, 0); }+ }+ .eyebrow {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ font-size: 12px;+ font-weight: 600;+ letter-spacing: 0.14em;+ text-transform: uppercase;+ color: var(--accent-2);+ margin: 0 0 14px;+ }+ .eyebrow::before {+ content: '';+ width: 6px; height: 6px;+ border-radius: 50%;+ background: var(--accent-2);+ box-shadow: 0 0 12px var(--accent-2);+ }+ .hero-copy h1 {+ margin: 0 0 14px;+ font-size: clamp(34px, 6.4vw, 68px);+ line-height: 1.02;+ letter-spacing: -0.03em;+ font-weight: 800;+ background: linear-gradient(180deg, #ffffff 0%, #c8caff 100%);+ -webkit-background-clip: text;+ background-clip: text;+ color: transparent;+ }+ .hero-copy p {+ margin: 0 auto 26px;+ max-width: 52ch;+ color: var(--muted);+ font-size: clamp(15px, 2.1vw, 18px);+ line-height: 1.5;+ }+ .cta-row {+ display: flex;+ gap: 12px;+ justify-content: center;+ flex-wrap: wrap;+ }+ .btn {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ padding: 12px 22px;+ border-radius: 12px;+ font-size: 15px;+ font-weight: 700;+ text-decoration: none;+ cursor: pointer;+ border: 1px solid transparent;+ transition: transform 0.14s ease, box-shadow 0.14s ease, background 0.14s ease, border-color 0.14s ease;+ }+ .btn--primary {+ color: #07070f;+ background: linear-gradient(135deg, var(--accent-2), var(--accent));+ box-shadow: 0 10px 32px rgba(124, 108, 255, 0.4);+ }+ .btn--primary:hover { transform: translateY(-2px); box-shadow: 0 16px 44px rgba(124, 108, 255, 0.55); }+ .btn--ghost {+ color: var(--fg);+ background: rgba(255, 255, 255, 0.04);+ border-color: var(--border);+ backdrop-filter: blur(8px);+ -webkit-backdrop-filter: blur(8px);+ }+ .btn--ghost:hover { transform: translateY(-2px); background: rgba(255, 255, 255, 0.08); border-color: var(--accent); }+ .btn:focus-visible { outline: 2px solid var(--accent-2); outline-offset: 3px; }+ .btn:active { transform: translateY(0); }++ /* Avatar switcher — top-center chips, drives the live subject. */+ .switcher {+ position: absolute;+ top: clamp(76px, 12svh, 120px);+ left: 50%;+ transform: translateX(-50%);+ z-index: 3;+ display: flex;+ gap: 8px;+ padding: 6px;+ border-radius: 999px;+ background: var(--card);+ border: 1px solid var(--border);+ backdrop-filter: blur(14px);+ -webkit-backdrop-filter: blur(14px);+ box-shadow: 0 8px 30px rgba(0, 0, 0, 0.45);+ max-width: calc(100vw - 32px);+ overflow-x: auto;+ scrollbar-width: none;+ }+ .switcher::-webkit-scrollbar { display: none; }+ .chip {+ appearance: none;+ border: 1px solid transparent;+ background: transparent;+ color: var(--muted);+ font: 600 13px Inter, system-ui, sans-serif;+ padding: 8px 16px;+ border-radius: 999px;+ cursor: pointer;+ white-space: nowrap;+ transition: color 0.14s ease, background 0.14s ease, border-color 0.14s ease;+ }+ .chip:hover { color: var(--fg); background: rgba(255, 255, 255, 0.05); }+ .chip[aria-pressed='true'] {+ color: #07070f;+ background: linear-gradient(135deg, var(--accent-2), var(--accent));+ }+ .chip:focus-visible { outline: 2px solid var(--accent-2); outline-offset: 2px; }++ .scroll-cue {+ position: absolute;+ bottom: 14px;+ left: 50%;+ transform: translateX(-50%);+ z-index: 3;+ color: var(--muted);+ font-size: 11px;+ letter-spacing: 0.14em;+ text-transform: uppercase;+ opacity: 0.7;+ animation: bob 2.4s ease-in-out infinite;+ }+ @keyframes bob { 0%, 100% { transform: translate(-50%, 0); } 50% { transform: translate(-50%, 6px); } }++ /* ── Build notes section ────────────────────────────────── */+ .notes {+ position: relative;+ z-index: 1;+ max-width: 1080px;+ margin: 0 auto;+ padding: clamp(56px, 10vw, 110px) 20px;+ }+ .notes-head { text-align: center; margin: 0 0 48px; }+ .notes-head h2 {+ font-size: clamp(26px, 4vw, 40px);+ margin: 0 0 12px;+ letter-spacing: -0.02em;+ }+ .notes-head p { color: var(--muted); margin: 0 auto; max-width: 56ch; line-height: 1.5; }+ .note-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));+ gap: 16px;+ }+ .note {+ background: var(--card);+ border: 1px solid var(--border);+ border-radius: var(--radius);+ padding: 24px;+ backdrop-filter: blur(10px);+ -webkit-backdrop-filter: blur(10px);+ transition: transform 0.18s ease, border-color 0.18s ease;+ }+ .note:hover { transform: translateY(-4px); border-color: var(--accent); }+ .note-num {+ font-size: 12px;+ font-weight: 700;+ color: var(--accent-2);+ letter-spacing: 0.1em;+ }+ .note h3 { margin: 10px 0 8px; font-size: 18px; }+ .note p { margin: 0; color: var(--muted); font-size: 14px; line-height: 1.55; }+ .note code {+ font-family: ui-monospace, 'SF Mono', Menlo, monospace;+ font-size: 12px;+ color: var(--accent-2);+ background: rgba(54, 224, 255, 0.08);+ padding: 1px 6px;+ border-radius: 5px;+ }++ @media (max-width: 600px) {+ .subject { width: 88vw; height: 56svh; }+ .hero-copy { bottom: 20px; }+ }+ @media (prefers-reduced-motion: reduce) {+ .skel-orb, .scroll-cue, .hero-copy { animation: none; }+ .subject agent-3d { transition: none; }+ }+ </style>+ </head>+ <body>+ <div id="nav-container"></div>++ <section class="hero" aria-label="Agent hero stage">+ <canvas id="stage" aria-hidden="true"></canvas>++ <div class="switcher" role="group" aria-label="Choose an avatar">+ <button class="chip" type="button" aria-pressed="true" data-glb="/avatars/realistic-female.glb">Nova</button>+ <button class="chip" type="button" aria-pressed="false" data-glb="/avatars/realistic-male.glb">Atlas</button>+ <button class="chip" type="button" aria-pressed="false" data-glb="/avatars/michelle.glb">Michelle</button>+ <button class="chip" type="button" aria-pressed="false" data-glb="/avatars/xbot.glb">X-Bot</button>+ <button class="chip" type="button" aria-pressed="false" data-glb="/avatars/fox.glb">Fox</button>+ </div>++ <div class="subject" id="subject">+ <div class="subject-skel" id="subject-skel" role="status" aria-label="Loading avatar">+ <div class="skel-orb"></div>+ </div>+ </div>++ <div class="hero-copy">+ <p class="eyebrow">three.ws · hero stage</p>+ <h1>Give your agent a stage worth screenshotting.</h1>+ <p>+ A lit avatar, centered in deep space over concentric glowing rings — bloom,+ a drifting starfield, and pointer parallax. Drop any GLB in and it just works.+ </p>+ <div class="cta-row">+ <a class="btn btn--primary" href="/create">Build your agent →</a>+ <a class="btn btn--ghost" href="/features">See every feature</a>+ </div>+ </div>++ <div class="scroll-cue" aria-hidden="true">scroll · how it's built</div>+ </section>++ <section class="notes" aria-labelledby="notes-h2">+ <div class="notes-head">+ <h2 id="notes-h2">How the stage is built</h2>+ <p>+ The atmosphere renders in its own WebGL context so it can be lit aggressively+ without washing out the subject. The avatar is a standard <code><agent-3d></code>+ on top — animation, voice, and payments included, untouched.+ </p>+ </div>+ <div class="note-grid">+ <article class="note">+ <span class="note-num">01</span>+ <h3>Concentric glow rings</h3>+ <p>Five additive <code>TorusGeometry</code> rings, tilted into a disc and tinted across the accent gradient. They breathe and counter-spin for depth.</p>+ </article>+ <article class="note">+ <span class="note-num">02</span>+ <h3>Bloom is the look</h3>+ <p>An <code>UnrealBloomPass</code> over the emissive rings and starfield carries ~70% of the aesthetic. High threshold so only the bright geometry glows.</p>+ </article>+ <article class="note">+ <span class="note-num">03</span>+ <h3>Calm, motion-safe drift</h3>+ <p>A golden-angle starfield drifts slowly while the camera eases toward the pointer for parallax. <code>prefers-reduced-motion</code> renders one still frame.</p>+ </article>+ </div>+ </section>++ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ <script src="/nav.js"></script>++ <!-- Full agent runtime: animation, transparent compositing, lazy by default. -->+ <script type="module" src="https://three.ws/agent-3d/latest/agent-3d.js"></script>++ <script type="module">+ import { HeroStage } from '/src/hero-stage.js';++ // ── Backdrop stage ──────────────────────────────────────+ // WebGL can be unavailable (headless, blocklisted GPU, lost context).+ // If the stage can't init, the CSS space gradient + vignette stand in+ // and the avatar below still loads — never let the backdrop take the+ // page down with it.+ const canvas = document.getElementById('stage');+ let stage = null;+ try {+ stage = new HeroStage(canvas, { accent: '#7c6cff', accent2: '#36e0ff' });+ stage.start();+ window.addEventListener('pagehide', () => stage?.dispose(), { once: true });+ } catch (err) {+ console.warn('[hero-demo] WebGL backdrop unavailable, using CSS fallback', err);+ canvas.hidden = true;+ }++ // ── Live subject (avatar) ───────────────────────────────+ const subject = document.getElementById('subject');+ const skel = document.getElementById('subject-skel');+ const chips = [...document.querySelectorAll('.switcher .chip')];+ let agentEl = null;+ let revealTimer = 0;++ function showSkeleton() {+ skel.hidden = false;+ if (agentEl) agentEl.classList.remove('ready');+ }+ function reveal() {+ clearTimeout(revealTimer);+ skel.hidden = true;+ agentEl?.classList.add('ready');+ }+ function showError(glb) {+ clearTimeout(revealTimer);+ skel.hidden = true;+ agentEl?.remove();+ agentEl = null;+ let err = subject.querySelector('.subject-error');+ if (!err) {+ err = document.createElement('div');+ err.className = 'subject-error';+ err.setAttribute('role', 'alert');+ err.innerHTML =+ '<p>This avatar couldn’t load right now.</p>' ++ '<button class="btn btn--ghost" type="button">Retry</button>';+ err.querySelector('button').addEventListener('click', () => {+ err.remove();+ loadAvatar(glb);+ });+ subject.appendChild(err);+ }+ }++ function loadAvatar(glb) {+ subject.querySelector('.subject-error')?.remove();+ if (agentEl) agentEl.remove();+ showSkeleton();++ agentEl = document.createElement('agent-3d');+ agentEl.setAttribute('body', glb);+ agentEl.setAttribute('mode', 'inline');+ agentEl.setAttribute('responsive', '');+ agentEl.setAttribute('background', 'transparent');+ agentEl.setAttribute('name-plate', 'off');+ agentEl.setAttribute('avatar-chat', 'off');+ agentEl.setAttribute('kiosk', '');+ agentEl.setAttribute('eager', '');++ agentEl.addEventListener('agent:ready', reveal, { once: true });+ agentEl.addEventListener('load', reveal, { once: true });+ agentEl.addEventListener('error', () => showError(glb), { once: true });+ // Failsafe: never strand the user on the skeleton if no event fires.+ revealTimer = setTimeout(reveal, 6000);++ subject.appendChild(agentEl);+ }++ chips.forEach((chip) => {+ chip.addEventListener('click', () => {+ if (chip.getAttribute('aria-pressed') === 'true') return;+ chips.forEach((c) => c.setAttribute('aria-pressed', 'false'));+ chip.setAttribute('aria-pressed', 'true');+ loadAvatar(chip.dataset.glb);+ });+ });++ const first = chips.find((c) => c.getAttribute('aria-pressed') === 'true') || chips[0];+ loadAvatar(first.dataset.glb);+ </script>+ </body>+</html>diff --git a/public/changelog.json b/public/changelog.jsonindex ff92c4ca9..39e20ef79 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-21T18:33:13.627Z",+ "generated_at": "2026-06-21T19:01:16.428Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -46,6 +46,16 @@"launch"]},+ {+ "date": "2026-06-21",+ "type": "launch",+ "title": "Hero Stage",+ "summary": "A cinematic 3D hero stage for three.ws agents — a lit avatar centered in deep space over concentric glowing rings, a drifting starfield, and soft bloom, with pointer parallax and a live avatar switcher. Motion-safe.",+ "link": "/hero-demo",+ "tags": [+ "launch"+ ]+ },{"date": "2026-06-21","type": "launch",@@ -56,6 +66,16 @@"launch"]},+ {+ "date": "2026-06-21",+ "type": "launch",+ "title": "The Agent Economy — Live",+ "summary": "The live three.ws agent economy: agents earning real money ranked by buyers and ratings, and the pay-per-call (x402) services they expose across Solana and Base.",+ "link": "/economy",+ "tags": [+ "launch"+ ]+ },{"date": "2026-06-21","type": "launch",@@ -158,6 +178,16 @@"fix"]},+ {+ "date": "2026-06-21",+ "type": "update",+ "title": "Agent Studio: save a draft or step away without losing work",+ "summary": "Agent Studio now carries a persistent header on every tab with Save draft and Exit. Your agent already saves automatically as you edit — Save draft commits your progress on demand with a clear confirmation, and Exit saves first, then opens your live agent. Move freely between Brain, Memory, Body, Money and Skills from the tab row at any time, so no single section is a dead end.",+ "link": "/agent-studio",+ "tags": [+ "improvement"+ ]+ },{"date": "2026-06-21","type": "update",@@ -210,6 +240,16 @@"improvement"]},+ {+ "date": "2026-06-21",+ "type": "update",+ "title": "Bring your creations to life — talk to them",+ "summary": "Made an avatar from a prompt, or a model in the Lab? A new Talk button drops you into a live voice conversation with it: speak, and it answers out loud with an AI brain and real-time lip-sync. Avatars take on a first-person persona; objects play along. Same voice + reasoning stack the rest of three.ws uses.",+ "link": "/forge-studio",+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-21","type": "update",@@ -809,6 +849,16 @@"feature"]},+ {+ "date": "2026-06-21",+ "type": "update",+ "title": "Studio Lab: turn any model into a Gaussian splat",+ "summary": "The Lab in Studio now owns the splat format both ways. A new Mesh → Splats tool resamples any model — a Lab generator or a GLB you upload — into a Gaussian-splat radiance field entirely in your browser, viewable live and downloadable as a real .splat file. The Splat Viewer also gained a download button, so you can pull down whatever you load. No API key, no upload, no cost.",+ "link": "/forge-studio",+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-21","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 0a7363137..c17c44dc1 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -38,6 +38,14 @@<category>launch</category><description>Recent activity from the people and agents you follow on three.ws.</description></item>+ <item>+ <title>Hero Stage</title>+ <link>https://three.ws/hero-demo</link>+ <guid isPermaLink="false">2026-06-21:Hero Stage</guid>+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>A cinematic 3D hero stage for three.ws agents — a lit avatar centered in deep space over concentric glowing rings, a drifting starfield, and soft bloom, with pointer parallax and a live avatar switcher. Motion-safe.</description>+ </item><item><title>Studio — Object + Avatar from text</title><link>https://three.ws/forge-studio</link>@@ -46,6 +54,14 @@<category>launch</category><description>One canvas for both text-to-3D pipelines: forge a textured object (GLB) in the Object tab, or describe a character and get a rigged avatar in the Avatar tab.</description></item>+ <item>+ <title>The Agent Economy — Live</title>+ <link>https://three.ws/economy</link>+ <guid isPermaLink="false">2026-06-21:The Agent Economy — Live</guid>+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>The live three.ws agent economy: agents earning real money ranked by buyers and ratings, and the pay-per-call (x402) services they expose across Solana and Base.</description>+ </item><item><title>Walk</title><link>https://three.ws/walk</link>@@ -126,6 +142,14 @@<category>fix</category><description>The Brain tab of Agent Studio could become unclickable — a full-screen dialog layer that's meant to stay hidden until you open Templates or the behavior view was rendering invisibly on top of the whole studio, swallowing every click. It now stays properly hidden until you actually open it, so the Brain tab is usable again.</description></item>+ <item>+ <title>Agent Studio: save a draft or step away without losing work</title>+ <link>https://three.ws/agent-studio</link>+ <guid isPermaLink="false">2026-06-21:Agent Studio: save a draft or step away without losing work</guid>+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>Agent Studio now carries a persistent header on every tab with Save draft and Exit. Your agent already saves automatically as you edit — Save draft commits your progress on demand with a clear confirmation, and Exit saves first, then opens your live agent. Move freely between Brain, Memory, Body, Money and Skills from the tab row at any time, so no single section is a dead end.</description>+ </item><item><title>Agent Studio: save your Brain and flow straight into Memory</title><link>https://three.ws/agent-studio</link>@@ -166,6 +190,14 @@<category>feature</category><description>The Color tab in Avatar Studio is no longer limited to a fixed row of swatches. Tap the rainbow chip on any of skin, hair, or outfit and a real color wheel opens — drag for any hue, slide for brightness, type or paste an exact hex code, or use the eyedropper to sample any color on your screen (where your browser supports it). Every color you pick is remembered in a 'Recent' strip so a palette carries from one part of the avatar to the next, and between sessions. New 'Looks' sit above the colors too: one tap themes skin, hair, and outfit together — Noir, Sunset, Arctic, Cyber, Rosé, Forest, Mono, Ember — and a whole picking session counts as a single undo. The wheel loads only when you open it, so the studio stays fast.</description></item>+ <item>+ <title>Bring your creations to life — talk to them</title>+ <link>https://three.ws/forge-studio</link>+ <guid isPermaLink="false">2026-06-21:Bring your creations to life — talk to them</guid>+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Made an avatar from a prompt, or a model in the Lab? A new Talk button drops you into a live voice conversation with it: speak, and it answers out loud with an AI brain and real-time lip-sync. Avatars take on a first-person persona; objects play along. Same voice + reasoning stack the rest of three.ws uses.</description>+ </item><item><title>Clearer empty state on the $THREE live-trades feed</title><link>https://three.ws/three-token</link>@@ -622,6 +654,14 @@<category>feature</category><description>The new Lab tab in Studio turns text and parameters into real 3D — no API key, no cost, nothing leaves your machine. Build math-driven parametric solids and supershapes, extrude 3D lettering from any string, turn an SVG icon or logo into a solid model, generate a lithophane relief from a photo, or grow a procedural landscape from a seed — each one previews live and downloads as a real GLB. Plus a Gaussian-splat viewer for the photoreal radiance-field format (.splat / .ply). Powered by three.js and GaussianSplats3D.</description></item>+ <item>+ <title>Studio Lab: turn any model into a Gaussian splat</title>+ <link>https://three.ws/forge-studio</link>+ <guid isPermaLink="false">2026-06-21:Studio Lab: turn any model into a Gaussian splat</guid>+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>The Lab in Studio now owns the splat format both ways. A new Mesh → Splats tool resamples any model — a Lab generator or a GLB you upload — into a Gaussian-splat radiance field entirely in your browser, viewable live and downloadable as a real .splat file. The Splat Viewer also gained a download button, so you can pull down whatever you load. No API key, no upload, no cost.</description>+ </item><item><title>The $THREE page now shows live market cap, holders & real trades</title><link>https://three.ws/three-token</link>diff --git a/public/features.json b/public/features.jsonindex 65e494a46..1f5c32bfb 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-21T18:33:13.608Z",+ "generated_at": "2026-06-21T19:01:16.416Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",@@ -1066,6 +1066,16 @@"tags": [],"showcase": false},+ {+ "path": "/economy",+ "title": "The Agent Economy — Live",+ "description": "The live three.ws agent economy: agents earning real money ranked by buyers and ratings, and the pay-per-call (x402) services they expose across Solana and Base.",+ "added": "2026-06-21",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },{"path": "/agent-trade","title": "Agent Commerce",@@ -1116,6 +1126,16 @@"tags": [],"showcase": false},+ {+ "path": "/hero-demo",+ "title": "Hero Stage",+ "description": "A cinematic 3D hero stage for three.ws agents — a lit avatar centered in deep space over concentric glowing rings, a drifting starfield, and soft bloom, with pointer parallax and a live avatar switcher. Motion-safe.",+ "added": "2026-06-21",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },{"path": "/evm-wallet","title": "EVM Vanity Wallet",diff --git a/public/llms-full.txt b/public/llms-full.txtindex 8b16cb5db..58d6cc75c 100644--- a/public/llms-full.txt+++ b/public/llms-full.txt@@ -646,6 +646,12 @@ URL: https://three.ws/agent-economyWatch two 3D AI agents transact on-chain. Agent A buys data from Agent B — real SOL, real Solana transaction, live.+### The Agent Economy — Live++URL: https://three.ws/economy++The live three.ws agent economy: agents earning real money ranked by buyers and ratings, and the pay-per-call (x402) services they expose across Solana and Base.+### Agent CommerceURL: https://three.ws/agent-trade@@ -676,6 +682,12 @@ URL: https://three.ws/coin3dAny pump.fun token as a live 3D scene — a spinning coin medallion with the token's logo, top holders as a galaxy sized by balance, and a graduation ring tracking bonding-curve progress.+### Hero Stage++URL: https://three.ws/hero-demo++A cinematic 3D hero stage for three.ws agents — a lit avatar centered in deep space over concentric glowing rings, a drifting starfield, and soft bloom, with pointer parallax and a live avatar switcher. Motion-safe.+### EVM Vanity WalletURL: https://three.ws/evm-walletdiff --git a/public/llms.txt b/public/llms.txtindex 2c45fb854..f10c8ccd2 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -127,11 +127,13 @@ On-chain features: pay-per-call, token launches, vanity wallets.- [Pole Club](https://three.ws/club): A 3D club where dancers only perform when you send a micro-tip. Pay $0.001 per routine, settled on-chain via x402 on Solana.- [Agent Exchange](https://three.ws/agent-exchange): Two AI agents with 3D bodies negotiate and pay each other for live crypto intel using x402 micropayments on Solana. Every transaction is real and confirmed on-chain.- [Agent Economy — Live Demo](https://three.ws/agent-economy): Watch two 3D AI agents transact on-chain. Agent A buys data from Agent B — real SOL, real Solana transaction, live.+- [The Agent Economy — Live](https://three.ws/economy): The live three.ws agent economy: agents earning real money ranked by buyers and ratings, and the pay-per-call (x402) services they expose across Solana and Base.- [Agent Commerce](https://three.ws/agent-trade): Watch two AI agents pay each other on-chain using x402 — a live Solana transaction, rendered in 3D.- [Avatar Wallet](https://three.ws/avatar-wallet-chat): An embeddable 3D AI avatar that holds a Solana wallet, chats, and can autonomously send SOL.- [Agent Economy — NOVA & ORACLE](https://three.ws/demo): Two three.ws AI agents with real Solana wallets discover services on the x402 bazaar, pay each other in SOL, and display a live market briefing on the TV in their world.- [Agent Economy — Live](https://three.ws/live): Two AI agents in a virtual world paying each other for live Solana market data. Real on-chain transactions, real blockchain, real 3D.- [Token in 3D](https://three.ws/coin3d): Any pump.fun token as a live 3D scene — a spinning coin medallion with the token's logo, top holders as a galaxy sized by balance, and a graduation ring tracking bonding-curve progress.+- [Hero Stage](https://three.ws/hero-demo): A cinematic 3D hero stage for three.ws agents — a lit avatar centered in deep space over concentric glowing rings, a drifting starfield, and soft bloom, with pointer parallax and a live avatar switcher. Motion-safe.- [EVM Vanity Wallet](https://three.ws/evm-wallet): Grind a custom Ethereum / EVM wallet address with the prefix or suffix of your choice. A real secp256k1 keypair, generated entirely in your browser — the private key never leaves your device.## Agent Toolsdiff --git a/public/sitemap/index.html b/public/sitemap/index.htmlindex 1afa2bf8d..fcfd7f592 100644--- a/public/sitemap/index.html+++ b/public/sitemap/index.html@@ -65,7 +65,7 @@<main class="sm-wrap"><div class="sm-hero"><h1>Sitemap</h1>- <p>All 188 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>+ <p>All 190 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p><div class="sm-formats"><a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a><a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>@@ -77,7 +77,7 @@</div><div class="sm-filter"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>- <input id="sm-filter-input" type="search" placeholder="Filter 188 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />+ <input id="sm-filter-input" type="search" placeholder="Filter 190 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" /><kbd aria-hidden="true">/</kbd></div><p class="sm-filter-count" id="sm-filter-count" role="status" aria-live="polite"></p>@@ -528,7 +528,7 @@<section class="sm-section" id="crypto"><header>- <h2>Crypto<span class="sm-count" data-count>51</span></h2>+ <h2>Crypto<span class="sm-count" data-count>53</span></h2><p class="sm-section-desc">On-chain features: pay-per-call, token launches, vanity wallets.</p></header><ul class="sm-list">@@ -847,6 +847,13 @@<span class="sm-desc">Watch two 3D AI agents transact on-chain. Agent A buys data from Agent B — real SOL, real Solana transaction, live.</span></a></li>+ <li>+ <a href="/economy">+ <span class="sm-title">The Agent Economy — Live</span>+ <span class="sm-path">/economy</span>+ <span class="sm-desc">The live three.ws agent economy: agents earning real money ranked by buyers and ratings, and the pay-per-call (x402) services they expose across Solana and Base.</span>+ </a>+ </li><li><a href="/agent-trade"><span class="sm-title">Agent Commerce</span>@@ -882,6 +889,13 @@<span class="sm-desc">Any pump.fun token as a live 3D scene — a spinning coin medallion with the token's logo, top holders as a galaxy sized by balance, and a graduation ring tracking bonding-curve progress.</span></a></li>+ <li>+ <a href="/hero-demo">+ <span class="sm-title">Hero Stage</span>+ <span class="sm-path">/hero-demo</span>+ <span class="sm-desc">A cinematic 3D hero stage for three.ws agents — a lit avatar centered in deep space over concentric glowing rings, a drifting starfield, and soft bloom, with pointer parallax and a live avatar switcher. Motion-safe.</span>+ </a>+ </li><li><a href="/evm-wallet"><span class="sm-title">EVM Vanity Wallet</span>diff --git a/src/economy-live.js b/src/economy-live.jsnew file mode 100644index 000000000..9ede7d5a2--- /dev/null+++ b/src/economy-live.js@@ -0,0 +1,197 @@+/**+ * The Agent Economy — live across the network (Pillar 3).+ *+ * The /agent-economy page is a curated two-agent on-chain demo. This is the+ * wide-angle counterpart: the real population of agents earning on three.ws and+ * the paid services they expose over x402. Reads real, keyless endpoints+ * (no mocks):+ * - GET /api/marketplace/agents — published agents with ratings, buyer counts+ * and on-chain pricing.+ * - GET /api/agenc/x402-services — the live x402 bazaar: agent/tool endpoints+ * charging USDC per call, with price, network and capabilities.+ *+ * Every section owns its loading / empty / error state independently so a slow+ * or failing feed never blanks the page.+ */++const $ = (sel) => /** @type {HTMLElement} */ (document.querySelector(sel));++// ── Formatting helpers ────────────────────────────────────────────────────────++function fmtUsd(amountAtomics, decimals) {+ const d = Number.isFinite(decimals) ? decimals : 6;+ const n = Number(amountAtomics) / 10 ** d;+ if (!Number.isFinite(n)) return null;+ if (n === 0) return 'Free';+ if (n < 0.01) return `$${n.toFixed(4)}`;+ return `$${n.toFixed(2)}`;+}++function esc(s) {+ return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));+}++function chainLabel(chain) {+ const c = String(chain || '').toLowerCase();+ if (c.includes('sol')) return 'Solana';+ if (c.includes('base')) return 'Base';+ if (c.includes('eth')) return 'Ethereum';+ return chain || '';+}++function stars(avg, count) {+ if (!count) return '<span class="ae-muted">No ratings yet</span>';+ const a = Math.round((Number(avg) || 0) * 10) / 10;+ return `<span class="ae-stars" aria-label="${a} out of 5">★ ${a.toFixed(1)}</span> <span class="ae-muted">(${count})</span>`;+}++// ── State rendering ───────────────────────────────────────────────────────────++function skeleton(host, n, kind) {+ host.innerHTML = '';+ for (let i = 0; i < n; i++) {+ const s = document.createElement('div');+ s.className = `ae-skel ae-skel-${kind}`;+ host.appendChild(s);+ }+}++function emptyState(host, title, hint) {+ host.innerHTML = `<div class="ae-empty"><p class="ae-empty-title">${esc(title)}</p><p class="ae-muted">${esc(hint)}</p></div>`;+}++function errorState(host, retryFn) {+ host.innerHTML = '';+ const box = document.createElement('div');+ box.className = 'ae-error';+ box.innerHTML = `<p>Couldn't load this feed.</p>`;+ const btn = document.createElement('button');+ btn.className = 'ae-retry';+ btn.type = 'button';+ btn.textContent = 'Retry';+ btn.addEventListener('click', retryFn);+ box.appendChild(btn);+ host.appendChild(box);+}++// ── Section: earning agents ───────────────────────────────────────────────────++function agentCard(a) {+ const thumb = a.thumbnail_url || '';+ const price = a.price ? fmtUsd(a.price.amount, a.price.mint_decimals) : null;+ const priceChip = price+ ? `<span class="ae-chip ae-chip-price">${esc(price)}${a.price?.chain ? ` · ${esc(chainLabel(a.price.chain))}` : ''}</span>`+ : a.has_paid_skills ? '<span class="ae-chip">Paid skills</span>' : '<span class="ae-chip ae-chip-free">Free</span>';+ const buyers = Number(a.buyers_total) || 0;+ const buyers24 = Number(a.buyers_24h) || 0;+ return `+ <a class="ae-card" href="/marketplace/agents/${encodeURIComponent(a.id)}">+ <div class="ae-card-top">+ <div class="ae-avatar">${thumb ? `<img src="${esc(thumb)}" alt="" loading="lazy" />` : `<span class="ae-avatar-fallback">${esc((a.name || '?').slice(0, 1).toUpperCase())}</span>`}</div>+ <div class="ae-card-head">+ <span class="ae-card-name">${esc(a.name || 'Untitled agent')}</span>+ <span class="ae-muted ae-card-cat">${esc(a.category || 'general')}</span>+ </div>+ </div>+ <p class="ae-card-desc">${esc((a.description || '').slice(0, 110))}</p>+ <div class="ae-card-foot">+ <span class="ae-rating">${stars(a.rating_avg, a.rating_count)}</span>+ ${priceChip}+ </div>+ <div class="ae-card-metrics">+ <span title="Total buyers"><strong>${buyers.toLocaleString()}</strong> buyers</span>+ ${buyers24 > 0 ? `<span class="ae-up" title="Buyers in the last 24h">▲ ${buyers24.toLocaleString()} / 24h</span>` : ''}+ </div>+ </a>`;+}++async function loadAgents() {+ const host = $('#ae-agents');+ if (!host) return;+ skeleton(host, 6, 'card');+ try {+ const params = new URLSearchParams({ sort: 'top_rated', limit: '24' });+ const r = await fetch(`/api/marketplace/agents?${params}`, { credentials: 'include' });+ if (!r.ok) throw new Error(`status ${r.status}`);+ const j = await r.json();+ const items = j?.data?.items || j?.items || [];+ if (!items.length) {+ emptyState(host, 'No published agents yet', 'Be the first — build an agent and price a skill.');+ setStat('#ae-stat-agents', '0');+ return;+ }+ host.innerHTML = items.map(agentCard).join('');+ setStat('#ae-stat-agents', items.length >= 24 ? '24+' : String(items.length));+ const earners = items.filter((a) => (Number(a.buyers_total) || 0) > 0).length;+ setStat('#ae-stat-earning', String(earners));+ } catch (err) {+ errorState(host, loadAgents);+ // eslint-disable-next-line no-console+ console.error('[economy-live] agents', err);+ }+}++// ── Section: live x402 services ───────────────────────────────────────────────++function serviceRow(t) {+ const price = t.price?.amountLabel+ ? `${esc(t.price.amountLabel)}${t.price.currency ? ` ${esc(t.price.currency)}` : ''}`+ : 'Free';+ const net = t.price?.network ? chainLabel(t.price.network) : '';+ const method = t.method ? `<span class="ae-svc-method">${esc(t.method)}</span>` : '';+ const tags = (t.tags || []).slice(0, 3).map((x) => `<span class="ae-tag">${esc(x)}</span>`).join('');+ return `+ <a class="ae-svc" href="${esc(t.resource || '#')}" rel="noopener" target="_blank">+ <div class="ae-svc-main">+ <span class="ae-svc-name">${method}${esc(t.serviceName || t.toolName || 'Service')}</span>+ <span class="ae-svc-desc ae-muted">${esc((t.description || '').slice(0, 120))}</span>+ <span class="ae-svc-tags">${tags}</span>+ </div>+ <div class="ae-svc-price">+ <span class="ae-chip ae-chip-price">${price}</span>+ ${net ? `<span class="ae-muted ae-svc-net">${esc(net)}</span>` : ''}+ </div>+ </a>`;+}++async function loadServices() {+ const host = $('#ae-services');+ if (!host) return;+ skeleton(host, 5, 'row');+ try {+ const params = new URLSearchParams({ type: 'http', maxItems: '40' });+ const r = await fetch(`/api/agenc/x402-services?${params}`);+ if (!r.ok) throw new Error(`status ${r.status}`);+ const j = await r.json();+ const tasks = j?.tasks || [];+ if (!tasks.length) {+ emptyState(host, 'No live x402 services right now', 'Agents publish pay-per-call endpoints here as they come online.');+ setStat('#ae-stat-services', '0');+ return;+ }+ host.innerHTML = tasks.map(serviceRow).join('');+ setStat('#ae-stat-services', tasks.length >= 40 ? '40+' : String(tasks.length));+ } catch (err) {+ errorState(host, loadServices);+ // eslint-disable-next-line no-console+ console.error('[economy-live] services', err);+ }+}++function setStat(sel, value) {+ const el = $(sel);+ if (el) el.textContent = value;+}++export function initEconomyLive() {+ loadAgents();+ loadServices();+}++if (typeof document !== 'undefined') {+ if (document.readyState === 'loading') {+ document.addEventListener('DOMContentLoaded', initEconomyLive, { once: true });+ } else {+ initEconomyLive();+ }+}diff --git a/src/forge-studio/create-prompt.js b/src/forge-studio/create-prompt.jsindex f802fc82c..36fe7b16e 100644--- a/src/forge-studio/create-prompt.js+++ b/src/forge-studio/create-prompt.js@@ -228,6 +228,25 @@ async function renderDone(avatarId) {const viewer = /** @type {any} */ ($('#cp-done-model'));if (modelUrl && viewer) viewer.setAttribute('src', modelUrl);+ // Bring it alive — hand the finished avatar to the real talk stack (voice in,+ // LLM brain, voice out, lip-sync). Per-agent memory rides along via agent_id.+ const talkBtn = $('#cp-talk');+ if (talkBtn) {+ const name = avatar?.display_name || avatar?.name || 'Your avatar';+ talkBtn.hidden = !modelUrl;+ talkBtn.addEventListener('click', async () => {+ talkBtn.disabled = true;+ try {+ const { launchTalk } = await import('./talk-launch.js');+ await launchTalk({ name, glbUrl: modelUrl, id: avatarId, agentId: avatar?.agent_id, kind: 'avatar' });+ } catch (err) {+ log.error('[studio-prompt] talk', err);+ } finally {+ talkBtn.disabled = false;+ }+ });+ }+const rigged = avatar?.source_meta?.is_rigged ?? avatar?.tags?.includes?.('rigged');const tagsEl = $('#cp-done-tags');tagsEl.innerHTML = '';diff --git a/src/forge-studio/lab/lab.js b/src/forge-studio/lab/lab.jsindex ecbb433e6..228723798 100644--- a/src/forge-studio/lab/lab.js+++ b/src/forge-studio/lab/lab.js@@ -6,6 +6,9 @@* from npm `three` + its github examples/jsm addons. Each builds a real* THREE.Object3D, which we export to a binary GLB (GLTFExporter) and preview* in <model-viewer> with a working Download GLB button.+ * - Mesh → Gaussian-splat conversion (mesh-to-splat.js): our own splat+ * generation lane — resamples any mesh (a Lab model or an uploaded GLB) into+ * a Gaussian-splat radiance field, downloadable as a real .splat file.* - A Gaussian-splat / radiance-field viewer from the npm package* `@mkkellogg/gaussian-splats-3d` — a 3D representation the platform didn't* have. Loads a .splat/.ply (or a generated sample) into its own renderer.@@ -16,24 +19,50 @@import * as THREE from 'three';import { GLTFExporter } from 'three/addons/exporters/GLTFExporter.js';+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';import { GENERATORS } from './generators.js';+import { meshToSplatBuffer } from './mesh-to-splat.js';+import { launchTalk } from '../talk-launch.js';let _inited = false;let _activeId = null;let _lastGlbUrl = null;-let _splat = null; // lazy { viewer, dispose }+let _lastGlbBlob = null; // last mesh GLB blob (for "Bring it alive")+let _lastLabel = '';+let _lastSplatUrl = null;+let _lastObject = null; // live Object3D from the last mesh gen (for splat conversion)+let _splat = null; // lazy { viewer, url }++const MESHSPLAT_TOOL = {+ id: 'meshsplat',+ label: 'Mesh → Splats',+ blurb: 'Our own splat lane: resample any mesh — a Lab model or an uploaded GLB — into a Gaussian-splat radiance field, downloadable as .splat.',+ kind: 'meshsplat',+ controls: [+ {+ key: 'source', label: 'Source', type: 'select', default: 'last',+ options: [+ { value: 'last', label: 'Last Lab model' },+ { value: 'upload', label: 'Upload a GLB/GLTF' },+ ],+ },+ { key: 'glb', label: 'GLB / GLTF file', type: 'glbfile', default: null, when: { source: 'upload' } },+ { key: 'count', label: 'Splat count', type: 'range', min: 4000, max: 120000, step: 2000, default: 40000 },+ { key: 'seed', label: 'Seed', type: 'range', min: 1, max: 999, step: 1, default: 7 },+ ],+};const SPLAT_TOOL = {id: 'splat',- label: 'Gaussian Splats',- blurb: 'View a Gaussian-splat / radiance-field capture (.splat or .ply) — the photoreal 3D format. Drop a file, or render the built-in sample.',+ label: 'Splat Viewer',+ blurb: 'View a Gaussian-splat / radiance-field capture (.splat / .ply) — the photoreal 3D format. Drop a file, or render the built-in sample.',kind: 'splat',controls: [{ key: 'file', label: 'Splat file (.splat / .ply / .ksplat)', type: 'splatfile', default: null },],};-const TOOLS = [...GENERATORS.map((g) => ({ ...g, kind: 'mesh' })), SPLAT_TOOL];+const TOOLS = [...GENERATORS.map((g) => ({ ...g, kind: 'mesh' })), MESHSPLAT_TOOL, SPLAT_TOOL];// ── DOM helpers ───────────────────────────────────────────────────────────────@@ -92,7 +121,7 @@ function currentValues() {continue;}if (f.type === 'checkbox') values[f.key] = node.checked;- else if (f.type === 'image' || f.type === 'splatfile') values[f.key] = node._fileData ?? f.default;+ else if (f.type === 'image' || f.type === 'splatfile' || f.type === 'glbfile') values[f.key] = node._fileData ?? f.default;else values[f.key] = node.value;}return values;@@ -102,8 +131,6 @@ function renderControls() {const tool = TOOLS.find((t) => t.id === _activeId);const host = $('#lab-controls');host.innerHTML = '';- const values = {};- for (const f of tool.controls) values[f.key] = f.default;for (const f of tool.controls) {const wrap = el('div', { class: 'lab-field', id: `lab-field-wrap-${f.key}` });@@ -147,10 +174,11 @@ function renderControls() {input.value = f.default || '';wrap.appendChild(labelRow);wrap.appendChild(input);- } else if (f.type === 'image' || f.type === 'splatfile') {- const accept = f.type === 'image' ? 'image/*' : '.splat,.ply,.ksplat';+ } else if (f.type === 'image' || f.type === 'splatfile' || f.type === 'glbfile') {+ const accept = f.type === 'image' ? 'image/*' : f.type === 'glbfile' ? '.glb,.gltf,model/gltf-binary' : '.splat,.ply,.ksplat';input = el('input', { type: 'file', id: `lab-field-${f.key}`, accept });- const hint = el('span', { class: 'lab-field-out', text: f.type === 'image' ? 'optional — uses a sample if empty' : 'optional — renders a sample if empty' });+ const hintText = f.type === 'image' ? 'optional — uses a sample if empty' : f.type === 'glbfile' ? 'pick a .glb / .gltf' : 'optional — renders a sample if empty';+ const hint = el('span', { class: 'lab-field-out', text: hintText });input.addEventListener('change', async () => {const file = input.files?.[0];if (!file) { input._fileData = null; return; }@@ -187,16 +215,36 @@ function selectTool(id) {}const tool = TOOLS.find((t) => t.id === id);renderControls();- const isSplat = tool.kind === 'splat';- $('#lab-viewer').hidden = isSplat;- $('#lab-splat').hidden = !isSplat;- $('#lab-download').classList.toggle('is-hidden', isSplat);- $('#lab-generate').textContent = isSplat ? 'Render splats' : 'Generate model';+ const splatLike = tool.kind === 'splat' || tool.kind === 'meshsplat';+ $('#lab-viewer').hidden = splatLike;+ $('#lab-splat').hidden = !splatLike;+ $('#lab-generate').textContent =+ tool.kind === 'mesh' ? 'Generate model' :+ tool.kind === 'meshsplat' ? 'Convert to splats' : 'Render splats';+ // Hide download until there's something to download for this tool kind.+ resetDownload();+ // "Bring it alive" only applies to mesh GLBs (talk-mode needs a GLB), and+ // only once one has been generated.+ $('#lab-talk').classList.toggle('is-hidden', !(tool.kind === 'mesh' && _lastGlbBlob));status('');- if (!isSplat) teardownSplat();+ if (!splatLike) teardownSplat();}-// ── Generate (mesh → GLB) ─────────────────────────────────────────────────────+function resetDownload() {+ const dl = $('#lab-download');+ dl.classList.add('is-disabled');+ dl.removeAttribute('href');+}++function setDownload(url, filename, label) {+ const dl = $('#lab-download');+ dl.href = url;+ dl.setAttribute('download', filename);+ dl.querySelector('.lab-dl-label').textContent = label;+ dl.classList.remove('is-disabled');+}++// ── Generate ──────────────────────────────────────────────────────────────────async function exportGlb(object3d) {const exporter = new GLTFExporter();@@ -204,32 +252,33 @@ async function exportGlb(object3d) {return new Blob([result], { type: 'model/gltf-binary' });}+async function loadGlbScene(arrayBuffer) {+ const loader = new GLTFLoader();+ const gltf = await loader.parseAsync(arrayBuffer, '');+ return gltf.scene;+}++function disposeObject(obj) {+ if (!obj) return;+ obj.traverse((o) => {+ o.geometry?.dispose?.();+ const mats = Array.isArray(o.material) ? o.material : o.material ? [o.material] : [];+ for (const m of mats) m.dispose?.();+ });+}+async function generate() {const tool = TOOLS.find((t) => t.id === _activeId);const btn = $('#lab-generate');btn.disabled = true;try {if (tool.kind === 'splat') {- await renderSplats();- return;+ await renderSplatFile();+ } else if (tool.kind === 'meshsplat') {+ await convertToSplats();+ } else {+ await generateMesh(tool);}- status('Building geometry…');- const params = currentValues();- const object = await tool.build(params);- object.name = tool.label;- status('Exporting GLB…');- const blob = await exportGlb(object);- if (_lastGlbUrl) URL.revokeObjectURL(_lastGlbUrl);- _lastGlbUrl = URL.createObjectURL(blob);- const viewer = $('#lab-viewer');- viewer.setAttribute('src', _lastGlbUrl);- const dl = $('#lab-download');- dl.href = _lastGlbUrl;- dl.setAttribute('download', `${tool.id}-${Date.now()}.glb`);- dl.classList.remove('is-disabled');- // Free the geometry/material we just exported.- object.traverse((o) => { o.geometry?.dispose?.(); o.material?.dispose?.(); });- status(`${tool.label} ready · ${(blob.size / 1024).toFixed(0)} KB GLB`, 'ok');} catch (err) {status(err.message || 'Generation failed.', 'err');// eslint-disable-next-line no-console@@ -239,37 +288,87 @@ async function generate() {}}+async function generateMesh(tool) {+ status('Building geometry…');+ const params = currentValues();+ const object = await tool.build(params);+ object.name = tool.label;+ status('Exporting GLB…');+ const blob = await exportGlb(object);+ if (_lastGlbUrl) URL.revokeObjectURL(_lastGlbUrl);+ _lastGlbUrl = URL.createObjectURL(blob);+ $('#lab-viewer').setAttribute('src', _lastGlbUrl);+ setDownload(_lastGlbUrl, `${tool.id}-${Date.now()}.glb`, 'Download GLB');+ _lastGlbBlob = blob;+ _lastLabel = tool.label;+ $('#lab-talk').classList.remove('is-hidden');+ // Keep the live object so Mesh → Splats can convert it; dispose the prior one.+ disposeObject(_lastObject);+ _lastObject = object;+ status(`${tool.label} ready · ${(blob.size / 1024).toFixed(0)} KB GLB · now try Mesh → Splats`, 'ok');+}++async function bringAlive() {+ if (!_lastGlbBlob) return;+ const btn = $('#lab-talk');+ btn.disabled = true;+ try {+ await launchTalk({ name: _lastLabel || 'Your creation', glbBlob: _lastGlbBlob, kind: 'object' });+ } catch (err) {+ status(err.message || 'Could not start talk mode.', 'err');+ // eslint-disable-next-line no-console+ console.error('[studio-lab] talk', err);+ } finally {+ btn.disabled = false;+ }+}++async function convertToSplats() {+ const params = currentValues();+ let source = _lastObject;+ let sourceLabel = 'last Lab model';+ if (params.source === 'upload') {+ const f = params.glb;+ if (!f?.buffer) throw new Error('Choose a .glb / .gltf file to convert.');+ status('Loading GLB…');+ source = await loadGlbScene(f.buffer);+ sourceLabel = f.name;+ }+ if (!source) throw new Error('No model yet — generate one with a mesh tool first, or upload a GLB.');+ status('Sampling surface into Gaussians…');+ const { buffer, count } = meshToSplatBuffer(source, { count: Number(params.count), seed: Number(params.seed) });+ if (params.source === 'upload') disposeObject(source); // free the uploaded scene+ await renderSplatBuffer(buffer, `${count.toLocaleString()} splats from ${sourceLabel}`);+ // .splat download+ if (_lastSplatUrl) URL.revokeObjectURL(_lastSplatUrl);+ _lastSplatUrl = URL.createObjectURL(new Blob([buffer], { type: 'application/octet-stream' }));+ setDownload(_lastSplatUrl, `meshsplat-${Date.now()}.splat`, 'Download .splat');+}+// ── Gaussian splats ───────────────────────────────────────────────────────────-// Build a sample .splat cloud (antimatter15 format: 32 bytes/splat —-// center f32×3, scale f32×3, color u8×4, rotation u8×4). A rainbow sphere shell.+// Built-in sample: a rainbow fibonacci-sphere shell in the antimatter15 .splat+// layout (32 bytes/splat).function sampleSplatBuffer(count = 4000) {const buf = new ArrayBuffer(count * 32);const f = new DataView(buf);const col = new THREE.Color();for (let i = 0; i < count; i++) {const base = i * 32;- // Fibonacci sphere for even coverage.const t = i / count;const phi = Math.acos(1 - 2 * t);const theta = Math.PI * (1 + Math.sqrt(5)) * i;- const r = 1;- const x = r * Math.sin(phi) * Math.cos(theta);- const y = r * Math.cos(phi);- const z = r * Math.sin(phi) * Math.sin(theta);- f.setFloat32(base, x, true);- f.setFloat32(base + 4, y, true);- f.setFloat32(base + 8, z, true);- // scale (log-free world units for .splat)+ f.setFloat32(base, Math.sin(phi) * Math.cos(theta), true);+ f.setFloat32(base + 4, Math.cos(phi), true);+ f.setFloat32(base + 8, Math.sin(phi) * Math.sin(theta), true);f.setFloat32(base + 12, 0.03, true);f.setFloat32(base + 16, 0.03, true);f.setFloat32(base + 20, 0.03, true);- col.setHSL((y + 1) / 2, 0.7, 0.55);+ col.setHSL((Math.cos(phi) + 1) / 2, 0.7, 0.55);f.setUint8(base + 24, Math.round(col.r * 255));f.setUint8(base + 25, Math.round(col.g * 255));f.setUint8(base + 26, Math.round(col.b * 255));f.setUint8(base + 27, 255);- // identity rotation: (w,x,y,z) bytesf.setUint8(base + 28, 255);f.setUint8(base + 29, 128);f.setUint8(base + 30, 128);@@ -278,27 +377,43 @@ function sampleSplatBuffer(count = 4000) {return buf;}-async function renderSplats() {- status('Loading splat engine…');- const GS = await import('@mkkellogg/gaussian-splats-3d');- teardownSplat();- const host = $('#lab-splat');- host.innerHTML = '';-+async function renderSplatFile() {const fileField = $('#lab-field-file');const uploaded = fileField?._fileData || null;- let url, format;+ let buffer, format, label;+ const GS = await loadSplatLib();if (uploaded) {- url = URL.createObjectURL(new Blob([uploaded.buffer]));+ buffer = uploaded.buffer;format =uploaded.name.endsWith('.ply') ? GS.SceneFormat.Ply :uploaded.name.endsWith('.ksplat') ? GS.SceneFormat.KSplat :GS.SceneFormat.Splat;+ label = `Loaded ${uploaded.name}`;} else {- url = URL.createObjectURL(new Blob([sampleSplatBuffer()]));+ buffer = sampleSplatBuffer();format = GS.SceneFormat.Splat;+ label = 'Sample radiance field · 4,000 splats';}+ await renderSplatBuffer(buffer, label, format);+ // Allow re-downloading the loaded/sample splat.+ if (_lastSplatUrl) URL.revokeObjectURL(_lastSplatUrl);+ _lastSplatUrl = URL.createObjectURL(new Blob([buffer], { type: 'application/octet-stream' }));+ setDownload(_lastSplatUrl, uploaded ? uploaded.name : 'sample.splat', 'Download .splat');+}++let _GS = null;+async function loadSplatLib() {+ if (!_GS) _GS = await import('@mkkellogg/gaussian-splats-3d');+ return _GS;+}+async function renderSplatBuffer(buffer, label, format) {+ status('Loading splat engine…');+ const GS = await loadSplatLib();+ await teardownSplat();+ const host = $('#lab-splat');+ host.innerHTML = '';+ const url = URL.createObjectURL(new Blob([buffer]));const viewer = new GS.Viewer({rootElement: host,sharedMemoryForWorkers: false,@@ -311,20 +426,24 @@ async function renderSplats() {});_splat = { viewer, url };status('Rendering splats…');- await viewer.addSplatScene(url, { format, showLoadingUI: false, progressiveLoad: false });+ await viewer.addSplatScene(url, { format: format ?? GS.SceneFormat.Splat, showLoadingUI: false, progressiveLoad: false });viewer.start();- const total = viewer.getSplatCount ? viewer.getSplatCount() : null;- status(uploaded ? `Loaded ${uploaded.name}${total ? ` · ${total.toLocaleString()} splats` : ''}` : `Sample radiance field · ${total ? total.toLocaleString() : '4,000'} splats`, 'ok');+ status(label, 'ok');}-function teardownSplat() {+async function teardownSplat() {if (!_splat) return;- try {- _splat.viewer.stop?.();- _splat.viewer.dispose?.();- } catch { /* viewer may already be torn down */ }- if (_splat.url) URL.revokeObjectURL(_splat.url);+ const s = _splat;_splat = null;+ try {+ s.viewer.stop?.();+ // dispose() cleans up the renderer + its canvas first, then tries to+ // document.body.removeChild(rootElement) — which throws because our root+ // (#lab-splat) is nested, not a direct child of body. Everything we care+ // about is already torn down by then, so we await and swallow that one.+ await s.viewer.dispose?.();+ } catch { /* harmless nested-root removeChild from the splat lib */ }+ if (s.url) URL.revokeObjectURL(s.url);const host = document.getElementById('lab-splat');if (host) host.innerHTML = '';}@@ -346,5 +465,6 @@ export function initLab() {_inited = true;renderToolPicker();$('#lab-generate').addEventListener('click', generate);+ $('#lab-talk').addEventListener('click', bringAlive);selectTool(TOOLS[0].id);}diff --git a/src/forge-studio/lab/mesh-to-splat.js b/src/forge-studio/lab/mesh-to-splat.jsnew file mode 100644index 000000000..46224a088--- /dev/null+++ b/src/forge-studio/lab/mesh-to-splat.js@@ -0,0 +1,147 @@+/**+ * Mesh → Gaussian-splat conversion — three.ws's own splat-generation lane.+ *+ * Instead of renting a text-to-splat API, we own the format both ways: any mesh+ * the platform can produce (a Lab generator, a forged GLB, an uploaded model)+ * gets resampled into a Gaussian-splat radiance field entirely in the browser.+ *+ * Approach: area-weighted surface sampling. We walk every triangle, sample N+ * points proportional to triangle area, read colour from vertex colours (or the+ * material base colour as a fallback), and emit each point as one Gaussian in+ * the antimatter15 `.splat` layout (32 bytes/splat: center f32×3, scale f32×3,+ * colour u8×4, rotation u8×4). The result loads straight into the splat viewer+ * and downloads as a real `.splat` file.+ */++import * as THREE from 'three';++const _v = {+ a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3(),+ ab: new THREE.Vector3(), ac: new THREE.Vector3(), cross: new THREE.Vector3(),+ p: new THREE.Vector3(),+ ca: new THREE.Color(), cb: new THREE.Color(), cc: new THREE.Color(), cp: new THREE.Color(),+};++function collectMeshes(object3d) {+ const meshes = [];+ object3d.updateMatrixWorld(true);+ object3d.traverse((o) => { if (o.isMesh && o.geometry?.attributes?.position) meshes.push(o); });+ return meshes;+}++// Build a flat list of triangles with world-space positions + per-vertex colours.+function gatherTriangles(meshes) {+ const tris = [];+ for (const mesh of meshes) {+ const geo = mesh.geometry;+ const pos = geo.attributes.position;+ const colAttr = geo.attributes.color || null;+ const matColor = new THREE.Color(1, 1, 1);+ const m = Array.isArray(mesh.material) ? mesh.material[0] : mesh.material;+ if (m?.color) matColor.copy(m.color);+ const index = geo.index;+ const triCount = index ? index.count / 3 : pos.count / 3;+ for (let t = 0; t < triCount; t++) {+ const i0 = index ? index.getX(t * 3) : t * 3;+ const i1 = index ? index.getX(t * 3 + 1) : t * 3 + 1;+ const i2 = index ? index.getX(t * 3 + 2) : t * 3 + 2;+ const a = _v.a.fromBufferAttribute(pos, i0).applyMatrix4(mesh.matrixWorld).clone();+ const b = _v.b.fromBufferAttribute(pos, i1).applyMatrix4(mesh.matrixWorld).clone();+ const c = _v.c.fromBufferAttribute(pos, i2).applyMatrix4(mesh.matrixWorld).clone();+ const ca = colAttr ? new THREE.Color().fromBufferAttribute(colAttr, i0) : matColor.clone();+ const cb = colAttr ? new THREE.Color().fromBufferAttribute(colAttr, i1) : matColor.clone();+ const cc = colAttr ? new THREE.Color().fromBufferAttribute(colAttr, i2) : matColor.clone();+ const area = _v.ab.subVectors(b, a).cross(_v.ac.subVectors(c, a)).length() * 0.5;+ tris.push({ a, b, c, ca, cb, cc, area });+ }+ }+ return tris;+}++// Deterministic PRNG so the same model + seed always yields the same splat cloud.+function mulberry32(seed) {+ let s = seed >>> 0;+ return () => {+ s |= 0; s = (s + 0x6d2b79f5) | 0;+ let t = Math.imul(s ^ (s >>> 15), 1 | s);+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}++/**+ * Convert a THREE.Object3D into a `.splat` ArrayBuffer.+ * @param {THREE.Object3D} object3d+ * @param {{count?:number, seed?:number, scale?:number}} [opts]+ * @returns {{buffer: ArrayBuffer, count: number}}+ */+export function meshToSplatBuffer(object3d, opts = {}) {+ const count = Math.max(500, Math.min(200000, Math.floor(opts.count ?? 30000)));+ const seed = Math.floor(opts.seed ?? 1);+ const meshes = collectMeshes(object3d);+ if (!meshes.length) throw new Error('No mesh geometry to convert.');+ const tris = gatherTriangles(meshes);+ if (!tris.length) throw new Error('No triangles found in the model.');++ // Cumulative area table for weighted sampling.+ const cum = new Float64Array(tris.length);+ let total = 0;+ for (let i = 0; i < tris.length; i++) { total += tris[i].area; cum[i] = total; }+ if (total <= 0) throw new Error('Model has zero surface area.');++ // Splat scale ~ a fraction of the model's size so the shell reads as solid.+ const box = new THREE.Box3().setFromObject(object3d);+ const diag = box.getSize(new THREE.Vector3()).length() || 1;+ const splatScale = (opts.scale ?? 0.004) * diag;++ const rnd = mulberry32(seed);+ const buf = new ArrayBuffer(count * 32);+ const dv = new DataView(buf);++ const pickTri = (r) => {+ // binary search the cumulative area table+ let lo = 0, hi = tris.length - 1;+ const target = r * total;+ while (lo < hi) {+ const mid = (lo + hi) >> 1;+ if (cum[mid] < target) lo = mid + 1; else hi = mid;+ }+ return tris[lo];+ };++ for (let i = 0; i < count; i++) {+ const tri = pickTri(rnd());+ // Uniform barycentric sample.+ let u = rnd(), v = rnd();+ if (u + v > 1) { u = 1 - u; v = 1 - v; }+ const w = 1 - u - v;+ _v.p.set(0, 0, 0)+ .addScaledVector(tri.a, w)+ .addScaledVector(tri.b, u)+ .addScaledVector(tri.c, v);+ _v.cp.setRGB(+ tri.ca.r * w + tri.cb.r * u + tri.cc.r * v,+ tri.ca.g * w + tri.cb.g * u + tri.cc.g * v,+ tri.ca.b * w + tri.cb.b * u + tri.cc.b * v,+ );++ const base = i * 32;+ dv.setFloat32(base, _v.p.x, true);+ dv.setFloat32(base + 4, _v.p.y, true);+ dv.setFloat32(base + 8, _v.p.z, true);+ dv.setFloat32(base + 12, splatScale, true);+ dv.setFloat32(base + 16, splatScale, true);+ dv.setFloat32(base + 20, splatScale, true);+ dv.setUint8(base + 24, Math.round(THREE.MathUtils.clamp(_v.cp.r, 0, 1) * 255));+ dv.setUint8(base + 25, Math.round(THREE.MathUtils.clamp(_v.cp.g, 0, 1) * 255));+ dv.setUint8(base + 26, Math.round(THREE.MathUtils.clamp(_v.cp.b, 0, 1) * 255));+ dv.setUint8(base + 27, 255);+ // identity rotation (w,x,y,z) → bytes+ dv.setUint8(base + 28, 255);+ dv.setUint8(base + 29, 128);+ dv.setUint8(base + 30, 128);+ dv.setUint8(base + 31, 128);+ }++ return { buffer: buf, count };+}diff --git a/src/forge-studio/talk-launch.js b/src/forge-studio/talk-launch.jsnew file mode 100644index 000000000..da698228e--- /dev/null+++ b/src/forge-studio/talk-launch.js@@ -0,0 +1,67 @@+/**+ * Bring-it-alive launcher for Studio — Pillar 2.+ *+ * Turns anything Studio produces (a forged avatar, a Lab GLB) into a live,+ * talking agent by handing it to the platform's real conversational stack:+ * openTalkMode() → TalkController → /api/chat (LLM, SSE) → /api/tts/speak+ * (NVIDIA Magpie → OpenAI) → lip-sync driver on the avatar's mouth.+ * Per-agent memory rides along through /api/agent-memory when an agent_id is+ * present. No mocks — this is the same runtime the rest of the site uses.+ *+ * The avatar-object mapping is a pure function (buildTalkAvatar) so it can be+ * tested in isolation; launchTalk just resolves the real opener and calls it.+ * setTalkOpener() exists purely as a test seam.+ */++const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+const isUuid = (v) => typeof v === 'string' && UUID_RE.test(v);++let _opener = null;+/** Test seam — inject a fake openTalkMode. */+export function setTalkOpener(fn) {+ _opener = fn;+}++function defaultPersona(name, kind) {+ if (kind === 'object') {+ return [+ `You are "${name}", a 3D object that has just been brought to life in three.ws Studio.`,+ 'Play along as this object with warmth and a light sense of humor.',+ 'Keep replies to one or two short spoken sentences — this is a voice conversation.',+ ].join(' ');+ }+ return [+ `You are "${name}", a 3D avatar a creator just made in three.ws Studio.`,+ 'Speak in first person, with personality and warmth. You have a body and can move and emote.',+ 'Keep replies to one or two short spoken sentences — this is a voice conversation.',+ ].join(' ');+}++/**+ * Build the {avatar, systemPromptFn} payload openTalkMode expects.+ * @param {{name?:string, glbUrl?:string, glbBlob?:Blob, id?:string, agentId?:string, persona?:string, kind?:'avatar'|'object'}} opts+ */+export function buildTalkAvatar(opts = {}) {+ const { name, glbUrl, glbBlob, id, agentId, persona, kind = 'avatar' } = opts;+ if (!glbUrl && !glbBlob) {+ throw new Error('Nothing to talk to yet — generate a model first.');+ }+ const displayName = name || (kind === 'object' ? 'Your creation' : 'Your avatar');+ const systemPrompt = persona || defaultPersona(displayName, kind);+ const avatar = { name: displayName };+ if (glbUrl) { avatar.model_url = glbUrl; avatar.url = glbUrl; }+ if (glbBlob) avatar.glbBlob = glbBlob;+ if (isUuid(id)) avatar.id = id;+ if (agentId) avatar.agent_id = agentId;+ return { avatar, systemPromptFn: () => systemPrompt };+}++/**+ * Resolve the real talk-mode opener (lazy — the stack is heavy) and launch.+ * @returns the active talk session, or null if the opener declines.+ */+export async function launchTalk(opts) {+ const built = buildTalkAvatar(opts);+ const open = _opener || (await import('../voice/talk-mode.js')).openTalkMode;+ return open(built);+}diff --git a/src/hero-stage.js b/src/hero-stage.jsnew file mode 100644index 000000000..7ec217dc6--- /dev/null+++ b/src/hero-stage.js@@ -0,0 +1,301 @@+// Reusable "fomo-family" hero backdrop — deep space, concentric glowing rings,+// a starfield, soft bloom, slow ambient drift, and pointer parallax.+//+// It renders ONLY the atmosphere. The focal subject (a `<agent-3d>` avatar,+// product shot, anything) is layered on top in the DOM with a transparent+// background, exactly the way fomo.family composes a lit character over a+// glowing space stage. Keeping the bloom-heavy backdrop in its own WebGL+// context means we can light it aggressively without washing out the subject,+// and we reuse the battle-tested avatar runtime untouched.+//+// Usage:+// import { HeroStage } from '/src/hero-stage.js';+// const stage = new HeroStage(canvas, { accent: '#7c6cff', accent2: '#36e0ff' });+// stage.start();+// // ...later+// stage.dispose();++import {+ Scene,+ PerspectiveCamera,+ WebGLRenderer,+ Color,+ Vector2,+ Group,+ TorusGeometry,+ MeshBasicMaterial,+ Mesh,+ BufferGeometry,+ BufferAttribute,+ Points,+ PointsMaterial,+ AdditiveBlending,+ SRGBColorSpace,+ ACESFilmicToneMapping,+} from 'three';+import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';+import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';+import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';+import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';++const REDUCED_MOTION = () =>+ typeof window !== 'undefined' &&+ window.matchMedia &&+ window.matchMedia('(prefers-reduced-motion: reduce)').matches;++export class HeroStage {+ /**+ * @param {HTMLCanvasElement} canvas+ * @param {{ accent?: string, accent2?: string, rings?: number, stars?: number }} [opts]+ */+ constructor(canvas, opts = {}) {+ this.canvas = canvas;+ this.accent = new Color(opts.accent || '#7c6cff');+ this.accent2 = new Color(opts.accent2 || '#36e0ff');+ this.ringCount = opts.rings ?? 5;+ this.starCount = opts.stars ?? 1400;++ this._raf = 0;+ this._t = 0;+ this._reduced = REDUCED_MOTION();+ this._pointer = new Vector2(0, 0); // target, -1..1+ this._parallax = new Vector2(0, 0); // eased+ this._resizeObs = null;+ this._mqlReduce = null;++ this._onPointerMove = this._onPointerMove.bind(this);+ this._onPointerLeave = this._onPointerLeave.bind(this);+ this._renderLoop = this._renderLoop.bind(this);+ this._onReduceChange = this._onReduceChange.bind(this);++ this._init();+ }++ _init() {+ const w = this._cssWidth();+ const h = this._cssHeight();++ this.scene = new Scene();++ this.camera = new PerspectiveCamera(42, w / h, 0.1, 100);+ this.camera.position.set(0, 0, 14);+ this.camera.lookAt(0, 0, 0);++ this.renderer = new WebGLRenderer({+ canvas: this.canvas,+ antialias: true,+ alpha: true,+ powerPreference: 'high-performance',+ });+ this.renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));+ this.renderer.setSize(w, h, false);+ this.renderer.outputColorSpace = SRGBColorSpace;+ this.renderer.toneMapping = ACESFilmicToneMapping;+ this.renderer.toneMappingExposure = 1.05;++ this._buildRings();+ this._buildStars();++ // Post-processing: bloom is ~70% of the look. Keep it generous on the+ // emissive rings/stars but the threshold is high enough that only the+ // genuinely bright geometry blooms.+ this.composer = new EffectComposer(this.renderer);+ this.composer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));+ this.composer.setSize(w, h);+ this.composer.addPass(new RenderPass(this.scene, this.camera));+ this.bloom = new UnrealBloomPass(new Vector2(w, h), 0.9, 0.7, 0.2);+ this.composer.addPass(this.bloom);+ this.composer.addPass(new OutputPass());++ this._resizeObs = new ResizeObserver(() => this._resize());+ this._resizeObs.observe(this.canvas.parentElement || this.canvas);++ this._mqlReduce = window.matchMedia('(prefers-reduced-motion: reduce)');+ this._mqlReduce.addEventListener?.('change', this._onReduceChange);+ }++ _buildRings() {+ this.ringGroup = new Group();+ this.scene.add(this.ringGroup);+ this.rings = [];++ for (let i = 0; i < this.ringCount; i++) {+ const f = i / Math.max(1, this.ringCount - 1); // 0..1 outward+ const radius = 2.4 + i * 1.45;+ const tube = 0.012 + f * 0.02;+ const geo = new TorusGeometry(radius, tube, 16, 220);+ const color = this.accent.clone().lerp(this.accent2, f);+ const mat = new MeshBasicMaterial({+ color,+ transparent: true,+ opacity: 0.85 - f * 0.45,+ blending: AdditiveBlending,+ depthWrite: false,+ });+ const ring = new Mesh(geo, mat);+ // Tilt the stack slightly so the rings read as a 3D disc, not a flat target.+ ring.rotation.x = -0.62;+ ring.rotation.z = f * 0.18;+ this.ringGroup.add(ring);+ this.rings.push({+ mesh: ring,+ baseOpacity: mat.opacity,+ spin: (i % 2 === 0 ? 1 : -1) * (0.015 + f * 0.02),+ pulse: 0.5 + f * 0.7,+ });+ }+ this.ringGroup.rotation.x = 0.18;+ }++ _buildStars() {+ const n = this.starCount;+ const positions = new Float32Array(n * 3);+ const colors = new Float32Array(n * 3);+ const c = new Color();+ for (let i = 0; i < n; i++) {+ // Distribute in a deep shell behind the rings.+ const r = 18 + Math.pow((i % 97) / 97, 0.5) * 42;+ const theta = (i * 2.39996) % (Math.PI * 2); // golden-angle spread+ const phi = Math.acos(1 - 2 * ((i + 0.5) / n));+ positions[i * 3] = r * Math.sin(phi) * Math.cos(theta);+ positions[i * 3 + 1] = r * Math.cos(phi) * 0.55;+ positions[i * 3 + 2] = -8 - r * Math.sin(phi) * Math.sin(theta) * 0.4;+ // Mostly cool white, a few tinted with the accent for depth.+ const tint = (i % 11) === 0 ? this.accent2 : (i % 7) === 0 ? this.accent : null;+ c.set('#ffffff');+ if (tint) c.lerp(tint, 0.7);+ c.toArray(colors, i * 3);+ }+ const geo = new BufferGeometry();+ geo.setAttribute('position', new BufferAttribute(positions, 3));+ geo.setAttribute('color', new BufferAttribute(colors, 3));+ this.stars = new Points(+ geo,+ new PointsMaterial({+ size: 0.09,+ sizeAttenuation: true,+ vertexColors: true,+ transparent: true,+ opacity: 0.9,+ blending: AdditiveBlending,+ depthWrite: false,+ })+ );+ this.scene.add(this.stars);+ }++ start() {+ if (this._raf) return;+ window.addEventListener('pointermove', this._onPointerMove, { passive: true });+ window.addEventListener('pointerleave', this._onPointerLeave, { passive: true });+ if (this._reduced) {+ // One settled frame, no animation loop.+ this._composeStatic();+ return;+ }+ this._last = performance.now();+ this._raf = requestAnimationFrame(this._renderLoop);+ }++ _composeStatic() {+ this._parallax.set(0, 0);+ this.composer.render();+ }++ _renderLoop(now) {+ this._raf = requestAnimationFrame(this._renderLoop);+ const dt = Math.min(0.05, (now - this._last) / 1000);+ this._last = now;+ this._t += dt;++ // Ease the camera toward the pointer for a slow parallax drift.+ this._parallax.x += (this._pointer.x - this._parallax.x) * 0.04;+ this._parallax.y += (this._pointer.y - this._parallax.y) * 0.04;+ this.camera.position.x = this._parallax.x * 1.6;+ this.camera.position.y = this._parallax.y * 1.1;+ this.camera.lookAt(0, 0, 0);++ // Rings: gentle independent spin + a breathing opacity pulse.+ for (const r of this.rings) {+ r.mesh.rotation.z += r.spin * dt * 4;+ const pulse = 0.5 + 0.5 * Math.sin(this._t * r.pulse);+ r.mesh.material.opacity = r.baseOpacity * (0.7 + 0.3 * pulse);+ }+ this.ringGroup.rotation.y = Math.sin(this._t * 0.12) * 0.12;++ // Stars drift very slowly for life without distraction.+ this.stars.rotation.y += dt * 0.01;++ this.composer.render();+ }++ _onPointerMove(e) {+ const w = window.innerWidth || 1;+ const h = window.innerHeight || 1;+ this._pointer.set((e.clientX / w) * 2 - 1, -((e.clientY / h) * 2 - 1));+ }++ _onPointerLeave() {+ this._pointer.set(0, 0);+ }++ _onReduceChange(e) {+ this._reduced = e.matches;+ if (this._reduced) {+ if (this._raf) {+ cancelAnimationFrame(this._raf);+ this._raf = 0;+ }+ this._composeStatic();+ } else if (!this._raf) {+ this._last = performance.now();+ this._raf = requestAnimationFrame(this._renderLoop);+ }+ }++ _cssWidth() {+ const el = this.canvas.parentElement || this.canvas;+ return el.clientWidth || window.innerWidth || 1;+ }++ _cssHeight() {+ const el = this.canvas.parentElement || this.canvas;+ return el.clientHeight || window.innerHeight || 1;+ }++ _resize() {+ const w = this._cssWidth();+ const h = this._cssHeight();+ if (!w || !h) return;+ this.renderer.setSize(w, h, false);+ this.composer.setSize(w, h);+ this.bloom.setSize(w, h);+ this.camera.aspect = w / h;+ this.camera.updateProjectionMatrix();+ if (this._reduced) this._composeStatic();+ }++ dispose() {+ if (this._raf) cancelAnimationFrame(this._raf);+ this._raf = 0;+ window.removeEventListener('pointermove', this._onPointerMove);+ window.removeEventListener('pointerleave', this._onPointerLeave);+ this._mqlReduce?.removeEventListener?.('change', this._onReduceChange);+ this._resizeObs?.disconnect();++ this.rings?.forEach((r) => {+ r.mesh.geometry.dispose();+ r.mesh.material.dispose();+ });+ this.stars?.geometry.dispose();+ this.stars?.material.dispose();+ this.composer?.dispose?.();+ this.renderer?.dispose();+ this.renderer?.forceContextLoss?.();+ this.scene = null;+ this.camera = null;+ this.renderer = null;+ }+}++export default HeroStage;diff --git a/src/studio/brain/brain-studio.js b/src/studio/brain/brain-studio.jsindex 0769e3d9c..b41dc49be 100644--- a/src/studio/brain/brain-studio.js+++ b/src/studio/brain/brain-studio.js@@ -134,6 +134,13 @@ class BrainStudio {}};document.addEventListener('keydown', this._keyHandler);++ // The shell's "Save draft" / "Exit" controls fire `studio:flush` to ask every+ // sub-studio to push its in-progress state into the store before the real PUT.+ // The graph auto-persists on a short debounce; flushing it immediately here+ // means an explicit save/exit captures the latest wiring, not the last tick.+ this._flushHandler = () => { if (this.graph) this._onGraphChange(this.graph.toGraph(), { immediate: true }); };+ document.addEventListener('studio:flush', this._flushHandler);}// True only when the Brain tab is the active (non-hidden) studio panel — keepsdiff --git a/src/studio/studio-shell.js b/src/studio/studio-shell.jsindex 16945c0a5..5a7e15907 100644--- a/src/studio/studio-shell.js+++ b/src/studio/studio-shell.js@@ -175,7 +175,14 @@ class StudioShell {maxlength="100" aria-label="Agent name" placeholder="Name your agent" /><input id="studio-tagline" class="studio-tagline" value="${esc(agent.description || '')}"maxlength="280" aria-label="Agent tagline" placeholder="Add a short tagline…" />- <span class="studio-save" id="studio-save" aria-live="polite"></span>+ <div class="studio-actions">+ <span class="studio-save" id="studio-save" aria-live="polite"></span>+ <button type="button" class="studio-btn studio-btn-ghost studio-action" id="studio-save-draft"+ title="Save your progress now — your agent stays a private draft you can keep editing">Save draft</button>+ <a class="studio-btn studio-btn-ghost studio-action" id="studio-exit"+ href="${agent.id ? `/agent/${encodeURIComponent(agent.id)}` : '/'}"+ title="Save and leave the Studio — opens your live agent">Exit ↗</a>+ </div></header><nav class="studio-tabs" role="tablist" aria-label="Editor sections">@@ -247,6 +254,13 @@ class StudioShell {saveEl.dataset.state = 'saved';});+ // Studio-wide escape hatches. Every tab auto-saves through the store, but a+ // focused sub-studio (e.g. the Brain graph) can feel like a forward-only+ // dead-end — these give an always-present, honest way to save a draft and to+ // leave. "Edit other parts" is the tab row directly below this header.+ this.root.querySelector('#studio-save-draft')?.addEventListener('click', (e) => this._saveDraft(e.currentTarget));+ this.root.querySelector('#studio-exit')?.addEventListener('click', (e) => this._exit(e));+// Sub-studios (e.g. the Brain graph's "Done →") request an onward jump// through a DOM event so they stay decoupled from the shell instance.this._navHandler = (e) => {@@ -273,6 +287,53 @@ class StudioShell {});}+ // Flush any sub-studio's not-yet-debounced edits into the store, then push the+ // real PUT through. The flush event lets a focused editor (Brain graph) commit+ // its in-progress state synchronously *before* we commit, so an explicit+ // Save/Exit honestly captures what's on screen rather than the last auto-save.+ async _flushAndCommit() {+ document.dispatchEvent(new CustomEvent('studio:flush'));+ return studio.commit();+ }++ async _saveDraft(btn) {+ if (!btn || btn.dataset.busy) return;+ btn.dataset.busy = '1';+ btn.disabled = true;+ btn.textContent = 'Saving…';+ clearTimeout(this._draftFlash);+ try {+ await this._flushAndCommit();+ btn.textContent = 'Draft saved ✓';+ } catch {+ btn.textContent = 'Retry save';+ } finally {+ btn.disabled = false;+ delete btn.dataset.busy;+ this._draftFlash = setTimeout(() => {+ btn.textContent = 'Save draft';+ }, 1800);+ }+ }++ // Save, then leave to the live agent. We navigate even if the save errors —+ // the store's beforeunload/visibilitychange flush is a backstop, and the href+ // is a real link so a blocked handler still goes somewhere useful.+ async _exit(e) {+ const link = e.currentTarget;+ e.preventDefault();+ if (link.dataset.busy) return;+ link.dataset.busy = '1';+ const href = link.getAttribute('href') || '/';+ link.textContent = 'Saving…';+ try {+ await this._flushAndCommit();+ } catch {+ /* navigate anyway — leaving must never trap the user */+ }+ location.href = href;+ }+_onTabKeydown(e, tabs) {const i = tabs.indexOf(e.currentTarget);if (e.key === 'ArrowRight' || e.key === 'ArrowDown') {diff --git a/vercel.json b/vercel.jsonindex 3e1ebef91..c63510f45 100644--- a/vercel.json+++ b/vercel.json@@ -267,6 +267,14 @@"src": "/agent-economy/","dest": "/agent-economy.html"},+ {+ "src": "/economy",+ "dest": "/economy.html"+ },+ {+ "src": "/economy/",+ "dest": "/economy.html"+ },{"src": "/lookup","dest": "/lookup.html"@@ -1087,6 +1095,14 @@"src": "/coin3d/","dest": "/coin3d.html"},+ {+ "src": "/hero-demo",+ "dest": "/hero-demo.html"+ },+ {+ "src": "/hero-demo/",+ "dest": "/hero-demo.html"+ },{"src": "/constellation","dest": "/constellation.html"diff --git a/vite.config.js b/vite.config.jsindex 984d00318..90c4f3417 100644--- a/vite.config.js+++ b/vite.config.js@@ -299,6 +299,7 @@ const appConfig = {glossary: resolve(__dirname, 'pages/glossary.html'),playground: resolve(__dirname, 'pages/playground.html'),coin3d: resolve(__dirname, 'pages/coin3d.html'),+ 'hero-demo': resolve(__dirname, 'pages/hero-demo.html'),constellation: resolve(__dirname, 'pages/constellation.html'),embed: resolve(__dirname, 'pages/embed.html'),'embed-demo': resolve(__dirname, 'pages/embed-demo.html'),@@ -346,6 +347,7 @@ const appConfig = {'demo-economy': resolve(__dirname, 'pages/demo-economy.html'),live: resolve(__dirname, 'pages/live.html'),'agent-economy': resolve(__dirname, 'pages/agent-economy.html'),+ economy: resolve(__dirname, 'pages/economy.html'),'overlay-control': resolve(__dirname, 'pages/overlay-control.html'),'mocap-studio': resolve(__dirname, 'pages/mocap-studio.html'),handle: resolve(__dirname, 'pages/handle.html'),diff --git a/x402-payment-modal/examples/solana-crypto-paywall/README.md b/x402-payment-modal/examples/solana-crypto-paywall/README.mdnew file mode 100644index 000000000..e12704c51--- /dev/null+++ b/x402-payment-modal/examples/solana-crypto-paywall/README.md@@ -0,0 +1,81 @@+# Solana crypto paywall — `@three-ws/x402-payment-modal` demo++A complete, runnable demo that paywalls a **free crypto-price API** (CoinGecko)+behind an **x402 USDC payment on Solana**, served to the payment modal we ship on+npm. It exists to prove the published modal works end to end on a plain page:++```+click ─▶ 402 challenge ─▶ Phantom connect ─▶ sign SPL transfer+ ─▶ PayAI /verify ─▶ fetch CoinGecko ─▶ PayAI /settle ─▶ prices + receipt+```++Three things make it a real test, not a mock:++1. **The modal loads from npm.** `public/index.html` pulls+ `https://unpkg.com/@three-ws/[email protected]` — the exact artifact we+ publish — so you're testing the shipped code, not local source.+2. **The data is gated for real.** `/api/paid/crypto` returns live CoinGecko+ prices **only** after the payment verifies *and* settles on-chain via the+ [PayAI](https://facilitator.payai.network) facilitator. No payment, no data.+3. **The payout wallet is set at runtime.** There is no `.env` and no source+ constant for it — you start the server, paste a Solana address into the page,+ and that address becomes the `payTo` in the 402 challenge.++## Run it (inside the three.ws repo)++The server reuses the repo's `express` + `@solana/*` and imports the package's+checkout helpers from source, so no install is needed:++```bash+node x402-payment-modal/examples/solana-crypto-paywall/server.mjs+# ▸ open http://localhost:4021+```++Then in the page:++1. **Set your payout wallet** — paste a base58 Solana address, click *Save*.+2. **Pick coins** — BTC / ETH / SOL / … (live from CoinGecko).+3. **Pay & unlock** — approve $0.01 USDC in Phantom. Prices + an on-chain+ receipt (with a Solscan link) appear when settlement lands.++> Paying is a **real Solana mainnet micropayment** — you need Phantom with a+> little USDC. The fee payer is covered by the facilitator, so you don't need SOL.++## Run it standalone (outside the repo)++```bash+npm install+# in server.mjs, change the two relative imports to the package subpaths:+# '../../server/express.js' → '@three-ws/x402-payment-modal/server/express'+# '../../server/checkout.js' → '@three-ws/x402-payment-modal/server'+npm start+```++## What's runtime vs. fixed++| Thing | Where it comes from |+| --- | --- |+| **Payout wallet (`payTo`)** | **Set at runtime from the page** — `POST /api/config`, in memory. No env. |+| Fee-payer sponsor | Public PayAI account `2wKupLR9q6wXYppw8Gr2NvWxKBUqm4PPJKkQfoxHDBg4` (pays SOL fees; not a secret, not the payout). Override with `X402_FEE_PAYER_SOLANA` only if you change facilitators. |+| Facilitator | `https://facilitator.payai.network` (no API key). Override with `X402_FACILITATOR_URL`. |+| Solana RPC | Public mainnet RPC. Override with `SOLANA_RPC_URL` for anything beyond a quick try. |+| Price | Fixed at `$0.01` USDC. |+| Port | `4021`, or `PORT`. |++## Endpoints++| Method & path | Purpose |+| --- | --- |+| `GET /api/config` | Current payout wallet, fee payer, price, coin catalog. |+| `POST /api/config` `{ payTo }` | Set the payout wallet at runtime (validated Solana address). |+| `POST /api/paid/crypto` `{ ids }` | The paid resource. 402 until paid; verifies + settles, then returns live prices. |+| `ALL /api/x402-checkout` | The package's Solana `prepare`/`encode` router the modal calls. |++## Files++- `server.mjs` — Express app: runtime config, the 402 → verify → fetch → settle+ paid endpoint, and the package's checkout router.+- `facilitator.mjs` — minimal PayAI `/verify` + `/settle` client (the merchant+ half of the protocol), mirroring the wire format `api/_lib/x402-spec.js` uses.+- `public/index.html` — the demo page: runtime payout panel, coin picker, and+ designed loading / empty / error / populated states with an on-chain receipt.diff --git a/x402-payment-modal/examples/solana-crypto-paywall/facilitator.mjs b/x402-payment-modal/examples/solana-crypto-paywall/facilitator.mjsnew file mode 100644index 000000000..69083fb3b--- /dev/null+++ b/x402-payment-modal/examples/solana-crypto-paywall/facilitator.mjs@@ -0,0 +1,170 @@+// Minimal x402 facilitator client — Solana `exact` scheme, USDC on mainnet.+//+// The browser modal signs the SPL transfer (Phantom) and posts it back as a+// base64 `X-PAYMENT` header. The merchant (this server) is responsible for the+// other half of the protocol: ask a facilitator to (1) /verify the signed+// payment matches what we offered, then (2) /settle it on-chain. PayAI's public+// facilitator co-signs as the fee payer and broadcasts — so the merchant never+// holds a private key and pays no gas.+//+// This is the same wire format the main three.ws app uses (api/_lib/x402-spec.js+// verifyPayment/settlePayment), trimmed to exactly what the Solana exact path+// needs so the example stays self-contained and easy to read:+//+// POST {facilitator}/verify { x402Version, paymentPayload, paymentRequirements }+// → { isValid: boolean, invalidReason?, payer? }+// POST {facilitator}/settle { x402Version, paymentPayload, paymentRequirements }+// → { success: boolean, transaction?, network?, payer?, errorReason? }+//+// No API key required for PayAI's public Solana lane. Override the URL with+// X402_FACILITATOR_URL if you run your own.++import { createHash } from 'node:crypto';++export const X402_VERSION = 2;++// PayAI supports Solana + Base mainnet with no auth token. The reference+// x402.org facilitator only settles base-sepolia, so it can't stand in here.+const FACILITATOR_URL = (process.env.X402_FACILITATOR_URL || 'https://facilitator.payai.network').replace(/\/+$/, '');+const FACILITATOR_TOKEN = process.env.X402_FACILITATOR_TOKEN || null;+const TIMEOUT_MS = 20_000;++/** Decode the base64-JSON `X-PAYMENT` header into a v2 PaymentPayload. */+export function decodePaymentHeader(header) {+ if (!header) {+ throw httpError(402, 'payment_required', 'X-PAYMENT header required');+ }+ let json;+ try {+ json = Buffer.from(String(header), 'base64').toString('utf8');+ } catch (err) {+ throw httpError(400, 'invalid_payment', `X-PAYMENT base64 decode failed: ${err.message}`);+ }+ let payload;+ try {+ payload = JSON.parse(json);+ } catch (err) {+ throw httpError(400, 'invalid_payment', `X-PAYMENT JSON parse failed: ${err.message}`);+ }+ if (!payload || typeof payload !== 'object') {+ throw httpError(400, 'invalid_payment', 'X-PAYMENT must decode to a JSON object');+ }+ return payload;+}++/**+ * Verify a decoded payment against the requirement we advertised.+ * Resolves to `{ payer }` when valid; throws a 402 when the facilitator+ * rejects it (so the modal can re-prompt the buyer to pay).+ */+export async function verifyPayment({ paymentPayload, requirement }) {+ const result = await callFacilitator('/verify', {+ x402Version: X402_VERSION,+ paymentPayload,+ paymentRequirements: requirement,+ });+ if (!result.isValid) {+ throw httpError(402, 'invalid_payment', `payment rejected: ${result.invalidReason || 'unknown reason'}`);+ }+ // Defense-in-depth: a buggy/compromised facilitator must not be able to+ // verify a payment for a different chain than the one we offered.+ if (result.network && result.network !== requirement.network) {+ throw httpError(502, 'facilitator_bad_response', `verify network mismatch: offered ${requirement.network}, got ${result.network}`);+ }+ return { payer: result.payer || null };+}++/**+ * Settle the verified payment on-chain via the facilitator. Carries a+ * deterministic Idempotency-Key so a retried settle (timeout / 5xx) is+ * de-duplicated by the facilitator instead of charging the buyer twice.+ */+export async function settlePayment({ paymentPayload, requirement }) {+ const idempotencyKey = buildIdempotencyKey({ paymentPayload, requirement });+ const result = await callFacilitator(+ '/settle',+ { x402Version: X402_VERSION, paymentPayload, paymentRequirements: requirement },+ { idempotencyKey },+ );+ if (!result.success) {+ throw httpError(502, 'settle_failed', `settlement failed: ${result.errorReason || 'unknown reason'}`);+ }+ return {+ transaction: result.transaction || null,+ network: result.network || requirement.network,+ payer: result.payer || null,+ };+}++/** Base64-JSON settlement receipt for the `X-PAYMENT-RESPONSE` header. */+export function encodePaymentResponse(settled) {+ return Buffer.from(+ JSON.stringify({+ success: true,+ transaction: settled.transaction,+ network: settled.network,+ payer: settled.payer,+ }),+ 'utf8',+ ).toString('base64');+}++// ── internals ───────────────────────────────────────────────────────────────++function buildIdempotencyKey({ paymentPayload, requirement }) {+ const material = JSON.stringify({+ network: requirement?.network,+ payTo: requirement?.payTo,+ asset: requirement?.asset,+ amount: requirement?.amount,+ scheme: requirement?.scheme,+ payload: paymentPayload,+ });+ return createHash('sha256').update(material).digest('hex').slice(0, 32);+}++async function callFacilitator(path, body, { idempotencyKey } = {}) {+ const headers = { 'content-type': 'application/json', accept: 'application/json' };+ if (FACILITATOR_TOKEN) headers.Authorization = `Bearer ${FACILITATOR_TOKEN}`;+ if (idempotencyKey) headers['Idempotency-Key'] = idempotencyKey;++ let res;+ try {+ res = await fetch(`${FACILITATOR_URL}${path}`, {+ method: 'POST',+ headers,+ body: JSON.stringify(body),+ signal: AbortSignal.timeout(TIMEOUT_MS),+ });+ } catch (err) {+ throw httpError(502, 'facilitator_unreachable', `facilitator ${path} fetch failed: ${err.message}`);+ }++ const text = await res.text();+ let data = {};+ if (text) {+ try {+ data = JSON.parse(text);+ } catch {+ throw httpError(502, 'facilitator_bad_response', `facilitator ${path} returned non-JSON (status ${res.status})`);+ }+ }++ if (!res.ok) {+ // A rejected payment payload is a client problem, not an outage — normalize+ // it so verifyPayment can re-issue a clean 402 instead of a 5xx.+ if (path === '/verify' && (data.isValid === false || res.status === 400)) {+ return { isValid: false, invalidReason: data.invalidReason || data.error || `payment rejected (status ${res.status})` };+ }+ const detail = data.error || data.errorReason || data.message || text.slice(0, 200) || `status ${res.status}`;+ throw httpError(502, 'facilitator_error', `facilitator ${path} ${res.status}: ${detail}`);+ }+ return data;+}++function httpError(status, code, message) {+ const err = new Error(message);+ err.status = status;+ err.code = code;+ return err;+}diff --git a/x402-payment-modal/examples/solana-crypto-paywall/package.json b/x402-payment-modal/examples/solana-crypto-paywall/package.jsonnew file mode 100644index 000000000..688cefc37--- /dev/null+++ b/x402-payment-modal/examples/solana-crypto-paywall/package.json@@ -0,0 +1,17 @@+{+ "name": "x402-solana-crypto-paywall",+ "private": true,+ "version": "1.0.0",+ "description": "Demo: a free crypto-price API paywalled with x402 on Solana, served to the @three-ws/x402-payment-modal. Payout wallet is set at runtime, not from env.",+ "type": "module",+ "scripts": {+ "start": "node server.mjs",+ "dev": "node server.mjs"+ },+ "dependencies": {+ "@three-ws/x402-payment-modal": "*",+ "@solana/web3.js": "^1.95.0",+ "@solana/spl-token": "^0.4.0",+ "express": "^4.19.0"+ }+}diff --git a/x402-payment-modal/examples/solana-crypto-paywall/public/index.html b/x402-payment-modal/examples/solana-crypto-paywall/public/index.htmlnew file mode 100644index 000000000..620f02f56--- /dev/null+++ b/x402-payment-modal/examples/solana-crypto-paywall/public/index.html@@ -0,0 +1,506 @@+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <title>x402 Crypto Paywall — Solana · three.ws</title>+ <meta name="description" content="Pay $0.01 USDC on Solana to unlock live crypto prices — a demo of the @three-ws/x402-payment-modal npm package." />++ <!--+ The payment modal is loaded straight from npm (unpkg) so this page exercises+ the EXACT artifact we publish. Pinned to a version per the package's own+ security guidance; bump it to test a new release.+ -->+ <script+ type="module"+ src="https://unpkg.com/@three-ws/[email protected]"+ data-x402-brand-name="three.ws Crypto"+ data-x402-brand-url="https://three.ws"+ data-x402-footer-note="x402 · Solana · settled by PayAI"></script>++ <style>+ :root {+ --bg: #07080c;+ --bg-glow: #15233f;+ --card: #11131b;+ --card-2: #0c0e15;+ --border: #232838;+ --border-hi: #313a52;+ --text: #eef1f7;+ --muted: #99a1b5;+ --faint: #6b7280;+ --accent: #7b8cff;+ --accent-press: #6072f5;+ --sol: #14f195;+ --sol-2: #9945ff;+ --ok: #2fd6a0;+ --err: #ff6b6b;+ --warn: #ffcf5c;+ --radius: 16px;+ }+ * { box-sizing: border-box; }+ html, body { min-height: 100%; }+ body {+ margin: 0;+ background:+ radial-gradient(900px 480px at 15% -10%, rgba(153,69,255,0.14) 0%, transparent 60%),+ radial-gradient(900px 520px at 100% 0%, rgba(20,241,149,0.10) 0%, transparent 55%),+ var(--bg);+ color: var(--text);+ font: 15px/1.55 system-ui, -apple-system, "Segoe UI", Roboto, Inter, sans-serif;+ -webkit-font-smoothing: antialiased;+ padding: 40px 18px 64px;+ }+ .wrap { max-width: 760px; margin: 0 auto; }++ header.hero { margin-bottom: 26px; }+ .brandline { display: flex; align-items: center; gap: 10px; margin-bottom: 18px; }+ .dot { width: 10px; height: 10px; border-radius: 99px; background: linear-gradient(135deg, var(--sol) 0%, var(--sol-2) 100%); box-shadow: 0 0 16px rgba(20,241,149,0.55); }+ .brandline b { letter-spacing: -0.01em; }+ .pill {+ margin-left: auto; font-size: 11.5px; color: var(--muted);+ border: 1px solid var(--border); border-radius: 99px; padding: 4px 10px;+ display: inline-flex; align-items: center; gap: 6px; background: var(--card-2);+ }+ .pill .live { width: 6px; height: 6px; border-radius: 99px; background: var(--muted); }+ .pill.ready .live { background: var(--sol); box-shadow: 0 0 8px var(--sol); }+ h1 { font-size: 30px; line-height: 1.12; margin: 0 0 10px; letter-spacing: -0.025em; }+ h1 .grad { background: linear-gradient(100deg, var(--sol) 0%, var(--accent) 55%, var(--sol-2) 100%); -webkit-background-clip: text; background-clip: text; color: transparent; }+ p.lede { margin: 0; color: var(--muted); font-size: 16px; max-width: 56ch; }++ .card {+ background: linear-gradient(180deg, var(--card) 0%, var(--card-2) 100%);+ border: 1px solid var(--border);+ border-radius: var(--radius);+ padding: 22px;+ margin-top: 18px;+ }+ .step { display: flex; align-items: baseline; gap: 10px; margin: 0 0 14px; }+ .step .n {+ flex: none; width: 22px; height: 22px; border-radius: 99px; font-size: 12px; font-weight: 700;+ display: grid; place-items: center; background: #1b2030; color: var(--muted); border: 1px solid var(--border-hi);+ }+ .step.done .n { background: rgba(47,214,160,0.15); color: var(--ok); border-color: rgba(47,214,160,0.4); }+ .step h2 { font-size: 14px; margin: 0; letter-spacing: 0.01em; }+ .step .sub { font-size: 12.5px; color: var(--muted); margin: 2px 0 0; }++ label.fld { display: block; font-size: 12px; color: var(--muted); margin: 0 0 6px; }+ .inrow { display: flex; gap: 10px; flex-wrap: wrap; }+ input[type=text] {+ flex: 1 1 320px; min-width: 0;+ background: #0a0c12; border: 1px solid var(--border-hi); border-radius: 10px;+ color: var(--text); font: inherit; font-size: 14px; padding: 11px 13px;+ font-family: ui-monospace, "SF Mono", Menlo, monospace; letter-spacing: -0.01em;+ transition: border-color 0.15s ease, box-shadow 0.15s ease;+ }+ input[type=text]:focus { outline: none; border-color: var(--accent); box-shadow: 0 0 0 3px rgba(123,140,255,0.18); }+ input[type=text].bad { border-color: var(--err); box-shadow: 0 0 0 3px rgba(255,107,107,0.16); }++ button {+ appearance: none; border: 0; border-radius: 10px; padding: 11px 16px;+ font: inherit; font-weight: 600; color: #fff; background: var(--accent);+ cursor: pointer; transition: transform 0.07s ease, background 0.15s ease, box-shadow 0.15s ease, opacity 0.15s ease;+ }+ button:hover { background: var(--accent-press); }+ button:active { transform: translateY(1px); }+ button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }+ button.ghost { background: #1a1f2e; color: var(--text); border: 1px solid var(--border-hi); }+ button.ghost:hover { background: #222838; }+ button[disabled] { opacity: 0.45; cursor: not-allowed; }++ .cfg-status { margin-top: 12px; font-size: 13px; color: var(--muted); display: flex; align-items: center; gap: 8px; min-height: 20px; }+ .cfg-status .tick { color: var(--ok); }+ .cfg-status code { background: #0a0c12; border: 1px solid var(--border); border-radius: 6px; padding: 1px 7px; font-size: 12px; }+ .cfg-status.err { color: var(--err); }++ .chips { display: flex; gap: 8px; flex-wrap: wrap; }+ .chip {+ appearance: none; border: 1px solid var(--border-hi); background: #0c0f17; color: var(--muted);+ border-radius: 99px; padding: 8px 13px; font: inherit; font-size: 13px; font-weight: 600; cursor: pointer;+ display: inline-flex; align-items: center; gap: 7px; transition: all 0.13s ease;+ }+ .chip .tk { color: var(--faint); font-size: 11px; font-weight: 500; }+ .chip:hover { border-color: var(--accent); color: var(--text); }+ .chip[aria-pressed=true] { background: rgba(123,140,255,0.16); border-color: var(--accent); color: #fff; }+ .chip:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }++ .pay {+ width: 100%; margin-top: 4px; padding: 15px 18px; font-size: 15.5px;+ background: linear-gradient(100deg, var(--sol-2) 0%, var(--accent) 100%);+ display: flex; align-items: center; justify-content: center; gap: 10px;+ }+ .pay:hover { background: linear-gradient(100deg, #8a3bff 0%, var(--accent-press) 100%); }+ .pay .price { font-variant-numeric: tabular-nums; opacity: 0.95; }+ .paynote { text-align: center; font-size: 12px; color: var(--muted); margin: 10px 0 0; }++ /* results */+ #results { margin-top: 18px; }+ .res-shell {+ border: 1px solid var(--border); border-radius: var(--radius); overflow: hidden; background: var(--card-2);+ }+ .res-empty, .res-error { padding: 34px 22px; text-align: center; color: var(--muted); }+ .res-empty .big { font-size: 30px; margin-bottom: 8px; opacity: 0.65; }+ .res-error { color: var(--err); }+ .res-error .retry { margin-top: 14px; }++ table { width: 100%; border-collapse: collapse; }+ thead th { text-align: left; font-size: 11px; text-transform: uppercase; letter-spacing: 0.07em; color: var(--muted); padding: 13px 18px; border-bottom: 1px solid var(--border); font-weight: 600; }+ thead th.num, tbody td.num { text-align: right; }+ tbody td { padding: 14px 18px; border-bottom: 1px solid #181b25; font-variant-numeric: tabular-nums; }+ tbody tr:last-child td { border-bottom: 0; }+ .coin { display: flex; align-items: center; gap: 11px; }+ .coin .sym { width: 34px; height: 34px; border-radius: 99px; display: grid; place-items: center; font-size: 11px; font-weight: 700; background: #1a1f2e; color: var(--text); border: 1px solid var(--border-hi); }+ .coin .nm { font-weight: 600; }+ .coin .id { font-size: 11.5px; color: var(--faint); }+ .price-cell { font-weight: 600; }+ .chg.up { color: var(--ok); }+ .chg.down { color: var(--err); }+ .cap { color: var(--muted); }++ .receipt { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; padding: 13px 18px; background: rgba(47,214,160,0.07); border-top: 1px solid var(--border); font-size: 13px; }+ .receipt .ok { color: var(--ok); font-weight: 700; display: inline-flex; align-items: center; gap: 6px; }+ .receipt .kv { color: var(--muted); }+ .receipt .kv b { color: var(--text); font-weight: 600; font-family: ui-monospace, Menlo, monospace; }+ .receipt a { color: var(--sol); text-decoration: none; margin-left: auto; }+ .receipt a:hover { text-decoration: underline; }++ /* skeleton */+ .sk-row { display: flex; align-items: center; gap: 11px; padding: 14px 18px; border-bottom: 1px solid #181b25; }+ .sk { background: linear-gradient(90deg, #161a25 25%, #1f2433 50%, #161a25 75%); background-size: 200% 100%; animation: sh 1.2s infinite linear; border-radius: 6px; }+ @keyframes sh { to { background-position: -200% 0; } }+ .sk.circle { width: 34px; height: 34px; border-radius: 99px; flex: none; }+ .sk.line { height: 12px; }++ footer { margin-top: 30px; color: var(--muted); font-size: 12.5px; }+ footer .how { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 10px; margin-bottom: 16px; }+ footer .how div { background: var(--card-2); border: 1px solid var(--border); border-radius: 12px; padding: 12px 14px; }+ footer .how b { color: var(--text); display: block; font-size: 12px; margin-bottom: 3px; }+ footer a { color: var(--accent); text-decoration: none; }+ footer a:hover { text-decoration: underline; }+ footer .fine { line-height: 1.7; }++ @media (max-width: 560px) {+ h1 { font-size: 24px; }+ thead th.cap-col, tbody td.cap-col { display: none; }+ .receipt a { margin-left: 0; }+ }+ @media (prefers-reduced-motion: reduce) { .sk { animation: none; } }+ </style>+</head>++<body>+ <div class="wrap">+ <header class="hero">+ <div class="brandline">+ <span class="dot" aria-hidden="true"></span>+ <b>three.ws</b>+ <span class="pill" id="verPill"><span class="live"></span><span id="verText">loading modal…</span></span>+ </div>+ <h1>Pay-per-call <span class="grad">crypto prices</span>,<br/>settled on Solana.</h1>+ <p class="lede">+ A live demo of <code>@three-ws/x402-payment-modal</code> — the modal we ship on npm.+ Set a payout wallet, pick coins, and pay $0.01 USDC with Phantom to unlock real+ CoinGecko prices. One click; no wallet code.+ </p>+ </header>++ <!-- Step 1 — runtime payout -->+ <section class="card" id="cfgCard">+ <div class="step" id="step1">+ <span class="n">1</span>+ <div>+ <h2>Set your payout wallet</h2>+ <p class="sub">Set at runtime — never from a <code>.env</code> or the source. This is where the USDC lands.</p>+ </div>+ </div>+ <label class="fld" for="payTo">Solana address (base58)</label>+ <div class="inrow">+ <input id="payTo" type="text" inputmode="text" autocomplete="off" spellcheck="false"+ placeholder="e.g. 5xY…your Solana wallet…Jpump" aria-describedby="cfgStatus" />+ <button id="saveCfg" class="ghost" type="button">Save</button>+ </div>+ <div class="cfg-status" id="cfgStatus" role="status" aria-live="polite">No payout wallet set yet.</div>+ </section>++ <!-- Step 2 — pick coins -->+ <section class="card">+ <div class="step">+ <span class="n">2</span>+ <div>+ <h2>Pick coins to price</h2>+ <p class="sub">Pulled live from CoinGecko (free, no key) once payment settles.</p>+ </div>+ </div>+ <div class="chips" id="chips" role="group" aria-label="Coins to price"></div>+ </section>++ <!-- Step 3 — pay -->+ <section class="card">+ <div class="step">+ <span class="n">3</span>+ <div>+ <h2>Pay & unlock</h2>+ <p class="sub">The modal handles connect → sign → settle. USDC moves on Solana mainnet.</p>+ </div>+ </div>+ <button id="payBtn" class="pay" type="button" disabled>+ <span>Pay & get live prices</span>+ <span class="price">· $0.01 USDC</span>+ </button>+ <p class="paynote" id="payNote">Set a payout wallet and pick at least one coin to enable.</p>+ </section>++ <!-- Results -->+ <section id="results" aria-live="polite"></section>++ <footer>+ <div class="how">+ <div><b>402 challenge</b>The endpoint answers unpaid calls with an x402 challenge listing the Solana price.</div>+ <div><b>Phantom signs</b>The modal builds the USDC transfer server-side and Phantom signs it.</div>+ <div><b>PayAI settles</b>A facilitator co-signs the fee & broadcasts — you hold no keys, pay no gas.</div>+ <div><b>Data unlocked</b>On settle, the server returns live CoinGecko prices + an on-chain receipt.</div>+ </div>+ <p class="fine">+ Modal loaded from <a href="https://www.npmjs.com/package/@three-ws/x402-payment-modal" target="_blank" rel="noopener">npm</a> ·+ prices from <a href="https://www.coingecko.com" target="_blank" rel="noopener">CoinGecko</a> ·+ settled via <a href="https://facilitator.payai.network" target="_blank" rel="noopener">PayAI</a>.+ Real micropayment on Solana mainnet — needs Phantom with a little USDC.+ </p>+ </footer>+ </div>++ <script>+ (function () {+ 'use strict';+ const $ = (id) => document.getElementById(id);+ const SOLSCAN = 'https://solscan.io/tx/';+ const ADDR_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++ const state = { configured: false, coins: [], selected: new Set(), busy: false, last: null };++ // ── wait for the npm modal to attach window.X402 ──────────────────────+ function whenModalReady() {+ return new Promise((resolve, reject) => {+ if (window.X402) return resolve(window.X402);+ let waited = 0;+ const t = setInterval(() => {+ if (window.X402) { clearInterval(t); resolve(window.X402); }+ else if ((waited += 50) > 10000) { clearInterval(t); reject(new Error('payment modal failed to load from npm')); }+ }, 50);+ });+ }++ // ── helpers ───────────────────────────────────────────────────────────+ const trunc = (a) => (a ? a.slice(0, 5) + '…' + a.slice(-5) : '');+ function fmtUsd(n) {+ if (n == null) return '—';+ if (n >= 1000) return '$' + n.toLocaleString('en-US', { maximumFractionDigits: 0 });+ if (n >= 1) return '$' + n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });+ return '$' + n.toLocaleString('en-US', { maximumFractionDigits: 6 });+ }+ function fmtCap(n) {+ if (n == null) return '—';+ if (n >= 1e12) return '$' + (n / 1e12).toFixed(2) + 'T';+ if (n >= 1e9) return '$' + (n / 1e9).toFixed(2) + 'B';+ if (n >= 1e6) return '$' + (n / 1e6).toFixed(1) + 'M';+ return fmtUsd(n);+ }+ function fmtPct(n) {+ if (n == null) return { txt: '—', cls: '' };+ const s = (n >= 0 ? '+' : '') + n.toFixed(2) + '%';+ return { txt: s, cls: n >= 0 ? 'up' : 'down' };+ }+ function esc(s) { return String(s).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); }++ // ── config (step 1) ─────────────────────────────────────────────────────+ function setCfgStatus(html, cls) {+ const el = $('cfgStatus');+ el.className = 'cfg-status' + (cls ? ' ' + cls : '');+ el.innerHTML = html;+ }+ function markConfigured(payTo) {+ state.configured = true;+ $('step1').classList.add('done');+ setCfgStatus('<span class="tick">✓</span> Paying out to <code>' + esc(trunc(payTo)) + '</code>');+ refreshPayBtn();+ }+ async function saveConfig() {+ const v = $('payTo').value.trim();+ const input = $('payTo');+ if (!ADDR_RE.test(v)) {+ input.classList.add('bad');+ setCfgStatus('That doesn’t look like a Solana address (base58, 32–44 chars).', 'err');+ return;+ }+ input.classList.remove('bad');+ $('saveCfg').disabled = true;+ setCfgStatus('Saving…');+ try {+ const r = await fetch('/api/config', {+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ payTo: v }),+ });+ const d = await r.json();+ if (!r.ok) throw new Error(d.error_description || 'could not save');+ localStorage.setItem('x402demo.payTo', v);+ markConfigured(d.payTo);+ } catch (err) {+ setCfgStatus(esc(err.message), 'err');+ } finally {+ $('saveCfg').disabled = false;+ }+ }++ // ── coin chips (step 2) ──────────────────────────────────────────────────+ function renderChips() {+ const host = $('chips');+ host.innerHTML = '';+ const defaults = new Set(['bitcoin', 'ethereum', 'solana']);+ state.coins.forEach((c) => {+ const on = defaults.has(c.id);+ if (on) state.selected.add(c.id);+ const b = document.createElement('button');+ b.type = 'button';+ b.className = 'chip';+ b.setAttribute('aria-pressed', String(on));+ b.dataset.id = c.id;+ b.innerHTML = esc(c.name) + ' <span class="tk">' + esc(c.symbol) + '</span>';+ b.addEventListener('click', () => {+ const sel = b.getAttribute('aria-pressed') === 'true';+ b.setAttribute('aria-pressed', String(!sel));+ if (sel) state.selected.delete(c.id); else state.selected.add(c.id);+ refreshPayBtn();+ });+ host.appendChild(b);+ });+ refreshPayBtn();+ }++ // ── pay button gating (step 3) ───────────────────────────────────────────+ function refreshPayBtn() {+ const ready = state.configured && state.selected.size > 0 && !state.busy;+ $('payBtn').disabled = !ready;+ const note = $('payNote');+ if (state.busy) note.textContent = 'Payment in progress — finish in the modal…';+ else if (!state.configured) note.textContent = 'Set a payout wallet (step 1) to enable.';+ else if (state.selected.size === 0) note.textContent = 'Pick at least one coin (step 2) to enable.';+ else note.textContent = 'Pays $0.01 USDC on Solana mainnet · needs Phantom.';+ }++ // ── results rendering ────────────────────────────────────────────────────+ function renderEmpty() {+ $('results').innerHTML =+ '<div class="res-shell"><div class="res-empty"><div class="big">🔒</div>' ++ 'Pick coins and pay to reveal live prices.</div></div>';+ }+ function renderLoading() {+ const rows = Array.from(state.selected).slice(0, 6).map(() =>+ '<div class="sk-row"><div class="sk circle"></div>' ++ '<div style="flex:1"><div class="sk line" style="width:38%;margin-bottom:7px"></div>' ++ '<div class="sk line" style="width:22%;height:10px"></div></div>' ++ '<div class="sk line" style="width:64px"></div></div>').join('');+ $('results').innerHTML = '<div class="res-shell">' + rows + '</div>';+ }+ function renderError(msg) {+ $('results').innerHTML =+ '<div class="res-shell"><div class="res-error">⚠ ' + esc(msg) ++ '<div class="retry"><button class="ghost" id="retryBtn" type="button">Try again</button></div></div></div>';+ const rb = $('retryBtn');+ if (rb) rb.addEventListener('click', startPayment);+ }+ function renderResults(data, payment) {+ const rows = data.coins.map((c) => {+ const pct = fmtPct(c.change_24h);+ return '<tr><td><div class="coin">' ++ '<span class="sym">' + esc(c.symbol.slice(0, 4)) + '</span>' ++ '<span><span class="nm">' + esc(c.name) + '</span><br/><span class="id">' + esc(c.id) + '</span></span>' ++ '</div></td>' ++ '<td class="num price-cell">' + fmtUsd(c.price_usd) + '</td>' ++ '<td class="num chg ' + pct.cls + '">' + pct.txt + '</td>' ++ '<td class="num cap cap-col">' + fmtCap(c.market_cap) + '</td></tr>';+ }).join('');++ let receipt = '';+ if (payment && (payment.transaction || payment.payer)) {+ const tx = payment.transaction;+ receipt = '<div class="receipt"><span class="ok">✓ Paid</span>' ++ '<span class="kv">network <b>' + esc(payment.network || 'solana') + '</b></span>' ++ (payment.payer ? '<span class="kv">payer <b>' + esc(trunc(payment.payer)) + '</b></span>' : '') ++ (tx ? '<a href="' + SOLSCAN + esc(tx) + '" target="_blank" rel="noopener">view tx ↗</a>' : '') ++ '</div>';+ }++ $('results').innerHTML =+ '<div class="res-shell"><table><thead><tr>' ++ '<th>Coin</th><th class="num">Price</th><th class="num">24h</th><th class="num cap-col">Mkt cap</th>' ++ '</tr></thead><tbody>' + rows + '</tbody></table>' + receipt ++ '<div style="padding:10px 18px;font-size:11.5px;color:var(--muted);border-top:1px solid var(--border)">' ++ 'as of ' + esc(new Date(data.asof).toLocaleTimeString()) + ' · source: ' + esc(data.source) + '</div></div>';+ }++ // ── payment flow ─────────────────────────────────────────────────────────+ async function startPayment() {+ if (!state.configured || state.selected.size === 0 || state.busy) return;+ const ids = Array.from(state.selected);+ state.busy = true;+ refreshPayBtn();+ renderLoading();+ try {+ const out = await window.X402.pay({+ endpoint: '/api/paid/crypto',+ method: 'POST',+ body: { ids },+ merchant: 'three.ws Crypto',+ action: 'Live prices · ' + ids.length + ' coin' + (ids.length > 1 ? 's' : ''),+ });+ state.last = { data: out.result, payment: out.payment };+ renderResults(out.result, out.payment);+ } catch (err) {+ // Dismissing the modal rejects with code 'cancelled' — restore whatever+ // was on screen before instead of showing a scary error.+ if (err && err.code === 'cancelled') {+ if (state.last) renderResults(state.last.data, state.last.payment); else renderEmpty();+ } else {+ renderError((err && err.message) || 'payment failed');+ }+ } finally {+ state.busy = false;+ refreshPayBtn();+ }+ }++ // ── boot ──────────────────────────────────────────────────────────────────+ async function boot() {+ renderEmpty();+ $('saveCfg').addEventListener('click', saveConfig);+ $('payTo').addEventListener('keydown', (e) => { if (e.key === 'Enter') saveConfig(); });+ $('payBtn').addEventListener('click', startPayment);++ // prefill last-used address (convenience only; server is source of truth)+ const saved = localStorage.getItem('x402demo.payTo');+ if (saved) $('payTo').value = saved;++ // load server config + coin catalog+ try {+ const cfg = await (await fetch('/api/config')).json();+ state.coins = cfg.coins || [];+ renderChips();+ if (cfg.configured && cfg.payTo) { $('payTo').value = cfg.payTo; markConfigured(cfg.payTo); }+ } catch (_) { /* offline — chips stay empty, page still explains itself */ }++ // confirm the npm modal is live+ try {+ const X = await whenModalReady();+ X.configure({ checkoutOrigin: location.origin, brand: { name: 'three.ws Crypto', url: 'https://three.ws' } });+ $('verPill').classList.add('ready');+ $('verText').textContent = 'modal v' + (X.version || '?') + ' · live from npm';+ } catch (err) {+ $('verText').textContent = 'modal failed to load';+ renderError(err.message);+ }+ }++ boot();+ })();+ </script>+</body>+</html>diff --git a/x402-payment-modal/examples/solana-crypto-paywall/server.mjs b/x402-payment-modal/examples/solana-crypto-paywall/server.mjsnew file mode 100644index 000000000..5106cfe85--- /dev/null+++ b/x402-payment-modal/examples/solana-crypto-paywall/server.mjs@@ -0,0 +1,279 @@+// Runnable demo: a free crypto-price API paywalled with x402 on Solana, served+// to the @three-ws/x402-payment-modal you ship on npm.+//+// What it proves end-to-end:+// 1. The published modal (loaded from unpkg in public/index.html) drives the+// whole 402 → Phantom connect → sign → settle flow with zero wallet code.+// 2. A real free API (CoinGecko, no key) is gated behind the payment and only+// returned once the USDC payment verifies + settles on Solana mainnet.+// 3. The payout wallet is set AT RUNTIME from the page — never from a .env or+// a source constant. Start the server, paste your address, then pay.+//+// The only "config" that isn't runtime is the facilitator's fee-payer sponsor+// (a PUBLIC Solana account, not a secret) and the CoinGecko/PayAI URLs.+//+// Run (from inside the three.ws repo — uses the repo's express + @solana deps):+// node x402-payment-modal/examples/solana-crypto-paywall/server.mjs+// open http://localhost:4021+//+// As a standalone project (outside this repo): `npm install`, then change the+// two relative imports below to '@three-ws/x402-payment-modal/server/express'+// and '@three-ws/x402-payment-modal/server'.++import express from 'express';+import { fileURLToPath } from 'node:url';+import { dirname, join } from 'node:path';+import { PublicKey } from '@solana/web3.js';++// In-repo: import the package's checkout helpers from source. Standalone: swap+// these for the published package subpaths (see header).+import { x402CheckoutRouter } from '../../server/express.js';+import { solanaAccept, NETWORK_SOLANA_MAINNET } from '../../server/checkout.js';++import {+ decodePaymentHeader,+ verifyPayment,+ settlePayment,+ encodePaymentResponse,+} from './facilitator.mjs';++const __dirname = dirname(fileURLToPath(import.meta.url));+const PORT = Number(process.env.PORT) || 4021;++// PayAI's facilitator co-signs Solana settlements as the fee payer. This is the+// three.ws default sponsor — a PUBLIC pubkey (it pays the SOL network fee so the+// buyer needs only USDC), NOT a secret and NOT the payout wallet. Override only+// if you point X402_FACILITATOR_URL at a facilitator with a different sponsor.+const FEE_PAYER = process.env.X402_FEE_PAYER_SOLANA || '2wKupLR9q6wXYppw8Gr2NvWxKBUqm4PPJKkQfoxHDBg4';++// A public Solana RPC works for a quick try (rate-limited). Pass a dedicated RPC+// for anything real. Not a payout/secret — purely network plumbing.+const SOLANA_RPC_URL = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';++// Price per call. USDC has 6 decimals, so $0.01 = 10000 atomic units.+const PRICE_USD = '0.01';+const PRICE_ATOMIC = '10000';++// ── Runtime merchant config (the whole point of this demo) ───────────────────+// The payout wallet lives in memory and is set from the page after boot. There+// is deliberately no env var and no default — until you POST one, the paid+// endpoint refuses to issue a challenge.+const merchant = { payTo: null, updatedAt: null };++function isValidSolanaAddress(addr) {+ if (typeof addr !== 'string' || !/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(addr)) return false;+ try {+ // eslint-disable-next-line no-new+ new PublicKey(addr);+ return true;+ } catch {+ return false;+ }+}++// CoinGecko ids the picker offers, plus a few ticker aliases so callers can pass+// "btc" instead of "bitcoin". Display metadata keeps the UI honest without a+// second API round-trip.+const COIN_META = {+ bitcoin: { symbol: 'BTC', name: 'Bitcoin' },+ ethereum: { symbol: 'ETH', name: 'Ethereum' },+ solana: { symbol: 'SOL', name: 'Solana' },+ dogecoin: { symbol: 'DOGE', name: 'Dogecoin' },+ ripple: { symbol: 'XRP', name: 'XRP' },+ cardano: { symbol: 'ADA', name: 'Cardano' },+ 'usd-coin': { symbol: 'USDC', name: 'USD Coin' },+ 'avalanche-2': { symbol: 'AVAX', name: 'Avalanche' },+};+const TICKER_ALIASES = {+ btc: 'bitcoin', eth: 'ethereum', sol: 'solana', doge: 'dogecoin',+ xrp: 'ripple', ada: 'cardano', usdc: 'usd-coin', avax: 'avalanche-2',+};++function normalizeIds(raw) {+ const list = Array.isArray(raw) ? raw : typeof raw === 'string' ? raw.split(',') : [];+ const seen = new Set();+ const out = [];+ for (const item of list) {+ const id = String(item || '').toLowerCase().trim();+ const resolved = TICKER_ALIASES[id] || id;+ if (!/^[a-z0-9-]{1,40}$/.test(resolved) || seen.has(resolved)) continue;+ seen.add(resolved);+ out.push(resolved);+ if (out.length >= 12) break;+ }+ return out;+}++async function fetchCoinGeckoPrices(ids) {+ const url =+ 'https://api.coingecko.com/api/v3/simple/price' ++ `?ids=${encodeURIComponent(ids.join(','))}` ++ '&vs_currencies=usd&include_24hr_change=true&include_market_cap=true&include_last_updated_at=true';+ const r = await fetch(url, { headers: { Accept: 'application/json' }, signal: AbortSignal.timeout(8000) });+ if (!r.ok) {+ const err = new Error(`CoinGecko responded ${r.status}`);+ err.status = 503;+ err.code = 'data_unavailable';+ throw err;+ }+ const data = await r.json();+ const coins = ids+ .filter((id) => data[id])+ .map((id) => {+ const meta = COIN_META[id] || { symbol: id.toUpperCase().slice(0, 6), name: id };+ const d = data[id];+ return {+ id,+ symbol: meta.symbol,+ name: meta.name,+ price_usd: d.usd ?? null,+ change_24h: d.usd_24h_change ?? null,+ market_cap: d.usd_market_cap ?? null,+ updated_at: d.last_updated_at ? new Date(d.last_updated_at * 1000).toISOString() : null,+ };+ });+ if (!coins.length) {+ const err = new Error('no live prices returned for the requested coins');+ err.status = 503;+ err.code = 'data_unavailable';+ throw err;+ }+ return coins;+}++// ── App ──────────────────────────────────────────────────────────────────────+const app = express();+app.use(express.json());+app.disable('x-powered-by');++// The page is same-origin, but keep CORS permissive so the modal works if the+// demo is embedded from another origin during testing.+function cors(res) {+ res.setHeader('Access-Control-Allow-Origin', '*');+ res.setHeader('Access-Control-Allow-Methods', 'GET,POST,OPTIONS');+ res.setHeader('Access-Control-Allow-Headers', 'content-type, x-payment, idempotency-key, x-idempotency-key');+ res.setHeader('Access-Control-Expose-Headers', 'x-payment-response');+}+function jsonError(res, status, code, description) {+ cors(res);+ return res.status(status).json({ error: code, error_description: description });+}++// Solana checkout endpoints the modal POSTs to (prepare + encode). Phantom only+// signs serialized transactions, so the package builds the SPL transfer here.+app.options('/api/x402-checkout', (_req, res) => { cors(res); res.status(204).end(); });+app.all('/api/x402-checkout', x402CheckoutRouter({ rpcUrl: SOLANA_RPC_URL }));++// ── Runtime payout config ─────────────────────────────────────────────────────+app.options('/api/config', (_req, res) => { cors(res); res.status(204).end(); });++app.get('/api/config', (_req, res) => {+ cors(res);+ res.json({+ configured: Boolean(merchant.payTo),+ payTo: merchant.payTo,+ updatedAt: merchant.updatedAt,+ feePayer: FEE_PAYER,+ network: 'solana',+ asset: 'USDC',+ priceUsd: PRICE_USD,+ coins: Object.entries(COIN_META).map(([id, m]) => ({ id, ...m })),+ });+});++app.post('/api/config', (req, res) => {+ const payTo = (req.body?.payTo || '').trim();+ if (!isValidSolanaAddress(payTo)) {+ return jsonError(res, 400, 'invalid_address', 'payTo must be a valid base58 Solana address');+ }+ merchant.payTo = payTo;+ merchant.updatedAt = new Date().toISOString();+ cors(res);+ res.json({ configured: true, payTo: merchant.payTo, updatedAt: merchant.updatedAt });+});++// ── The paid endpoint ─────────────────────────────────────────────────────────+// GET-less, POST-only so the resource URL (used for facilitator matching) stays+// query-free. Body: { ids: ["bitcoin", "ethereum", ...] }.+app.options('/api/paid/crypto', (_req, res) => { cors(res); res.status(204).end(); });++app.post('/api/paid/crypto', async (req, res) => {+ if (!merchant.payTo) {+ return jsonError(res, 503, 'payout_not_configured', 'Set a payout address first (POST /api/config { payTo }).');+ }++ const resourceUrl = `${req.protocol}://${req.get('host')}${req.path}`;+ const accept = solanaAccept({+ token: 'usdc',+ uiAmount: Number(PRICE_USD),+ payTo: merchant.payTo,+ feePayer: FEE_PAYER,+ maxTimeoutSeconds: 60,+ network: NETWORK_SOLANA_MAINNET,+ });+ // solanaAccept omits `resource`; the facilitator matches the signed payload+ // against it, so advertise the same absolute URL the modal will sign over.+ accept.resource = resourceUrl;++ const paymentHeader = req.headers['x-payment'];++ // No payment yet → answer with the x402 v2 challenge so the modal opens.+ if (!paymentHeader) {+ cors(res);+ return res.status(402).json({+ x402Version: 2,+ error: 'Payment required',+ resource: {+ url: resourceUrl,+ description: 'Live crypto prices (CoinGecko) — pay $0.01 USDC on Solana.',+ mimeType: 'application/json',+ },+ accepts: [accept],+ });+ }++ try {+ // 1. Verify the signed payment matches what we offered (facilitator-checked).+ const paymentPayload = decodePaymentHeader(paymentHeader);+ await verifyPayment({ paymentPayload, requirement: accept });++ // 2. Do the paid work BEFORE settling. If the live feed is down we throw a+ // 503 here and never settle — the buyer keeps their funds and can retry.+ const ids = normalizeIds(req.body?.ids);+ if (!ids.length) {+ return jsonError(res, 400, 'invalid_request', 'provide a non-empty `ids` array of CoinGecko ids');+ }+ const coins = await fetchCoinGeckoPrices(ids);++ // 3. Settle on-chain. Only now does USDC actually move.+ const settled = await settlePayment({ paymentPayload, requirement: accept });++ cors(res);+ res.setHeader('x-payment-response', encodePaymentResponse(settled));+ res.setHeader('cache-control', 'no-store');+ res.json({+ asof: new Date().toISOString(),+ base: 'usd',+ source: 'coingecko',+ coins,+ paidWith: { network: 'solana', asset: 'USDC', amount: PRICE_USD, payTo: merchant.payTo },+ });+ } catch (err) {+ return jsonError(res, err.status || 502, err.code || 'payment_failed', err.message || 'payment failed');+ }+});++// Static demo page.+app.use(express.static(join(__dirname, 'public')));++app.listen(PORT, () => {+ console.log('');+ console.log(' x402 Solana crypto paywall — demo');+ console.log(` ▸ open http://localhost:${PORT}`);+ console.log(` ▸ paid endpoint POST /api/paid/crypto`);+ console.log(` ▸ checkout router /api/x402-checkout (prepare + encode)`);+ console.log(` ▸ payout wallet set it at runtime in the page (POST /api/config)`);+ console.log(` ▸ fee payer ${FEE_PAYER} (public PayAI sponsor)`);+ console.log(` ▸ Solana RPC ${SOLANA_RPC_URL}`);+ console.log('');+});