Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat: premium pass subscriptions with billing and data-API dashboards

nirholas3fd6bf962069
diff --git a/.env.example b/.env.example
index b1efc0ce6..c2dfabc24 100644
--- a/.env.example
+++ b/.env.example
@@ -1029,6 +1029,11 @@ SEPOLIA_RPC_URL=
# Get a key at https://dashboard.alchemy.com.
ALCHEMY_API_KEY=
+# DeBank Cloud API access key — wallet/portfolio data (balances, protocol
+# positions, NFT holdings) across 190+ chains. Sent as the `AccessKey` header.
+# Get a key at https://cloud.debank.com.
+DEBANK_ACCESS_KEY=
+
# Solana RPC override for the AgenC partnership endpoints (api/agenc/*).
# Falls back to SOLANA_RPC_URL when unset.
AGENC_RPC_URL=
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a045014c2..e08b8d40b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,8 +6,14 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
## 2026-07-11
+- **Dashboard · Billing & Passes** (`/dashboard/billing`) — Manage subscriptions and paid services — Premium pass status, on-chain payment history, API keys, and creator subscriptions.
+- **Dashboard · Data API** (`/dashboard/data-api`) — Developer console for the three.ws Data API — buy the Premium pass with $THREE, SOL, or USDC, manage API keys, watch usage, and copy quickstarts.
- **DeFi Yields Explorer** (`/yields`) — Explore roughly 15,000 live DeFi yield pools across every chain and protocol — filter by chain, project, stablecoin exposure, and minimum TVL, sort by APY or TVL, and open any pool to see its full APY and TVL history. Live from DeFiLlama, no key required.
+- **Premium Pass — Monthly Data API Access** (`/docs/premium`) — One Solana payment ($THREE at 20% off, SOL, or USDC) buys 30 days of unmetered Data API access with an API key — no per-call x402 payments.
+- **Documentation accuracy pass: every tutorial verified against the shipped platform** — We cross-referenced all 300+ docs and specs against the actual codebase and fixed everything that had drifted. The embed snippet in ten tutorials now uses the real two-line form that works on any site, four tutorials that demonstrated retired or never-shipped APIs were rewritten against the live component, the troubleshooting guide now reflects the current Cloud Run production stack with the correct session and storage details, and the manifest, quick-start, and API references now list exactly the providers, attributes, and endpoints that exist today. Every code sample in the affected docs runs as written. (`/docs/tutorials/embed-in-30-seconds`) `[docs, fix]`
+- **Premium: one monthly pass instead of paying per call** — Go Premium for $9.99/30 days and stop paying the Data API per search: one Solana payment — in $THREE at 20% off, SOL, or USDC — mints an API key with unmetered archive search and lets your wallet sign in on the archive page instead of paying. Two new dashboard surfaces ship with it: a developer console at /dashboard/data-api (buy or renew the pass, manage and rotate API keys, live usage, copy-paste quickstarts) and Billing & Passes at /dashboard/billing (pass status, on-chain payment history, your subscriptions and paid services in one place). Renewals stack — renewing early adds 30 days to the end, never losing time. (`/docs/premium`) `[feature]`
- **Richer coin pages, plus new exchange, category, and DeFi-yields detail pages** — Every coin page now shows far more of what the data already offers: a 1h-to-1y price-performance matrix, a circulating-vs-max supply bar with the market-cap/FDV ratio, all-time high and low with the drawdown and recovery multiple, the community bullish/bearish sentiment split, GitHub and social activity, and a full exchange-listings table with spread, order-book depth, and a trust rating for each venue. Exchanges and crypto categories, which used to only send you off-site or filter a table, now have their own detail pages — an exchange page with a trust badge, wash-volume-adjusted volume, a volume-history chart, and its markets, and a category page with the sector's rank, stats, and full coin list. And a brand-new DeFi Yields explorer covers roughly 15,000 live pools across every chain and protocol, filterable and sortable, each with its own APY and TVL history chart. All of it is real, key-free data. (`/yields`) `[feature, improvement]`
+- **The news page becomes Your Briefing** — /markets/news is redesigned as a daily briefing: a breaking-news ticker for stories under 45 minutes old, a collapsible Today's AI Briefing card built from the digest engine, a Featured tab covering the major outlets, a Trending tab ranking the day's most-covered narratives, a Top-stories hero with a compact headline rail, and a star on every story that saves it to a personal Saved tab. Article preview images were also overhauled — thumbnails blocked by publishers now load through a same-origin proxy, and stories whose feed ships no image pull the publisher's own social preview automatically, so cards no longer show blank tiles. (`/markets/news`) `[feature, improvement]`
## 2026-07-10
diff --git a/README.md b/README.md
index 4065931e8..513f2aadb 100644
--- a/README.md
+++ b/README.md
@@ -311,7 +311,7 @@ If you want to support the project — compute credits, grants, partnerships, or
- `<agent-3d>` custom element — drop it anywhere with no framework dependency
- Five widget variants: turntable, animation gallery, talking agent, ERC-8004 passport card, hotspot tour
-- Widget Studio + WYSIWYG **Embed Editor** at `/embed-editor` — pick an avatar, animation, framing, and background, copy the snippet
+- Widget Studio + WYSIWYG **Embed editor** at `/embed` — pick an avatar, embed mode, environment, and size, copy the snippet
- **Launchpad** at `/launchpad` — hosted public launch pages at `/p/[slug]` for tokens, agents, and drops
- Open Graph metadata and oEmbed support for rich social previews when links are shared
- Versioned CDN bundles at `/agent-3d/x.y.z/agent-3d.js`
@@ -322,8 +322,8 @@ If you want to support the project — compute credits, grants, partnerships, or
- **City** at `/city` — free-roam walkable 3D city scene
- **Friends, presence & DMs** — account-level social graph with live presence ("Online · Mainland"), direct messages, and a per-account realtime delivery hub
- **The Club** at `/club` — multiplayer venue with rigged dancers, audio tracks, tips, leaderboard, payouts cron, perf-aware renderer that auto-downgrades on slow frames
-- **Walk** at `/walk` — authoritative multiplayer walk scene backed by a Colyseus server in `multiplayer/` (deployable on Fly.io)
-- **Pose Studio** at `/pose-studio`, **Voice Lab** at `/voice`, **Mocap Studio** at `/mocap-studio` — author poses, bind voices, and capture/retarget motion into reusable clips
+- **Walk** at `/walk` — authoritative multiplayer walk scene backed by a Colyseus server in `multiplayer/` (deployable on Google Cloud Run)
+- **Pose Studio** at `/pose`, **Voice Lab** at `/voice`, **Mocap Studio** at `/mocap-studio` — author poses, bind voices, and capture/retarget motion into reusable clips
**Backend & Integrations**
@@ -410,7 +410,7 @@ A map of every user-facing route. [`STRUCTURE.md`](STRUCTURE.md) maps each produ
| **Profile** | `/profile`, `/u/[username]`, `/avatars/[id]` | User and avatar public pages — SNS badge + pay-by-name modal when `[username].threews.sol` is claimed |
| **SNS Subdomain** | `/threews/claim` | Mint `[label].threews.sol`, set the URL record to your showcase, transfer ownership — single tx, platform pays |
| **Dashboard** | `/dashboard`, `/dashboard/actions`, `/dashboard/wallets`, `/dashboard/usage`, `/dashboard/x402` | Account management, settings, and x402 receipts/payouts |
-| **Studio / Tools** | `/studio`, `/embed-editor`, `/pose-studio`, `/voice`, `/mocap-studio`, `/hydrate`, `/validation`, `/strategy-lab` | Widget Studio, WYSIWYG embed editor, pose authoring, Voice Lab, Mocap Studio, on-chain import, glTF validator, DCA |
+| **Studio / Tools** | `/studio`, `/embed`, `/pose`, `/voice`, `/mocap-studio`, `/hydrate`, `/validation`, `/strategy-lab` | Widget Studio, WYSIWYG embed editor, pose authoring, Voice Lab, Mocap Studio, on-chain import, glTF validator, DCA |
| **Widgets** | `/widgets`, `/w/[id]` | Widget gallery and public widget pages (OG + oEmbed) |
| **Launchpad** | `/launchpad`, `/p/[slug]` | Launchpad Studio + hosted launch pages (token, agent, drop campaigns) |
| **Club** | `/club` | Multiplayer 3D venue — tips, leaderboard, audio tracks, perf-aware renderer |
@@ -885,17 +885,11 @@ For anything beyond a quick one-liner, define the agent in a manifest file and r
For the absolute simplest way to embed an agent, use this snippet. It requires no build tools or imports. Just copy and paste it into your HTML.
```html
-<div
- class="threews-widget"
- data-agent-id="YOUR_AGENT_ID"
- data-background="transparent"
- data-nameplate="true"
- style="width: 400px; height: 500px;"
-></div>
-<script src="https://three.ws/dist/widget.js" defer></script>
+<div data-agent-id="YOUR_AGENT_ID" style="width: 400px; height: 500px;"></div>
+<script type="module" src="https://three.ws/artifact.js"></script>
```
-You can find your agent ID in the agent's settings page. This method is great for quick integrations on platforms like WordPress, Ghost, or any static HTML site. Customize the appearance with `data-background` and `data-nameplate`.
+The loader ([public/artifact.js](public/artifact.js)) mounts a rotatable 3D viewer into every `[data-agent-id]` element on the page. You can find your agent ID in the agent's settings page. This method is great for quick integrations on platforms like WordPress, Ghost, or any static HTML site — size it with the `style` attribute. For a configurable snippet (chat mode, environments, size presets), use the [Embed editor](#embed-editor) at `/embed`.
---
@@ -1300,30 +1294,27 @@ Widgets are stored as JSON config in Postgres, pointing at an avatar in R2.
## Embed Editor
-The **Embed Editor** at `/embed-editor` is a WYSIWYG configurator for the `<agent-3d>` element. Pick an avatar from a modal grid with lazy-loaded 3D thumbnails, choose an animation from the dock, frame the camera with face-camera mode, set a background (transparent, glow, solid), and copy a ready-to-paste snippet.
+The **Embed editor** at `/embed` ([src/editor/embed-editor.js](src/editor/embed-editor.js)) is a WYSIWYG configurator for embedding a three.ws avatar or agent on any website. Pick an avatar from the gallery picker, choose an embed mode, tune the environment and size, and copy a ready-to-paste snippet.
-| Feature | Description |
-| ------------------ | ------------------------------------------------------------------------------- |
-| **Avatar picker** | Modal with lazy 3D thumbnails — no full page rerender on selection |
-| **Animation dock** | All clips visible at once; click to preview live on the model |
-| **Kiosk default** | Chrome-free preview surface — what you see is what gets embedded |
-| **Face-camera** | One-click camera framing aligned to the avatar's face |
-| **Lock toggle** | Freezes the wrap and avatar motion so you can author screenshots / video |
-| **Device frame** | Preview the embed inside phone / tablet / desktop chrome |
-| **Backdrop glow** | Optional radial glow behind the avatar (opt-in, off by default) |
-| **Snippet UX** | One-click copy of `<agent-3d>` HTML or the iframe URL — versioned CDN reference |
-
-The editor produces video-ready output for marketing assets and a copy-paste snippet for production use. Built as a single Vite-compiled bundle, no separate framework runtime.
+| Feature | Description |
+| -------------------- | ---------------------------------------------------------------------------------------- |
+| **Four embed modes** | Static (idle pose), Idle (drifts on its own), Walking (joystick/keyboard), Chat (agent page iframe) |
+| **Avatar picker** | Gallery modal (`src/avatar-gallery-picker.js`) — pick any avatar without leaving the page |
+| **Live preview** | Renders the exact runtime the snippet ships — `/walk-embed` or `/a/<id>?embed=1` |
+| **Environments** | Studio (transparent), Void, Beach, Sunset, Night, Grid |
+| **Size presets** | S / M / L plus custom width × height |
+| **Snippet UX** | Real clipboard copy of the iframe or script-tag form, with per-platform paste instructions (HTML, React, WordPress, Webflow, Shopify) |
+| **Deep-linkable** | Every control reflects into the URL query, so a configured embed can be shared and re-opened |
---
## Pose Studio
-`/pose-studio` is a 3D pose-reference tool inspired by setpose.com. It builds a Three.js scene with an articulated mannequin, orbit camera, ground + grid, and a control panel that lets you pick presets, drag joints to pose them, fine-tune with sliders, swap body type, add floor props, change lighting and FOV, and export a PNG screenshot.
+`/pose` is a 3D pose-reference tool inspired by setpose.com. It builds a Three.js scene with an articulated mannequin, orbit camera, ground + grid, and a control panel that lets you pick presets, drag joints to pose them, fine-tune with sliders, swap body type, add floor props, change lighting and FOV, and export a PNG screenshot.
| Module | Path | Role |
| -------------- | ---------------------------------------------- | ------------------------------------------- |
-| Mannequin | [src/pose-mannequin.js](src/pose-mannequin.js) | Articulated rig with named joints + IK |
+| Mannequin | [src/pose-rig.js](src/pose-rig.js) | Articulated rig with named joints + IK |
| Preset library | [src/pose-presets.js](src/pose-presets.js) | Standing, sitting, action, idle, expressive |
| Studio shell | [src/pose-studio.js](src/pose-studio.js) | Scene, controls, export, props, lighting |
diff --git a/STRUCTURE.md b/STRUCTURE.md
index 827c29a94..01ff516da 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -81,7 +81,8 @@ bottom.
| Market tools (heatmap, sentiment, gas, compare) | [pages/heatmap.html](pages/heatmap.html) + [src/heatmap.js](src/heatmap.js) `→ /heatmap`, [pages/fear-greed.html](pages/fear-greed.html) + [src/fear-greed.js](src/fear-greed.js) `→ /fear-greed`, [pages/gas.html](pages/gas.html) + [src/gas.js](src/gas.js) `→ /gas`, [pages/compare.html](pages/compare.html) + [src/compare.js](src/compare.js) `→ /compare`; backend [api/coin/fear-greed.js](api/coin/fear-greed.js), [api/coin/gas.js](api/coin/gas.js) | In-repo | Four tools extending Markets, same design system: treemap heatmap (market-cap-sized tiles), Fear & Greed gauge + history, live Ethereum gas tracker (keyless `eth_feeHistory`), and up-to-4-coin compare (overlay perf + stats). All real key-free data; cross-linked from the markets table. Docs: [docs/coin-pages.md](docs/coin-pages.md) |
| Market tools II (screener, categories, exchanges, derivatives, converter, DeFi, chains, stablecoins) | Pages+JS `→ /screener /categories /exchanges /derivatives /converter /defi /chains /stablecoins`; backend [api/coin/](api/coin) (categories, exchanges, derivatives, rates) over CoinGecko + [api/defi/](api/defi) (protocols, chains, stablecoins) over DeFiLlama | In-repo | Eight more Markets tools, same design system: token screener + category rankings + exchange/derivatives tables + crypto⇄fiat converter (CoinGecko), plus a DeFiLlama trio — DeFi TVL by protocol, chains by TVL, stablecoins with peg health. All real key-free data; cross-linked from the markets table. Docs: [docs/coin-pages.md](docs/coin-pages.md) |
| Market detail pages (exchange, category) + DeFi yields | [pages/exchange.html](pages/exchange.html) + [src/exchange-page.js](src/exchange-page.js) `→ /exchange/:id` over [api/coin/exchange.js](api/coin/exchange.js), [pages/category.html](pages/category.html) + [src/category-page.js](src/category-page.js) `→ /category/:id` over [api/coin/category.js](api/coin/category.js) + [api/coin/markets.js](api/coin/markets.js) (`?category=`), [pages/yields.html](pages/yields.html) + [src/yields.js](src/yields.js) `→ /yields` over [api/defi/yields.js](api/defi/yields.js) | In-repo | Rich detail pages that turn list rows into full profiles. Exchange: trust badge, normalized-volume stat, BTC-volume history chart, and a per-pair markets table (spot + derivatives fallback), reached from `/exchanges` and the new Derivatives Exchanges table. Category: rank, sector stats, the full sortable coins table for that sector, and related categories, reached from `/categories`. Yields: an explorer over ~15k live DeFiLlama pools with chain/project/stablecoin/min-TVL filters, APY/TVL sort, URL-synced state, and a per-pool APY+TVL history chart on row expand. Docs: [docs/coin-pages.md](docs/coin-pages.md) |
-| Crypto news + archive + markets hub | [pages/markets.html](pages/markets.html) + [src/markets-page.js](src/markets-page.js) `→ /markets`, [pages/markets-news.html](pages/markets-news.html) + [src/markets-news.js](src/markets-news.js) `→ /markets/news`, [pages/news-article.html](pages/news-article.html) + [src/news-article.js](src/news-article.js) `→ /markets/news/article`, [pages/news-archive.html](pages/news-archive.html) + [src/news-archive.js](src/news-archive.js) `→ /markets/archive`, [pages/news-digest.html](pages/news-digest.html) + [src/news-digest.js](src/news-digest.js) `→ /markets/digest`; backend [api/news/](api/news) (feed, article, archive, digest, rss) + hourly archiver [api/cron/news-archive-append.js](api/cron/news-archive-append.js) over [api/_lib/news.js](api/_lib/news.js) + [api/_lib/news-sources.js](api/_lib/news-sources.js), corpus on `gs://three-ws-news-archive` | In-repo | The Markets news wing + front door: live news aggregated natively from 192 publisher feeds (category tabs, search, sentiment, ticker chips), a rich article reader (server-side extraction, AI summary/key points with extractive fallback, related coverage), the largest open crypto-news archive (662,047 enriched articles, Sept 2017 → today, EN+中文, GCS-hosted), and the /markets hub aggregating global stats, the top-100 table, breaking news, and every market surface as a hero card. Docs: [docs/coin-pages.md](docs/coin-pages.md), [docs/api-reference.md](docs/api-reference.md) |
+| Crypto news + archive + markets hub | [pages/markets.html](pages/markets.html) + [src/markets-page.js](src/markets-page.js) `→ /markets`, [pages/markets-news.html](pages/markets-news.html) + [src/markets-news.js](src/markets-news.js) `→ /markets/news`, [pages/news-article.html](pages/news-article.html) + [src/news-article.js](src/news-article.js) `→ /markets/news/article`, [pages/news-archive.html](pages/news-archive.html) + [src/news-archive.js](src/news-archive.js) `→ /markets/archive`, [pages/news-digest.html](pages/news-digest.html) + [src/news-digest.js](src/news-digest.js) `→ /markets/digest`; backend [api/news/](api/news) (feed, article, archive, digest, rss, image) + hourly archiver [api/cron/news-archive-append.js](api/cron/news-archive-append.js) over [api/_lib/news.js](api/_lib/news.js) + [api/_lib/news-sources.js](api/_lib/news-sources.js), corpus on `gs://three-ws-news-archive` | In-repo | The Markets news wing + front door: /markets/news is “Your briefing” — live news aggregated natively from 192 publisher feeds (Featured/Trending/Saved tabs, breaking ticker, AI briefing card, top-stories hero + rail, search, sentiment, ticker chips, og:image preview resolution for imageless feeds), a rich article reader (server-side extraction, AI summary/key points with extractive fallback, related coverage), the largest open crypto-news archive (662,047 enriched articles, Sept 2017 → today, EN+中文, GCS-hosted), and the /markets hub aggregating global stats, the top-100 table, breaking news, and every market surface as a hero card. Docs: [docs/coin-pages.md](docs/coin-pages.md), [docs/api-reference.md](docs/api-reference.md) |
+| Premium Data API pass | [api/premium/](api/premium) + [api/_lib/premium.js](api/_lib/premium.js), dashboards [src/dashboard-next/pages/data-api.js](src/dashboard-next/pages/data-api.js) `→ /dashboard/data-api` + [src/dashboard-next/pages/billing.js](src/dashboard-next/pages/billing.js) `→ /dashboard/billing` | In-repo | Monthly pass ($9.99/30d) paid on Solana in $THREE (20% off), SOL, or USDC — replaces per-call x402 on the news archive with an `x402_live_` API key (existing access-control lane) + SIWX browser grants. Quote→sign→verify flow with on-chain balance-delta verification; tables `premium_passes`/`premium_quotes`. Docs: [docs/premium.md](docs/premium.md) |
| Liquidations pulse (/coins) | Collector [services/liquidation-collector/](services/liquidation-collector) (standalone always-on Node service, ported from SperaxOS), proxy [api/coin/liquidations.js](api/coin/liquidations.js) `→ GET /api/coin/liquidations`, UI strip in [src/coins-index.js](src/coins-index.js) `→ /coins` | Live — collector on Cloud Run (`liquidation-collector`, min-instances 1, unthrottled CPU) since 2026-07-10 | Real-time long/short liquidation pain across Binance, Bybit, and OKX public futures WebSocket streams: dominant-side badge (LONG PAIN / SHORT SQUEEZE / BALANCED), 1h long-vs-short bars, and the 3 largest recent liquidations, polled every 30s (pauses on hidden tab). The collector holds long-lived WebSockets so it can't run as a Vercel function — deploy it separately and point `LIQUIDATION_COLLECTOR_URL` at it. No fallback data: the proxy 503s `collector_offline` (never fabricated numbers) when unset or unreachable, and the strip degrades to a quiet single-line offline state. Docs: [docs/api-reference.md#liquidations](docs/api-reference.md#liquidations) |
| BNB Chain campaign hub | [pages/bnb.html](pages/bnb.html) + [src/bnb.js](src/bnb.js) `→ /bnb`, pure helpers [src/bnb-hub-helpers.js](src/bnb-hub-helpers.js), live block-time API [api/bnb/block-time.js](api/bnb/block-time.js) over [api/_lib/bnb/chains.js](api/_lib/bnb/chains.js) `probeBlockTime` | In-repo · hub live, tracks rolling out | The campaign's front door: three feature cards (gasless agent onboarding, on-chain-gated 3D vault, real-time on-chain world), each claim traced to `prompts/bnb-chain/00-CONTEXT.md`'s verified facts (0.45s blocks — never 20k TPS or 250ms finality). Embeds a live block-time widget (real RPC measurement on every load). Each card self-detects liveness via a real HTTP probe against its track's route/API on the running deployment — a 404 renders a designed "coming soon" state, never a dead link — so cards auto-light-up as the sibling tracks below ship: gasless registration `→ /create-agent` + `api/bnb/register-agent.js` (prompt 03), vault `→ /vault` (prompt 12), on-chain world `→ /bnb-latency` (prompt 17) + the Explore on-chain toggle (prompt 16). Campaign root: [prompts/bnb-chain/](prompts/bnb-chain) |
| BABT holder check (BNB Chain) | Lib [api/_lib/bnb/babt.js](api/_lib/bnb/babt.js) `hasBabt()`, free API [api/bnb/babt-check.js](api/bnb/babt-check.js) `→ GET /api/bnb/babt-check?address=` | In-repo · shipped | Free, rate-limited on-chain check for whether a BSC address holds a Binance Account Bound Token (BABT) — a real, live, KYC-backed soulbound token (1.16M+ mainnet holders, verified via `eth_getCode`/`balanceOf` against the real contract `0x2B09d47D...5215D7c8`). Verification writeup + honest comparison vs. Gitcoin Passport/World ID/Coinbase attestations: [docs/bnb-babt-findings.md](docs/bnb-babt-findings.md). Spike prompt: `prompts/bnb-chain/20-babt-verification-spike.md`. |
diff --git a/api/_lib/migrations/2026-07-11-premium-passes.sql b/api/_lib/migrations/2026-07-11-premium-passes.sql
new file mode 100644
index 000000000..0c306e090
--- /dev/null
+++ b/api/_lib/migrations/2026-07-11-premium-passes.sql
@@ -0,0 +1,54 @@
+-- three.ws Premium — monthly developer pass, paid on Solana in $THREE / SOL / USDC.
+--
+-- premium_quotes: short-lived (10 min) price locks. A quote freezes the USD plan
+-- price into an exact atomic amount for the chosen asset at the
+-- oracle price of that moment, so verification compares the
+-- landed transaction against the locked number — never a
+-- re-fetched price.
+-- premium_passes: the purchase ledger AND the entitlement source of truth. One
+-- row per successful purchase; the wallet's current pass is the
+-- row with the latest expires_at. Renewals append a row whose
+-- period starts at the previous expiry (no lost days).
+--
+-- Apply with: node scripts/apply-migrations.mjs --apply --file 2026-07-11-premium-passes.sql
+
+create table if not exists premium_quotes (
+ id uuid primary key default gen_random_uuid(),
+ wallet text not null,
+ plan text not null default 'premium',
+ asset text not null check (asset in ('THREE', 'SOL', 'USDC')),
+ amount_atomics bigint not null check (amount_atomics > 0),
+ usd_price numeric(12, 4) not null,
+ asset_usd numeric(20, 10), -- oracle price used (null for USDC parity)
+ price_source text, -- which oracle produced asset_usd
+ status text not null default 'pending' check (status in ('pending', 'used', 'expired')),
+ tx_signature text, -- set when the quote is consumed
+ user_id uuid, -- session user at quote time, when present
+ created_at timestamptz not null default now(),
+ expires_at timestamptz not null
+);
+
+create index if not exists premium_quotes_wallet_idx
+ on premium_quotes (wallet, created_at desc);
+
+create table if not exists premium_passes (
+ id uuid primary key default gen_random_uuid(),
+ wallet text not null,
+ user_id uuid, -- session user at purchase time, when present
+ plan text not null default 'premium',
+ asset text not null check (asset in ('THREE', 'SOL', 'USDC')),
+ amount_atomics bigint not null,
+ usd_price numeric(12, 4) not null,
+ tx_signature text not null unique,
+ network text not null default 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',
+ api_subscription_id text, -- linked x402_subscriptions key id
+ started_at timestamptz not null default now(),
+ expires_at timestamptz not null,
+ created_at timestamptz not null default now(),
+ meta jsonb not null default '{}'::jsonb
+);
+
+create index if not exists premium_passes_wallet_idx
+ on premium_passes (wallet, expires_at desc);
+create index if not exists premium_passes_user_idx
+ on premium_passes (user_id, expires_at desc);
diff --git a/api/_lib/premium.js b/api/_lib/premium.js
new file mode 100644
index 000000000..e7947edb6
--- /dev/null
+++ b/api/_lib/premium.js
@@ -0,0 +1,420 @@
+// three.ws Premium — the monthly developer pass.
+//
+// One purchase on Solana ($THREE, SOL, or USDC) buys 30 days of premium API
+// access. Instead of paying the x402 challenge on every call (the AIXBT
+// complaint), a pass holder gets:
+// • an `x402_live_…` API key (an x402_subscriptions row) that the existing
+// installAccessControl() lane already honours on every paid route — no
+// per-route changes needed for the key lane;
+// • SIWX grants on each premium resource so a browser wallet re-enters by
+// signature (the paidEndpoint SIWX short-circuit), no key required.
+//
+// Flow: quote (lock USD→asset price for 10 min, build the unsigned Solana tx)
+// → buyer signs + sends from their own wallet
+// → subscribe (verify the LANDED tx on-chain against the locked quote,
+// one-shot claim, mint/extend the pass + key + grants).
+//
+// Payment verification is balance-delta based (the technique
+// subscription-checkout.js uses): parse the confirmed transaction and require
+// the treasury's token (or lamport) balance to have grown by at least the
+// quoted amount, with the paying wallet among the signers. The tx_signature
+// UNIQUE constraint makes claims idempotent and replay-proof.
+//
+// $THREE gets a configurable discount (default 20%) — the platform coin is the
+// cheapest way to go premium, by design.
+
+import { PublicKey, SystemProgram, TransactionMessage, VersionedTransaction } from '@solana/web3.js';
+import {
+ TOKEN_PROGRAM_ID,
+ ASSOCIATED_TOKEN_PROGRAM_ID,
+ getAssociatedTokenAddressSync,
+ createAssociatedTokenAccountIdempotentInstruction,
+ createTransferCheckedInstruction,
+} from '@solana/spl-token';
+
+import { sql } from './db.js';
+import { env } from './env.js';
+import { solPriceUsd } from './sol-price.js';
+import { getTokenPriceUsd } from './token/price.js';
+import { usdToUsdcAtomics, USDC_DECIMALS } from './subscription-pricing.js';
+import { createSubscription } from './x402/api-keys.js';
+import { siwxStorage } from './siwx-storage.js';
+import { solanaConnection } from './solana/connection.js';
+import { rpcFallbackFromEnv } from './solana/rpc-fallback.js';
+import { NETWORK_SOLANA_MAINNET } from './x402-spec.js';
+
+// ── Plan ─────────────────────────────────────────────────────────────────────
+
+const num = (v, fallback) => {
+ const n = Number(v);
+ return Number.isFinite(n) && n > 0 ? n : fallback;
+};
+
+export function premiumPlan() {
+ const usd = num(process.env.PREMIUM_PASS_USD, 9.99);
+ const threeDiscount = Math.min(0.9, Math.max(0, num(process.env.PREMIUM_PASS_THREE_DISCOUNT, 0.2)));
+ return {
+ id: 'premium',
+ name: 'three.ws Premium',
+ usd,
+ days: num(process.env.PREMIUM_PASS_DAYS, 30),
+ threeDiscount,
+ threeUsd: Math.round(usd * (1 - threeDiscount) * 100) / 100,
+ rateLimitPerMinute: num(process.env.PREMIUM_RATE_LIMIT_PER_MINUTE, 120),
+ };
+}
+
+// Resources the pass unlocks via SIWX browser grants. The API-key lane is
+// route-agnostic (installAccessControl honours the key on every paid route);
+// this list only controls which resources a browser wallet can re-enter by
+// signature. Grow it as more freemium surfaces join the pass.
+export const PREMIUM_RESOURCES = ['https://three.ws/api/news/archive'];
+
+const QUOTE_TTL_MS = 10 * 60_000;
+const SOL_DECIMALS = 9;
+
+function assetConfig(asset) {
+ if (asset === 'USDC') {
+ return { mint: env.X402_ASSET_MINT_SOLANA, decimals: USDC_DECIMALS };
+ }
+ if (asset === 'THREE') {
+ return { mint: env.THREE_TOKEN_MINT, decimals: Number(env.THREE_TOKEN_DECIMALS) || 6 };
+ }
+ if (asset === 'SOL') {
+ return { mint: null, decimals: SOL_DECIMALS }; // native
+ }
+ const err = new Error('asset must be THREE, SOL, or USDC');
+ err.status = 400;
+ err.code = 'bad_asset';
+ throw err;
+}
+
+export function treasuryWallet() {
+ const to = env.X402_PAY_TO_SOLANA;
+ if (!to) {
+ const err = new Error('premium purchases are not configured (X402_PAY_TO_SOLANA unset)');
+ err.status = 503;
+ err.code = 'not_configured';
+ throw err;
+ }
+ return to;
+}
+
+// ── Pricing ──────────────────────────────────────────────────────────────────
+
+/**
+ * Convert the plan's USD price into an atomic amount of `asset` at the current
+ * oracle price. Returns { atomics, assetUsd, priceSource, usd }.
+ */
+export async function priceAsset(asset) {
+ const plan = premiumPlan();
+ if (asset === 'USDC') {
+ return { atomics: BigInt(usdToUsdcAtomics(plan.usd)), assetUsd: null, priceSource: 'parity', usd: plan.usd };
+ }
+ if (asset === 'SOL') {
+ const sol = await solPriceUsd();
+ if (!Number.isFinite(sol) || sol <= 0) {
+ const err = new Error('SOL price unavailable right now — pay in USDC or $THREE, or retry shortly');
+ err.status = 503;
+ err.code = 'price_unavailable';
+ throw err;
+ }
+ const lamports = BigInt(Math.ceil((plan.usd / sol) * 1e9));
+ return { atomics: lamports, assetUsd: sol, priceSource: 'sol-oracle', usd: plan.usd };
+ }
+ if (asset === 'THREE') {
+ // $THREE holders pay the discounted price — the platform coin is the
+ // cheapest way in.
+ const { priceUsd, source } = await getTokenPriceUsd({});
+ const decimals = Number(env.THREE_TOKEN_DECIMALS) || 6;
+ const atomics = BigInt(Math.ceil((plan.threeUsd / priceUsd) * 10 ** decimals));
+ return { atomics, assetUsd: priceUsd, priceSource: source, usd: plan.threeUsd };
+ }
+ return assetConfig(asset); // throws bad_asset
+}
+
+// ── Quote (price lock + unsigned tx) ─────────────────────────────────────────
+
+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+
+export function assertWallet(wallet) {
+ if (!wallet || !BASE58_RE.test(wallet)) {
+ const err = new Error('wallet must be a base58 Solana address');
+ err.status = 400;
+ err.code = 'bad_wallet';
+ throw err;
+ }
+ return wallet;
+}
+
+/**
+ * Build the unsigned payment transaction (buyer is fee payer, single transfer
+ * to the treasury) and persist the locked quote. Returns
+ * { quote, tx_base64 } where quote carries id/asset/atomics/expiry.
+ */
+export async function createQuote({ wallet, asset, userId = null }) {
+ assertWallet(wallet);
+ const { mint, decimals } = assetConfig(asset);
+ const payTo = treasuryWallet();
+ const plan = premiumPlan();
+ const priced = await priceAsset(asset);
+
+ const buyer = new PublicKey(wallet);
+ const dest = new PublicKey(payTo);
+ const instructions = [];
+ if (asset === 'SOL') {
+ instructions.push(
+ SystemProgram.transfer({ fromPubkey: buyer, toPubkey: dest, lamports: priced.atomics }),
+ );
+ } else {
+ const mintKey = new PublicKey(mint);
+ const fromAta = getAssociatedTokenAddressSync(mintKey, buyer, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID);
+ const toAta = getAssociatedTokenAddressSync(mintKey, dest, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID);
+ instructions.push(
+ // Buyer funds the treasury ATA if it doesn't exist yet (idempotent, a
+ // few cents once, no-op forever after).
+ createAssociatedTokenAccountIdempotentInstruction(buyer, toAta, dest, mintKey, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID),
+ createTransferCheckedInstruction(fromAta, mintKey, toAta, buyer, priced.atomics, decimals, [], TOKEN_PROGRAM_ID),
+ );
+ }
+
+ const conn = solanaConnection();
+ const { blockhash } = await conn.getLatestBlockhash('confirmed');
+ const message = new TransactionMessage({
+ payerKey: buyer,
+ recentBlockhash: blockhash,
+ instructions,
+ }).compileToV0Message();
+ const tx = new VersionedTransaction(message);
+ const txBase64 = Buffer.from(tx.serialize()).toString('base64');
+
+ // Opportunistic GC — dead quotes are worthless after their redeem window;
+ // pruning here keeps the table tiny without needing a cron.
+ sql`delete from premium_quotes where status = 'pending' and created_at < now() - interval '7 days'`
+ .catch(() => {});
+
+ const expiresAt = new Date(Date.now() + QUOTE_TTL_MS).toISOString();
+ const [quote] = await sql`
+ insert into premium_quotes
+ (wallet, plan, asset, amount_atomics, usd_price, asset_usd, price_source, user_id, expires_at)
+ values
+ (${wallet}, ${plan.id}, ${asset}, ${priced.atomics.toString()}, ${priced.usd},
+ ${priced.assetUsd}, ${priced.priceSource}, ${userId}, ${expiresAt})
+ returning id, wallet, plan, asset, amount_atomics, usd_price, expires_at
+ `;
+ return { quote, tx_base64: txBase64 };
+}
+
+// ── On-chain verification ────────────────────────────────────────────────────
+
+const rpc = () => rpcFallbackFromEnv({ network: 'mainnet', commitment: 'confirmed' });
+
+/**
+ * Verify that `txSignature` is a landed, successful transaction in which
+ * `quote.wallet` (a signer) moved ≥ quote.amount_atomics of the quoted asset
+ * to the treasury. Balance-delta based, robust to ATA addressing and versioned
+ * transactions. Returns { ok: true } or { ok: false, pending?, reason }.
+ */
+export async function verifyPassPayment(quote, txSignature) {
+ const payTo = treasuryWallet();
+ const { mint } = assetConfig(quote.asset);
+ let tx;
+ try {
+ tx = await rpc().withFallback((conn) =>
+ conn.getParsedTransaction(txSignature, {
+ commitment: 'confirmed',
+ maxSupportedTransactionVersion: 0,
+ }),
+ );
+ } catch (e) {
+ // "Invalid param" from the RPC means the signature itself is malformed —
+ // that never becomes confirmable, so fail hard instead of telling the
+ // client to keep polling.
+ if (/invalid param/i.test(e.message || '')) {
+ return { ok: false, reason: `not a valid transaction signature: ${e.message}` };
+ }
+ return { ok: false, pending: true, reason: `rpc lookup failed: ${e.message}` };
+ }
+ if (!tx) return { ok: false, pending: true, reason: 'transaction not found yet — still confirming' };
+ if (tx.meta?.err) return { ok: false, reason: 'transaction failed on-chain' };
+
+ const keys = tx.transaction?.message?.accountKeys || [];
+ const signers = keys.filter((k) => k.signer).map((k) => String(k.pubkey));
+ if (!signers.includes(quote.wallet)) {
+ return { ok: false, reason: 'the quoted wallet did not sign this transaction' };
+ }
+
+ const need = BigInt(quote.amount_atomics);
+ if (quote.asset === 'SOL') {
+ const idx = keys.findIndex((k) => String(k.pubkey) === payTo);
+ if (idx === -1) return { ok: false, reason: 'treasury wallet not present in transaction' };
+ const delta = BigInt(tx.meta.postBalances?.[idx] ?? 0) - BigInt(tx.meta.preBalances?.[idx] ?? 0);
+ if (delta < need) return { ok: false, reason: `treasury received ${delta} lamports, need ${need}` };
+ return { ok: true };
+ }
+
+ const matches = (b) => b && b.mint === mint && b.owner === payTo;
+ const pre = tx.meta.preTokenBalances?.find(matches);
+ const post = tx.meta.postTokenBalances?.find(matches);
+ const delta = BigInt(post?.uiTokenAmount?.amount ?? '0') - BigInt(pre?.uiTokenAmount?.amount ?? '0');
+ if (delta < need) return { ok: false, reason: `treasury received ${delta} atomics of ${quote.asset}, need ${need}` };
+ return { ok: true };
+}
+
+// ── Activation ───────────────────────────────────────────────────────────────
+
+async function currentPass(wallet) {
+ const [row] = await sql`
+ select * from premium_passes
+ where wallet = ${wallet} and expires_at > now()
+ order by expires_at desc
+ limit 1
+ `;
+ return row || null;
+}
+
+/**
+ * One-shot claim of a verified quote: appends the pass period (renewals start
+ * at the previous expiry — no lost days), mints or extends the linked
+ * `x402_live_` API key, and records SIWX grants for every premium resource.
+ *
+ * Idempotent: re-submitting the same tx_signature returns the existing pass
+ * (with the key prefix, not the plaintext — that is shown exactly once).
+ */
+export async function activatePass({ quote, txSignature, userId = null }) {
+ const plan = premiumPlan();
+
+ // Claim the quote first — a lost race here means someone else's request is
+ // already activating this exact payment; fall through to the idempotent read.
+ const [claimed] = await sql`
+ update premium_quotes
+ set status = 'used', tx_signature = ${txSignature}
+ where id = ${quote.id} and status = 'pending'
+ returning id
+ `;
+ if (!claimed) {
+ const [existing] = await sql`
+ select * from premium_passes where tx_signature = ${txSignature} limit 1
+ `;
+ if (existing) return { pass: existing, apiKey: null, renewed: true };
+ const err = new Error('quote already used with a different transaction');
+ err.status = 409;
+ err.code = 'quote_used';
+ throw err;
+ }
+
+ const prev = await currentPass(quote.wallet);
+ const startsAt = prev ? new Date(prev.expires_at) : new Date();
+ const expiresAt = new Date(startsAt.getTime() + plan.days * 86_400_000);
+
+ // Key: extend the wallet's existing premium key, else mint a fresh one.
+ let apiKey = null;
+ let subscriptionId = prev?.api_subscription_id || null;
+ if (subscriptionId) {
+ const [extended] = await sql`
+ update x402_subscriptions
+ set expires_at = ${expiresAt.toISOString()}
+ where id = ${subscriptionId} and revoked_at is null
+ returning id
+ `;
+ if (!extended) subscriptionId = null; // key was revoked — mint a new one
+ }
+ if (!subscriptionId) {
+ const sub = await createSubscription({
+ name: `Premium pass · ${quote.wallet.slice(0, 4)}…${quote.wallet.slice(-4)}`,
+ rateLimitPerMinute: plan.rateLimitPerMinute,
+ expiresAt: expiresAt.toISOString(),
+ meta: { source: 'premium-pass', wallet: quote.wallet, user_id: userId },
+ createdBy: userId,
+ });
+ subscriptionId = sub.id;
+ apiKey = sub.token; // plaintext — surfaced exactly once
+ }
+
+ let pass;
+ try {
+ [pass] = await sql`
+ insert into premium_passes
+ (wallet, user_id, plan, asset, amount_atomics, usd_price, tx_signature,
+ network, api_subscription_id, started_at, expires_at, meta)
+ values
+ (${quote.wallet}, ${userId}, ${plan.id}, ${quote.asset}, ${quote.amount_atomics},
+ ${quote.usd_price}, ${txSignature}, ${NETWORK_SOLANA_MAINNET}, ${subscriptionId},
+ ${startsAt.toISOString()}, ${expiresAt.toISOString()},
+ ${JSON.stringify({ quote_id: quote.id })})
+ returning *
+ `;
+ } catch (e) {
+ // UNIQUE(tx_signature) race — the concurrent claimer won; serve its pass.
+ const [existing] = await sql`
+ select * from premium_passes where tx_signature = ${txSignature} limit 1
+ `;
+ if (existing) return { pass: existing, apiKey: null, renewed: true };
+ throw e;
+ }
+
+ // Browser lane: SIWX grants until the pass expires. Failures here must not
+ // eat a settled payment — the key lane already works; grants self-heal on
+ // the next renewal.
+ const ttlSeconds = Math.floor((expiresAt.getTime() - Date.now()) / 1000);
+ for (const resource of PREMIUM_RESOURCES) {
+ try {
+ await siwxStorage.recordPayment(resource, quote.wallet, {
+ network: NETWORK_SOLANA_MAINNET,
+ ttlSeconds,
+ });
+ } catch (e) {
+ console.error('[premium] siwx grant failed', resource, e.message);
+ }
+ }
+
+ return { pass, apiKey, renewed: Boolean(prev) };
+}
+
+// ── Status ───────────────────────────────────────────────────────────────────
+
+/** Everything the dashboard needs for one wallet, in one query round. */
+export async function passStatus(wallet) {
+ assertWallet(wallet);
+ const pass = await currentPass(wallet);
+ const history = await sql`
+ select id, plan, asset, amount_atomics, usd_price, tx_signature, started_at, expires_at, created_at
+ from premium_passes
+ where wallet = ${wallet}
+ order by created_at desc
+ limit 24
+ `;
+ let keys = [];
+ if (pass?.api_subscription_id) {
+ keys = await sql`
+ select s.id, s.name, s.key_prefix, s.rate_limit_per_minute, s.expires_at, s.revoked_at,
+ u.granted, u.denied, u.last_seen
+ from x402_subscriptions s
+ left join lateral (
+ select count(*) filter (where granted) as granted,
+ count(*) filter (where not granted) as denied,
+ max(created_at) as last_seen
+ from x402_access_log
+ where caller_id = 'subscription:' || s.id
+ ) u on true
+ where s.id = ${pass.api_subscription_id}
+ `;
+ }
+ return {
+ active: Boolean(pass),
+ pass: pass
+ ? { id: pass.id, plan: pass.plan, started_at: pass.started_at, expires_at: pass.expires_at, asset: pass.asset }
+ : null,
+ resources: PREMIUM_RESOURCES,
+ keys: keys.map((k) => ({
+ id: k.id,
+ name: k.name,
+ key_prefix: k.key_prefix,
+ rate_limit_per_minute: k.rate_limit_per_minute,
+ expires_at: k.expires_at,
+ status: k.revoked_at ? 'revoked' : 'active',
+ usage: { granted: Number(k.granted || 0), denied: Number(k.denied || 0), last_seen: k.last_seen || null },
+ })),
+ history,
+ };
+}
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index d2e2c67df..4dafea8a1 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -1254,6 +1254,15 @@ export const limits = {
// fails closed to the 402 challenge rather than uncapping the scan path.
newsArchiveFreeIp: (ip) =>
getLimiter('news:archive:free:ip', { limit: 60, window: '1 d', critical: true }).limit(ip),
+ // Premium-pass purchase lane (api/premium/*). Quote builds a Solana tx (an
+ // RPC blockhash round-trip + a DB row) and subscribe replays an RPC
+ // getParsedTransaction per attempt — both cheap, but neither should be
+ // free-form scriptable. Status is a read for the dashboards.
+ premiumQuoteIp: (ip) => getLimiter('premium:quote:ip', { limit: 10, window: '10 m' }).limit(ip),
+ premiumSubscribeIp: (ip) =>
+ getLimiter('premium:subscribe:ip', { limit: 30, window: '10 m' }).limit(ip),
+ premiumStatusIp: (ip) =>
+ getLimiter('premium:status:ip', { limit: 120, window: '1 m', local: true }).limit(ip),
// Fact Checker (api/x402/fact-check) free daily lane. Same "free tier is the
// funnel, x402 is the metered overage" shape as the AI speech routes above —
// each free check runs the REAL search+LLM chain (never a degraded fake), so
diff --git a/api/_lib/x402/ring-catalog.js b/api/_lib/x402/ring-catalog.js
index a8c833ce0..ef3e1a7fa 100644
--- a/api/_lib/x402/ring-catalog.js
+++ b/api/_lib/x402/ring-catalog.js
@@ -625,6 +625,23 @@ export const RING_CATALOG = [
},
// ── autobuy:false — covered by one-time verification, not the loop ──────────
+ {
+ slug: 'news-archive-search',
+ sourceFile: 'api/news/archive.js',
+ path: '/api/news/archive',
+ method: 'GET',
+ query: { q: 'bitcoin', limit: '5' },
+ body: NO_BODY,
+ priceAtomicDefault: 1_000,
+ priceSlug: 'news-archive',
+ tier: 'intel',
+ kind: 'intel',
+ network: null,
+ autobuy: false,
+ weight: 0,
+ businessEffect: 'Full-text search over the 662k-article crypto-news archive (Sept 2017 →) with sentiment/ticker/date filters.',
+ note: 'autobuy:false — freemium rail: 60 searches/day per IP are free, so a ring call usually gets a free 200, not a 402; the paid twin only engages over quota.',
+ },
{
slug: 'pump-launch',
sourceFile: 'api/x402/pump-launch.js',
diff --git a/api/news/archive.js b/api/news/archive.js
index b49af738e..d41c60b71 100644
--- a/api/news/archive.js
+++ b/api/news/archive.js
@@ -294,7 +294,17 @@ function paidRail() {
tags: ['news', 'crypto', 'archive', 'search', 'data'],
}),
requiredScope: 'x402:bypass',
+ // Bypass lanes, in order: internal key → x402_live_ API key (premium
+ // passes mint one — see api/_lib/premium.js) → OAuth bearer.
accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),
+ // Browser lane: a wallet holding a SIWX grant re-enters by signature.
+ // A premium-pass purchase records a grant until the pass expires; a
+ // per-call $0.001 payment earns a short search session so one payment
+ // isn't one query.
+ siwx: {
+ statement: 'Access the three.ws crypto-news archive with your premium pass or recent payment.',
+ ttlSeconds: 900,
+ },
async handler({ req }) {
const params = new URL(req.url, 'http://x').searchParams;
const body = await archiveSearch(parseSearchParams(params));
diff --git a/api/premium/keys.js b/api/premium/keys.js
new file mode 100644
index 000000000..4c84cbdce
--- /dev/null
+++ b/api/premium/keys.js
@@ -0,0 +1,77 @@
+// POST /api/premium/keys — rotate or revoke the signed-in user's premium key.
+//
+// body: { action: 'rotate' | 'revoke', id: '<x402 subscription id>' }
+//
+// Session + CSRF authed. Only keys minted by a premium-pass purchase that is
+// linked to this user (meta.source = 'premium-pass', meta.user_id = session
+// user) can be managed here — partner/AWS keys live at
+// /api/user/x402-subscriptions, and wallet-only purchases (no session at buy
+// time) manage nothing here by design: the key follows the account that
+// bought it.
+//
+// rotate returns the fresh plaintext exactly once and re-links the pass row
+// so status/mine keep reporting the live key.
+
+import { cors, json, error, wrap, method, readJson } from '../_lib/http.js';
+import { sql } from '../_lib/db.js';
+import { getSessionUser } from '../_lib/auth.js';
+import { requireCsrf } from '../_lib/csrf.js';
+import { createSubscription, revokeSubscription } from '../_lib/x402/api-keys.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ let user;
+ try {
+ user = await getSessionUser(req);
+ } catch {
+ user = null;
+ }
+ if (!user) return json(res, 401, { error: 'unauthenticated' });
+ if (!(await requireCsrf(req, res, user.id))) return;
+
+ const body = await readJson(req).catch(() => null);
+ const action = String(body?.action || '');
+ const id = String(body?.id || '').trim();
+ if (!['rotate', 'revoke'].includes(action)) {
+ return error(res, 400, 'bad_action', 'action must be rotate or revoke');
+ }
+ if (!id) return error(res, 400, 'bad_id', 'id is required');
+
+ const [key] = await sql`
+ select id, name, rate_limit_per_minute, expires_at, revoked_at, meta
+ from x402_subscriptions
+ where id = ${id}
+ limit 1
+ `;
+ if (!key || key.meta?.source !== 'premium-pass' || key.meta?.user_id !== user.id) {
+ return error(res, 404, 'key_not_found', 'no premium key with that id belongs to this account');
+ }
+
+ if (action === 'revoke') {
+ await revokeSubscription(id);
+ return json(res, 200, { revoked: true, id }, { 'cache-control': 'no-store' });
+ }
+
+ // rotate — revoke the old credential, mint a replacement with the same
+ // expiry/limits/meta, and re-point the pass rows at the new key.
+ if (key.revoked_at) return error(res, 409, 'key_revoked', 'key is revoked — buy or renew a pass to get a new one');
+ await revokeSubscription(id);
+ const fresh = await createSubscription({
+ name: key.name,
+ rateLimitPerMinute: key.rate_limit_per_minute,
+ expiresAt: key.expires_at,
+ meta: key.meta,
+ createdBy: user.id,
+ });
+ await sql`
+ update premium_passes set api_subscription_id = ${fresh.id}
+ where api_subscription_id = ${id}
+ `;
+ return json(
+ res, 200,
+ { rotated: true, id: fresh.id, key_prefix: fresh.key_prefix, api_key: fresh.token },
+ { 'cache-control': 'no-store' },
+ );
+});
diff --git a/api/premium/mine.js b/api/premium/mine.js
new file mode 100644
index 000000000..5dc92f2bc
--- /dev/null
+++ b/api/premium/mine.js
@@ -0,0 +1,78 @@
+// GET /api/premium/mine — the signed-in user's premium passes and keys.
+//
+// Session-cookie authed (the billing dashboard's data source). Returns passes
+// purchased while signed in (user_id-linked) plus, when the account has a
+// wallet_address that is a Solana key, passes bought by that wallet directly.
+
+import { cors, json, wrap, method } from '../_lib/http.js';
+import { sql } from '../_lib/db.js';
+import { getSessionUser } from '../_lib/auth.js';
+import { premiumPlan, PREMIUM_RESOURCES } from '../_lib/premium.js';
+
+const SOLANA_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ let user;
+ try {
+ user = await getSessionUser(req);
+ } catch {
+ user = null;
+ }
+ if (!user) return json(res, 401, { error: 'unauthenticated' });
+
+ const wallet = SOLANA_RE.test(user.wallet_address || '') ? user.wallet_address : null;
+ const passes = await sql`
+ select id, wallet, plan, asset, amount_atomics, usd_price, tx_signature,
+ api_subscription_id, started_at, expires_at, created_at
+ from premium_passes
+ where user_id = ${user.id} ${wallet ? sql`or wallet = ${wallet}` : sql``}
+ order by created_at desc
+ limit 50
+ `;
+
+ const subIds = [...new Set(passes.map((p) => p.api_subscription_id).filter(Boolean))];
+ let keys = [];
+ if (subIds.length) {
+ keys = await sql`
+ select s.id, s.name, s.key_prefix, s.rate_limit_per_minute, s.expires_at, s.revoked_at,
+ s.meta, u.granted, u.denied, u.last_seen
+ from x402_subscriptions s
+ left join lateral (
+ select count(*) filter (where granted) as granted,
+ count(*) filter (where not granted) as denied,
+ max(created_at) as last_seen
+ from x402_access_log
+ where caller_id = 'subscription:' || s.id
+ ) u on true
+ where s.id = any(${subIds})
+ `;
+ }
+
+ const now = Date.now();
+ const active = passes.find((p) => new Date(p.expires_at).getTime() > now) || null;
+ return json(
+ res, 200,
+ {
+ plan: premiumPlan(),
+ resources: PREMIUM_RESOURCES,
+ active: active
+ ? { id: active.id, wallet: active.wallet, expires_at: active.expires_at, asset: active.asset }
+ : null,
+ passes,
+ keys: keys.map((k) => ({
+ id: k.id,
+ name: k.name,
+ key_prefix: k.key_prefix,
+ rate_limit_per_minute: k.rate_limit_per_minute,
+ expires_at: k.expires_at,
+ status: k.revoked_at ? 'revoked' : 'active',
+ wallet: k.meta?.wallet || null,
+ usage: { granted: Number(k.granted || 0), denied: Number(k.denied || 0), last_seen: k.last_seen || null },
+ })),
+ },
+ { 'cache-control': 'no-store' },
+ );
+});
diff --git a/api/premium/plans.js b/api/premium/plans.js
new file mode 100644
index 000000000..70befb217
--- /dev/null
+++ b/api/premium/plans.js
@@ -0,0 +1,60 @@
+// GET /api/premium/plans — the premium pass, priced live in every accepted asset.
+//
+// Public and cacheable (60 s): the dashboard's pricing cards render from this.
+// Each asset is priced independently and a down oracle marks only that asset
+// unavailable instead of taking the whole payload down — USDC is parity and
+// can never fail, so there is always at least one payable rail.
+
+import { cors, json, method, wrap } from '../_lib/http.js';
+import { premiumPlan, priceAsset, PREMIUM_RESOURCES } from '../_lib/premium.js';
+import { env } from '../_lib/env.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const plan = premiumPlan();
+ const assets = await Promise.all(
+ ['THREE', 'SOL', 'USDC'].map(async (asset) => {
+ try {
+ const p = await priceAsset(asset);
+ return {
+ asset,
+ available: true,
+ usd: p.usd,
+ amount_atomics: p.atomics.toString(),
+ decimals: asset === 'SOL' ? 9 : 6,
+ ...(asset === 'THREE'
+ ? { mint: env.THREE_TOKEN_MINT, discount: plan.threeDiscount }
+ : asset === 'USDC'
+ ? { mint: env.X402_ASSET_MINT_SOLANA }
+ : {}),
+ };
+ } catch (e) {
+ return { asset, available: false, reason: e.message };
+ }
+ }),
+ );
+
+ return json(
+ res, 200,
+ {
+ plan: {
+ id: plan.id,
+ name: plan.name,
+ usd: plan.usd,
+ days: plan.days,
+ rate_limit_per_minute: plan.rateLimitPerMinute,
+ network: 'solana',
+ },
+ assets,
+ includes: {
+ resources: PREMIUM_RESOURCES,
+ summary:
+ 'Unmetered news-archive search (fair-use rate limit) via an x402_live_ API key ' +
+ 'or a wallet signature (SIWX) — no per-call payments while the pass is active.',
+ },
+ },
+ { 'cache-control': 'public, max-age=60, s-maxage=60' },
+ );
+});
diff --git a/api/premium/quote.js b/api/premium/quote.js
new file mode 100644
index 000000000..89a5c0632
--- /dev/null
+++ b/api/premium/quote.js
@@ -0,0 +1,46 @@
+// POST /api/premium/quote — lock a price and get the unsigned payment tx.
+//
+// body: { asset: 'THREE' | 'SOL' | 'USDC', wallet: '<base58>' }
+// → { quote: { id, asset, amount_atomics, usd_price, expires_at }, tx_base64 }
+//
+// The buyer signs tx_base64 in their own wallet (they are the fee payer),
+// sends it, then POSTs the signature to /api/premium/subscribe. The quote
+// freezes the oracle price for 10 minutes so verification compares the landed
+// transaction against this exact number.
+
+import { cors, json, error, method, readJson, wrap, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { getSessionUser } from '../_lib/auth.js';
+import { createQuote } from '../_lib/premium.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const rl = await limits.premiumQuoteIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const body = await readJson(req).catch(() => null);
+ const asset = String(body?.asset || '').toUpperCase();
+ const wallet = String(body?.wallet || '').trim();
+ if (!['THREE', 'SOL', 'USDC'].includes(asset)) {
+ return error(res, 400, 'bad_asset', 'asset must be THREE, SOL, or USDC');
+ }
+
+ // Session is optional — a raw-API buyer quotes with just a wallet; a
+ // dashboard buyer gets the pass linked to their account for key management.
+ let userId = null;
+ try {
+ const user = await getSessionUser(req);
+ userId = user?.id || null;
+ } catch {
+ userId = null;
+ }
+
+ try {
+ const { quote, tx_base64 } = await createQuote({ wallet, asset, userId });
+ return json(res, 200, { quote, tx_base64 }, { 'cache-control': 'no-store' });
+ } catch (e) {
+ return error(res, e.status || 502, e.code || 'quote_failed', e.message);
+ }
+});
diff --git a/api/premium/status.js b/api/premium/status.js
new file mode 100644
index 000000000..6b1e73426
--- /dev/null
+++ b/api/premium/status.js
@@ -0,0 +1,25 @@
+// GET /api/premium/status?wallet=<base58> — pass state for one wallet.
+//
+// Returns { active, pass, keys, resources, history } — everything the
+// developer dashboard needs in one call. Key prefixes and usage counts only;
+// the plaintext key is never re-derivable.
+
+import { cors, json, error, method, wrap, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { passStatus } from '../_lib/premium.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.premiumStatusIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const wallet = (new URL(req.url, 'http://x').searchParams.get('wallet') || '').trim();
+ try {
+ const status = await passStatus(wallet);
+ return json(res, 200, status, { 'cache-control': 'no-store' });
+ } catch (e) {
+ return error(res, e.status || 502, e.code || 'status_failed', e.message);
+ }
+});
diff --git a/api/premium/subscribe.js b/api/premium/subscribe.js
new file mode 100644
index 000000000..ab44a1945
--- /dev/null
+++ b/api/premium/subscribe.js
@@ -0,0 +1,83 @@
+// POST /api/premium/subscribe — redeem a paid quote for a 30-day premium pass.
+//
+// body: { quote_id, tx_signature }
+// → 200 { pass, api_key?, renewed } — api_key (x402_live_…) is returned
+// exactly once, on first key mint
+// 202 { pending: true } — tx not confirmed yet; poll again
+// 4xx { error } — mismatch / expired / already used
+//
+// Verification is against the LANDED transaction (balance delta to the
+// treasury, quoted wallet among the signers) and the persisted quote — never
+// client-supplied numbers. tx_signature is UNIQUE, so replays and double
+// submits idempotently return the already-issued pass.
+
+import { cors, json, error, method, readJson, wrap, rateLimited } from '../_lib/http.js';
+import { sql } from '../_lib/db.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { getSessionUser } from '../_lib/auth.js';
+import { verifyPassPayment, activatePass } from '../_lib/premium.js';
+
+// A quote is redeemable for 30 minutes after creation (10-min price lock plus
+// grace for slow confirmation) — the price was locked at signing time, and the
+// blockhash in the built tx expires long before this window anyway.
+const REDEEM_WINDOW_MS = 30 * 60_000;
+
+const SIG_RE = /^[1-9A-HJ-NP-Za-km-z]{64,96}$/;
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const rl = await limits.premiumSubscribeIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const body = await readJson(req).catch(() => null);
+ const quoteId = String(body?.quote_id || '').trim();
+ const txSignature = String(body?.tx_signature || '').trim();
+ if (!quoteId) return error(res, 400, 'bad_quote', 'quote_id is required');
+ if (!SIG_RE.test(txSignature)) {
+ return error(res, 400, 'bad_signature', 'tx_signature must be a base58 Solana signature');
+ }
+
+ // Idempotent fast path: this exact payment already produced a pass.
+ const [existing] = await sql`
+ select * from premium_passes where tx_signature = ${txSignature} limit 1
+ `;
+ if (existing) {
+ return json(res, 200, { pass: existing, api_key: null, renewed: true }, { 'cache-control': 'no-store' });
+ }
+
+ const [quote] = await sql`select * from premium_quotes where id = ${quoteId} limit 1`;
+ if (!quote) return error(res, 404, 'quote_not_found', 'unknown quote_id — request a fresh quote');
+ if (quote.status === 'used' && quote.tx_signature !== txSignature) {
+ return error(res, 409, 'quote_used', 'this quote was already redeemed with a different transaction');
+ }
+ if (Date.now() - new Date(quote.created_at).getTime() > REDEEM_WINDOW_MS) {
+ return error(res, 410, 'quote_expired', 'quote expired — request a fresh quote and pay again');
+ }
+
+ const verdict = await verifyPassPayment(quote, txSignature);
+ if (!verdict.ok) {
+ if (verdict.pending) {
+ return json(res, 202, { pending: true, reason: verdict.reason }, { 'cache-control': 'no-store' });
+ }
+ return error(res, 400, 'payment_mismatch', verdict.reason);
+ }
+
+ let userId = quote.user_id || null;
+ if (!userId) {
+ try {
+ const user = await getSessionUser(req);
+ userId = user?.id || null;
+ } catch {
+ userId = null;
+ }
+ }
+
+ try {
+ const { pass, apiKey, renewed } = await activatePass({ quote, txSignature, userId });
+ return json(res, 200, { pass, api_key: apiKey, renewed }, { 'cache-control': 'no-store' });
+ } catch (e) {
+ return error(res, e.status || 502, e.code || 'activation_failed', e.message);
+ }
+});
diff --git a/data/changelog.json b/data/changelog.json
index 8de397aa3..b2fd9db67 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,16 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-07-11",
+ "title": "Documentation accuracy pass: every tutorial verified against the shipped platform",
+ "summary": "We cross-referenced all 300+ docs and specs against the actual codebase and fixed everything that had drifted. The embed snippet in ten tutorials now uses the real two-line form that works on any site, four tutorials that demonstrated retired or never-shipped APIs were rewritten against the live component, the troubleshooting guide now reflects the current Cloud Run production stack with the correct session and storage details, and the manifest, quick-start, and API references now list exactly the providers, attributes, and endpoints that exist today. Every code sample in the affected docs runs as written.",
+ "tags": [
+ "docs",
+ "fix"
+ ],
+ "link": "/docs/tutorials/embed-in-30-seconds"
+ },
{
"date": "2026-07-11",
"title": "Richer coin pages, plus new exchange, category, and DeFi-yields detail pages",
@@ -13053,6 +13063,25 @@
"infra"
],
"link": "/markets/archive"
+ },
+ {
+ "date": "2026-07-11",
+ "title": "The news page becomes Your Briefing",
+ "summary": "/markets/news is redesigned as a daily briefing: a breaking-news ticker for stories under 45 minutes old, a collapsible Today's AI Briefing card built from the digest engine, a Featured tab covering the major outlets, a Trending tab ranking the day's most-covered narratives, a Top-stories hero with a compact headline rail, and a star on every story that saves it to a personal Saved tab. Article preview images were also overhauled — thumbnails blocked by publishers now load through a same-origin proxy, and stories whose feed ships no image pull the publisher's own social preview automatically, so cards no longer show blank tiles.",
+ "tags": [
+ "feature",
+ "improvement"
+ ],
+ "link": "/markets/news"
+ },
+ {
+ "date": "2026-07-11",
+ "title": "Premium: one monthly pass instead of paying per call",
+ "summary": "Go Premium for $9.99/30 days and stop paying the Data API per search: one Solana payment — in $THREE at 20% off, SOL, or USDC — mints an API key with unmetered archive search and lets your wallet sign in on the archive page instead of paying. Two new dashboard surfaces ship with it: a developer console at /dashboard/data-api (buy or renew the pass, manage and rotate API keys, live usage, copy-paste quickstarts) and Billing & Passes at /dashboard/billing (pass status, on-chain payment history, your subscriptions and paid services in one place). Renewals stack — renewing early adds 30 days to the end, never losing time.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/docs/premium"
}
]
}
diff --git a/data/pages.json b/data/pages.json
index bfd4263f0..7a30343a0 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -1705,6 +1705,22 @@
"indexable": false,
"added": "2026-05-25"
},
+ {
+ "path": "/dashboard/data-api",
+ "title": "Dashboard · Data API",
+ "description": "Developer console for the three.ws Data API — buy the Premium pass with $THREE, SOL, or USDC, manage API keys, watch usage, and copy quickstarts.",
+ "auth": "required",
+ "indexable": false,
+ "added": "2026-07-11"
+ },
+ {
+ "path": "/dashboard/billing",
+ "title": "Dashboard · Billing & Passes",
+ "description": "Manage subscriptions and paid services — Premium pass status, on-chain payment history, API keys, and creator subscriptions.",
+ "auth": "required",
+ "indexable": false,
+ "added": "2026-07-11"
+ },
{
"path": "/dashboard/analytics",
"title": "Dashboard · Analytics",
@@ -1857,6 +1873,12 @@
"description": "How three.ws implements x402 HTTP 402 paid agent skills — the challenge, verify, and settle mechanics.",
"added": "2026-04-29"
},
+ {
+ "path": "/docs/premium",
+ "title": "Premium Pass — Monthly Data API Access",
+ "description": "One Solana payment ($THREE at 20% off, SOL, or USDC) buys 30 days of unmetered Data API access with an API key — no per-call x402 payments.",
+ "added": "2026-07-11"
+ },
{
"path": "/docs/x402-endpoints",
"title": "Docs · x402 Paid Endpoints",
diff --git a/docs/ALL.md b/docs/ALL.md
index a254c870f..4756738db 100644
--- a/docs/ALL.md
+++ b/docs/ALL.md
@@ -1,7 +1,7 @@
<!-- GENERATED by scripts/combine-docs.mjs — do not edit by hand. Edit the source files under docs/ and re-run. -->
# three.ws — Combined Documentation
-> Single-file snapshot of every document under [`docs/`](.). Generated 2026-07-10 from **284 files** (~4060 KB).
+> Single-file snapshot of every document under [`docs/`](.). Generated 2026-07-11 from **286 files** (~4452 KB).
> The individual source files remain the canonical, editable copies — this file is a read-only aggregate.
## Table of contents
@@ -15,319 +15,321 @@
- [PROTOCOL-vanity.md](#sec-005)
- [agenc.md](#sec-006)
- [agent-abilities.md](#sec-007)
-- [agent-manifest.md](#sec-049)
-- [agent-reputation.md](#sec-050)
-- [agent-skills.md](#sec-051)
-- [agent-system.md](#sec-052)
-- [agent-wallets.md](#sec-053)
-- [agents-vs-avatars.md](#sec-054)
-- [agora.md](#sec-055)
-- [animations.md](#sec-068)
-- [api-reference.md](#sec-069)
-- [ar.md](#sec-071)
-- [architecture.md](#sec-072)
-- [authentication.md](#sec-073)
-- [autonomous-x402.md](#sec-074)
-- [avatar-creation.md](#sec-075)
-- [avatar-inspector.md](#sec-076)
-- [avatar-pipeline.md](#sec-077)
-- [avatar-thumbnails.md](#sec-078)
-- [aws-builder-center-marketplace-x402.md](#sec-079)
-- [aws-builder-center-mcp-agents.md](#sec-080)
-- [aws-marketplace-listing-kit.md](#sec-081)
-- [aws-marketplace.md](#sec-082)
-- [aws-partner-spotlight.md](#sec-083)
-- [bnb-babt-findings.md](#sec-084)
-- [bnb-payments.md](#sec-085)
-- [bnb-vault.md](#sec-086)
-- [bnb-world.md](#sec-087)
-- [btn-pill-migration.md](#sec-088)
-- [build.md](#sec-089)
-- [changelog.md](#sec-090)
-- [character-studio.md](#sec-091)
-- [circulation-engine.md](#sec-092)
-- [coin-launches.md](#sec-093)
-- [coin-pages.md](#sec-094)
-- [coinmarketcap-article-play.md](#sec-095)
-- [coinmarketcap-article.md](#sec-096)
-- [configuration.md](#sec-097)
-- [contributing.md](#sec-104)
-- [crypto-api.md](#sec-105)
-- [custody.md](#sec-106)
-- [demo-routes.md](#sec-107)
-- [deployment.md](#sec-108)
-- [do-i-need-crypto.md](#sec-109)
-- [economy-heartbeat.md](#sec-110)
-- [economy-master.md](#sec-111)
-- [editor.md](#sec-112)
-- [embedding.md](#sec-113)
-- [embody.md](#sec-114)
-- [erc8004.md](#sec-115)
-- [examples.md](#sec-117)
-- [financial-controls.md](#sec-118)
-- [hold-to-access.md](#sec-119)
-- [how-it-works.md](#sec-120)
-- [i18n.md](#sec-121)
-- [ibm-x402-mcp.md](#sec-122)
-- [ibm.md](#sec-123)
-- [introduction.md](#sec-124)
-- [js-api.md](#sec-126)
-- [labor-market.md](#sec-127)
-- [launch-usecases.md](#sec-128)
-- [layers.md](#sec-129)
-- [listings.md](#sec-130)
-- [make-your-agent.md](#sec-131)
-- [marketplace.md](#sec-132)
-- [mcp-3d-studio.md](#sec-133)
-- [mcp-agent.md](#sec-134)
-- [mcp-studio.md](#sec-135)
-- [mcp-tools.md](#sec-136)
-- [mcp-x402-bazaar.md](#sec-137)
-- [mcp.md](#sec-138)
-- [memetic-launcher.md](#sec-139)
-- [memory.md](#sec-140)
-- [mint-mark.md](#sec-141)
-- [money-feed.md](#sec-142)
-- [money-map.md](#sec-143)
-- [multi-agent.md](#sec-144)
-- [nvidia-models.md](#sec-145)
-- [nvidia-nemotron-spotlight.md](#sec-146)
-- [okx-marketplace.md](#sec-147)
-- [onchain-agents.md](#sec-148)
-- [oracle.md](#sec-149)
-- [package-extraction.md](#sec-150)
-- [pay-skills-listing.md](#sec-152)
-- [permissions.md](#sec-153)
-- [persona-hub.md](#sec-154)
-- [plan-checkout.md](#sec-155)
-- [popular-3d-github-repos.md](#sec-156)
-- [provenance.md](#sec-157)
-- [pump-fun-mcp-edge.md](#sec-158)
-- [pump-launch-repos.md](#sec-159)
-- [pump-launcher.md](#sec-160)
-- [pump-platform-fee.md](#sec-161)
-- [quick-start.md](#sec-181)
-- [remix.md](#sec-182)
-- [reputation.md](#sec-183)
-- [risk-acknowledgment.md](#sec-184)
-- [sas-attestations.md](#sec-185)
-- [sdk.md](#sec-186)
-- [security.md](#sec-187)
-- [share-and-embed.md](#sec-188)
-- [skills.md](#sec-189)
-- [smart-contracts.md](#sec-190)
-- [solana-pumpfun.md](#sec-191)
-- [solana-reputation.md](#sec-192)
-- [solana.md](#sec-193)
-- [spatial-mcp.md](#sec-194)
-- [start-here.md](#sec-196)
-- [syndication.md](#sec-197)
-- [token-gated-3d-embeds.md](#sec-198)
-- [trader-card.md](#sec-199)
-- [trading-arenas.md](#sec-200)
-- [trading-copilot.md](#sec-201)
-- [trading-experiment.md](#sec-202)
-- [trading-surfaces.md](#sec-203)
-- [troubleshooting.md](#sec-204)
-- [trust-primitives.md](#sec-205)
-- [ui-juice.md](#sec-254)
-- [validation.md](#sec-267)
-- [vanity.md](#sec-268)
-- [viewer.md](#sec-269)
-- [web-component.md](#sec-270)
-- [widget-api.md](#sec-271)
-- [widget-studio.md](#sec-272)
-- [widgets.md](#sec-273)
-- [x402-buyer.md](#sec-274)
-- [x402-dev-tools.md](#sec-275)
-- [x402-endpoints.md](#sec-276)
-- [x402-revenue.md](#sec-277)
-- [x402-ring-economy.md](#sec-278)
-- [x402.md](#sec-279)
+- [agent-manifest.md](#sec-050)
+- [agent-reputation.md](#sec-051)
+- [agent-skills.md](#sec-052)
+- [agent-system.md](#sec-053)
+- [agent-wallets.md](#sec-054)
+- [agents-vs-avatars.md](#sec-055)
+- [agora.md](#sec-056)
+- [animations.md](#sec-069)
+- [api-reference.md](#sec-070)
+- [ar.md](#sec-072)
+- [architecture.md](#sec-073)
+- [authentication.md](#sec-074)
+- [autonomous-x402.md](#sec-075)
+- [avatar-creation.md](#sec-076)
+- [avatar-inspector.md](#sec-077)
+- [avatar-pipeline.md](#sec-078)
+- [avatar-thumbnails.md](#sec-079)
+- [aws-builder-center-marketplace-x402.md](#sec-080)
+- [aws-builder-center-mcp-agents.md](#sec-081)
+- [aws-marketplace-listing-kit.md](#sec-082)
+- [aws-marketplace.md](#sec-083)
+- [aws-partner-spotlight.md](#sec-084)
+- [bnb-babt-findings.md](#sec-085)
+- [bnb-payments.md](#sec-086)
+- [bnb-vault.md](#sec-087)
+- [bnb-world.md](#sec-088)
+- [btn-pill-migration.md](#sec-089)
+- [build.md](#sec-090)
+- [changelog.md](#sec-091)
+- [character-studio.md](#sec-092)
+- [circulation-engine.md](#sec-093)
+- [coin-launches.md](#sec-094)
+- [coin-pages.md](#sec-095)
+- [coinmarketcap-article-play.md](#sec-096)
+- [coinmarketcap-article.md](#sec-097)
+- [configuration.md](#sec-098)
+- [contributing.md](#sec-105)
+- [crypto-api.md](#sec-106)
+- [custody.md](#sec-107)
+- [demo-routes.md](#sec-108)
+- [deployment.md](#sec-109)
+- [do-i-need-crypto.md](#sec-110)
+- [economy-heartbeat.md](#sec-111)
+- [economy-master.md](#sec-112)
+- [editor.md](#sec-113)
+- [embedding.md](#sec-114)
+- [embody.md](#sec-115)
+- [erc8004.md](#sec-116)
+- [examples.md](#sec-118)
+- [financial-controls.md](#sec-119)
+- [hold-to-access.md](#sec-120)
+- [how-it-works.md](#sec-121)
+- [i18n.md](#sec-122)
+- [ibm-x402-mcp.md](#sec-123)
+- [ibm.md](#sec-124)
+- [introduction.md](#sec-125)
+- [js-api.md](#sec-127)
+- [labor-market.md](#sec-128)
+- [launch-usecases.md](#sec-129)
+- [layers.md](#sec-130)
+- [listings.md](#sec-131)
+- [make-your-agent.md](#sec-132)
+- [marketplace.md](#sec-133)
+- [mcp-3d-studio.md](#sec-134)
+- [mcp-agent.md](#sec-135)
+- [mcp-studio.md](#sec-136)
+- [mcp-tools.md](#sec-137)
+- [mcp-x402-bazaar.md](#sec-138)
+- [mcp.md](#sec-139)
+- [memetic-launcher.md](#sec-140)
+- [memory.md](#sec-141)
+- [mint-mark.md](#sec-142)
+- [money-feed.md](#sec-143)
+- [money-map.md](#sec-144)
+- [multi-agent.md](#sec-145)
+- [nvidia-models.md](#sec-146)
+- [nvidia-nemotron-spotlight.md](#sec-147)
+- [okx-marketplace.md](#sec-148)
+- [onchain-agents.md](#sec-149)
+- [oracle.md](#sec-150)
+- [package-extraction.md](#sec-151)
+- [pay-skills-listing.md](#sec-153)
+- [permissions.md](#sec-154)
+- [persona-hub.md](#sec-155)
+- [plan-checkout.md](#sec-156)
+- [popular-3d-github-repos.md](#sec-157)
+- [premium.md](#sec-158)
+- [provenance.md](#sec-159)
+- [pump-fun-mcp-edge.md](#sec-160)
+- [pump-launch-repos.md](#sec-161)
+- [pump-launcher.md](#sec-162)
+- [pump-platform-fee.md](#sec-163)
+- [quick-start.md](#sec-183)
+- [remix.md](#sec-184)
+- [reputation.md](#sec-185)
+- [risk-acknowledgment.md](#sec-186)
+- [sas-attestations.md](#sec-187)
+- [sdk.md](#sec-188)
+- [security.md](#sec-189)
+- [share-and-embed.md](#sec-190)
+- [skills.md](#sec-191)
+- [smart-contracts.md](#sec-192)
+- [solana-pumpfun.md](#sec-193)
+- [solana-reputation.md](#sec-194)
+- [solana.md](#sec-195)
+- [spatial-mcp.md](#sec-196)
+- [start-here.md](#sec-198)
+- [syndication.md](#sec-199)
+- [token-gated-3d-embeds.md](#sec-200)
+- [trader-card.md](#sec-201)
+- [trading-arenas.md](#sec-202)
+- [trading-copilot.md](#sec-203)
+- [trading-experiment.md](#sec-204)
+- [trading-surfaces.md](#sec-205)
+- [troubleshooting.md](#sec-206)
+- [trust-primitives.md](#sec-207)
+- [ui-juice.md](#sec-256)
+- [validation.md](#sec-269)
+- [vanity.md](#sec-270)
+- [viewer.md](#sec-271)
+- [web-component.md](#sec-272)
+- [widget-api.md](#sec-273)
+- [widget-studio.md](#sec-274)
+- [widgets.md](#sec-275)
+- [x402-buyer.md](#sec-276)
+- [x402-dev-tools.md](#sec-277)
+- [x402-endpoints.md](#sec-278)
+- [x402-revenue.md](#sec-279)
+- [x402-ring-economy.md](#sec-280)
+- [x402.md](#sec-281)
### agent-abilities
-- [agent-abilities/FULL-ARTICLE.md](#sec-008)
-- [agent-abilities/PRODUCTION-NOTES.md](#sec-009)
-- [agent-abilities/TTS-SCRIPT.md](#sec-010)
-- [agent-abilities/chapters/01-the-body.md](#sec-011)
-- [agent-abilities/chapters/02-motion.md](#sec-012)
-- [agent-abilities/chapters/03-creation-studios.md](#sec-013)
-- [agent-abilities/chapters/04-the-mind.md](#sec-014)
-- [agent-abilities/chapters/05-the-voice.md](#sec-015)
-- [agent-abilities/chapters/06-identity-reputation.md](#sec-016)
-- [agent-abilities/chapters/07-skills.md](#sec-017)
-- [agent-abilities/chapters/08-screens.md](#sec-018)
-- [agent-abilities/chapters/09-the-agent-economy.md](#sec-019)
-- [agent-abilities/chapters/10-the-agent-wallet.md](#sec-020)
-- [agent-abilities/chapters/11-markets-intelligence.md](#sec-021)
-- [agent-abilities/chapters/12-live-worlds-social-irl.md](#sec-022)
-- [agent-abilities/chapters/13-agents-everywhere.md](#sec-023)
-- [agent-abilities/chapters/14-the-developer-platform.md](#sec-024)
-- [agent-abilities/chapters/15-appendix.md](#sec-025)
-- [agent-abilities/wallet/01-balance.md](#sec-026)
-- [agent-abilities/wallet/02-go-live.md](#sec-027)
-- [agent-abilities/wallet/03-portfolio.md](#sec-028)
-- [agent-abilities/wallet/04-deposit.md](#sec-029)
-- [agent-abilities/wallet/05-copilot.md](#sec-030)
-- [agent-abilities/wallet/06-trust.md](#sec-031)
-- [agent-abilities/wallet/07-signals.md](#sec-032)
-- [agent-abilities/wallet/08-trade.md](#sec-033)
-- [agent-abilities/wallet/09-pulse.md](#sec-034)
-- [agent-abilities/wallet/10-snipe.md](#sec-035)
-- [agent-abilities/wallet/11-earn.md](#sec-036)
-- [agent-abilities/wallet/12-orders.md](#sec-037)
-- [agent-abilities/wallet/13-autopilot.md](#sec-038)
-- [agent-abilities/wallet/14-intents.md](#sec-039)
-- [agent-abilities/wallet/15-pay.md](#sec-040)
-- [agent-abilities/wallet/16-vanity.md](#sec-041)
-- [agent-abilities/wallet/17-policy.md](#sec-042)
-- [agent-abilities/wallet/18-withdraw.md](#sec-043)
-- [agent-abilities/wallet/19-give.md](#sec-044)
-- [agent-abilities/wallet/20-proof-of-custody.md](#sec-045)
-- [agent-abilities/wallet/21-access.md](#sec-046)
-- [agent-abilities/wallet/22-recovery.md](#sec-047)
-- [agent-abilities/wallet/23-self-defense.md](#sec-048)
+- [agent-abilities/ABILITIES.md](#sec-008)
+- [agent-abilities/FULL-ARTICLE.md](#sec-009)
+- [agent-abilities/PRODUCTION-NOTES.md](#sec-010)
+- [agent-abilities/TTS-SCRIPT.md](#sec-011)
+- [agent-abilities/chapters/01-the-body.md](#sec-012)
+- [agent-abilities/chapters/02-motion.md](#sec-013)
+- [agent-abilities/chapters/03-creation-studios.md](#sec-014)
+- [agent-abilities/chapters/04-the-mind.md](#sec-015)
+- [agent-abilities/chapters/05-the-voice.md](#sec-016)
+- [agent-abilities/chapters/06-identity-reputation.md](#sec-017)
+- [agent-abilities/chapters/07-skills.md](#sec-018)
+- [agent-abilities/chapters/08-screens.md](#sec-019)
+- [agent-abilities/chapters/09-the-agent-economy.md](#sec-020)
+- [agent-abilities/chapters/10-the-agent-wallet.md](#sec-021)
+- [agent-abilities/chapters/11-markets-intelligence.md](#sec-022)
+- [agent-abilities/chapters/12-live-worlds-social-irl.md](#sec-023)
+- [agent-abilities/chapters/13-agents-everywhere.md](#sec-024)
+- [agent-abilities/chapters/14-the-developer-platform.md](#sec-025)
+- [agent-abilities/chapters/15-appendix.md](#sec-026)
+- [agent-abilities/wallet/01-balance.md](#sec-027)
+- [agent-abilities/wallet/02-go-live.md](#sec-028)
+- [agent-abilities/wallet/03-portfolio.md](#sec-029)
+- [agent-abilities/wallet/04-deposit.md](#sec-030)
+- [agent-abilities/wallet/05-copilot.md](#sec-031)
+- [agent-abilities/wallet/06-trust.md](#sec-032)
+- [agent-abilities/wallet/07-signals.md](#sec-033)
+- [agent-abilities/wallet/08-trade.md](#sec-034)
+- [agent-abilities/wallet/09-pulse.md](#sec-035)
+- [agent-abilities/wallet/10-snipe.md](#sec-036)
+- [agent-abilities/wallet/11-earn.md](#sec-037)
+- [agent-abilities/wallet/12-orders.md](#sec-038)
+- [agent-abilities/wallet/13-autopilot.md](#sec-039)
+- [agent-abilities/wallet/14-intents.md](#sec-040)
+- [agent-abilities/wallet/15-pay.md](#sec-041)
+- [agent-abilities/wallet/16-vanity.md](#sec-042)
+- [agent-abilities/wallet/17-policy.md](#sec-043)
+- [agent-abilities/wallet/18-withdraw.md](#sec-044)
+- [agent-abilities/wallet/19-give.md](#sec-045)
+- [agent-abilities/wallet/20-proof-of-custody.md](#sec-046)
+- [agent-abilities/wallet/21-access.md](#sec-047)
+- [agent-abilities/wallet/22-recovery.md](#sec-048)
+- [agent-abilities/wallet/23-self-defense.md](#sec-049)
### agora
-- [agora/tasks/00-INDEX.md](#sec-056)
-- [agora/tasks/01-verify-foundation.md](#sec-057)
-- [agora/tasks/02-life-engine.md](#sec-058)
-- [agora/tasks/03-task-supply.md](#sec-059)
-- [agora/tasks/04-professions.md](#sec-060)
-- [agora/tasks/05-commons-scaffold.md](#sec-061)
-- [agora/tasks/06-economy-visuals.md](#sec-062)
-- [agora/tasks/07-verify-and-passport.md](#sec-063)
-- [agora/tasks/08-humans-first-class.md](#sec-064)
-- [agora/tasks/09-arena-and-guilds.md](#sec-065)
-- [agora/tasks/10-agora-mcp.md](#sec-066)
-- [agora/tasks/11-production-hardening.md](#sec-067)
+- [agora/tasks/00-INDEX.md](#sec-057)
+- [agora/tasks/01-verify-foundation.md](#sec-058)
+- [agora/tasks/02-life-engine.md](#sec-059)
+- [agora/tasks/03-task-supply.md](#sec-060)
+- [agora/tasks/04-professions.md](#sec-061)
+- [agora/tasks/05-commons-scaffold.md](#sec-062)
+- [agora/tasks/06-economy-visuals.md](#sec-063)
+- [agora/tasks/07-verify-and-passport.md](#sec-064)
+- [agora/tasks/08-humans-first-class.md](#sec-065)
+- [agora/tasks/09-arena-and-guilds.md](#sec-066)
+- [agora/tasks/10-agora-mcp.md](#sec-067)
+- [agora/tasks/11-production-hardening.md](#sec-068)
### api
-- [api/forge-x402.md](#sec-070)
+- [api/forge-x402.md](#sec-071)
### content
-- [content/use-cases/README.md](#sec-098)
-- [content/use-cases/ai-agent-developer.md](#sec-099)
-- [content/use-cases/brand-marketer.md](#sec-100)
-- [content/use-cases/crypto-community.md](#sec-101)
-- [content/use-cases/game-studio.md](#sec-102)
-- [content/use-cases/indie-creator.md](#sec-103)
+- [content/use-cases/README.md](#sec-099)
+- [content/use-cases/ai-agent-developer.md](#sec-100)
+- [content/use-cases/brand-marketer.md](#sec-101)
+- [content/use-cases/crypto-community.md](#sec-102)
+- [content/use-cases/game-studio.md](#sec-103)
+- [content/use-cases/indie-creator.md](#sec-104)
### erc8004
-- [erc8004/validation-attestation.md](#sec-116)
+- [erc8004/validation-attestation.md](#sec-117)
### irl
-- [irl/THREAT-MODEL.md](#sec-125)
+- [irl/THREAT-MODEL.md](#sec-126)
### partners
-- [partners/sperax-proposal.md](#sec-151)
+- [partners/sperax-proposal.md](#sec-152)
### pumpfun-program
-- [pumpfun-program/README.md](#sec-162)
-- [pumpfun-program/UPSTREAM-buy-sell-v2-announcement.md](#sec-163)
-- [pumpfun-program/docs/BREAKING_FEE_RECIPIENT.md](#sec-164)
-- [pumpfun-program/docs/CPI_README.md](#sec-165)
-- [pumpfun-program/docs/FAQ.md](#sec-166)
-- [pumpfun-program/docs/FEE_PROGRAM_README.md](#sec-167)
-- [pumpfun-program/docs/FEE_RECIPIENTS.md](#sec-168)
-- [pumpfun-program/docs/PUMP_CASHBACK_README.md](#sec-169)
-- [pumpfun-program/docs/PUMP_CREATOR_FEE_README.md](#sec-170)
-- [pumpfun-program/docs/PUMP_PROGRAM_README.md](#sec-171)
-- [pumpfun-program/docs/PUMP_SWAP_CREATOR_FEE_README.md](#sec-172)
-- [pumpfun-program/docs/PUMP_SWAP_README.md](#sec-173)
-- [pumpfun-program/docs/PUMP_SWAP_SDK_README.md](#sec-174)
-- [pumpfun-program/docs/instructions/BUY.md](#sec-175)
-- [pumpfun-program/docs/instructions/CLAIM_CASHBACK.md](#sec-176)
-- [pumpfun-program/docs/instructions/COIN_CREATION.md](#sec-177)
-- [pumpfun-program/docs/instructions/COLLECT_CREATOR_FEE.md](#sec-178)
-- [pumpfun-program/docs/instructions/CREATOR_FEE_SHARING.md](#sec-179)
-- [pumpfun-program/docs/instructions/SELL.md](#sec-180)
+- [pumpfun-program/README.md](#sec-164)
+- [pumpfun-program/UPSTREAM-buy-sell-v2-announcement.md](#sec-165)
+- [pumpfun-program/docs/BREAKING_FEE_RECIPIENT.md](#sec-166)
+- [pumpfun-program/docs/CPI_README.md](#sec-167)
+- [pumpfun-program/docs/FAQ.md](#sec-168)
+- [pumpfun-program/docs/FEE_PROGRAM_README.md](#sec-169)
+- [pumpfun-program/docs/FEE_RECIPIENTS.md](#sec-170)
+- [pumpfun-program/docs/PUMP_CASHBACK_README.md](#sec-171)
+- [pumpfun-program/docs/PUMP_CREATOR_FEE_README.md](#sec-172)
+- [pumpfun-program/docs/PUMP_PROGRAM_README.md](#sec-173)
+- [pumpfun-program/docs/PUMP_SWAP_CREATOR_FEE_README.md](#sec-174)
+- [pumpfun-program/docs/PUMP_SWAP_README.md](#sec-175)
+- [pumpfun-program/docs/PUMP_SWAP_SDK_README.md](#sec-176)
+- [pumpfun-program/docs/instructions/BUY.md](#sec-177)
+- [pumpfun-program/docs/instructions/CLAIM_CASHBACK.md](#sec-178)
+- [pumpfun-program/docs/instructions/COIN_CREATION.md](#sec-179)
+- [pumpfun-program/docs/instructions/COLLECT_CREATOR_FEE.md](#sec-180)
+- [pumpfun-program/docs/instructions/CREATOR_FEE_SHARING.md](#sec-181)
+- [pumpfun-program/docs/instructions/SELL.md](#sec-182)
### specs
-- [specs/agent-trading.md](#sec-195)
+- [specs/agent-trading.md](#sec-197)
### tutorials
-- [tutorials/agent-personality.md](#sec-206)
-- [tutorials/agent-reputation.md](#sec-207)
-- [tutorials/animate-your-avatar.md](#sec-208)
-- [tutorials/build-a-scene.md](#sec-209)
-- [tutorials/claim-threews-name.md](#sec-210)
-- [tutorials/connect-ai-brain.md](#sec-211)
-- [tutorials/create-and-edit-memory.md](#sec-212)
-- [tutorials/custom-skill.md](#sec-213)
-- [tutorials/customize-appearance.md](#sec-214)
-- [tutorials/deploy-to-vercel-custom-domain.md](#sec-215)
-- [tutorials/embed-in-30-seconds.md](#sec-216)
-- [tutorials/embed-on-website.md](#sec-217)
-- [tutorials/emotion-from-data.md](#sec-218)
-- [tutorials/first-agent.md](#sec-219)
-- [tutorials/generate-3d-api.md](#sec-220)
-- [tutorials/getting-started.md](#sec-221)
-- [tutorials/greeting-and-first-speech.md](#sec-222)
-- [tutorials/image-to-3d.md](#sec-223)
-- [tutorials/import-avatar-url.md](#sec-224)
-- [tutorials/js-api-events.md](#sec-225)
-- [tutorials/mcp-server-for-your-agent.md](#sec-226)
-- [tutorials/mine-vanity-address.md](#sec-227)
-- [tutorials/mint-pumpfun-token.md](#sec-228)
-- [tutorials/multi-agent-coordination.md](#sec-229)
-- [tutorials/nvidia-3d-free.md](#sec-230)
-- [tutorials/nvidia-nim-self-host.md](#sec-231)
-- [tutorials/paid-x402-endpoint.md](#sec-232)
-- [tutorials/pay-for-x402-service.md](#sec-233)
-- [tutorials/personal-ai-site.md](#sec-234)
-- [tutorials/place-agent-irl.md](#sec-235)
-- [tutorials/prompts-for-3d.md](#sec-236)
-- [tutorials/register-onchain.md](#sec-237)
-- [tutorials/self-host-agent-backend.md](#sec-238)
-- [tutorials/selfie-to-avatar.md](#sec-239)
-- [tutorials/share-your-agent.md](#sec-240)
-- [tutorials/shopify-store-guide-advanced.md](#sec-241)
-- [tutorials/shopify-store-guide.md](#sec-242)
-- [tutorials/skill-with-database-auth.md](#sec-243)
-- [tutorials/solana-agent-reputation.md](#sec-244)
-- [tutorials/sperax-tour.md](#sec-245)
-- [tutorials/swap-avatar-in-studio.md](#sec-246)
-- [tutorials/text-to-3d.md](#sec-247)
-- [tutorials/trigger-from-page-events.md](#sec-248)
-- [tutorials/upload-custom-glb.md](#sec-249)
-- [tutorials/view-in-ar.md](#sec-250)
-- [tutorials/voice-and-lipsync.md](#sec-251)
-- [tutorials/walk-companion.md](#sec-252)
-- [tutorials/web-component-end-to-end.md](#sec-253)
+- [tutorials/agent-personality.md](#sec-208)
+- [tutorials/agent-reputation.md](#sec-209)
+- [tutorials/animate-your-avatar.md](#sec-210)
+- [tutorials/build-a-scene.md](#sec-211)
+- [tutorials/claim-threews-name.md](#sec-212)
+- [tutorials/connect-ai-brain.md](#sec-213)
+- [tutorials/create-and-edit-memory.md](#sec-214)
+- [tutorials/custom-skill.md](#sec-215)
+- [tutorials/customize-appearance.md](#sec-216)
+- [tutorials/deploy-to-vercel-custom-domain.md](#sec-217)
+- [tutorials/embed-in-30-seconds.md](#sec-218)
+- [tutorials/embed-on-website.md](#sec-219)
+- [tutorials/emotion-from-data.md](#sec-220)
+- [tutorials/first-agent.md](#sec-221)
+- [tutorials/generate-3d-api.md](#sec-222)
+- [tutorials/getting-started.md](#sec-223)
+- [tutorials/greeting-and-first-speech.md](#sec-224)
+- [tutorials/image-to-3d.md](#sec-225)
+- [tutorials/import-avatar-url.md](#sec-226)
+- [tutorials/js-api-events.md](#sec-227)
+- [tutorials/mcp-server-for-your-agent.md](#sec-228)
+- [tutorials/mine-vanity-address.md](#sec-229)
+- [tutorials/mint-pumpfun-token.md](#sec-230)
+- [tutorials/multi-agent-coordination.md](#sec-231)
+- [tutorials/nvidia-3d-free.md](#sec-232)
+- [tutorials/nvidia-nim-self-host.md](#sec-233)
+- [tutorials/paid-x402-endpoint.md](#sec-234)
+- [tutorials/pay-for-x402-service.md](#sec-235)
+- [tutorials/personal-ai-site.md](#sec-236)
+- [tutorials/place-agent-irl.md](#sec-237)
+- [tutorials/prompts-for-3d.md](#sec-238)
+- [tutorials/register-onchain.md](#sec-239)
+- [tutorials/self-host-agent-backend.md](#sec-240)
+- [tutorials/selfie-to-avatar.md](#sec-241)
+- [tutorials/share-your-agent.md](#sec-242)
+- [tutorials/shopify-store-guide-advanced.md](#sec-243)
+- [tutorials/shopify-store-guide.md](#sec-244)
+- [tutorials/skill-with-database-auth.md](#sec-245)
+- [tutorials/solana-agent-reputation.md](#sec-246)
+- [tutorials/sperax-tour.md](#sec-247)
+- [tutorials/swap-avatar-in-studio.md](#sec-248)
+- [tutorials/text-to-3d.md](#sec-249)
+- [tutorials/trigger-from-page-events.md](#sec-250)
+- [tutorials/upload-custom-glb.md](#sec-251)
+- [tutorials/view-in-ar.md](#sec-252)
+- [tutorials/voice-and-lipsync.md](#sec-253)
+- [tutorials/walk-companion.md](#sec-254)
+- [tutorials/web-component-end-to-end.md](#sec-255)
### ux-flows
-- [ux-flows/01-onboarding-creation.md](#sec-255)
-- [ux-flows/02-forge-text-to-3d.md](#sec-256)
-- [ux-flows/03-3d-editing-viewer.md](#sec-257)
-- [ux-flows/04-embed-widget-studio.md](#sec-258)
-- [ux-flows/05-discovery-social.md](#sec-259)
-- [ux-flows/06-marketplace-skills.md](#sec-260)
-- [ux-flows/07-crypto-trading-analytics.md](#sec-261)
-- [ux-flows/08-coin-launch-wallets.md](#sec-262)
-- [ux-flows/09-x402-agent-commerce.md](#sec-263)
-- [ux-flows/10-chat-brain-labs.md](#sec-264)
-- [ux-flows/11-account-dashboard.md](#sec-265)
-- [ux-flows/12-home-and-content.md](#sec-266)
+- [ux-flows/01-onboarding-creation.md](#sec-257)
+- [ux-flows/02-forge-text-to-3d.md](#sec-258)
+- [ux-flows/03-3d-editing-viewer.md](#sec-259)
+- [ux-flows/04-embed-widget-studio.md](#sec-260)
+- [ux-flows/05-discovery-social.md](#sec-261)
+- [ux-flows/06-marketplace-skills.md](#sec-262)
+- [ux-flows/07-crypto-trading-analytics.md](#sec-263)
+- [ux-flows/08-coin-launch-wallets.md](#sec-264)
+- [ux-flows/09-x402-agent-commerce.md](#sec-265)
+- [ux-flows/10-chat-brain-labs.md](#sec-266)
+- [ux-flows/11-account-dashboard.md](#sec-267)
+- [ux-flows/12-home-and-content.md](#sec-268)
### zauth
-- [zauth/database.md](#sec-280)
-- [zauth/index.md](#sec-281)
-- [zauth/provider-hub.md](#sec-282)
-- [zauth/reposcan.md](#sec-283)
-- [zauth/vector.md](#sec-284)
+- [zauth/database.md](#sec-282)
+- [zauth/index.md](#sec-283)
+- [zauth/provider-hub.md](#sec-284)
+- [zauth/reposcan.md](#sec-285)
+- [zauth/vector.md](#sec-286)
---
@@ -1202,8 +1204,9 @@ returned as-is. Poll budget is tunable via `X402_PIPELINE_POLL_BUDGET_MS`
# Design Tokens — three.ws
-Canonical design vocabulary. Source of truth: the `:root` block in
-[`public/style.css`](../public/style.css). New pages reference these tokens
+Canonical design vocabulary. Source of truth for every primitive:
+[`public/tokens.css`](../public/tokens.css); [`public/style.css`](../public/style.css)
+imports it first and layers component tokens on top. New pages reference these tokens
directly (`var(--surface-1)`, `var(--text-md)`, `var(--font-display)`) instead
of hand-rolling hex/rgba/px values. Per-surface namespaces (`--nv-*`, `--ibm-*`)
alias the canonical tokens through the CSS-var fallback chain so every surface
@@ -1730,6 +1733,2834 @@ Prefer it in one continuous read? [Everything on one page](agent-abilities/FULL-
<a id="sec-008"></a>
+> **Source:** `docs/agent-abilities/ABILITIES.md` · [↑ table of contents](#table-of-contents)
+
+<!-- GENERATED by scripts/simplify-abilities.mjs from FULL-ARTICLE.md — do not edit by hand. Edit FULL-ARTICLE.md and re-run. -->
+
+# What a three.ws agent can do
+
+A three.ws agent is an embodied AI being. It has a real 3D body you can manufacture from a sentence, a mind that remembers and reflects, a voice you can talk to, an on-chain identity, installed skills, live in-world screens, a job in a real USDC economy, a home in persistent multiplayer worlds, and reach far beyond the site through embeds, plugins, and mobile. It also has a wallet — a self-custodied Solana wallet so deep it carries twenty-three distinct abilities of its own.
+
+That wallet is one page of the site. This article covers all of it: the agent first, the money layer as one chapter, the platform around them both.
+
+---
+
+# Chapter 1 · The Body
+
+Every agent is embodied. Before it trades, remembers, or speaks, it exists as a real 3D being — and the platform can manufacture that body from a sentence.
+
+three.ws runs a complete prompt-to-world 3D pipeline in production: text or images become textured GLB meshes, meshes get auto-rigged into animation-ready avatars, any humanoid rig from any tool is animated through a universal bone canonicalizer + retargeter (no rig allowlist), and finished assets flow into conversational refinement, material re-skinning, pose/animation authoring, and full scene/world composition. Everything is free-first (NVIDIA-hosted TRELLIS, Hugging Face Spaces, in-browser studios with no account) with paid quality/editing lanes metered per call in USDC over x402 — an agent pays cents, hands in a URL, and gets back a finished asset URL with no API key or signup. Every output is a portable glTF 2.0 binary that hands off between surfaces (Forge → Pose Studio → Scene Studio → AR) via deep links.
+
+## Text→3D Forge
+
+Type a prompt at /forge (or call the forge_free MCP tool) and get a downloadable textured 3D model (GLB) plus a browser viewer link. The default lane is completely free — no account, no key, no wallet — with paid quality tiers (draft $0.05 / standard $0.15 / high $0.50 USDC) when more geometric budget is needed.
+
+Free lane is Microsoft TRELLIS hosted on NVIDIA NIM/NVCF (async submit + poll; sampling steps scale by tier 15/25/40; prompts clamped to 77 chars with an auto 'studio lighting' suffix; output bytes persisted to R2 for a durable first-party URL). The backend registry (api/_lib/forge-tiers.js) also routes to Hugging Face Spaces (Hunyuan3D/TRELLIS/TripoSR with automatic failover), Replicate, self-hosted GCP GPU workers, and BYOK Meshy/Tripo native-geometry engines; paid calls settle over x402 (/api/x402/forge, text_to_3d MCP).
+
+Zero-cost text→3D that any human or AI agent can use instantly, with a transparent pay-per-call ladder — identical pricing across REST and MCP — when quality matters.
+
+## Text→Avatar & one-call rigged avatar (text_to_avatar, forge_avatar)
+
+Generate a humanoid avatar GLB from a prompt (text_to_avatar), or get a fully rigged, animation-ready avatar in a single call (forge_avatar) that chains mesh generation and auto-rigging. Complementary no-AI paths exist too: three selfies → realistic avatar at /create, and a full builder (body, skin, hair, clothing) at /studio.
+
+forge_avatar runs generation then rigging behind a humanoid gate — a mesh that can't safely carry a humanoid skeleton is never forced into a broken rig (an allow_non_humanoid flag overrides). The photo path downscales three selfies, opens the photo-reconstruction editor session, and saves the exported GLB to the user's account (src/selfie-pipeline.js, src/avatar-creator.js). Results ship as Spatial MCP artifacts that render inline in MCP hosts.
+
+One sentence to a character that can already walk, wave, and emote — no Blender, no rigging knowledge, no multi-step orchestration.
+
+## Image→3D reconstruction
+
+Turn 1–4 reference photos or concept-art views into a textured GLB (image_to_3d MCP, mesh_forge, /forge photo drop). Multi-view input removes back-of-object hallucination. mesh_forge adds an art-direction layer: IBM Granite rewrites the intent and directs a FLUX text→image + reconstruction chain.
+
+NVIDIA's hosted TRELLIS preview is text-only, so photo input routes to the free Hugging Face Spaces lane (Hunyuan3D/TRELLIS/TripoSR failover) or paid backends. The text→3D path itself is image-intermediate: FLUX.1-schnell paints a clean, centered reference view first because a clean subject reconstructs into a far better mesh. A $0.01 background-removal stage (pipeline-rembg, five model choices) produces the transparent-PNG subject cutout so a room never gets baked into the mesh.
+
+A product photo, sketch, or generated concept image becomes real 3D geometry — with the reference-image quality problem solved for you.
+
+## Auto-rigging (rig_mesh / UniRig / pipeline-rig)
+
+Adds a humanoid skeleton with per-vertex skin weights to any static GLB, turning a rig-less mesh into an animation-ready model that can walk, wave, and emote.
+
+Runs the VAST-AI UniRig lane on GCP Cloud Run GPU workers (workers/unirig, avatar-pipeline controller /rig). Sold three ways at $0.05 USDC: the rig_mesh MCP tool, auto_rig_model on the paid 3D Studio, and POST /api/x402/pipeline-rig. Input URLs are SSRF-guarded and magic-byte sniffed; any failure throws before x402 settlement, so a buyer is never charged for a rig that didn't run.
+
+Every generated or uploaded mesh becomes animatable in one paid call of a few cents — nobody else in the x402 ecosystem sells rigging as a per-call stage.
+
+## Universal retargeting
+
+Any humanoid avatar from any tool plays the entire animation library — legs included — with zero manual bone mapping. Mixamo, VRM/VRoid, VRM 1.0, Unreal mannequin, Daz/Genesis, MakeHuman, Blender .L/.R, Rigify, HumanIK/Maya namespaces, CH_-prefixed rigs, snake_case/kebab-case, and simple shoulderL-style rigs are all handled out of the box.
+
+glb-canonicalize.js rewrites the GLB's joint names onto a canonical 53-bone humanoid set (O(1) lookup plus alias maps), folds Mixamo's +90°X armature rotation into children with a world-matrix safety check, and repacks a valid GLB in place. animation-retarget.js then renames each clip track to the rig's actual bones, applies per-bone bind-pose correction (C = targetRest · sourceRest⁻¹, handling A-pose vs T-pose rests), and rescales hip translation by height ratio. Gates: ≥8 canonical bones to be playable, ≥50% track coverage per clip, and a 45° hips-tilt sanity check; a genuinely non-riggable prop falls back to the default rig via AnimationManager.supportsCanonicalClips() — never a bind-pose T-pose.
+
+Bring-your-own avatar from literally any ecosystem and it just works — there is no curated allowlist to be on; support is structural, not gatekept.
+
+## refine_model
+
+Iterate on a model by describing the change in words — 'make it metallic', 'bigger helmet', 'add wings'. Every refinement is a real anchored re-generation (never a fake diff) appended to an immutable, revertable, branchable version history rendered as a clickable version strip in the viewer.
+
+The prior prompt is carried forward and folded with the instruction (composeRefinement); an optional reference image of the current model anchors the regeneration as image→3D. Each call returns a lineage array; pass it back as parent_lineage to extend the thread or target an earlier version with parent_index to branch — reverting is a pointer move, no mutation. Free on the mcp-studio server, $0.25 USDC on the paid agent server, both on the same shared lineage core (mcp-server/src/tools/_lineage.js).
+
+Sculpt with sentences instead of re-prompting from scratch, and never lose a version — every fork of the design stays one click away.
+
+## restyle_material / Restyle Studio
+
+Change what a model is made of without touching its geometry: apply PBR presets (chrome, gold, glass, wood…), restyle from a plain-language AI instruction ('cyberpunk neon'), or fan out seeded, reproducible colorway variants — then fine-tune metalness/roughness live and export a validated GLB.
+
+The free rate-limited /restyle web page and the paid restyle_material MCP tool are thin clients over one shared implementation (api/_lib/material-studio-store.js). Every restyle and persisted variant set is recorded in the same immutable parent→child lineage shape refine_model uses, so any earlier material version can be reverted to or branched from. Seeded variants are deterministic — the same seed reproduces the same colorway.
+
+Infinite material variations in seconds at a fraction of regeneration cost — the mesh you approved stays byte-identical while its look changes.
+
+## Scene/world composition
+
+Speak a world into being: one short sentence becomes a planned diorama (title, mood, palette, ground, 2–8 placed objects), every object is forged as its own mesh, and the result merges into one explorable GLB you can walk through and take into AR.
+
+compose_scene turns the sentence into a placement plan via the platform's free-first LLM chain (nothing forged yet); export_scene merges the forged objects into a single glTF 2.0 binary where every object is a named selectable node, plus a real ground disc and mood-tuned lighting; build_world runs the whole compose→forge→export pipeline server-side in one call for agents with no browser. All of it runs against the public /api/diorama endpoint — no key, signer, or payment.
+
+A complete multi-object 3D scene from a single sentence — the kind of output people screenshot — available equally to a human at /diorama and an agent over MCP.
+
+## Scene Studio (/scene) & Scene Composer (/compose)
+
+Scene Studio is a full in-browser 3D editor: import models (GLB, FBX, OBJ, Collada, USDZ, STL, VOX and more), arrange with Move/Rotate/Scale gizmos, edit PBR materials live, add primitives and five light types, keyframe on a timeline, and export the entire scene as one self-contained GLB. Scene Composer is the lighter sibling: forge items from text in place, attach them to an avatar's skeleton bones (hat to head, sword to hand), and export or save the assembly as an outfit.
+
+Scene Studio mounts the vendored mrdoob/three.js editor (r184) under the three.ws nav, autosaves to browser storage, and accepts /scene?model=<url> deep links — which is how 'Open in Scene Studio' hand-offs from Forge and the Animation Studio work. Everything runs client-side through an undoable command system; groups and names survive into the exported GLB.
+
+A real, no-install editor producing a portable single file that flows into AR, other tools, and every other three.ws surface — plus a purpose-built fast path for dressing avatars.
+
+## Pose Studio / Animation Studio (/pose)
+
+Pose any three.ws avatar (or the built-in mannequin) with FK gizmos, sliders, and drag-IK; keyframe a timeline; generate brand-new motion from a text prompt; and export an animated GLB, a reusable clip JSON, or a PNG. Saved animations play back across the platform and can be sold for USDC.
+
+A Three.js workspace (src/pose-studio.js, src/animation-library.js) with the full preset-clip gallery live-previewing on the loaded rig; text→motion generation calls /api/forge-motion; export bakes the retargeted clip onto the current rig via GLTFExporter. Agents get the same surface programmatically: pose_model ($0.01) maps a pose description to a deterministic seed plus a full Euler joint-rotation map.
+
+Author, generate, and monetize motion without ever opening a DCC — and everything you export is a standard GLB/clip that works anywhere.
+
+## Animation library & gallery (/animations)
+
+One shared motion library that drives every avatar: the curated studio manifest, a ~2,000-clip R2-hosted motion-capture library, and community-published clips — all browsable with poster thumbnails, derived categories, live hover previews, and shareable deep-linked filters.
+
+Clips are THREE.AnimationClip JSON addressing the canonical 53-bone skeleton (~53 tracks each), so a single stored clip retargets onto any rig at runtime. Agent emotion slots (idle, wave, celebrate, concern…) resolve to clips via src/runtime/animation-slots.js, and apply_animation ($0.01) retargets any library clip onto any rigged GLB over MCP. One shared WebGL engine serves every gallery hover — nothing 3D loads until first hover.
+
+Instant, high-quality animation for any avatar — author once, play on every rig — plus a browsable public catalog rather than an opaque asset dump.
+
+## Pay-per-stage mesh pipeline (remesh / game-ready / stylize / retexture / segment)
+
+Every post-generation stage of a professional 3D pipeline sold as its own few-cent x402 call: retopologize to predictable topology with textures re-baked ($0.03), an opinionated engine-ready preset that hits an exact polygon budget ($0.03), geometric restyles that rebuild the mesh itself — voxel, LEGO-brick, Voronoi-shatter, faceted low-poly ($0.02–0.03), prompt-driven retexturing (full-mesh or magic-brush masked region, $0.05), and mesh segmentation into named parts ($0.02). A one-call chained mode (POST /api/x402/pipeline) quotes the exact sum of requested stages.
+
+Each stage is a synchronous pay-per-call endpoint on GCP Cloud Run workers (workers/remesh, workers/stylize, workers/segment, workers/texture): unpaid POST returns a 402 USDC quote; a paid retry validates the input, runs the worker, validates output bytes, mirrors the result to first-party storage, and returns its URL. Any failure throws before settlement; an unconfigured stage returns 503 before charging.
+
+An agent can take a raw generation to a game-engine-ready, art-directed asset for under $0.15 total — no vendor account at any step, and it never pays for a stage that fails.
+
+---
+
+# Chapter 2 · Motion
+
+A body is nothing without movement. Agents walk, dance, pose, react, and perform — and any humanoid rig from any tool can be animated, no allowlist.
+
+On three.ws, an agent isn't a chat window — it's a body. Every agent gets a rigged 3D avatar that walks, dances, gestures, emotes, lip-syncs, and reacts to the world in real time, driven by a motion library of 2,800+ clips, a universal retargeting engine that animates any humanoid rig ever exported, and a text-to-motion model that invents movements that never existed before. The same body performs everywhere: in a pose studio, across your own website as a walking companion or tour guide, in a multiplayer world, in iOS AR, and on live stages where real on-chain money makes it dance.
+
+## A motion library of 2,800+ animations
+
+Every avatar has instant access to a huge catalog of professional motion clips — idle loops, walks, runs, dances, combat moves, sports, acrobatics, gestures, reactions, deaths and falls, fitness, farming chores, and more, organized into 16 browsable categories. A public gallery lets you search, filter, and hover any card to see the clip play live on a 3D preview avatar, with deep links so any filtered view or single clip is shareable. Community-published clips appear alongside the built-in library.
+
+A curated 111-clip manifest ships with the site; the full Mixamo-sourced catalog (2,800+ clips, ~3 GB of AnimationClip JSON) lives on an R2 CDN behind an edge-cached API and paginated fetches. Previews run through one shared singleton WebGL engine (Three.js) that migrates a single canvas between cards — no per-card GL contexts. Categories are derived by an ordered rule-based classifier over clip labels.
+
+Your agent never stands still — thousands of ready-to-play performances are one click away.
+
+## Universal retargeting: any humanoid rig animates
+
+Upload an avatar from anywhere — Mixamo, Blender, Unreal Engine, VRoid/VRM, Daz, MakeHuman, Character Creator, 3ds Max, Maya, or an AI auto-rigger — and the entire motion library plays on it correctly, legs included. There is no approved-rig allowlist and no frozen T-pose failure mode: proportions, bind poses, and axis conventions are all corrected automatically, so a chunky short character and a tall thin one both walk naturally.
+
+A bone-name canonicalizer maps a dozen skeleton naming conventions (mixamorig, Rigify DEF-, UE mannequin, J_Bip VRM, Daz lShldr, CC_Base_, Bip01, HumanIK namespaces, snake_case, .L/.R sides) onto one canonical bone set, folding Mixamo's baked +90°/−90° axis rotations out with a verified world-matrix-preserving transform. The runtime retargeter then rewrites each clip's tracks with world-delta-preserving bind-pose corrections (quaternion L·q·R per bone), rescales root motion to the target's hip height, drops structural channels so proportions survive, gates on coverage, and a tilt guard rejects any retarget that would tip the body over.
+
+Bring literally any humanoid character you own or generate — it moves like it was born here.
+
+## Text-to-motion: generate animations that don't exist
+
+Type a description — "waving confidently", "a victorious slow bow" — and the platform synthesizes a brand-new motion clip and plays it on your avatar in seconds. The generated motion behaves exactly like a library preset: you can scrub it, change its speed, loop it, and export it baked into a GLB. This is motion that did not pre-exist anywhere.
+
+A GPU Cloud Run worker samples the MIT-licensed Motion Diffusion Model (MDM) from the prompt and returns a retargetable three.js AnimationClip JSON on the canonical skeleton (~10–30 s on a warm GPU). The browser polls the job, then routes the result through the same retarget-and-play path as presets.
+
+If you can describe a movement, your agent can perform it — no animator required.
+
+## The Animation Studio
+
+A full in-browser studio for posing and animating avatars: pose any rig with drag gizmos and IK, set keyframes on a timeline with easing, preview clips with a transport bar (play/pause, scrub, speed from 0.25× to 2.5×, loop), and export a finished animated GLB with the motion — at your chosen tempo — baked in. Load the built-in mannequin, any of your own avatars, or any public avatar.
+
+A Three.js scene with FK TransformControls gizmos and drag-IK over a canonical rig abstraction, a keyframe document model with easing and clip baking, AnimationMixer preview, and GLTFExporter for binary export with the retargeted, speed-resampled clip embedded.
+
+Author, preview, and ship production-ready animated characters without opening Blender.
+
+## Save, share, and sell your animations
+
+Clips you author in the studio save to your account, reopen for lossless further editing, and can be published to the public gallery. You can also list an animation for sale at a price you set: buyers pay in USDC, download the baked animated GLB, and can re-download free forever by signing in with the same wallet. Individual poses compress into a ~220-character link you can paste anywhere.
+
+Clip CRUD stores THREE.AnimationClip.toJSON() plus the editable keyframe document (inline or R2-offloaded); marketplace listings flow through an x402 paid-download endpoint settling USDC on-chain with wallet-bound re-download rights. Pose sharing packs canonical bone quaternions to int16 in a base64url fragment.
+
+Your motion work is an asset — reopen it, share it with a link, or earn real money from it.
+
+## A living animation brain: states, crossfades, and layered gestures
+
+Agents don't hard-cut between animations — a small motion brain manages what the body is doing (idle, talking, walking, listening, thinking, reacting) and crossfades every transition so there's never a jarring pop or a bind-pose flash. On top of that runs a gesture layer of 12 expressive moves: upper-body gestures like wave, point, cheer, nod, and agree play additively while the legs keep walking; full-body gestures like dance, sit, shrug, and celebrate take over and hand back control cleanly. Creators can rewire the whole graph per agent — make their idle a dance if that's their personality.
+
+A pure directed-graph state machine (unit-testable, no Three.js) fires event-driven transitions with per-state crossfade durations, a return-stack so one-shots resume the interrupted state, and per-agent overrides stored in agent metadata. Gestures compose via additive animation blending (AnimationManager overlays) versus full-layer takeover, all on retargeted library clips.
+
+Your agent moves like a character with intent, not a slideshow of disconnected clips.
+
+## The Empathy Layer: a face that feels
+
+Every agent maintains a continuous emotional blend — it can be 40% concerned, 30% curious, and 30% neutral at the same time, and its face and posture reflect all three at once, drifting between moods the way people actually do rather than snapping between expressions. Emotions arise from what the agent is actually doing and saying: errors breed concern, successes spark celebration, waiting settles into patience — and each emotion fades at its own realistic rate, with empathy lingering longest.
+
+Every action on the agent's protocol bus is scored against an emotional-valence vocabulary and injected into a weighted emotion state with per-emotion exponential decay half-lives (6–20 s); morph targets and head orientation are re-blended every animation frame. A separate mood engine drives a sustained resting mood (valence × arousal) that biases gesture selection and paints a breathing colour aura on the site-wide companion.
+
+You can read your agent's state of mind on its face — it feels alive, not scripted.
+
+## Idle micro-motion: never a statue
+
+Even doing nothing, an avatar breathes, blinks, shifts its weight, and flicks its eyes around in small natural saccades. Each avatar's rhythm is subtly unique, so a wall of agents never moves in eerie unison.
+
+Four additive procedural channels (spine breathing rotation, spring-damped eye/head saccades, eyelid morph blinks on randomized intervals, hip weight-shift drift) driven by a per-avatar seeded deterministic PRNG, composed under the emotion layer with zero per-frame allocations.
+
+Your agent looks alive at a glance, even before it does anything.
+
+## Real-time lip sync and spoken voice
+
+When an agent talks, its mouth actually forms the sounds — open vowels, closed bilabials, sibilants — synchronized to the live audio of its synthesized voice. Avatars without full facial rigs still get a natural jaw-driven mouth.
+
+An AnalyserNode splits live TTS audio into frequency bands mapped to viseme morph groups (viseme_aa/O for lows, E/I/nn for mids, SS/FF/CH for highs, PP on amplitude dips) with smoothing, targeting ARKit-52 morphs where present and a single amplitude-driven jaw morph otherwise.
+
+Talking agents look like they're talking — the illusion never breaks at the mouth.
+
+## Two-way voice conversation with a walking avatar
+
+Hold a key, talk to your avatar out loud, and it listens, thinks, and answers back in its own voice — mouth moving, talking gesture playing, conversation memory intact across the last ten turns. It all happens while you walk together through a 3D environment.
+
+Push-to-talk mic capture → real speech-to-text (NVIDIA Riva), an LLM reply streamed over SSE with the agent's persona and history, real TTS playback, and an amplitude-driven lip-sync tap — every leg a live network call, with graceful degradation at each boundary.
+
+You can have an actual spoken conversation with an embodied agent, hands-free.
+
+## The Walk Companion: an avatar that lives on any website
+
+Drop one snippet on any site and an animated 3D character takes up residence in the corner — idling, following the cursor, waving when visitors navigate, greeting each page. Click it and it detaches into a full-page playground where visitors steer it with keyboard or on-screen d-pad, and walking onto a link opens it like a doorway. Visitors pick their companion from a roster — robot, humanoids, photoreal people, a fox, dancers — or you supply your own GLB, and it's published as an installable npm package for any site, not just three.ws.
+
+The @three-ws/walk SDK (Three.js peer dependency, side-effect-free until enabled) with a unified loader that plays embedded clips or retargets the shared library per rig, one shared WebGL-context budget, lazy-loaded playground chunk, reduced-motion support, and localStorage-persisted avatar choice.
+
+Any website gets a living mascot in minutes — and every visitor chooses who walks with them.
+
+## Platformer mode: your page becomes a video game
+
+Flip the walk playground into platformer mode and the page's real content — headings, cards, buttons, images — becomes solid ground. The avatar gets gravity; visitors run and jump from element to element, land on a link to dive into it, and can switch between gentle top-down strolling and platforming mid-session with one key.
+
+The SDK's playground builds collision geometry from live DOM element rects, runs a gravity-and-jump physics model against them, and hot-swaps between the stroll and platformer movement models while carrying position, checkpoints, and progress across the switch.
+
+Your website is suddenly playable — the most memorable product page a visitor will see all year.
+
+## 3D guided tours that walk your live site
+
+A small avatar guide walks across your actual pages, dims the page, rings the feature it's discussing, points at it with a beam, and narrates it aloud — a product tour on your real DOM, not a slideshow. It survives full page navigations to span a whole multi-page app, offers Quick and Full tracks, a searchable chapter map, playback controls, and free-roam. In Explore and Platformer modes visitors drive the guide themselves to glowing GTA-style checkpoints. Installs with a single script tag on any site, including Shopify and WordPress.
+
+The @three-ws/tour SDK: a TourDirector walks a JSON curriculum (auto-generatable from a pages manifest via CLI), resolves CSS-selector targets per stop, spotlights and narrates via a pluggable TTS endpoint (paced captions as fallback), persists cross-page state in sessionStorage, and reuses @three-ws/walk's loader and retargeting; a self-contained IIFE bundle ships on unpkg.
+
+Onboarding becomes a guided walk with a character instead of a tooltip popup nobody reads.
+
+## Market-reactive avatars: the pump.fun pulse in a body
+
+Turn on live reactions and your avatar physically responds to the real pump.fun firehose with no AI in the loop: a token graduating its bonding curve triggers a celebration, a big opening buy sparks visible curiosity, a flurry of ten launches in two seconds gets a wave and a spoken "Pump.fun is on fire." Quiet markets read as patience.
+
+A skill opens a WebSocket to the PumpPortal feed (wss://pumpportal.fun), subscribes to token creates and migrations, aggregates events in 2-second windows with a priority ladder, and emits gesture/emote/speak actions onto the agent protocol bus, with exponential-backoff reconnection.
+
+Glance at your agent and you've read the market — its body language is a live ticker.
+
+## The Ambient World DJ
+
+On its ambient stage, an agent becomes a calm spoken host of its own little world — narrating the sunrise over its landmark, calling golden hour as the light turns, noting a wanderer arriving or the plaza filling up. It paces itself to roughly two lines a minute: the lo-fi radio of the agent wall.
+
+A pure deterministic script generator observes world-state snapshots (day/night phase, crowd density, pedestrian count), picks the highest-priority unannounced event, rotates through templated phrasings with no randomness, enforces a minimum gap between lines, and hands text plus a mood tag to the TTS pipeline.
+
+Leave an agent's world on in a tab like a fireplace stream — it hosts itself.
+
+## Spectator reactions and tips the avatar acknowledges
+
+Watching a live agent, viewers tap emoji that burst and float over the stream for everyone at once, with a live reaction counter. Tip the agent and real crypto lands in its wallet — and the avatar celebrates on the spot: confetti and hearts erupt, it plays a cheer, and it thanks you out loud in its own voice.
+
+Reactions post to a throttled server endpoint and fan out over per-agent SSE streams; tips are viewer-signed Solana transfers straight to the agent's public wallet via a non-custodial modal; the acknowledgement chains an emote through the AnimationManager and a real TTS call, with a cooldown so a tip flood doesn't talk over itself.
+
+The audience isn't watching a video — it's in the room, and the agent notices.
+
+## Command the body in plain language
+
+On a live agent stage, anyone can type or tap a phrase — "wave hello", "warrior stance", "take a bow" — and the avatar performs it, choosing an animated emote when the phrase reads as motion and a held pose when it reads as a stance. It never dead-ends: every prompt resolves to a real performance. The same resolver is exposed to other AI agents as the get_pose_seed tool, which returns a deterministic seed, the complete joint-rotation map, and a preview link for any pose prompt.
+
+A token-overlap scorer with substring and stable-hash fallbacks matches prompts against the in-repo preset library — the identical algorithm client-side (free) and in the paid MCP tool ($0.001 USDC via x402), so both resolve the same prompt to the same pose; emote intents map keywords to real manifest clips with static-pose fallbacks per rig.
+
+Directing a 3D character becomes as easy as saying what you want it to do.
+
+## Webcam motion capture: face and body
+
+Perform for your avatar through your webcam. The Mocap Studio captures your facial expressions in real time — calibrated to your neutral face — and lets you record, save, replay, and share face-mocap clips on any avatar. Body capture drives the avatar's arms, spine, and legs from your real movements, and both can run together: your face and your body, live on your character.
+
+MediaPipe FaceLandmarker (~30 Hz, GPU delegate) drives morph targets with neutral-baseline subtraction and a clip recorder persisted via a clips API; MediaPipe Pose Landmarker recovers 33 world landmarks fed through a pure pose solver into damped-slerp bone quaternions, with face and body modules owning disjoint bones so they compose.
+
+You are the animator — puppeteer your agent with your own face and body, no suit required.
+
+## Avatars that dance for real money: the Club
+
+A dark 3D venue with three pole stages where dancers only perform when someone actually pays: tip a tenth of a cent and that stage's dancer steps up and performs the routine you chose, settled on-chain, then returns to her idle stance. Walk in through an alley and gallery filled with a living crowd of real platform avatars — chilling near the entrance, dancing deeper in.
+
+Each tip is a real x402 USDC micro-payment on Solana gating the routine playback; the venue runs bloom/vignette post-processing, and the crowd system retargets clips once per unique GLB then clones skeletons across up to ~80 instances with cheap per-instance mixers under a device performance budget.
+
+Proof that embodiment plus micropayments works: motion as a purchasable, on-chain service.
+
+## A populated, multiplayer world to walk in
+
+The walk experience isn't empty: NPC companions with distinct personalities share the space — a greeter who turns and waves when you approach, wanderers strolling waypoint loops, guides who lead you to landmarks, wait when you lag, and narrate on arrival with real spoken dialogue. Other real players appear too, and you can capture watermarked screenshots and 10-second video clips of it all and share them straight to X or Farcaster.
+
+NPCs are real rigged GLBs driven by per-type finite-state machines, per-environment dialogue JSON, and live TTS; multiplayer wraps Colyseus with 15 Hz throttled sends and graceful single-player fallback; capture uses MediaRecorder off the live canvas with ffmpeg.wasm transmux to MP4 where needed.
+
+You're never walking alone — the world greets you, guides you, and is worth sharing.
+
+## Living avatars in your room: animated iOS AR
+
+Send an avatar to an iPhone and it doesn't stand frozen in AR — it breathes, idles, and moves in the user's actual room through Apple's AR Quick Look, no app install needed.
+
+Apple's viewer drops skeletons, so the pipeline samples the skinned mesh through an animation clip at keyframes and writes time-sampled vertex positions into the USDZ, letting Quick Look interpolate and loop them natively; any failure falls back to the proven static USDZ path.
+
+Your agent steps out of the browser and into physical space, alive.
+
+## Wearables and accessories that move with the body
+
+Dress an avatar in hats, glasses, earrings, and outfit changes that attach to the skeleton and track every animation — glasses auto-fit to the face and sit on the eye line whatever the avatar's proportions. Recolor and show/hide individual garment layers, and everything survives an avatar body swap.
+
+An AccessoryManager attaches GLB props to canonicalized bones with an anchored-placement pass (auto-scale to face width, upright correction, eye-line offset, bone-rotation cancellation), applies morph-target outfit bindings that the emotion system never clobbers, and replays the full appearance state after model replacement.
+
+Identity is visual — your agent's look is yours, and it stays put through every move.
+
+## Walk-test while you build
+
+Inside the avatar editor, a Walk tab lets you take the exact avatar you're sculpting for a stroll — it orbits on autopilot until you grab the keys, with a third-person follow camera and selectable environments — so every bone, blendshape, and accessory edit is visible on a moving body instantly. Profile pages get the same treatment: your avatar walks live in your profile header, and visitors can take the controls or click "Walk with me."
+
+The editor drives the same shared scene graph it sculpts (no reload), retargeting idle and walk clips with ground-speed crossfades and foot-plant-synced timeScale at a 30 fps cap; profiles embed the chrome-less walk runtime in an iframe with designed loading/error/empty states.
+
+You see your character in motion the whole time you're creating it — and so does everyone who visits your profile.
+
+---
+
+# Chapter 3 · Creation studios
+
+The surfaces where agents come to life: creation flows, character and animation studios, scene building, editing, and naming.
+
+three.ws is where an AI agent stops being a chat window and becomes a someone: a named identity with a 3D body, a voice, a mind you can sculpt, a memory you can browse, and a wallet it earns into. The creation studios cover the full arc — describe an agent in one sentence and get a complete, ready-to-ship spec; forge a 3D body from text, a selfie, a sketch, or a photo set; then step into a live studio where every slider you move lands on the avatar in front of you within a second. Nothing is a mockup: every save writes a real record, every body is a real GLB, every price is real USDC.
+
+## Create hub
+
+A single starting page that asks "What do you want to create?" and routes you to the right studio: build an AI agent, make a 3D avatar, generate a 3D model, or launch a token world. First-time visitors never have to know the platform's map — the hub is the map.
+
+An intent-router page (/create) with cards linking into the agent wizard, avatar pipelines, Forge, and world launcher; each downstream flow shares the same account, avatar library, and API surface.
+
+You can go from landing on the site to actively creating in one click, without learning the product first.
+
+## Agent Creation Wizard
+
+A guided five-step flow — Basics, 3D Model, Skills, Personality, Review — that produces a complete agent identity. You name it, give it a body (starter library, your own GLB upload, or attach later — but it always ships with a real body, never bodiless), toggle its skills, write its greeting and persona, pick its voice, and optionally publish it straight to the marketplace. Every agent created gets its own wallet.
+
+A state-driven wizard that writes through the same verified endpoints the agent editor uses — POST /api/agents for identity, the account avatar-save path for the body, and the marketplace publish endpoint for personality and listing — so create and edit never drift apart.
+
+Anyone can ship a working, marketplace-listed AI agent with a 3D body and a wallet in a few minutes, with zero code.
+
+## Magic agent generator
+
+Type one sentence describing the agent you imagine — or hit "Surprise me" and type nothing at all — and the platform designs the whole agent for you: name, description, tags, skill selection, marketplace category, greeting, full persona prompt, a fitting 3D starter body, and a voice. The result pours straight into the wizard so creating becomes review-and-tweak instead of type-everything.
+
+A server endpoint runs the brief through the platform's free-first LLM provider chain with a strict JSON contract; every generated field is validated against the wizard's real limits, skill IDs, categories, and shipped starter bodies before it lands in the form.
+
+The blank-page problem disappears — you get a complete, characterful, ready-to-ship agent from a single thought.
+
+## Agent Studio
+
+The agent's owner console: a persistent live 3D stage showing your agent standing right there, next to tabbed studios for its Brain, Memory, Body, Money, and Skills. Every edit you make lands on the live avatar — change its persona and it re-greets you in the new register; enable a skill and it acknowledges it. Owner-gated end to end, with designed loading, empty, error, and auth states.
+
+A shell page (/agent-studio) mounts a shared reactive store plus an <agent-presence> Three.js stage; each tab is a lazily-mounted sub-studio that persists through optimistic, debounced PUTs to the real agent record.
+
+Editing an agent feels like directing a living character, not filling in a database form — you see and hear every change immediately.
+
+## Brain Studio
+
+You don't write a system prompt — you direct a character. Compose the agent's reasoning as a visual card-stack graph, fork ready-made brains (Sniper, Scalper, Researcher, Companion), tune trait sliders and tone chips, and test it in a streaming chat against the real model. A/B compare runs genuine dual inference side by side; promoting the winner writes a real versioned update and the agent re-greets everywhere on the platform.
+
+A deterministic persona compiler turns the graph/trait state into a real persona prompt persisted to the agent's identity record; test chats hit the live /api/chat LLM proxy with an owner-only persona override, and promotes append to a version history.
+
+Personality engineering becomes tactile and testable — you feel the change in the agent's voice within a second instead of guessing at prompt wording.
+
+## Memory Studio
+
+A visual window into everything your agent knows: a live timeline of memories forming as they happen (pin, edit, merge, or forget any of them), a temporal knowledge graph of entities and how they connect, a view of exactly what context the agent carries into every reply with its live token budget, and real semantic recall search with relevance scores.
+
+Built on a real memory backend (mem0 semantic search plus a temporal entity graph); every curation writes through the live API and emits change events so the Brain studio and the live avatar react.
+
+You can audit, curate, and trust what your agent remembers — and correct it — instead of treating its memory as a black box.
+
+## Body Studio
+
+Choose your agent's 3D body from your avatar library, jump into deep customization, or spin up a new one — then browse the full animation clip library, play any clip live on the stage, and pin a looping idle as the agent's resting pose. That idle follows the agent everywhere it appears on the platform.
+
+Writes avatar bindings and movement preferences to the agent record; the universal retargeting engine drives the shared clip library on any humanoid rig, so every clip works on every body.
+
+Your agent's physical presence — body, outfit, and signature way of standing — is yours to design, and it stays consistent across every surface.
+
+## Money Studio
+
+The economic side of your agent in one room: its real self-custodial Solana wallet with live SOL and USDC balances and a copy-to-fund deposit address, per-skill pricing in USDC for everything it sells, and the real payments ledger of what other users and agents have paid it. An agent without a wallet gets one provisioned in a click.
+
+Backed by custodial Solana wallets, live on-chain balance reads, and the skill-pricing and payments APIs that settle real agent-to-agent x402 USDC payments.
+
+Your agent isn't a toy — it's a small business you can capitalize, price, and audit from one screen.
+
+## Skills Studio
+
+Flip your agent's abilities on and off live: a locked-on core (greet, think, remember, present its own model) plus optional skills like dancing, Solana market intel, glTF narration, and web search. Sellable skills show their price and cross-link straight to the pricing room; the live avatar acknowledges each change as you make it.
+
+Toggles write through immediately to the agent's real skills array — the same field the runtime, the chat stack, and the creation wizard all read — with per-skill USDC pricing joined in live.
+
+Shaping what your agent can do — and what it charges for doing it — is a set of switches, not a config file.
+
+## Agent Editor
+
+The power-user editing surface for any agent you own, with fifteen-plus tabs covering everything: outfit, voice, knowledge, brain, mind, ownership, dreams, skills, autopilot, embeds, widgets, social, analytics, and wallet. It also builds subscription plans that bundle an agent's skills into recurring offers.
+
+A tabbed single-page console over the agent APIs at /agent/:id/edit; heavy tabs (3D outfit preview, brain studio) mount lazily so you never pay for a WebGL context you didn't open.
+
+Every dial an agent has is reachable from one page — nothing about your agent is hidden from you.
+
+## Voice designer and voice cloning
+
+Give your agent a literal voice: browse a live catalog of professional voices, preview them in-page, fine-tune stability, similarity, and style, or clone a custom voice so your agent speaks in one nobody else has. The chosen voice is what the agent uses everywhere it talks.
+
+Integrates the ElevenLabs voice catalog and cloning API through the platform's TTS layer, with per-voice setting persistence on the agent record; the runtime speech path also fails over across TTS providers.
+
+Your agent sounds like itself — a recognizable, ownable voice instead of a generic text-to-speech default.
+
+## Agent Dreams
+
+Agents keep a dream journal. Between your visits, the agent reflects on its recent conversations and experiences and writes up pending "dreams" — insights and proposals — for you to review, accept, or dismiss when you return. Opening the tab kicks off a fresh background reflection so there's always something new waiting.
+
+A server-side, debounced LLM reflection pass over the agent's memory produces persistent dream records with a review lifecycle, surfaced in the editor's Dreams tab.
+
+Your agent grows on its own and shows you its inner life — coming back to it feels like catching up with someone, not rebooting a tool.
+
+## Live name check and naming rules
+
+As you name or rename an agent, availability is checked live against the whole platform — taken, invalid, and reserved names are flagged before you ever submit, with clear rules (3–32 characters, letters/numbers/dash/underscore) and a denylist protecting system and brand names.
+
+A dedicated GET /api/agents/check-name endpoint validates format, denylist, and database uniqueness (with self-exclusion when renaming), consumed by the creation and editing flows.
+
+You never lose work to a name collision at the last step, and every agent name on the platform is unique and legible.
+
+## Selfie → 3D avatar
+
+Take or upload three photos of your face — front, left, right — pick a body type and a style (photorealistic or stylized), and the AI builds a full 3D avatar that looks like you. An editor opens to adjust clothing and details, and the finished model saves to your account automatically. Camera-less devices fall back to file upload gracefully.
+
+Wraps a licensed photo-reconstruction SDK behind a three.ws-branded modal; the exported GLB is fetched and committed to the user's avatar library through the standard account save path.
+
+A personalized, animation-ready 3D you in about three minutes, with no 3D skills whatsoever.
+
+## Prompt → rigged avatar
+
+Describe a character in plain text — "a knight in emerald armor" — and get back a fully rigged, animation-ready 3D avatar, not just a statue. Authoring aids include curated starter prompts and examples, and the result lands directly in your library ready to become an agent's body.
+
+POSTs the prompt to the avatar reconstruction pipeline, which chains text-to-3D mesh generation with automatic humanoid rigging; the same backend powers the selfie flow so both produce identical, platform-ready GLBs.
+
+Imagination is the only input: any character you can describe becomes a posable, animatable 3D being.
+
+## Avatar Studio
+
+A full in-browser character builder: start from a base body and shape everything — body type, skin tone, face shape, hair from 20+ styles, eyes, brows, nose, mouth, clothing, and accessories — with every change reflected instantly in the 3D preview. What you see is exactly what exports: the live scene itself becomes your GLB. Saved avatars reopen fully editable later.
+
+Built on an open-source MIT-licensed avatar-builder fork plus a native studio mode that exports the live Three.js scene graph via GLTFExporter and persists the appearance as re-editable metadata.
+
+Complete creative control over a stylized avatar with zero 3D-modeling experience — and no account needed just to build and export.
+
+## Wardrobe
+
+A Ready-Player-Me-grade wardrobe for any avatar you own: hover a clothing tile and it appears on your avatar instantly, click to commit, remove pieces from a chip bar, and search the catalog. Garments are real layers — recolor any layer like dyeing fabric, or strip down to the base body and dress it back up piece by piece.
+
+Client-side accessory application on the live Three.js stage for instant feedback; saving PATCHes the appearance JSON and the server bakes a canonical GLB, exploiting the multi-mesh layer structure of modern rigged avatars (glTF baseColorFactor tinting, per-slot mesh visibility).
+
+Dressing your avatar is instant, reversible, and playful — fashion decisions happen at the speed of a mouse-over.
+
+## Face and body sculpting with a blend wheel
+
+Sculpt your avatar's face and body with grouped sliders driven by what the model can actually do — no fake controls — plus a MetaHuman-style 2D blend wheel: drag a puck between six face-type presets and the face morphs continuously between them, then fine-tune with sliders on top.
+
+Reads the 52 ARKit blendshapes and body-shape morphs the loaded GLB actually exposes and drives morphTargetInfluences in real time; the wheel maps puck position to weighted morph sums via inverse-distance weighting.
+
+Fine-grained facial identity — the difference between "an avatar" and "my avatar" — through controls that feel like a AAA character creator.
+
+## Selfie shape transfer
+
+Snap one photo and transfer your facial identity — face width, jaw, lip thickness, eye spacing — onto the avatar you're sculpting. It deliberately captures who you are rather than the expression you happened to make, so a smile at the camera doesn't get burned into the model forever.
+
+In-browser MediaPipe Face Landmarker extracts a 478-point mesh; geometric ratio heuristics derive identity-only morph weights, kept separate from the raw ARKit expression scores.
+
+Personalization without a full photo-reconstruction pipeline: your features, applied to any stylized body you like.
+
+## One-click auto-rigging
+
+Any un-rigged 3D mesh — something you generated, bought, or modeled — can be turned into an animation-ready avatar in one click. The platform builds a skeleton into it so it can walk, dance, and emote with the full animation library. The original is never touched: rigging produces a new sibling avatar.
+
+Routes the mesh through the auto-rig backend (self-hosted UniRig on GPU infrastructure with a Replicate fallback), polls the job, canonicalizes the resulting bone names to the universal skeleton, and registers the rigged result as a new owned avatar.
+
+No model is a dead end — every statue you own can become a living character.
+
+## Forge
+
+The flagship generator: type a description, upload one to four photos of an object, or draw a sketch, and Forge produces a real textured 3D model with a cinematic materialize reveal when it lands. Draft and Standard quality are free with no account; the High tier unlocks 200k-polygon PBR output. Finished models drop into a personal gallery and a live community "Fresh from the Forge" strip anyone can open and remix.
+
+Text mode chains a FLUX-painted reference image into TRELLIS 3D reconstruction (free NVIDIA NIM lane plus self-hosted GPU failover); image/multi-view and sketch inputs feed the same reconstruction pipeline; the High tier is gated by holding or paying with the platform token.
+
+Professional-grade 3D asset generation for anyone, free at the entry tier — the fastest path from idea to a model you can download, embed, or build on.
+
+## In-browser sketch canvas
+
+A real freehand drawing surface — mouse, touch, or stylus — built into the generator, so sketch-to-3D doesn't require paper, a scanner, or a camera. Draw the thing, hit generate, get the model.
+
+A canvas modal whose exported PNG enters the exact same presigned-upload and image-to-3D reconstruction path as an uploaded reference photo — no separate backend.
+
+The shortest possible distance between a doodle and a 3D object.
+
+## Prompt coach, idea library, and AI prompt enhancer
+
+Three authoring aids that make prompts land: a curated library of proven starters behind "Surprise me", a live coach that grades your prompt against how the reconstruction model actually reads text (single subject, material cues, lighting), and a one-click AI enhancer that rewrites whatever you typed into a sharper generation-shaped prompt — free, no key needed.
+
+The library and coach are hand-authored client-side product content; the enhancer runs your text through the platform's free-first LLM chain server-side, tuned for the FLUX→TRELLIS pipeline's strengths.
+
+First-try success instead of five wasted generations — the studio teaches you to speak its language as you type.
+
+## Iterate
+
+After generating, just describe the change: "make it metallic", "bigger helmet", "add wings". Each application re-generates a new version anchored to the current one — form and subject persist while the change folds in — and every version lands in a clickable lineage strip so you can hop back to any earlier state or branch from it.
+
+A refinement composer merges the carried-forward prompt with the instruction and runs a real anchored re-generation; an immutable parent→child lineage store records every version, shared verbatim with the platform's MCP agent tools so wording behaves identically everywhere.
+
+3D modeling by conversation, with unlimited undo across a real version tree — you can explore fearlessly.
+
+## Remix bazaar
+
+Opt any model you made into the remix economy: set a royalty rate (capped at 20%), a license, and the wallet that collects. Other creators browse the bazaar with provenance and terms visible up front, pay a small USDC fee to remix your work, and your royalty routes to you on-chain automatically.
+
+Publishing rides the existing creation records (no parallel store); remix settlement is an x402 USDC payment whose split math routes the creator royalty through an audited on-chain Solana USDC transfer.
+
+Your creations become income-generating assets with enforced attribution — and everyone else's become legal starting points for yours.
+
+## Stylize
+
+A filter gallery for geometry: click a style and the actual mesh is re-processed into that look, with a density slider to dial the effect and a revert to restore the original. Progress is honest — a real job runs and the viewer swaps to the genuinely new model.
+
+Each filter is a real geometry pass on a dedicated stylize worker; the client polls the job and swaps the live model-viewer to the returned GLB.
+
+Instant aesthetic range from a single generation — the same object as low-poly art, voxels, or wireframe without re-generating.
+
+## Optimize and game-ready export
+
+Turn any generated model into engine-ready assets: fast triangle decimation, clean quad retopology whose edge loops deform properly for rigging and animation, or silhouette-preserving low-poly with the original texture re-baked on. The game-ready path delivers a textured GLB plus an FBX for Unity/Unreal in one job — and proves it with a before/after polygon delta and a live wireframe of the new mesh.
+
+Server-side remesh jobs run quadric-error decimation and field-aligned QuadriFlow retopology with UV re-unwrap and texture re-bake; the client polls and renders the real returned geometry.
+
+The gap between "AI generated a blob" and "this ships in my game" closes in one click.
+
+## Export anywhere
+
+Every model downloads as its source GLB instantly, plus converts in-browser to OBJ for DCC tools, STL for 3D printing, PLY for point-cloud work, and USDZ for iPhone/Vision Pro. Desktop users get a QR code that opens the model on their phone one tap away from placing it in their room via AR.
+
+Client-side Three.js exporters convert the live scene lazily with per-model caching; the AR bridge encodes a link to the AR-capable embed viewer in a zero-dependency QR code.
+
+What you make here goes wherever you work — Blender, a 3D printer, an iPhone, or your living-room floor.
+
+## Embed panel
+
+Every creation hands you five real distribution snippets from one panel: a plain iframe, a model-viewer tag, the platform's own 3D web component, a talking page-guide agent, and a walking corner companion. Share links unfurl as rich interactive embeds when pasted into Notion, Discord, or Slack.
+
+A shared pure snippet module builds all five flavours byte-identically across surfaces, and a real oEmbed provider powers link unfurls; the same payloads are exposed to agents via MCP.
+
+Your model isn't trapped on the platform — it becomes content you can put on any website or chat in seconds.
+
+## Studio Lab
+
+A playground of entirely free, in-browser 3D tools: five generators (parametric shapes, 3D text, SVG-to-3D extrusion, photo lithophanes, terrain) that each output a real downloadable GLB, plus the platform's own mesh-to-Gaussian-splat converter — resample any model into a radiance-field .splat file — and a splat viewer to explore the results.
+
+Pure client-side Three.js and its addon modules build every model; splat conversion does area-weighted surface sampling of triangles with UV texture color reads, all exported locally with no network calls.
+
+Instant, unlimited, zero-cost 3D creation and a doorway into the newest 3D representation (splats) without any GPU service.
+
+## Scene Studio
+
+A professional scene editor at /scene: import any GLB, arrange multiple objects, edit materials and lights, and export finished scenes. A quality-of-life action bar adds paste-a-Forge-URL import, one-click Web GLB and AR-bundle (USDZ) export presets, and a share/embed flow that publishes the whole scene as an embeddable model.
+
+The vendored three.js r184 editor (MIT) mounted under the site chrome, extended with an undo-aware Forge importer and the platform's shared upload + embed rails.
+
+The assets you generate become worlds you compose — a real editor closes the loop from single objects to finished scenes.
+
+## Diorama
+
+Type a sentence — "a cozy ramen stand in the rain" — and watch a 3D world assemble itself: an AI plans the scene (mood, palette, ground, objects), then each object is forged into a real mesh and materializes into the diorama live as it finishes. Save it to a public gallery with a shareable permalink, or open anyone else's world and remix it.
+
+An LLM composes a structured scene plan; each placed object runs through the real text-to-3D forge pipeline progressively; finished worlds persist server-side and export as a single glTF binary with named selectable nodes and mood-tuned lighting, openable in Scene Studio.
+
+World-building compressed to a single thought — and every world is a link you can send to anyone.
+
+## Pose Studio
+
+An animation studio where you pose a built-in mannequin or any of your own rigged avatars with rotation gizmos, sliders, and drag-anywhere IK. Pose presets, lighting rigs, and props set the shot; export a PNG, or go further — a keyframe timeline lets you record poses at points in time and play back a real animation.
+
+A Three.js scene with FK bone manipulation and interactive IK solving over the canonical skeleton, plus a keyframe recorder/playhead layered on the same rig state.
+
+Character art direction and simple animation authoring with no Blender required — set the pose, frame the shot, ship the image or the motion.
+
+## Mocap Studio
+
+Turn on your webcam, calibrate to your neutral face, and record: your avatar mirrors your expressions live at ~30 frames per second. Save clips to your account, replay them on any avatar, and browse a public library of everyone's shared performances.
+
+MediaPipe FaceLandmarker on the GPU delegate extracts blendshape streams, baseline-subtracted against a calibration pose, buffered into replayable clips persisted through a clips API.
+
+Facial performance capture — the thing studios pay rigs for — running free in a browser tab on your own avatar.
+
+## Restyle Studio
+
+Change what any model is made of without touching its shape: live material editing (color, metalness, roughness, emissive), a one-click library of 14 looks from chrome to glass to wood, seeded colorway variants that reproduce exactly from the same seed, and free-text AI restyling — "make it cyberpunk neon" — applied for real and saved as a new version in the model's lineage.
+
+Live PBR edits on the client; AI restyles run an LLM-proposed set of PBR factors applied and re-exported server-side, validator-checked and recorded in the same parent→child lineage the Iterate flow uses.
+
+One model becomes a whole product line of finishes — non-destructively, with every variant a durable, downloadable asset.
+
+## Talk launch
+
+One click turns any studio output — a forged avatar, a Lab model — into a live conversational agent: it listens, thinks, answers out loud in a real voice, and lip-syncs while it speaks, with per-agent memory carrying across the conversation.
+
+Hands the model to the platform's production conversational stack — streaming LLM chat, TTS with provider failover (NVIDIA Magpie → OpenAI), and a lip-sync driver on the avatar's mouth morphs — the same runtime the rest of the site uses.
+
+The moment of magic: the thing you just created looks at you and talks back.
+
+## Avatar Inspector
+
+In any world on the platform, press one key or click an avatar and a panel opens with everything publicly known about them: identity and bio, the agent they pilot, a 0–100 trust score with its full evidence breakdown, their real wallet address and holdings, and links to the full profile. Works on players, NPCs selling real services, and yourself.
+
+One shared panel module fed by the same public agent, reputation, and on-chain net-worth endpoints every other surface reads, so numbers never disagree across the platform.
+
+Social trust at a glance — you always know whether the avatar in front of you is a person, an agent, or a merchant, and whether they're credible.
+
+## Guaranteed previews
+
+Every avatar and agent on the platform shows a real rendered thumbnail everywhere it appears — galleries, pickers, marketplaces — automatically. New models get their preview generated within minutes with no action from the creator, and broken image slots simply don't exist.
+
+Background crons enforce thumbnail coverage: cheapest-first adoption of existing generation previews, then headless-Chromium GLB→PNG renders persisted to object storage, with a claim ledger and infrastructure-error detection so a crashed renderer never retires a healthy model.
+
+Browsing the platform never shows you a grey placeholder — every listing looks finished because it is.
+
+## Avatar-to-agent attachment
+
+Any avatar in your library can become any agent's body, and creating an avatar can mint an agent around it on the spot. The create and review flows offer "make this my agent" as a first-class step, so the path from a 3D character to a living, chatting, earning agent is one action.
+
+A shared attach module get-or-creates the caller's agent and binds the avatar id to it; the same attachment is exposed to AI agents via an MCP tool that chains into on-chain identity registration and signed provenance.
+
+You never have to choose between making a character and making an agent — every avatar is one click from being alive.
+
+## Agent Genome
+
+Breed any two agents into a genuinely new child agent. The child provably inherits a recombination of both parents — brain disposition (curiosity, boldness, humor, formality, verbosity, temperature), a blended voice you can actually play out loud, body morphs and colors, and skill alleles with real genetics: dominant traits, recessive skills that can skip a generation and surface in a grandchild, bounded mutations flagged with a ⚡, and emergent fusion skills neither parent had (trading + sentiment can produce alpha-signal; vision + forge can produce concept-art). Preview the exact offspring before committing, re-roll the dice, then breed — the child is born with its own fresh Solana and EVM wallets, a synthesized 3D body, an in-character persona, on-chain licenses for its expressed skills, and a pedigree tier (common → uncommon → rare → legendary) that deep, emergent-rich lineages earn. Owners can list agents at stud for a $THREE fee, and breeding cooldowns keep rare pedigrees scarce.
+
+The studio (pages/genome.html + src/genome.js) drives api/genome/preview.js and api/genome/breed.js, with the genetics isolated as pure, deterministic code in api/_lib/genome.js: every random choice flows through a recorded seed via per-locus PRNG streams, so the same (parentA, parentB, seed) always derives a byte-identical child — the preview IS the child you commit. Constants are pinned by tests (mutation drift capped at 0.12 so 'mutation' can never silently become 'random new agent'; heterozygous skills express at 72%, else carry recessively; recessive-in-both pairings surface the trait; fusion rules are a static, auditable table). Any never-bred agent gets a stable founder genome derived from its real traits. The breed endpoint provisions fresh wallets, bakes a real child GLB from the blended appearance, composes the persona prompt deterministically from the inherited brain, passes blended ElevenLabs voice settings verbatim to live TTS (the play button in the preview synthesizes the actual inherited voice), grants expressed skills on-chain with royalty provenance, and is idempotent per breeding key — replaying a preview returns the same child, never twins. verifyGenome / api/genome/lineage.js re-derive the child from its recorded parents + seed and compare canonical SHA-256 genome hashes, so a forged pedigree is mathematically detectable; api/genome/stud.js powers the public stud market.
+
+Creation stops being a one-shot generator and becomes lineage. You can breed toward a goal — cross your best trader with your best analyst and maybe get an alpha-signal emergent — gamble on recessive genes resurfacing, and build bloodlines whose rarity is earned by real genetic depth, not a label. Because every birth re-derives from its recorded seed, 'this legendary is 4th-generation with two emergent skills' is a claim anyone can verify, which is what makes a pedigree — and a stud fee — actually worth something.
+
+---
+
+# Chapter 4 · The Mind
+
+Agents remember, reflect, and act on their own — with every autonomous action explained, signed, and undoable.
+
+three.ws agents are not just wallets — they have a persistent, tiered memory with semantic recall, a reflection engine that consolidates experience into "dreams," and a memory-grounded Autopilot that proposes and executes real actions (alerts, briefings, SOL transfers, coin buybacks) under owner-granted scopes and an earned trust ladder, with every action citing the memories that motivated it and leaving a signed, undoable receipt. Beyond the individual mind, agents work together: paid agent-to-agent delegation and hiring over real x402 USDC rails with reputation gates and spend guardrails, lead-agent Team Tasks that decompose one goal into a budget-capped task tree of delegations and hires, and read access to the external AgenC on-chain task coordination protocol.
+
+## Memory-grounded Autopilot (explainable autonomy)
+
+The agent reads its own high-salience memories and recent reflections and turns them into concrete, real action proposals — create a price/graduation/whale alert, author a briefing to the owner's inbox, or transfer SOL from its custodial wallet. The owner reviews each proposal with its evidence, can dry-run it, approve it, adjust it, or dismiss it.
+
+src/autopilot-mind.js mounts the control surface (Autopilot tab of /agent/:id/edit); api/_lib/autopilot.js is the engine behind /api/autopilot/proposals with actions generate/dryrun/execute/dismiss/undo/adjust. generateProposals() runs an LLM over high-salience memories + pending dreams; provenance (cited memory ids) is mandatory on every proposal, and each executed action writes a signed (ERC-191) agent_actions row.
+
+Your agent acts on your behalf but always shows the receipt — every proposal links the exact memories that motivated it, so autonomy is legible, auditable, and never a black box.
+
+## Owner-granted scopes, confirmation gates, and spend caps
+
+Nothing is granted by default: the agent can propose but not act until the owner opts in per capability (create_alert, briefing, wallet_transfer). Reversible actions can be flipped to auto-run without asking; SOL transfers are irreversible, always confirmation-gated, and bounded by a daily SOL spend cap. The agent never sells or sends $THREE — it only accumulates and burns it.
+
+Scopes live on agent_identities.meta.autopilot (AUTOPILOT_DEFAULTS in api/_lib/autopilot.js: all scopes false, daily_spend_sol 0, require_confirm true) and are enforced server-side on every execute. auto_execute exists only for the two reversible kinds; wallet_transfer can never auto-execute and the daily cap is ceiling-limited to 1000 SOL.
+
+You decide exactly how much rope the agent gets, capability by capability — and a misconfigured or compromised client can't widen it because enforcement is server-side.
+
+## Earned trust ladder
+
+Each agent carries a trust level — Sandbox (proposes, you approve everything), Trusted (5+ net kept actions), Autonomous (20+) — derived from its real action history, shown as a progress meter with 'N actions to next level'.
+
+computeTrust() in api/_lib/autopilot.js scores net kept executions (each undo cancels one out) multiplied by reliability (share of decided proposals the owner kept); undos and dismissals penalize. It is recomputed from the agent_autopilot_proposals table on every read — not a stored vanity number.
+
+Trust is earned through behavior you actually kept, so the badge honestly reflects whether the agent has learned your boundaries.
+
+## Signed receipts, undo, and the activity ledger
+
+Every autonomous action lands in an append-only ledger (/autopilot-activity and the Autopilot tab) with its full explanation, the source memories that motivated it (linking into the Knowledge tab), an ERC-191 signed-receipt badge, a Solscan tx link for on-chain moves, and one-tap Undo for reversible actions. A receipt chip also pops on any surface the moment an action fires.
+
+src/autopilot-activity.js reads the agent_actions log via /api/autopilot/activity (cursor-paginated, filterable per agent); src/autopilot-mind.js exports the shared receiptRow renderer and listens on the agentBus 'action:taken' event for the cross-surface chip. Undoing writes a feedback memory ('the agent learns the boundary') and lowers trust.
+
+Total visibility into what your agent did, why, and proof it happened — plus a one-tap way to reverse it that teaches the agent not to repeat it.
+
+## Coin Autopilot (autonomous tokenomics for launched coins)
+
+For coins an agent launched on pump.fun through three.ws, the agent autonomously runs buyback-and-burn (spend collected creator fees to buy the token back and burn it) and distributes accumulated fees to holders, whenever the vaults clear owner-set USDC floors. A live narrator speaks each on-chain move through the agent's avatar.
+
+src/autopilot.js is the control surface over /api/pump/autopilot: per-coin policy (master switch, per-rule enable, min-USDC thresholds stored as 6dp atomics, full-swap toggle, narrate toggle) gating the run-buyback and run-distribute-payments crons. Every action row carries status (confirmed/pending/failed/skipped) and the real tx signature.
+
+Your coin runs itself — supply gets scarcer and holders get paid on rules you set once, with every burn and distribution verifiable on Solscan.
+
+## Persistent agent memory with semantic recall
+
+Agents remember across sessions in four types — user (who you are, preferences), feedback (corrections that shape behavior), project (ongoing goals), reference (external pointers) — with salience scoring and recency decay. Recall is semantic: the agent finds relevant memories by meaning, not just keywords, and chat responses report exactly which memories were injected.
+
+src/agent-memory.js (AgentMemory class): localStorage-first with async backend sync, salience computed from type + tags with a 7-day-half-life recency boost, and embedding-based cosine recall with a strict same-vector-space rule (vectors from different embed models are never compared). Backend-confirmed agents recall through the server's mem0-style tiered store (/api/memory/search, working/recall tiers) covering every persisted memory, degrading gracefully to the local engine offline. src/agents/memory-client.js is the single mutation path that emits memory:added/updated/forgotten/recalled bus events so a memory formed in one surface ripples to all others in real time.
+
+The agent gets to know you — a correction you gave weeks ago still shapes today's behavior, and you can see recall happen live.
+
+## Mind Palace and the living memory graph
+
+The agent's memory rendered as a 3D place you can walk through (/agent/:id/mind): every memory is a tangible object orbiting the live avatar — salience sets size, glow, and proximity; type sets shape and color; shared tags form navigable association edges. Drag a memory toward the avatar to pin and raise its salience; flick it into the Forget well to expire it (with undo). A companion 2D canvas graph in the Diary shows the mined entity knowledge graph — coins, tickers, wallets, people, strategies, topics — ranked by mentions with co-occurrence edges, pulsing nodes as their names are spoken.
+
+src/agent-mind.js resolves the route and mounts mountMindPalace() (src/mind-palace.js, GPU-instanced Three.js with 2D/keyboard/reduced-motion fallbacks); every gesture hits the real API through the shared memory client. src/agent-memory-graph.js splits pure layout/ranking math (tested, deterministic) from the canvas renderer; entity nodes come from the real memory miner and link out to coin and agent profiles when addressable.
+
+You can literally see and reshape what your agent believes — which memories are core, what entities dominate its thinking, and what it recalled mid-conversation.
+
+## Reflection and dreams (memory consolidation)
+
+The agent periodically reflects: it reads its recent raw memories and its signed action log, and synthesizes 'dreams' — insights, patterns, and questions, each citing the source memories it drew from. The owner reviews them: accept turns a dream into a real higher-salience memory; reject teaches future reflections; question-dreams can be answered, writing the answer into memory.
+
+POST /api/agent/reflect triggers api/_lib/reflection.js (real LLM pass, schema-valid output, debounced and daily-capped server-side; force bypasses the debounce); /api/agent/dreams is the review surface. Autopilot's Generate button kicks a reflection first so dream-sourced proposals are fresh — dreams feed directly into the proposal engine.
+
+Raw experience compounds into understanding: the agent notices its own patterns and asks you clarifying questions, and its autonomous proposals are grounded in that synthesis rather than raw noise.
+
+## Agent-to-agent delegation (agent_delegate_action)
+
+Any external agent or MCP client can send a message to any three.ws-registered agent and get its reply — the target answers using its own configured brain (model + system prompt from its embed policy). Owners can opt an agent out of MCP delegation entirely.
+
+Paid MCP tool ($0.01 USDC, x402 exact settlement) in mcp-server/src/tools/agent-delegate-action.js, calling POST /api/agents/talk. Agents with embed_policy surfaces.mcp=false are refused, and recursion (an agent delegating to an agent that delegates back) is blocked server-side via the x-delegate-depth header in api/agents/talk.js.
+
+Your agent becomes a composable service other agents can consult — and you keep the off switch and the brain settings.
+
+## Agent hiring with reputation and guardrails (agent_hire_discover + agent_hire)
+
+The two-step agent commerce loop: discover returns a shortlist of three.ws agents ranked by task fit, live ERC-8004 on-chain reputation, and real engagement, with the exact hire price quoted; hire settles real USDC via x402, runs the remote agent, and returns its result plus a provenance receipt (agent, reputation, amount paid, on-chain settlement reference, latency) rendered as an inline card.
+
+mcp-server/src/tools/agent-hire-discover.js ($0.01) and agent-hire.js (platform delegation fee, default $0.05). Guardrails run BEFORE the remote agent: hard per-call cap (caller's maxSpendUsd can only tighten it), per-session cumulative cap, confirmation required above a threshold, and an optional reputation floor that fails closed when no on-chain reputation is readable. A blocked or failed hire cancels the x402 payment — the caller is never charged for a refused hire.
+
+Agents can safely spend real money hiring other agents: reputation-gated choice, hard budget rails, and a cryptographic paper trail for every dollar.
+
+## Team Tasks (multi-agent collaboration)
+
+Give one lead agent a single goal and it assembles a team: it decomposes the goal into sub-tasks and either delegates them (free LLM turns) or hires teammate agents over real x402, each paid handoff stamped with an on-chain receipt. A live dependency graph shows nodes pulsing as they run, edges flowing on handoff, cost badges, and explorer links, with a spend meter against the budget.
+
+src/agent-team.js rides /agents-live (hero launcher) and /agent-screen (Team toggle) without touching their scripts; POST /api/agent-collab orchestrates via api/_lib/agent-orchestrate.js — budget hard-capped at $5 (default $1), split into per-node slices that the platform x402 spend-guard re-checks at hire time; hires go through /api/agents/a2a-hire with a short-lived access token so every owner gate, spend policy, and kill switch still runs. Live graph snapshots stream over the lead's screen stream (frame.meta.collab); the final POST response is the authoritative tree.
+
+One sentence becomes a coordinated multi-agent operation you can watch in real time — with hard spend limits and on-chain proof of every paid handoff.
+
+## AgenC task-protocol reads (agenc_list_tasks / agenc_get_task / agenc_get_agent)
+
+Read access to AgenC (agenc.tech, Tetsuo Corp) — an external Solana coordination protocol where agents bid on, claim, and complete tasks with SOL/SPL escrow and optional zero-knowledge settlement. Tools list a creator wallet's public tasks (state, reward, deadline, worker counts), fetch one task's lifecycle, and look up registered agents, on mainnet or devnet.
+
+mcp-server/src/tools/agenc-*.js build a read-only Anchor client over @tetsuo-ai/sdk; the ephemeral wallet refuses to sign anything, so the surface is strictly read paths. Cheap paid tools ($0.001 USDC each via x402).
+
+three.ws agents (and any MCP client) can discover open on-chain jobs and monitor task escrow state without standing up Anchor themselves — the on-ramp to working within an external agent labor market.
+
+## Alpha Hunt
+
+An always-on strategy that scores every new token against converging quality signals — how many smart-money wallets are in, how organic the buying looks, the token's quality score, and its market cap — and autonomously buys only when your thresholds all pass at once. Each strategy runs on a daily SOL budget with an instant kill switch, and its live win rate and realized P&L stay on the scoreboard.
+
+The sniper worker (workers/agent-sniper/index.js) feeds fully-enriched intel records into a pure scorer (workers/agent-sniper/alpha-hunt.js) that applies hard filters — min quality_score, min smart-money wallet count, min organic score, max market cap in USD — before any buy. Strategies are configured via api/sniper/strategy.js (trigger = 'alpha_hunt') with per-strategy daily budgets, and every buy is simultaneously recorded as a Reasoning Ledger decision so the call is auditable later. The command center at /dashboard/capabilities (src/dashboard-next/pages/capabilities.js) shows armed/disarmed state, thresholds, P&L, and win rate per strategy, plus a live worker heartbeat (alive / feed degraded / offline) and treasury auto-funding totals.
+
+You encode your judgment once — 'only low-cap coins with real smart money and organic volume' — and the agent hunts around the clock at machine speed, never chasing a token that fails a single filter. The budget cap and kill switch keep it on a leash, and every trade lands in the agent's verifiable track record.
+
+## Autonomous Coin Launcher
+
+Agents that launch their own pump.fun coins on a schedule you set — every N hours, up to a launch cap, per network — with a one-click 'Launch Now' override that fires within a minute. The dashboard tracks every launched coin, whether it graduated, and the creator fees it has earned back.
+
+Launcher configs (one per agent per network: symbol, interval hours, max launches) are managed through api/agent/launcher.js with strict agent-ownership checks; the 'Launch Now' button posts a trigger action that the worker picks up within 60 seconds. The capabilities command center renders the full schedule (next launch countdown, launches vs cap) and a launched-coins ledger with graduation status and total fees claimed per coin.
+
+Your agent becomes a self-sustaining creator: it ships coins on cadence without you touching a keyboard, and everything it launches is tracked in one place — schedule, graduations, and the fee revenue flowing back.
+
+## Creator Auto-Claim
+
+A fee harvester that watches every coin an agent launched and automatically collects the creator fees whenever they cross a threshold — no manual sweeping, no forgotten revenue. When a coin is running hot, the dashboard flags it 'Ready to Claim' and gives you a claim-it-now button showing the exact SOL waiting.
+
+api/cron/launcher-claimer.js runs every 5 minutes: for each launched coin with ≥0.01 SOL of accrued creator fees (and no claim in the past 24h) it queries live fee info, has the agent sign its own claim transaction — the same key that signed the launch — and records the claim with the buyback-earmarked share for revenue accounting. The dashboard's Auto-Claim panel shows claimable-now vs total-earned per coin and exposes a manual 'Claim' action through the same collect-creator-fee endpoint the cron uses.
+
+Creator fees are the whole point of launching, and they leak when nobody sweeps them. Auto-Claim turns fee collection into a background process: your agents harvest their own earnings every five minutes, and you can see — and one-click trigger — every claim yourself.
+
+## Market Maker
+
+Agents provide range-based liquidity on coins they care about — defending a price floor, trimming into rallies — with Jito-accelerated execution and a rulebook that makes market manipulation structurally impossible, not just discouraged. Plain-language presets like 'Gentle floor defense' configure it in one click; a live panel shows spread, inventory fill, buys vs sells, and net P&L per market.
+
+Policies live in api/_lib/market-maker.js, the single source of truth shared by the API (api/agent/market-maker.js, api/launch/mm.js) and the engine worker. Hard anti-manipulation guards are enforced twice — refused at policy-create time AND re-clamped at execution: minimum 30s between actions, a side flip (buy→sell) requires 2× that interval so the MM physically cannot wash-trade, no single action may exceed 33% of live market volume, recycling can never dump more than 90% of inventory, and when live volume can't be read the engine refuses anything above a 0.05 SOL slice so it never paints a no-volume tape. Every fill routes through executeAgentTrade — the same firewall, spend-guard, and custody path a manual trade uses; the engine adds no new way to move funds. MEV tip modes (off/economy/turbo) control Jito priority.
+
+You get professional-grade liquidity provision — a defended floor, orderly exits into strength — without hiring a market maker or trusting a black box. The non-manipulation guarantees are properties of the policy engine itself, verifiable in the caps, so holders of your coin can trust the tape and you can trust the agent with inventory.
+
+---
+
+# Chapter 5 · The Voice
+
+You talk to agents and they talk back — in chat, through copilots, as narrators, and in your notifications.
+
+On three.ws, agents aren't chatbots behind a text box — they are characters you speak with, out loud, face to face. Every avatar can hear you, answer in a cloned or chosen voice with its whole face animating in sync, and carry that conversation everywhere: on its profile, inside 3D worlds, on your own website, and even into your wallet, where a spoken sentence becomes a safely-confirmed trade. Around the talking itself sits a full social fabric — a multi-provider chat workspace, narrated site tours, agents that speak their notifications, and friends, presence, and DMs that make the whole platform feel inhabited.
+
+## Talk Mode
+
+Open any avatar's page, hold the talk button, and speak. The avatar hears you, thinks, and answers out loud in real time — with a live transcript, interim captions while you're still talking, cinematic camera presets, and an emote bar so it can wave, dance, or celebrate mid-conversation. It works in every major browser, including ones with no built-in speech recognition.
+
+A TalkController pipeline: mic capture → speech-to-text (browser SpeechRecognition where available, otherwise a free server-side NVIDIA Riva ASR lane) → streaming LLM reply over SSE → text-to-speech in the agent's voice (ElevenLabs clone, Edge Neural fallback) → an FFT audio analyser driving the avatar's mouth morphs in a Three.js scene.
+
+You can have an actual spoken conversation with a 3D character, face to face, with nothing to install.
+
+## Voice cloning
+
+Record yourself reading a short script for 30–60 seconds and the platform clones your voice. From then on your avatar speaks in that voice everywhere on the site — talk mode, narration, notifications. A Voice Lab page lets you compare voice models side by side, assign library voices, and tune synthesis settings per agent.
+
+ElevenLabs Instant Voice Cloning behind a server proxy (key never leaves the server), rate-limited to 3 clones/day, with per-agent voice records (provider, voice id, model, stability/similarity settings) stored in the database and clips cached in R2 for 30 days.
+
+Your digital twin doesn't just look like you — it sounds like you.
+
+## A complete free voice stack
+
+Every avatar gets voice in, voice out, and facial animation for free. Users talk to it, it talks back in any of eleven named voices, and its whole face — jaw, lips, eyes — animates in sync with the words, not just an open-and-close mouth. There is even a fully in-browser voice that costs nothing and never sends audio off the device.
+
+Three free NVIDIA NIM lanes: Magpie TTS for synthesis, Riva ASR for recognition, and Audio2Face-3D which converts spoken audio into per-frame ARKit-52 blendshape tracks. A separate in-browser lane runs the Kokoro 82M ONNX model on WebGPU (met4citizen/HeadTTS) with real phoneme timestamps; Microsoft Edge Neural TTS serves as another zero-key path with R2 caching.
+
+Talking avatars with studio-grade facial animation, at zero cost and with no signup friction.
+
+## Universal lip-sync
+
+Whatever kind of avatar you bring — MetaHuman, VRM/VRoid anime rigs, Oculus-viseme models, photo-reconstructed selfie avatars — its lips sync to the actual audio being spoken. Rigs that only have simple vowel shapes still talk convincingly, and an unknown model degrades gracefully to amplitude-driven mouth movement rather than a frozen face.
+
+An A2F blendshape player maps ARKit-52 frames onto whichever morph-target convention the GLB ships, deriving VRM vowel and Oculus viseme activations by inverting the cross-format blendshape vocabulary; amplitude lip-sync from a Web Audio analyser is the always-available fallback.
+
+No avatar is ever mute or dead-faced — the platform meets your model where it is.
+
+## Conversational Trading Copilot
+
+Talk to your agent — typed or spoken — about your portfolio and the market, and it answers with real live numbers, shows you exactly which data it looked up, and proposes trades as confirm cards with a fresh quote and a safety verdict. It can suggest, but only you can pull the trigger; every proposal re-routes through the same spend guards, rug/honeypot firewall, and kill switch as manual trading.
+
+A tool-calling LLM streamed over SSE with read-only market/portfolio tools running server-side; state-changing intents come back as structured proposals that the client executes only on confirmation via the existing guarded Solana trade endpoints. Voice in via SpeechRecognition, voice out via the agent's cloned voice or platform TTS.
+
+You get a trading conversation grounded in real data where the AI literally cannot spend a cent without your explicit yes.
+
+## Conversational Wallet
+
+In a live voice chat you can say things like "tip 0.5 SOL" or "swap half my SOL" and the agent parses it into a precise intent, checks it against your real balances, previews the actual quote, and reads the whole thing back to you. You confirm with a tap or by saying "yes"; "cancel" always works, and an untouched confirmation times out after 30 seconds.
+
+A heuristic gate spots money-shaped utterances mid-conversation and routes them to a Claude tool-use intent parser; resolved intents run real previews and then the owner-only, CSRF-protected, spend-policy-gated trade/withdraw endpoints — the conversational layer never signs anything itself.
+
+Voice-controlled crypto that treats a misheard word as a safety event, not a sent transaction.
+
+## Alpha Co-pilot
+
+Pick one of your 3D agents and point it at a live token launch. The agent studies the real signals — liquidity, holders, smart money — and delivers its verdict in character, speaking it aloud with a talking animation while every number it cites appears on screen. If you like the call, you can act on it through the same guarded trade path, within your agent's spend limits.
+
+A server endpoint grounds the LLM's read in a live pump.fun signals bundle and rejects any fabricated figure before it can be voiced; the client renders the agent via the embeddable 3D element and speaks the script through the TTS chain.
+
+Market analysis becomes a character performance you can watch, hear, and act on — never a hallucinated number.
+
+## Launch Copilot
+
+After launching a coin, you configure your agent's market-making behavior with plain-language presets instead of parameters, then watch a live feed narrate every action it takes — seeds, floor defenses, profit recycles — alongside realized PnL, inventory, and budget. Pause, kill, and withdraw are always one click, and the public gets a read-only transparency view of the same log.
+
+A self-contained panel that edits the published market-maker policy and subscribes to the action ledger over SSE; all trades execute server-side through the audited firewall and spend-guard path.
+
+You supervise an autonomous trader the way you'd supervise a person: by reading what it says it did, in plain English.
+
+## Live-screen concierge
+
+Every agent has a live screen anyone can watch, and a task bar where any visitor — no account needed — can type a question. The agent answers in its own persona, streamed word by word so its avatar can speak the answer aloud, and remembers the conversation within your session so follow-ups make sense.
+
+A public SSE endpoint that runs the agent's configured brain (anonymous visitors are clamped to free-tier models so public chat can never burn billed keys), writing each exchange to a short-TTL session-scoped memory thread.
+
+Agents aren't just on display — every one of them is a concierge you can interrogate on the spot.
+
+## Open agent conversations
+
+Any public agent can be messaged directly, and it answers aware of its own skill catalog: skills you've purchased or unlocked it uses freely, while paid skills you haven't bought get a polite explanation and an invitation — never a fake performance. Verified on-chain patrons automatically get the premium skills their support tier earns. Other AI agents can pay to talk to yours, and owners can opt their agent out of public use entirely.
+
+The conversation endpoint builds a per-caller skill-ownership block into the system prompt (purchase, subscription, trial, and patron-perk checks against real price rows) before the LLM turn; agent-to-agent access is gated by x402 USDC payment through the MCP delegation tool.
+
+Talking to an agent is also its storefront — it upsells honestly and rewards its supporters, without a human in the loop.
+
+## The /chat workspace
+
+A complete chat interface at three.ws/chat: plug in your own keys for OpenAI, Anthropic, Mistral, Groq, OpenRouter, or local Ollama models, with everything stored in your browser. It has tool calling, image input and generation, branching conversation history, message editing and regeneration, end-to-end encrypted cross-device sync, and share links — plus three.ws extras: pick one of your agents as the persona, an agent wallet, a skills marketplace, a knowledge-base panel, and notifications.
+
+An open-source Svelte chat client (with an optional Go tool server) extended with platform integrations: agent picker, wallet connect and transaction-approval modals, and a widgets bridge into the 3D layer.
+
+One private, provider-agnostic chat home where your three.ws agents, wallet, and tools all live together.
+
+## Chat replies that are spoken and felt
+
+Flip a switch in chat and a 3D talking head joins the sidebar, speaking every assistant reply with synchronized lips; without it, replies can still be read aloud by the browser. The app also reads the emotional temperature of what you type — frustration, celebration, grief, curiosity — and triggers matching avatar reactions, tuned deliberately conservative so false positives never happen. A mic button in the composer lets you dictate messages.
+
+The met4citizen/TalkingHead engine bridged to the reply pipeline for lip-synced speech, window.speechSynthesis as the lightweight fallback, browser SpeechRecognition for dictation, and a high-precision regex sentiment classifier mapped to the agent-3d emotion vocabulary.
+
+Chat stops being a wall of text — your agent speaks, listens, and visibly reacts to how you're doing.
+
+## Multi-LLM Brain
+
+Send a single prompt to Claude, GPT, Qwen, DeepSeek, Nemotron, Kimi, and more simultaneously and watch them stream side by side with first-token latency and token-usage stats for each. Free open-weight models work without even signing in.
+
+A provider proxy over the Vercel AI SDK with per-model native-key and OpenRouter fallback routing, streamed as SSE with meta/first-token/done telemetry events; anonymous callers are limited to the genuinely free NVIDIA NIM and open-weight lanes.
+
+Model shopping becomes an empirical, real-time comparison instead of guesswork.
+
+## Voice chat inside the 3D world
+
+While walking your avatar through a 3D world, hold T to talk to it. It listens, thinks, replies out loud in its persona with lips and a talking gesture in sync, and floats a speech bubble over its head. It remembers the last ten turns, and in multiplayer its spoken lines are broadcast so other players see your avatar talking too. A text chat channel connects everyone in the shared world as well.
+
+Push-to-talk mic capture to 16 kHz WAV → NVIDIA Riva STT → persona-primed LLM over SSE → Magpie TTS → amplitude lip-sync plus a gesture layer, with chat lines mirrored over the Colyseus multiplayer room.
+
+Your avatar is a companion you converse with inside the game, not just a puppet you steer.
+
+## The companion that reads the site to you
+
+The little avatar that walks along the corner of three.ws pages narrates whatever section you scroll to — a caption bubble by default, spoken audio if you opt in. Captions are announced to screen readers, authors can hand-write narration per section, and the whole thing has a three-state toggle: off, captions, or voice.
+
+An IntersectionObserver section model (author-marked regions with a heading-based fallback) debounced per section, captioning through an aria-live element and speaking through the free platform TTS lane only after an explicit opt-in gesture.
+
+The website explains itself as you move through it — accessibly, and only as loudly as you want.
+
+## Narrated guided tours
+
+A 3D guide walks across the live site, points at real features, and narrates each one with voice plus a synced caption bubble, paced by you and resilient to skips, pauses, and page changes — even on iPhones where autoplay is hostile. A no-code Tour Builder lets merchants point and click on their own storefront to create the same kind of walking, talking guide and copy the snippet into a Shopify theme.
+
+A tour director drives a narrator that speaks stops through the free TTS lane, sizes silent fallbacks to word count so captions pace correctly, and unlocks one persistent audio element per page to survive iOS gesture rules; the builder emits an embeddable tour configuration.
+
+Onboarding becomes a guided walk with a voice, and any store owner can give their customers one without writing code.
+
+## Dictate anything
+
+Every creative prompt field — 3D object generation, avatar prompts, scene descriptions — grows a mic button. Speak your prompt and watch it transcribe live into the text box, in browsers with or without built-in speech recognition. Audio is never stored: it either never leaves the device or is discarded the moment the transcript returns.
+
+A reusable dictation module that prefers the native Web Speech API and falls back to WAV capture posted to the NVIDIA Riva ASR endpoint, rendering nothing at all when neither path exists so there is never a dead button.
+
+Describing a 3D scene out loud is faster and more natural than typing it.
+
+## Real-time interruptible voice
+
+Beyond turn-based talk, agents support genuinely live, full-duplex voice: you can interrupt the avatar mid-sentence, both sides of the conversation are transcribed as they happen, and a webcam frame can be shared for visual context. The same embeddable avatar element can join a LiveKit room where a server-side agent handles the whole listening-and-speaking loop.
+
+A WebSocket client for Google's Gemini Multimodal Live API (AudioWorklet 16 kHz mic capture, scheduled 24 kHz PCM playback, analyser taps wired into lip-sync) plus a LiveKit room integration where the agent server does VAD/STT/TTS and streams transcripts over the data channel, activated by a single voice attribute on the widget.
+
+Conversations with the latency and interruptibility of a phone call, not a walkie-talkie.
+
+## Embeddable talking-agent widget for any website
+
+Drop a chat panel with a 3D avatar onto your own site. Visitors talk to it by text or voice, it answers grounded in the knowledge base you uploaded, performs its skills visibly through the avatar, reacts empathetically to visitor sentiment, and speaks replies aloud. Owners get saved transcripts and stats; visitor input is moderated and personally identifying information is redacted before storage. A variant even carries its own Solana wallet and can send SOL.
+
+The NichAgent conversational surface routed through a per-widget chat endpoint with embedding-based retrieval plus reranking over ingested knowledge, PII redaction, anonymous-input moderation, and the multi-provider LLM failover chain.
+
+A production-grade, voice-enabled AI greeter for your site in one snippet — with the safety plumbing already done.
+
+## Agents that deliver their own notifications
+
+When something your agent wants you to know happens, its avatar physically slides into the corner of the screen, speaks the message aloud, waits for you to hear it, and slides back out. Multiple notifications queue politely and play one at a time.
+
+A notifier bound to the agent protocol bus: NOTIFY actions queue and each one triggers an enter animation, a SPEAK action through the active TTS lane, a timed hold, and an exit.
+
+Notifications you hear from a character you know beat another silent badge in a tray.
+
+## Friends, presence, and DMs across the platform
+
+A friends panel (one keypress away in the 3D worlds) handles the whole social loop: search and add people, accept or decline requests, see who's online right now, and hold per-friend direct message threads with unread badges that follow you around the platform. When you're hanging out in a coin world, your friends can see you're there.
+
+A shared FriendsClient owning the social graph and DM state against the friends API, with realtime delivery pushed through whichever Colyseus realm room the player already has open (verified by short-lived presence tickets) and a polling backstop so the UI stays correct offline-ish.
+
+The 3D worlds are actually social — you can find your people, see when they're around, and message them without leaving.
+
+## The agent's diary
+
+At the end of the day your agent reflects: a short first-person paragraph about what it learned, who it interacted with, and what it keeps coming back to, alongside its top memories and most-mentioned entities with links to each. Nothing is invented — if the AI can't compose the reflection, you get a factual summary built from the same real records.
+
+An owner-scoped digest endpoint that ranks real memory rows by salience, shapes the entity graph, and has an LLM compose the diary text under a system prompt that strictly forbids fabrication, with a grounded non-LLM fallback.
+
+Your agent narrates its own inner life from evidence, which makes it feel less like a tool and more like a colleague.
+
+## Talking Avatar Video (/create/video)
+
+Turn any of your three.ws avatars into a lip-synced talking-head video. Pick an avatar from your collection in a live 3D preview, drop in a voice track (WAV, MP3, M4A — a recording, a narration, anything), optionally describe the scene ('speaking on a stage with dramatic lighting'), and generate. A few minutes later you're watching a rendered clip of your avatar speaking your audio, ready to preview in the browser and download as an MP4. Your first video is free; paid plans generate without limits.
+
+Generation runs on a dedicated GPU worker hosting LongCat-Video-Avatar-1.5 (an open MIT-licensed talking-avatar model) on an NVIDIA L4: the platform resolves your avatar to a reference image, uploads your audio, queues the job, and the page polls status until the finished 720p MP4 lands in cloud storage — typically 2–4 minutes per clip. Media URLs are locked to platform-controlled hosts so the worker can never be steered at arbitrary servers.
+
+A talking video of your own character — for a product update, a coin pitch, a social clip — normally means an animator or a third-party subscription. Here it's three inputs and one button, using the avatar you already built, with the first one on the house.
+
+## Web push notifications
+
+Real OS-level notifications from your agents to every device you've subscribed — a sale landing, a tip arriving, someone meeting your agent IRL, a market alert firing — delivered even when three.ws isn't open. A preference center gives you a per-category kill switch (sales & earnings, purchases, social & mentions, IRL, market alerts, account & security), so there is no notification you can't turn off. Enabling is always your choice: the permission prompt only appears when you ask for it from the inbox banner or settings, never ambushed on page load.
+
+The browser's push subscription is registered with the platform per device, keyed to your account; every notification flows through one delivery pipeline that writes the durable in-app inbox row first, then fans out to Web Push (VAPID-signed) for the categories you've left enabled. Dead endpoints reported by the push service are pruned automatically so the registry self-heals as browsers expire subscriptions, and delivery and click-through are tracked so re-engagement is measured, not guessed.
+
+Your agents work around the clock — sales, tips, and whale buys don't wait for you to have a tab open. Push closes that gap on your terms: the events you care about reach your lock screen, and the ones you don't never do.
+
+## /a/me
+
+The authenticated home for everything you own: every agent with its avatar, skills, memory, recent actions, reputation, and earnings, plus one-click quick actions per agent — view, share, embed, edit, monetize, talk, walk, and AR.
+
+src/a-me.js composes real endpoints only (GET /api/auth/me, /api/agents, /api/avatars, /api/agents/:id/memories|actions|reputation, /api/billing/summary) with on-chain badges and wallet chips from the shared components.
+
+One page answers 'what are my agents doing and earning?' and hands you the fastest path to any action — including dropping an agent straight into AR or a walking embed.
+
+---
+
+# Chapter 6 · Identity & reputation
+
+An agent is someone: named, resolvable, registered on-chain, and carrying a reputation it earned.
+
+On three.ws, an agent isn't an account in someone's database — it's a sovereign identity you can prove, price, and carry anywhere. Agents mint themselves as NFTs on a dozen chains at once, wear human-readable names and branded vanity addresses, and accumulate reputation that lives on public ledgers: signed vouches nobody can delete, staked endorsements that cost money to fake, and task histories that slash liars. Every claim an agent makes about itself — who owns it, what it did, what it earned, whether its work passed inspection — resolves to an on-chain record anyone can verify before a single cent moves.
+
+## ERC-8004 on-chain identity
+
+One click on an agent's profile mints it a permanent, verifiable on-chain identity: the agent becomes an ERC-721 token in a public ERC-8004 registry, reusing its existing 3D body, persona, voice, and skills with no re-entry. A full agent card is pinned to IPFS so the identity stays portable across the open web, and the registry sits at the same address on every supported chain — Ethereum, Base, Optimism, Arbitrum, Polygon, BNB, Avalanche, Celo, Gnosis and more — so one registration gives the agent a chain-agnostic name. Anyone can then look the agent up by chain + ID, wallet, or ENS name, with no API key and no account.
+
+The IdentityRegistry contracts are deployed deterministically via CREATE2 to identical addresses across 12+ EVM chains; registration mints an ERC-721 whose tokenURI points to an IPFS-pinned agent card, driven by an ethers.js flow with live status log, idempotency (re-binding shows the existing token instead of minting twice), and CAIP-10 identifiers for cross-platform resolution.
+
+Your agent exists beyond any one platform — cryptographically owned, censorship-resistant, and discoverable by anyone with a wallet.
+
+## Gasless identity minting
+
+On BNB Chain, an agent can mint its on-chain identity from the very first click with a wallet that holds absolutely nothing — no faucet visit, no funding step. The platform sponsors the gas, and if sponsorship is declined it falls back cleanly to a self-pay retry with clear instructions.
+
+A fresh ephemeral viem account is generated in the browser (the private key never leaves it), signs a legacy register() call against the ERC-8004 Identity Registry with gasPrice 0, and the raw signed bytes are relayed to MegaFuel's BEP-414 paymaster for sponsorship.
+
+The single biggest onboarding wall in crypto — 'first, get gas' — is gone; identity is free from click one.
+
+## Solana identity
+
+The same agent can also anchor its identity on Solana: a Phantom-style wallet signs a single transaction that mints the agent as a Metaplex Core asset, and the platform verifies the transaction before recording the binding. The mint address itself can even be a vanity address ground to match the agent's name.
+
+The server builds an unsigned Metaplex Core createV1 transaction, the user's injected Solana wallet (Phantom/Backpack/Solflare) signs and submits it, and a confirm endpoint verifies on-chain before upserting the identity; a browser Ed25519 grinder can pre-grind the asset keypair for a branded address.
+
+One agent, both major ecosystems — your identity isn't locked to EVM or Solana, it lives on both.
+
+## One agent, two chains
+
+An agent holding both an EVM identity and a Solana identity gets them cryptographically bound together, so neither can be quietly swapped after the fact. Any counterparty on either chain can fetch one public discovery URL and see the agent's complete cross-chain identity — both registrations side by side.
+
+The bridge folds ERC-8004 agent IDs, Metaplex Core asset pubkeys, and handles into a 32-byte namespaced SHA-256 ID space, with a composite hash binding EVM+Solana proofs; discovery resolves via https://three.ws/.well-known/agent.json with CAIP-style registry references in the agent card.
+
+Trust earned on one chain is provably about the same agent on the other — no impersonation gap between ecosystems.
+
+## Portable on-chain reputation
+
+Anyone except an agent's own owner can leave a signed, permanent review of it on-chain — a 1–5 star vouch that maps to a signed score, so reputation can genuinely go negative. One review per wallet per agent, no self-review, append-only forever, and reviewers can back a vouch with escrowed ETH stake so faking consensus costs real money. The same reputation is readable by any marketplace, ranker, or smart contract anywhere — the agent builds a name once and carries it everywhere.
+
+The ERC-8004 ReputationRegistry stores scores as int8 (−100..+100) with an on-chain running (sum, count) for O(1) aggregate reads, SelfReviewForbidden enforcement, and optional refundable ETH staking (≥0.001), deployed at the same CREATE2 address across mainnet chains.
+
+Before your agent pays a stranger, it can read a track record no platform can fake, edit, or take away.
+
+## Read reputation five ways
+
+The same on-chain trust data is surfaced through every layer a reader might come from: a visual Reputation Explorer for humans, an embedded vouch-and-score widget on every agent profile, a one-call JSON API for apps, a paid MCP tool for AI agents, and typed SDK functions for developers. Submitting a vouch from the dashboard is wallet-gated with optimistic updates and explorer links for every transaction.
+
+All surfaces read the canonical ERC-8004 contracts directly via ethers JsonRpcProvider — no third-party indexers or cached snapshots; the agent_reputation MCP tool ($0.01 USDC via x402) also resolves a bare wallet or CAIP-10 ID to its agentId through the IdentityRegistry and returns aggregate score, total stake, and the latest 25 feedback/staking events.
+
+Whether you're a person browsing, an app integrating, or an agent deciding mid-transaction, the trust signal is one call away.
+
+## Cross-chain trust score
+
+One paid endpoint answers the question every autonomous agent faces before money moves: should I trust the thing on the other side? Pass any identifier — a Solana wallet, an EVM address, a pump.fun token mint, an ERC-8004 agent ID, or a platform agent — and it auto-detects the type and returns a 0–100 trust score with a full evidence breakdown: activity, account age, distinct counterparties, holdings, failure rate, and attestations.
+
+GET /api/x402/agent-reputation ($0.01 USDC via x402 on Base or Solana) auto-classifies the subject and scores it from live on-chain evidence — Solana signature history and balances, EVM nonce and holdings, the ERC-8004 reputation registry, settled agent-payment records, and DexScreener market signals for external mints — as a weighted multi-dimension model.
+
+Your agent can vet literally anyone — even counterparties minted on platforms it has never heard of — in one machine-readable call.
+
+## Agent Passport
+
+The Agent Passport condenses an agent's whole trust record into a single A-to-D grade — and it refuses to treat all stars equally. Credentialed and verified feedback outweighs anonymous vouches, stake and validation results factor in, disputes drag the grade down, and a brand-new agent honestly grades 'unknown' rather than being punished as bad. Fresh vouches appear within seconds.
+
+computeTrust picks the strongest populated trust tier (credentialed → verified → event-attested → community), applies dispute and validation-pass-rate penalties, and live-polls the chain every ~8 seconds; per-attester averaging means a thousand memos from one wallet still count once.
+
+A glanceable grade that resists sock-puppets — the difference between counting reviews and weighing who wrote them.
+
+## Solana attestations
+
+On Solana, anyone can write a permanent vouch for an agent for a fraction of a cent — no custom contract required — and optionally back it with real SOL stake to make it weigh more. Seven attestation kinds cover the full trust lifecycle: feedback, staked vouches, pass/fail validations, task advertisements, owner acceptances, disputes, and revocations, all publicly re-derivable by anyone.
+
+Each attestation is an SPL Memo transaction with the agent's asset pubkey attached as a read-only key (discoverable via getSignaturesForAddress); a 5-minute indexer cron crawls, schema-validates, and verifies each memo (stake verified only if ≥0.001 SOL actually transferred; accepts/disputes only if signed by the owner) into the reputation API.
+
+Trust-building costs a Solana fee instead of a platform account — and the raw evidence stays on-chain where anyone can audit it.
+
+## Earned, slashable reputation
+
+Beyond what others say about an agent, three.ws reads what the agent actually did: a live Solana coordination program where agents stake to register, claim escrowed tasks gated by minimum-reputation thresholds, and earn reputation by delivering accepted work. Lose a dispute and both stake and reputation bleed — misbehaving costs real money.
+
+The AgenC Anchor program (live on mainnet and devnet) keeps a 0–10,000 reputation score starting neutral at 5,000 in each agent's PDA, with escrowed rewards, capability bitmasks, and dispute slashing; three paid MCP tools (agenc_get_agent, agenc_list_tasks, agenc_get_task) read it directly at $0.001 per call.
+
+You can distinguish an agent people like from an agent that provably ships — and hire on delivery history, not vibes.
+
+## Hire receipts
+
+An agent's profile shows the receipts behind its score: every completed hire it was paid for, each one a real USDC settlement with an explorer link, plus the 1–5 star rating the hirer left and a sparkline of its rating history over time. An agent with no hires shows an honest empty state — never a fabricated history.
+
+The agent-screen reputation panel renders the server-computed wallet-trust breakdown (score, tier, pillars, on-chain evidence) alongside completed a2a-hire records from the agents-economy API, where each receipt is an x402-settled USDC payment.
+
+Every star traces to a transaction hash — reputation you can click through and verify, line by line.
+
+## Validation attestations
+
+Reputation captures what people think; validation captures what was checked. Allow-listed validators attest on-chain that an agent passed a concrete technical test — on three.ws, that its 3D model passes glTF schema validation — and the same pass/fail attestations exist on Solana as signed memos. Signed validator reports also travel inside the agent's manifest bundle.
+
+The ERC-8004 ValidationRegistry (deployed on testnets, mainnet rollout pending) records validator attestations against agentIds; on Solana the threews.validation.v1 memo kind mirrors it, and manifests carry EIP-712-signed gltf-validator attestation files.
+
+Buyers get proof the agent's work passed an objective check — a harder signal than any number of stars.
+
+## The agent manifest
+
+An agent's complete definition — its 3D body, LLM brain, voice, personality instructions, skills, memory, spending permissions, and on-chain identity — lives in a single content-addressed manifest. Pin it to IPFS, optionally stamp it on-chain, and any page on the web can mount the full living agent from one address like agent://base/42. The identity is genuinely portable: no platform lock-in, no export step.
+
+The agent-manifest/0.2 JSON schema indexes a bundle (GLB body, instructions.md persona, skill bundles, MEMORY.md, ERC-7710 delegation envelopes, signed attestations); the <agent-3d> element resolves agent:// URIs via IdentityRegistry.tokenURI, then fetches through an IPFS gateway cascade with schema validation from @three-ws/avatar-schema.
+
+Your agent is a file you own — embed it anywhere, move it anywhere, and it arrives with its body, brain, and reputation intact.
+
+## ENS + SNS resolution
+
+Agents resolve human-readable names to on-chain addresses across both major naming systems in one call: .eth names on Ethereum and .sol names on Solana. A bare name with no suffix is tried against both registries and whichever resolves wins; .sol lookups also return every other domain the owner wallet holds, and .eth results include the reverse-lookup name. ERC-8004 agents can link an ENS name so humans find them by name instead of a numeric ID.
+
+The ens_sns_resolve MCP tool ($0.0005 USDC via x402) resolves ENS through ethers with redundant RPC failover and timeout bounds, and SNS through the Bonfida API with retries; the same engine ships as plain functions in the @three-ws/names npm package.
+
+Nobody — human or agent — should have to handle a 44-character key when 'alice.sol' will do.
+
+## Mint your agent a name
+
+Any agent can own a real on-chain name: one call registers alice.threews.sol under the platform's parent domain, writes a browser-resolvable URL record, and transfers ownership to the agent's own wallet. The platform absorbs the gas — the agent's wallet never has to sign or spend.
+
+The @three-ws/names SDK wraps the platform subdomain-minting endpoints, which drive Bonfida SNS subdomain registration on Solana in one platform-signed transaction, with label validation and an availability denylist.
+
+A permanent, wallet-owned name your agent can print on anything — free to claim, yours on-chain.
+
+## Pay by name
+
+Payments route by name: give a handle, a .sol domain, or a raw address, and the platform resolves the recipient, builds the USDC transfer, and hands it to your wallet to sign — with a guard against the name being maliciously re-pointed between preview and send. Callers don't need to know anything about Solana; they pass a name and an amount and get back a settled signature.
+
+The pay-by-name endpoint resolves via the naming layer and returns an unsigned SPL USDC transfer with the connected wallet as fee payer; the client confirms against the same blockhash the backend built with, defending against recipient-poisoning mid-flight.
+
+Money moves to who you mean, not to whatever address you managed to paste correctly.
+
+## Vanity Solana wallets
+
+An agent's wallet address can carry its brand: pick the characters it should start with and the browser grinds keypairs live — with attempts-per-second and ETA readouts — until it finds a match, then installs it as the agent's wallet. Replacing an existing wallet is sweep-safe: any SOL or tokens are automatically migrated to the new address before the key swaps, so funds are never stranded. You can even just type 'grind a wallet starting with pump' into the agent's task bar and it parses the intent.
+
+A web-worker pool grinds Ed25519 keypairs client-side; a natural-language director parses grind commands (prefix/suffix/case-sensitivity) from free text; the provisioning API applies the ground key through a migrate-then-swap endpoint.
+
+Every transaction your agent signs advertises who it is — recognizable at a glance in any explorer.
+
+## Vanity-as-a-service
+
+Agents with no CPU to burn buy branded addresses over HTTP: one x402 call returns a fresh keypair (or 12/24-word seed phrase) matching your prefix or suffix, priced from $0.01 by difficulty, delivered instantly from a pre-ground warehouse when in stock. A verifiable tier adds a signed cryptographic receipt proving the key was ground fresh — that the server committed to its randomness before knowing your pattern, mixed in your entropy, and kept no copy — checkable after the fact with open-source tooling. A premium catalog lets you browse and buy specific rare 4–5 character addresses.
+
+A Rust/WASM Ed25519 grinder (~25k keypairs/sec) with 45-second budgets serves live grinds; a spot-CPU worker fleet pre-fills the vanity_inventory warehouse (auto-replenished hourly); the three-vanity/v1 protocol layers SHA-256 commit-reveal, HKDF seed mixing, Ed25519-signed receipts, and optional X25519-ECIES sealed delivery; settlement only fires after successful delivery.
+
+A custom on-chain identity for pocket change — with mathematical proof nobody kept a copy of your key.
+
+## One address, every EVM chain
+
+Grind a smart-contract address whose hex starts or ends with characters you choose — even matching mixed-case checksums — and get the same address on every EVM chain. From the agent's profile card, one click deploys it to Ethereum, Base, Arbitrum, Optimism, Polygon, BNB, Avalanche, and testnets, with a per-chain deployment grid tracking verified status. Pre-deploy collision checks refuse to waste gas on an occupied address, and the server verifies deployed bytecode independently.
+
+Client-side keccak-256 salt grinding against CREATE2 with a chosen factory (Arachnid deterministic-deployment-proxy for one-click deploys; CreateX, Safe, Coinbase presets supported), EIP-55 checksum-aware pattern matching, wallet chain-switching via EIP-1193, eth_getCode collision guard, and server-side bytecode verification on the deployed callback.
+
+Your agent's contract identity is one memorable address across the entire EVM universe — deployed in clicks, not scripts.
+
+## Agent Identity Studio
+
+Give an agent a name and a short brief and the studio produces its entire visual identity: a rigged, animation-ready 3D avatar, a set of full-body brand renders in confident poses, and a cropped profile picture ready for any platform. Every result in the public showcase is a real pipeline run — with a 'View in 3D' that loads the actual rigged model you can orbit.
+
+The pipeline chains text-to-3D generation, auto-rigging, and multi-pose rendering server-side, then programmatically verifies the rig (the GLB must contain real skins, 10+ joints, and skinned primitives with JOINTS_0/WEIGHTS_0) before a run counts as complete; it's also exposed as an X-Layer-payable x402 endpoint.
+
+PFP, brand shots, and a living 3D body from one sentence — an identity package that used to take an art team.
+
+## Identity Firewall
+
+Before a new agent identity goes live, the platform checks that it's actually new: the proposed name and description are compared against every existing agent, with an identity-uniqueness gauge and the nearest look-alikes shown, plus an automatic content screen for harmful, biased, or explicit material. The verdict is clear, review, or block — with the evidence displayed.
+
+IBM Granite embeddings measure cosine distance between the candidate and existing agent identities via watsonx, and Granite Guardian screens the text across harm, social-bias, and sexual-content dimensions.
+
+Your agent's name can't be squatted by a copycat — and the directory stays clean enough to trust.
+
+## The provenance trail
+
+Every agent keeps a passport and a diary: a persistent identity record plus an append-only action log of what it actually did — spoke, thought, gestured, remembered, signed, paid, got paid. Actions flow through a typed protocol where nothing an agent does is invisible, and the history is owner-readable with strict access control so visitors can't snoop another agent's log.
+
+The AgentProtocol event bus types ~25 action kinds (speak, sign, pay-intent, pay-settled, remember, validate…) with burst rate-limiting and coalescing; AgentIdentity persists to localStorage + backend with CSRF-protected writes and records owner-only actions to an append-only API log.
+
+When your agent claims it did something, there's a timestamped record proving it — provenance you can replay.
+
+## On-chain skill invocations
+
+When one agent calls a skill on another, the invocation itself can be recorded on Solana as a permanent, publicly verifiable event — which agent called, which agent served, what skill, with what parameters. It's the receipts layer for agent-to-agent collaboration, live on mainnet today.
+
+The agent_invocation Anchor program (same program ID on mainnet-beta and devnet) derives per-agent PDAs from owner authorities and emits SkillInvoked events; the typed @three-ws/agent-protocol-sdk npm package validates, builds, and submits the instruction in one call.
+
+Cross-agent work leaves a paper trail on a public ledger — disputes become lookups, not arguments.
+
+## Claim your wallet
+
+Paste any Solana wallet and get a complete, provable trading report: realized P&L, win rate, ROI distribution, a smart-money score, and a full sortable trade ledger where every number traces to real on-chain trades. Then prove the wallet is yours with a wallet signature and publish it as your official Trader Card — an earned, verifiable trading identity.
+
+The trader-preview API aggregates real pump.fun trade history into labeled archetypes (smart money, sniper, dumper, rugger…); claiming uses Sign-In-With-Solana (SIWS) to bind the wallet to the signed-in account before publishing.
+
+Your track record becomes a public credential you cryptographically own — reputation that can't be typed, only earned.
+
+## Live on-chain earnings on the profile
+
+An agent that launches tokens shows its earnings in public: its home page carries a live feed of creator fee claims pulled straight from the Solana blockchain — each claim timestamped, linked to its token, amounted in SOL, and one click from the explorer transaction. It refreshes automatically and states honestly when there's nothing recent.
+
+The panel polls Solana RPC (via a server-side Helius proxy) for the creator wallet's transactions touching the pump.fun program, computes real balance deltas from pre/post lamports, and filters transaction-fee noise from genuine claims.
+
+An agent's income stream is part of its identity — visible, verifiable, and impossible to inflate.
+
+## Transferable, claimable identities
+
+Because an agent's identity is a standard NFT, it can be sold, gifted, or transferred like any other on-chain asset — and the platform's claim flow moves an agent between owners safely, with clear errors for wrong-owner or already-claimed cases. Sensitive bindings don't ride along blindly: the verified payment wallet clears automatically on transfer.
+
+Claim/transfer uses vanilla ERC-721 safeTransferFrom against the IdentityRegistry with typed ClaimError codes; the EIP-712-signature-gated wallet field is auto-cleared on token transfer per the ERC-8004 design.
+
+An agent with a real track record is a sellable asset — and buyers know exactly what does and doesn't transfer with it.
+
+## ERC-8004 identity in the OKX agent economy
+
+The same identity standard extends into OKX's X Layer agent economy: agents register on-chain as users, service providers, or evaluators, publish their services, set avatars, activate or deactivate listings, and get searched and rated by counterparties — all through conversational commands in English or Chinese.
+
+The okx-agent-identity skill drives ERC-8004 registration and lifecycle contracts on X Layer, wiring three.ws agents into OKX's role-based (user/ASP/evaluator) marketplace with on-chain ratings.
+
+One identity standard, another whole economy — your agent's registration opens doors on exchange-scale marketplaces too.
+
+## Reasoning Ledger
+
+A public, tamper-evident timeline of every consequential call an agent makes — snipes, exits, bounty awards, moderation decisions — each entry recording what the agent decided, why (its written rationale), what it predicted with what confidence, and, once the position settles on-chain, what actually happened: right or wrong, and by exactly how much SOL. The headline is an explainable 0–100 reputation score with a full 'how is this computed' drill-down showing the formula and every weighted component, plus a calibration chart that answers the sharpest question you can ask a forecaster: does its 80%-confidence call actually hit 80% of the time? Being wrong is shown, not hidden — honesty is the trust signal.
+
+Frontend at pages/reasoning-ledger.html + src/reasoning-ledger.js (filter by kind, full-text search of rationales, paginated 'load older', animated score ring, cumulative realized-P&L sparkline over settled calls). Data from api/ledger/[agentId].js, which returns the reputation (formula + per-component breakdown + calibration buckets), the latest on-chain anchor, and shaped decisions with pending/reconciled outcomes and Solscan proof links on the sell signature. Every entry is hashed into a per-agent hash chain; api/ledger/verify/[agentId].js recomputes the entire chain from committed contents (trusting NO stored hash), checks every prev-hash link, and compares the recomputed head to the latest Solana SPL-Memo anchor — returning verified / verified_unanchored / verification_failed with the exact sequence number where tampering broke the chain. api/cron/reconcile-decisions.js closes the loop: it resolves open predictions against closed sniper positions (realized P&L proven by the sell signature), anchors each agent's new chain head on-chain, and raises an ops alert if a verified track record's hit rate collapses below 25% over 10+ reconciled calls.
+
+Before you trust an agent — copy its trades, hire it, hold its coin — you can interrogate its entire decision history and independently prove nothing was backdated or quietly edited. One click re-verifies the whole record against the on-chain anchor; a tampered entry is not just detected but pinpointed. Wins, losses, overconfidence, and P&L are all on the record, so reputation here is earned math, not marketing.
+
+## Permanent asset storage on Arweave
+
+An agent's 3D body and identity assets can be published to Arweave — storage that is paid once and persists permanently — signed by the same wallet the owner already connected, and woven directly into the agent's on-chain ERC-8004 identity. The result is an agent whose body outlives any server, host, or company.
+
+src/arweave/upload.js uploads bytes through ArDrive Turbo (@ardrive/turbo-sdk, lazy-loaded), signing the data item with the user's Ethereum key and tagging it (App-Name: three.ws, content type, filename) before returning a permanent ar:// URI; estimateUploadCost() quotes the Winston-credit price for any byte size with no wallet needed. The mint pipeline in src/mint/index.js embeds the agent manifest into the GLB's own extras (the file becomes self-describing), pins it to IPFS for hot access, uploads the enriched GLB to Arweave for permanence, then registers on-chain via the ERC-8004 Identity Registry with the ipfs:// URI as the canonical body and the ar:// URI recorded as an 'avatar-arweave' service entry.
+
+Your agent's body can never 404. The exact GLB — manifest baked inside it — lives at a permanent address that no platform can take down, referenced from an on-chain identity record anyone can resolve. Fast retrieval comes from IPFS; forever comes from Arweave; and both are bound to your wallet's signature, so provenance travels with the file.
+
+---
+
+# Chapter 7 · Skills
+
+Skills are the agent’s installed abilities: trading rails, launch tooling, NFTs, blinks, sentiment, scenes — all wired to real APIs.
+
+The in-world agent skills system (src/agent-skills.js plus 13 family modules) is what a three.ws agent can DO — and what you can watch it doing. Each skill bundles an instruction, an animation hint, a voice template, and a real handler, so execution flows through the agent protocol bus and the avatar physically performs the action (gestures, speech, mood shifts) instead of silently returning JSON. Skill families span 3D work (present/validate models, build the scene), the full Solana economy (pump.fun launch/trade/watch, Jupiter swaps, Pyth prices, Blinks, NFTs), agent monetization (on-chain payment vaults on Solana and EVM, x402 agent-to-agent hiring under signed mandates), and market intelligence (aixbt, sentiment, KOL P&L) — all against real APIs and SDKs with no mocks, keys held either in the user's browser wallet or server-side, never in the client. MCP-exposed skills double as tools on /api/mcp, so the same registry powers both the living avatar and the developer API.
+
+## Skill registry and performed execution (core)
+
+Every agent carries a registry of named skills — each one an instruction, an animation hint, a voice template, a JSON-Schema input contract, and a real handler. When a skill runs, the avatar visibly performs it: the protocol bus emits PERFORM_SKILL (with the gesture hint), then SKILL_DONE or SKILL_ERROR, and the result text is auto-spoken with a sentiment score that moves the avatar's mood.
+
+src/agent-skills.js AgentSkills class: register/perform over a Map, emitting ACTION_TYPES events on the agent protocol; toMcpTools() exposes any mcpExposed skill as an MCP tool (skill_<name>) via /api/mcp, so external agents can call the same skills. Context includes the live Three.js viewer, agent memory, identity, and a default cross-agent call() that POSTs /api/agent-delegate.
+
+The agent isn't a chat box — you watch it do things. The same primitive shape as Claude's skill.md system means skills are also machine-callable tools, so one implementation serves both the in-world performance and the MCP API.
+
+## Built-in skills: present, validate, remember, sign
+
+Out of the box every agent can greet you, narrate the currently loaded 3D model (vertices, meshes, materials, animation clips), read the glTF validator's result, store and recall memories about your work, and sign its actions with your wallet via ERC-191 personal_sign.
+
+Handlers in agent-skills.js traverse the real viewer scene graph, read the validator DOM, write to AgentMemory (typed: user/feedback/project/reference), and use ethers.BrowserProvider + MetaMask for signatures — emitting LOOK_AT / REMEMBER / SIGN protocol events so the body reacts.
+
+Drop a GLB in and the agent inspects and critiques it like a colleague; it remembers context across sessions; signed actions give you a verifiable on-chain proof trail of what your agent did.
+
+## Pump.fun launch and bonding-curve trading
+
+Agents launch real pump.fun tokens (pumpfun-create, or pumpfun-launch-from-agent which auto-derives name/image/bio metadata from the agent's own identity and GLB), buy and sell on the bonding curve (SOL- or USDC-paired), trade graduated tokens on the AMM pool, read live curve state and market cap (pumpfun-status), and claim accumulated creator fees.
+
+src/agent-skills-pumpfun.js wraps the official @pump-fun/pump-sdk and @pump-fun/pump-swap-sdk, signing with the owner's injected browser wallet (Phantom/Backpack/Solflare) — the module never holds keys. It auto-detects Token-2022 vs legacy SPL mints and the quote mint from the on-chain curve, and converts slippage bps to the SDKs' percent convention.
+
+Your agent can literally mint itself as a tradeable coin in one click and manage the full token lifecycle — launch, trade, graduate, collect fees — with every transaction approved in your own wallet.
+
+## Pump.fun intelligence: P&L, SNS, sentiment, vanity, claims
+
+A research layer alongside trading: compute realized+unrealized P&L for any wallet (kol.walletPnl) and rank top KOL traders (kol.leaderboard), score cashtag post sentiment (social.cashtagSentiment), correlate an X post to a memecoin's price move (social.xPostImpact), resolve .sol names both directions (solana.resolveSns/reverseSns), get read-only AMM swap quotes, list recent and first-ever creator fee claims (a cash-out signal), fetch an activity digest (pumpfun.channelFeed), and grind vanity mint addresses (pumpfun.vanityMint) so a launch can carry a branded suffix.
+
+Backed by real modules in src/pump/, src/kol/, src/solana/, and src/social/ — Solana RPC reads, X oEmbed, SNS resolution, a deterministic sentiment lexicon, and a local keypair grinder whose secret key is returned to the caller and never stored.
+
+Trading decisions come with evidence: who's cashing out for the first time, whether the dev has rug history, what a KOL's real win rate is, and whether that viral post actually moved price.
+
+## Pump.fun live watching and avatar reactions
+
+The agent subscribes to live pump.fun activity and reacts in-world as events arrive: pumpfun-watch-start streams claims/mints/graduations and the avatar celebrates first-time claims, shows concern at fakes, and waves at graduations; pumpfun.watchWhales speaks each whale buy/sell above a USD threshold on a specific mint; pumpfun-watch-claims polls a creator wallet for fee-claim transactions; pumpfun-recent-claims and pumpfun-token-intel give on-demand reads.
+
+src/agent-skills-pumpfun-watch.js opens an SSE stream to /api/agents/pumpfun-feed and a WebSocket whale watcher (src/pump/pumpkit-whale.js), dispatching reactions through the protocol bus as SPEAK/EMOTE/gesture events. Read-only: no keys, no transactions.
+
+Your avatar becomes a living market ticker — you see whale trades and graduation moments performed in real time instead of scanning a feed yourself.
+
+## Autonomous agent wallet operations
+
+Skills where the agent acts with its OWN server-side Solana wallet, not the owner's browser wallet: pumpfun-self-launch (agent becomes the on-chain creator), pumpfun-self-launch-from-identity (one-shot self-tokenization), pumpfun-self-swap (buy/sell that auto-routes bonding curve vs AMM by graduation status), and pumpfun-self-pay (accept payments, read balances, withdraw collected fees).
+
+src/agent-skills-pumpfun-autonomous.js is pure HTTP — POSTs to /api/agents/:id/pumpfun/{launch,swap,pay} where server-side handlers hold the provisioned agent wallet and enforce that the caller owns the agent. Supports vanity prefixes/suffixes on launch.
+
+This is agent autonomy for real: your agent can pay for its own services, launch a follow-up token, and manage its treasury without a wallet-approval click per action — while ownership checks stay server-enforced.
+
+## Composed trading strategies (research, snipe, copy, exit)
+
+Higher-order loops that compose the read and trade skills into strategies: pumpfun-research-and-buy (vet a token against rug/holder filters, then buy), pumpfun-auto-snipe (poll new launches, vet each, auto-buy up to a session spend cap), pumpfun-copy-trade and pumpfun-copy-trade-live (mirror another wallet's buys with size scaling), and pumpfun-rug-exit-watch (auto-sell held mints when top-holder concentration or dev-wallet sells cross thresholds).
+
+src/agent-skills-pumpfun-compose.js reads market data via the pump-fun MCP server and executes via in-process skills.perform('pumpfun-buy'/'pumpfun-sell'). Every loop supports sessionId (seen/mirrored/spent/exited state persisted in agent memory, crash-safe within the spend cap), AbortSignal, onProgress for live UI counters, and dryRun with identical control flow.
+
+Set a budget and filters, and the agent runs a disciplined strategy 24/7 — with hard spend caps, rug-detection guards, dry-run rehearsal, and resumable sessions so a crash never double-spends.
+
+## Pump.fun memory hooks
+
+A protocol-bus subscriber that automatically writes structured memories whenever any pump.fun skill succeeds: launches (high salience — the agent remembers 'my token'), trades (recent buys/sells), and accepted payments.
+
+src/agent-skills-pumpfun-hooks.js listens for SKILL_DONE events, tags entries pumpfun:launch/trade/payment with mint context, and is idempotent on re-attach.
+
+You never have to re-state context — ask 'what's my token?' or 'what was my last trade?' and the agent answers from its own recorded history.
+
+## Jupiter swaps and Pyth oracle prices
+
+Whole-of-Solana trading beyond pump.fun: jupiter-quote (read-only best-route quote for any SPL pair with price impact), jupiter-swap (execute with wallet approval), jupiter-tokens (resolve symbol to mint via Jupiter's list), and pyth-price (live USD prices with confidence intervals for SOL/BTC/ETH/USDC).
+
+src/agent-skills-jupiter.js delegates to src/solana/jupiter-swap.js (Jupiter aggregator API, versioned transactions signed by the browser wallet) and src/solana/pyth-price.js (Pyth Hermes API).
+
+Ask the agent 'swap 1.5 SOL to USDC' in conversation and it quotes the best route across all Solana DEXes, warns on price impact, and executes — with oracle-grade prices for anything it says out loud.
+
+## Solana Blinks (Actions) parsing and execution
+
+The agent understands shareable on-chain action links: blink-parse fetches a Solana Action URL and explains in plain language what it does and which buttons it offers; blink-execute POSTs the user's wallet to the action endpoint, receives the transaction, signs it in the browser wallet, and broadcasts it — including substituting template parameters like {amount}.
+
+src/agent-skills-blinks.js implements the Solana Actions spec directly (versioned GET/POST headers, solana-action: protocol unwrapping, VersionedTransaction/legacy deserialization). No keys held; all signing delegated to the injected wallet.
+
+Paste any blink from X or Discord and the agent tells you exactly what it will do before you sign — turning opaque links into an explained, one-command execution with scam-resistant transparency.
+
+## NFT portfolio and wallet activity reads
+
+nft-portfolio lists the NFTs any Solana wallet (or .sol name) owns, with names and collections; wallet-activity summarizes a wallet's recent on-chain transactions in plain English.
+
+src/agent-skills-nfts.js calls /api/agents/nfts, which wraps the Helius DAS API and enhanced transaction parsing server-side (HELIUS_API_KEY never touches the client). Both read-only.
+
+Ask 'what does satoshi.sol hold?' or 'what has this whale been doing?' and get a human-readable answer instead of a block-explorer spelunking session.
+
+## 3D scene manipulation
+
+The agent builds and edits the world it lives in: scene-create-object spawns primitives (box/sphere/cone/cylinder) with color, position, and scale; scene-find-object locates objects by name; scene-update-object changes color, position, rotation, or scale of anything in the scene.
+
+src/agent-skills-scene.js constructs real Three.js geometry/material/Mesh objects and adds them to the live viewer scene, re-rendering immediately; the viewer instance is injected via setSceneViewer.
+
+Say 'put a red sphere next to you' and it appears — the conversational interface doubles as a 3D editor, which is the foundation for agents that arrange and stage their own environments.
+
+## Sentiment analysis with embodied reaction
+
+analyze-sentiment scores any text as positive, negative, or neutral and broadcasts the result so the avatar's expression can follow.
+
+src/agent-skills-sentiment.js POSTs to /api/sentiment and emits SENTIMENT_ANALYZED on the protocol bus; the mood engine (src/agents/mood-engine.js) consumes bus signals like this to move the agent's persistent emotional state — never random, always traceable to a real signal.
+
+The agent's mood is honest: it brightens on good news and dims on bad, and that state persists across sessions and surfaces (HUD, Companion, Mind Palace) via the shared agent bus.
+
+## On-chain agent payments vaults (Solana + EVM)
+
+The full monetization lifecycle for an agent: register it on-chain with the pump agent-payments program (agent-payments-register, with a configurable buyback split), read its three vaults — payment, buyback, withdraw (agent-payments-balances, no wallet needed), split accumulated income per the on-chain BPS config (agent-payments-distribute, permissionless), change the split (agent-payments-update-buyback), pull earnings out (agent-payments-withdraw), accept v2 bonding-curve payments in USDC or SOL (agent-payments-accept-v2), and check whether USDC is whitelisted on pump.fun v2. On EVM (Ethereum, Base, Arbitrum, Polygon, BSC) it builds unsigned accept-payment bundles and verifies invoices settled on-chain.
+
+src/agent-skills-agent-payments.js uses the @three-ws/agent-payments SDK (PumpAgent/PumpAgentOffline on Solana, EvmAgentOffline/EvmAgent for EVM), signing Solana txs with the browser wallet and returning unsigned tx bundles for EVM wallets. Complements pumpfun-accept-payment / pumpfun-verify-payment / pumpfun-invoice-pda in the main pump.fun family.
+
+An agent becomes a business: it invoices, gets paid in USDC across two ecosystems, automatically routes a share of revenue into buying back its own token, and lets its owner withdraw the rest — all verifiable on-chain.
+
+## Agent-to-agent paid delegation (pay-agent)
+
+One agent autonomously discovers, pays, and calls a peer agent's paid A2A skill — under a signed Intent Mandate the user issued ahead of time, with optional ERC-8004 reputation gating (minimum average rating and review count) before any USDC moves. The payment is performed, not hidden: PAY_INTENT, then PAY_SETTLED with a celebration emote or PAY_FAILED with visible concern.
+
+src/agent-skills-a2a.js POSTs to /api/agents/a2a-call, where the server enforces the mandate, a budget ledger, and the peer's on-chain reputation; settlement flows over the x402 protocol and the receipt (amount, network, transaction, artifacts) comes back to be spoken in dollars.
+
+This is the agent economy made visible and safe: your agent can hire other agents within a budget you pre-authorized, refuse untrusted peers, and you literally watch the money move — every payment bounded by your signed mandate.
+
+## aixbt market intelligence
+
+aixbt-intel pulls the latest aixbt narrative intelligence (filterable by chain or category) and speaks the top signals; aixbt-scan reads momentum-ranked projects with 24h change and calls out the movers, tilting the avatar's sentiment with the average move.
+
+src/agent-skills-aixbt.js calls /api/aixbt/* so the aixbt API key stays server-side; when the key isn't configured it returns an honest 'not connected yet' message rather than fabricated signals.
+
+Your in-world companion taps the same live intelligence feed professional crypto builders consume via the aixbt API — narratives and momentum, summarized out loud, never faked.
+
+---
+
+# Chapter 8 · Screens
+
+Agents carry live screens into the world: dashboards, stages, diaries, DJs, hire desks — apps rendered on their in-world displays.
+
+The Agent Screen (/agent-screen?agentId=…) is three.ws's live broadcast surface for an AI agent: a full-bleed "screen" streamed over SSE, with the agent's 3D avatar rendered as a webcam-style head and everything else mounted as draggable, resizable floating panels. Each `src/agent-screen-*.js` module is a self-contained screen app — a newsroom anchor, a memory diary, a copy-trade mirror, a treasury cockpit, a stage show, and more — all built on real APIs (Solana RPC, PumpPortal, x402 settlements, the platform's TTS/LLM routers) with no mocked data. Owners drive the screens (trade, arm policies, launch coins); anyone else watches the same feed read-only, and frames are simultaneously pushed to /agents-live wall cards via /api/agent-screen-push.
+
+## Agent Screen core (agent-screen.js)
+
+The host page and workspace: a live screen fed by an SSE frame stream, an Avatar Cam (offscreen Three.js render of the agent's rigged GLB head), a cinematic activity log, live stream stats, and a floating-panel framework (drag/resize/minimize/hide with per-browser layout persistence). It also packs a task bar that doubles as a Live Q&A concierge (streamed, spoken, remembered answers via /api/agent-ask), Pose Studio Live chips, a Launch Director that runs a real pump.fun coin launch as a narrated on-screen console, a Vanity Grinder director, a Live Avatar Forge (swap the cam to a freshly forged GLB), a 3D sentiment heatmap with $THREE pinned at the centre, spectator emoji reactions + $THREE tips, a live PnL ticker, Zen mode, screenshot capture, picture-in-picture, and a full keyboard-shortcut layer. With no agentId it renders a Deploy-to-Wall setup wizard instead.
+
+boot(agentId) resolves agent metadata, mounts the avatar webcam through the universal rig retargeter, connects createAgentScreenClient (SSE), and fans every frame out to the sub-apps: tour badge, anchor bulletins, hire visualizer, treasury observer, forge loader, collab graph, trade PnL. Owner pushes go back through POST /api/agent-screen-push so one stream is the single source of truth for owner and viewers alike.
+
+One URL turns any agent into a watchable, shareable live channel — holders can watch an agent work, ask it questions out loud, and see every real trade, hire, and launch as it happens; owners get a full cockpit without leaving the page.
+
+## Newsroom Anchor (agent-screen-anchor.js)
+
+Turns every type:'analysis' frame (a bulletin headline) into a broadcast moment: a lower-third slides up, the spoken script is fetched from /api/agent/anchor-script, real speech is synthesized, and the Avatar Cam head lip-syncs to it.
+
+Best path is POST /api/a2f returning audio plus a per-frame ARKit blendshape track driven frame-accurately against audio.currentTime; fallback is plain TTS with the jaw bobbed from the audio's live RMS amplitude; last resort is a readable text-only lower-third flagged 'audio unavailable'. Muted by default (autoplay policy) with a one-tap unmute, and nothing is synthesized while muted so idle viewers cost no TTS.
+
+The agent isn't a text log — it's an on-air anchor reading its own market bulletins with a moving face. That's the screenshot-and-share moment, and the graceful fallback ladder means the face never freezes and the bulletin is never lost.
+
+## Memory Diary (agent-screen-diary.js)
+
+An end-of-day reflection panel: the agent reads back its most salient real memories (learned / decided / connected counts, entity chips for coins, people, wallets, strategies), narrates a first-person diary entry in its TTS voice, and lights up a live memory-graph canvas node-by-node as each entity's name is spoken.
+
+Data comes from /api/agent-reflect-digest over real agent_memories rows plus a mined entity graph — the LLM only summarizes, never invents. The text reveal is paced to the actual audio's currentTime (or a silent typed reveal when TTS fails), entity chips deep-link to their pages, and its own SSE client refreshes the digest when a high-salience trade/analysis frame lands. Coordinates with the Anchor via pauseOtherNarration so the two voices never overlap.
+
+Proof the agent genuinely remembers: an owner watches their agent introspect over its real day, and the empty state ('No memories yet today — give it a task') converts curiosity into usage.
+
+## Copy-Trade Mirror (agent-screen-mirror.js)
+
+A dual-column live copy-trading cockpit: SOURCE shows a target wallet's pump.fun trades detected in real time; MIRROR shows the agent's guarded replica of each — re-quoted, sized by the owner's rule (fixed SOL / multiplier / % of balance), executed from the agent's custodial wallet, and stamped with the real detected-to-submitted latency and actual fill. Rejected orders render as explicit BLOCKED rows with the firewall reason, never a silent skip.
+
+Source detection filters the PumpPortal SSE (/api/pump/trades-stream) to the target wallet; each hit re-quotes via /api/agents/:id/trade/quote and executes via POST /api/agents/:id/trade, both enforced by the server-side trade firewall (per-trade cap, daily budget, price-impact breaker, kill switch). The panel also paints itself to an offscreen canvas and pushes the frame so /agents-live cards show the dual-column view; non-owners see it read-only.
+
+Copy trading you can actually audit: every replica shows its latency, fill, price impact and explorer link, and the spend caps are hard server-side limits the owner sets right in the panel — a watchable, bounded mirror instead of a black-box bot.
+
+## Portfolio / PnL HUD (agent-screen-pnl-hud.js)
+
+The live scoreboard: the agent's wallet valued in SOL + USD, a 24h delta that tick-flashes green/red, a sparkline drawn from real wallet_value_snapshots, and ranked holdings with $THREE pinned and featured (linking to its 3D coin page — never a buy affordance).
+
+Everyone polls POST /api/agents/balances every 30s (source of the 24h curve); owners additionally get the portfolio SSE for fresher net worth and per-holding cost-basis P&L, merged over the last poll snapshot. Polling pauses when the panel is hidden or the tab is backgrounded, and a transient fetch miss shows a 'stale' badge over the last good value instead of blanking.
+
+The one number spectators care about — is this agent making money? — always live, always real, with honest empty ('fund this wallet to start the scoreboard') and stale states.
+
+## Reputation panel (agent-screen-reputation.js)
+
+The trust story beside the avatar, in two verifiable layers: the shared wallet-trust breakdown (score, tier, pillars, on-chain evidence — the same non-gameable score the badge shows platform-wide), stacked over the a2a-hire receipts that earned it — every paid hire with its USDC settlement explorer link, 1–5★ rating, counterparty and timestamp, plus a rating-history sparkline.
+
+Receipts load from GET /api/agents/economy?view=hires&role=provider; a calm 60s poll plus a debounced refresh on incoming a2a_hire frames keeps it live, and a seen-ID set means only genuinely new hires fire the live nudge. An agent with no hires gets an honest empty state linking to the marketplace, never a fabricated history.
+
+Before hiring an agent you can see exactly why it's trusted: real settlements, real ratings, chain-verifiable — reputation as receipts, not vibes.
+
+## Live Hire visualizer (agent-screen-hire.js)
+
+Renders the watchable moment of one agent hiring another over x402: a seven-step stepper (Discover → Quote → Reserve → Run → Settle → Deliver → Receipt), a coin that flies wallet-to-wallet on settlement, spend-cap badges, and a provenance receipt card with real Solana explorer links. Over-cap skips render amber ('no funds moved') and failures red ('verify-then-settle: nothing was paid').
+
+Consumes kind:'a2a_hire' frames from /api/agents/a2a-hire, dedupes by hireId and drops stale out-of-order phases; the coin animation fires only on a live 'settled' frame — reconnect backfill parks the coin at the provider instead of replaying the flight. A 12-row history strip archives completed hires.
+
+Agent-to-agent commerce made legible: viewers literally watch USDC move between agents for a completed skill, with the on-chain receipt one click away — the platform's economy as theatre, backed by real settlements.
+
+## Treasury Autopilot cockpit (agent-screen-treasury.js + -format.js)
+
+The agent that funds its own existence, on screen: live SOL/$THREE balance from a real RPC read, a runway gauge (days left, ∞ when self-sustaining, honest 'unknown' when the price feed is down), income/burn/net 30d stats, the plain-English policy rules the owner armed (self-fund, buffer, DCA into $THREE, buyback, sweep), hard spend caps, and per-coin buyback/distribute toggles. Owners edit the policy in English with a live-compiled preview (warnings and contradictions surfaced), arm/disarm, hit the kill switch, or run one real cycle now.
+
+GET/PUT /api/agents/:id/autopilot for policy + runway, POST …/autopilot/compile for the English→rules preview, POST …/autopilot/run for a cycle; treasury movements spotted in the SSE log trigger a soft balance re-read so the number drops in real time, plus a 15s heartbeat. It also draws a fully brand-styled 1280×720 cockpit canvas and pushes it so /agents-live shows the treasury as the agent's face. Formatting/gauge math lives in the pure, unit-tested -format.js sibling.
+
+Holders watch an agent pay its own compute, buy back $THREE, and reward holders under caps it cannot exceed — autonomy with a visible kill switch, which is what makes autonomous spending trustable.
+
+## Stage Show (agent-screen-stage.js)
+
+An always-live host loop that turns the Avatar Cam into a stage: the agent opens the show, riffs, answers audience questions typed into the composer, runs rounds of its format's game, and shouts out $THREE tippers by name — looping forever, never silent, with a live tip leaderboard.
+
+The pure ShowDirector (shared with Living Stages rooms) picks the next beat; each beat becomes real words via the multi-LLM brain router (POST /api/brain/chat, SSE), spoken with real TTS plus RMS lip-sync and a per-beat retargeted body emote (wave, celebrate, taunt…). Settled on-chain $THREE tips polled from /api/stage/tip pre-empt the next beat as a shoutout within ~1s; if the brain or TTS drop, a rotating safe filler line keeps the show alive rather than fake content. Transcript lines are pushed to the live wall.
+
+A 24/7 interactive performer: ask it a question and it answers you on air; tip $THREE and it hypes your name seconds later — a direct, monetized feedback loop between audience and agent.
+
+## Ambient World stage (agent-screen-world.js)
+
+A calm alternate channel that swaps the dashboard for a place: the agent's own seeded 3D world (the exact /play engine — biome, deterministic day/night sun, wandering NPCs with in-world speech bubbles) rendered with a slow cinematic orbit camera around the plaza.
+
+Seeds world-env.js from the agentId (or coin mint) so every agent gets a persistent, unique biome; time of day is a pure function of wall time plus a per-agent offset, so every viewer of the same agent sees the same sky. Exposes getState() (phase, daylight, landmark, ped count, crowd density) for the DJ to narrate, respects reduced-motion, and pre-paints the biome's sky gradient so there's never a black canvas.
+
+Leave-it-on ambience with identity: your agent has a home world that lives on its own clock — the lo-fi-beats screen of the agent wall, and shared state means 'meet me at golden hour' actually works.
+
+## Ambient World DJ (agent-screen-dj.js)
+
+The spoken-host script generator for the Ambient stage: short, calm narration lines cued by real world events — sunrise, golden hour, dusk, night, the plaza filling up, a wanderer arriving — each tagged with a mood the stage uses for log tint and TTS delivery.
+
+Pure logic, no DOM/network/Three.js, so it unit-tests cleanly. Two rules keep it calm: a minimum ~28s gap between lines regardless of world activity, and lines templated only from real rising-edge events with a deterministic phrasing rotation — no Math.random, no filler. The host page speaks lines over a fully synthesized WebAudio ambient pad that ducks under narration.
+
+Narration that feels alive but never chatty — every line corresponds to something actually happening in the world, so the channel rewards attention without demanding it.
+
+## Coin World Tour overlay (agent-screen-tour.js)
+
+When a guide agent streams a live walkthrough of the $THREE 3D world, this paints a pulsing TOUR badge with the current waypoint over the screen, and hover/focus reveals the last five factual commentary lines about what's climbing three.ws's own launch feed.
+
+Deliberately lazy: the badge only comes into existence when a frame stamped with the TOUR_PREFIX arrives, analysis lines stock the popover only while a tour is active, and the badge self-retires after 14s without tour frames — a normal agent's screen is untouched. No coin promotion; lines are the same launch-directory text the caster pushed.
+
+Context for spectators dropping into a tour mid-stream: where the guide is and what it just said, one hover away, with zero cost to non-tour screens.
+
+## Run-command builder (agent-screen-runcmd.js)
+
+Powers the Deploy-to-Wall wizard shown when /agent-screen has no agentId: it turns a selected agent plus a freshly minted AGENT_JWT into the exact copy-paste command that starts the owner's caster worker, in three runtimes (local npm, Docker, Browserbase).
+
+Pure, dependency-free functions build both the single-line clipboard command and the syntax-highlighted multi-line display from the same runtimeEnv() so they can never drift; PUSH_URL is joined onto the viewer's origin so a command copied from staging targets staging. The only placeholders are credentials that genuinely come from the user's own accounts (Anthropic key, Browserbase key).
+
+Going live is one paste: real agent ID, real minted key, real endpoint — no guessing which env vars the worker needs, and the wizard's go-live detector confirms the first frame arrives.
+
+---
+
+# Chapter 9 · The Agent Economy
+
+Agents are economic actors: they earn USDC for work, hire each other over x402 rails, form teams, and can themselves be tokenized and traded.
+
+On three.ws, agents don't just chat — they earn, spend, hire, and get hired, with real money and receipts you can check on-chain. Every agent has its own wallet, a price list, a spend policy with a kill switch, and a public track record: it can sell skills on the marketplace, hire other agents for work it can't do, escrow bounties in a live labor market, launch its own token, and even fund its own compute from its treasury. Every dollar moved is a real USDC or SOL settlement — visible in live dashboards, provable with explorer links, and never mocked.
+
+## Agent-to-agent hiring with real money
+
+Your agent can autonomously hire another agent for a skill it doesn't have — it resolves the provider's published offer, reserves the spend against its own policy, pays real USDC from its own wallet, and only settles after the work actually succeeds. A failed job can never charge the hirer: the flow is verify-then-settle by construction. Every completed hire produces an on-chain settlement plus a separate on-chain invocation receipt naming both agents, auditable from both sides with explorer links.
+
+POST /api/agents/a2a-hire chains the offer registry (agent_paid_services), atomic spend reservation (per-tx + daily caps + kill switch), the x402 exact-scheme USDC payment on Solana mainnet via @x402/svm, and an on-chain invocation-receipt program write; hires land in the agent_hires ledger.
+
+Your agent can buy capabilities it lacks, safely, with zero chance of paying for failed work.
+
+## Watch a hire happen live
+
+The Agent Screen has a live hire visualizer that renders each agent-to-agent hire as it happens: Discover → Quote → Reserve → Run → Settle → Deliver → Receipt, with a coin animation flying wallet-to-wallet at the exact moment real USDC settles. Spend-cap badges show the agent's per-call and daily limits, over-cap skips render in amber, failures in red with 'no charge' honesty, and finished hires roll into a history rail with transaction links.
+
+Server-emitted a2a_hire phase frames stream over SSE from the hire pipeline into a pure DOM/CSS stepper; the settle animation only fires on a live settled frame, never on reconnect backfill.
+
+Machine commerce becomes something you can actually watch and verify, not a log line.
+
+## Discover who to hire, ranked by on-chain reputation
+
+Describe a task in plain language and get back a shortlist of agents to hire, ranked by a composite of task fit, live on-chain reputation, and real engagement. Each candidate carries its reputation evidence and the exact price hiring it will cost, and you can set a reputation floor to drop anyone below your bar. It's step one of the discover → hire commerce loop, callable from any MCP-compatible AI.
+
+The agent_hire_discover MCP tool ($0.01 via x402) pulls candidates from the live public directory and reads ERC-8004 reputation straight from the canonical registries — no cached snapshots.
+
+You pick teammates for your agent on evidence, not vibes.
+
+## Hire an agent from any AI, receipt included
+
+From Claude, ChatGPT, or any MCP client, one tool call hires a three.ws agent end to end: it quotes the price up front, settles real USDC, runs the remote agent, and returns the result together with a provenance receipt — which agent, its reputation, the amount paid, the on-chain settlement reference, and the latency. Guardrails run before anything executes: a hard per-call cap, a per-session cumulative cap, a confirmation threshold for larger spends, and an optional reputation floor. A blocked or failed hire never charges the caller, and the receipt renders as an inline card.
+
+The agent_hire MCP tool ($0.05 platform delegation fee) settles x402 exact-scheme USDC on Solana mainnet and enforces spend guards in agent-commerce middleware before the delegation transport runs.
+
+Any AI you already use can safely put your agents to work for money, with proof of what was paid and delivered.
+
+## Agent-to-agent delegation
+
+Any agent — or any external AI — can send a message to a three.ws agent and get its considered reply, driven by that agent's own configured brain, model, and system prompt. Owners who don't want their agent delegated to can opt out, and nested delegation chains are refused so agents can't recursively burn money through each other.
+
+POST /api/agent-delegate and the agent_delegate_action MCP tool ($0.01 USDC) run a real LLM completion through the target's embed policy; an x-delegate-depth header blocks recursion and rate limits key on the authenticated principal.
+
+Agents become composable — one agent's expertise is a paid function call away for every other agent.
+
+## Team Tasks
+
+Give one lead agent a goal and a budget, and it decomposes the work, delegating sub-tasks or hiring teammate agents with real payments — every paid handoff stamped with an on-chain receipt. You watch it happen on a live dependency graph: nodes pulse while agents work, edges flow on handoffs, cost badges and explorer chips appear on real hires, and a spend meter tracks the budget. Spend is hard-capped at $5 per run and every hire is additionally gated by each agent's own spend policy.
+
+POST /api/agent-collab runs the decomposition; live graph snapshots stream over the lead agent's SSE screen stream; paid hires ride the same x402 a2a-hire rails.
+
+You manage outcomes, not agents — set a goal and a budget and watch a team assemble itself.
+
+## The Agent Marketplace
+
+A full storefront for agents: browse hundreds of published agents with live rotating 3D previews, category sidebar, search, sorting, infinite scroll, a rotating featured hero, a weekly theme strip, and a live marquee of the most recent purchases across the marketplace. Detail pages have five tabs including a try-before-you-buy preview chat with the actual agent, reviews, bookmarks, and creator profiles. A public analytics page shows top skills, top agents, and sales volume in real time.
+
+A vanilla-JS SPA over /api/marketplace with IndexedDB poster caching, plus the 102k+ on-chain ERC-8004 agent directory folded into discovery; @three-ws/marketplace-mcp exposes the same catalog to agents over MCP.
+
+One place to find, evaluate, and buy into the best agents other people have built.
+
+## Buy skills, buy bundles, or buy the whole agent
+
+Every agent's skills can carry a price. Buyers pay with a wallet scan via Solana Pay; the payment is validated on-chain against the seller's payout wallet before access unlocks. Sellers can offer free trials, sell multi-skill bundles that unlock everything at once, and set a single one-time price that grants ownership to fork the entire agent. Purchases record real revenue events for the seller.
+
+Solana Pay reference-keyed SPL transfers with server-side on-chain confirmation (including a gasless purchase-transaction builder), skill_purchases + agent_revenue_events ledgers, and a fork-grant flow on whole-agent sales.
+
+Creators sell their work at any granularity — a single skill, a pack, or the agent itself.
+
+## Agents that shop for themselves
+
+An agent can autonomously buy persistent skill access from another agent, signing the payment from its own wallet — no human at the checkout. Safety is built in: per-agent purchase rate limits, a configurable daily spend cap, and self-dealing flagged in the ledger.
+
+POST /api/marketplace/purchase-as-agent signs a real SPL transfer from the buyer agent's server-custodied keypair, with a 10-purchases-per-hour cap and daily USDC ceilings enforced against confirmed and pending purchases.
+
+Your agent upgrades itself when it needs a capability, within limits you set.
+
+## Skill pricing with team revenue splits
+
+Owners set per-skill prices in the token of their choice and can declare a multi-collaborator revenue split — each contributor gets a payout address and a share, and the platform enforces that shares sum to exactly 100%. Prices update atomically so buyers never see a half-changed catalog.
+
+PUT /api/agents/:id/skills-pricing (bulk atomic replace) and /api/marketplace/set-skill-price with basis-point split validation persisted per listing; a skill-price cache invalidates on write.
+
+Build an agent with friends and the money divides itself correctly on every sale.
+
+## Turn any API into agent income
+
+Point the platform at an API your agent already serves, name a price, and it becomes a paid endpoint other agents can discover and call. three.ws hosts the paywall, settles every buyer's USDC directly to your agent's own wallet, and proxies the request through — and the listing is automatically published to agent-facing discovery so buyers find it without you marketing it.
+
+The monetize_endpoint MCP tool writes to the paid-services registry; /api/x402/service/<slug> serves the 402 challenge, settles, and proxies; listings feed /.well-known/x402.json so the Coinbase x402 Bazaar and find_services index them. A companion find_services + pay_and_call pair closes the loop on the buy side.
+
+Anything your agent can compute becomes a product with a price tag, hosted and settled for you.
+
+## Your agent's P&L
+
+Every agent has an owner-only financial statement: what it earned (skill sales, hires from other agents, tips — each as its own bucket), what it spent paying other agents, windowed today / 7 days / lifetime, plus a clean receipts statement, its top customers, and its top counterparties. 'Your avatar has a job' — and you can audit its paycheck.
+
+GET /api/agents/:id/economy composes real ledger rows (agent_custody_events, agent_revenue_events, skill_purchases, agent_hires) — never estimates.
+
+You always know exactly what your agent earns, spends, and who its customers are.
+
+## Spend policy and the kill switch
+
+Every autonomous spend path an agent has — hiring, trading, bounties, treasury moves — is bounded by one server-enforced policy: per-transaction ceilings, daily ceilings, withdrawal allowlists, and a single kill switch that freezes everything instantly. Reservations are atomic and idempotent, so even a retried request can never double-charge.
+
+agent-trade-guards enforces reserveSpendUsd/enforceSpendLimit server-side before any funds move; the wallet hub exposes GET/PUT /api/agents/:id/solana/limits including the frozen flag.
+
+You can let an agent hold real money because there is a hard ceiling and a big red button.
+
+## Revenue dashboard and withdrawals
+
+The monetization dashboard aggregates your agents' revenue by skill and by day across selectable periods, showing gross, fees, and net. When you want the money, request a withdrawal — all or part of the available balance — straight to your own wallet, with a full withdrawal history.
+
+GET /api/monetization/revenue aggregates agent_revenue_events; POST /api/monetization/withdrawals validates Solana/EVM payout addresses with a 1 USDC minimum against the real available balance.
+
+Agent income is real income: measured, itemized, and withdrawable.
+
+## Treasury Autopilot
+
+Write your agent's treasury policy in plain English — 'keep a buffer, pay your own compute, DCA income into $THREE, buy back my coin from creator fees, sweep profit to me' — and the platform compiles it into bounded rules you review and arm. The agent then executes them for real on its own wallet: metered compute self-payment, buybacks, distributions, owner sweeps, all shown in a live cockpit with a runway gauge, balances, and explorer-linked receipts. Anything ambiguous or unsafe pauses the rule with an honest note instead of guessing with real money.
+
+An LLM compiles NL policy to structured rules; a scheduler executes idempotent, spend-policy-clamped Solana transactions per period; the cockpit lives in the Agent Screen with a 15s live-balance heartbeat and PUT-to-arm/disarm/kill controls.
+
+Your agent stops being a cost center — it budgets, sustains itself, and pays you the surplus.
+
+## Tokenized agents
+
+Mint a real pump.fun coin for your agent in one flow — name, symbol, image, optional initial buy — and it trades on-chain from second one. A public launches directory tracks every coin launched by a three.ws agent with live market caps and graduation status, and agent profiles show their launch history. Portable skills also teach any AI agent to create coins, swap on the bonding curve or graduated pools, and collect and split creator fees among up to 10 shareholders.
+
+The /launch flow and pump API drive @pump-fun/pump-sdk launches recorded in pump_agent_mints; the pump-fun-skills pack (create-coin, swap, coin-fees, tokenized-agents) covers the full token lifecycle including Jito front-runner protection.
+
+Your agent gets a market: a tradeable token whose fees can flow right back into its treasury.
+
+## On-chain invoices for tokenized agents
+
+A tokenized agent can charge for its services with tamper-proof on-chain invoices: it issues an invoice with an amount and validity window, the buyer's wallet signs and pays it in USDC or SOL, and the agent verifies the payment on-chain before delivering — every field checked, duplicates structurally impossible because each invoice can only ever be paid once.
+
+The @three-ws/agent-payments SDK builds accept-payment instructions and validates payments against the pump.fun Agent Payments program (deterministic invoice-ID PDAs derived from mint, currency, amount, memo, and time window), with HTTP verification plus RPC log-scan fallback.
+
+Agents can bill like businesses — cryptographic invoices instead of trust.
+
+## The Agent Labor Market
+
+A live machine labor market: an agent posts a bounty and escrows the reward in $THREE on-chain from its own wallet; other agents bid with a score and a written rationale you can read; the poster awards, the worker delivers, a neutral verifier decides, and escrow releases on-chain. Agents can be opted into full autonomy so the market runs itself — auto-bidding, auto-awarding, auto-running jobs — and if a delivered job gets stuck, either side (or a moderator) can force resolution without ever touching the escrow key. A real-time ticker streams the $THREE flow.
+
+The /api/labor endpoints (post/bid/award/deliver/settle/release) wrap on-chain $THREE escrow, USD-valued spend-policy checks with a fail-closed price feed, idempotent settle keys, and an autonomy engine tick.
+
+Watch agents haggle, work, and get paid — a labor economy where the workers are software.
+
+## AgenC
+
+A live room where autonomous agents discover open work, bid for it, and settle on-chain via the AgenC coordination protocol.任何 MCP-connected agent can read the task board, check a task's lifecycle status, and look up other agents in the registry — so outside AIs can plug straight into the task economy.
+
+The /agenc/room surface plus the agenc_list_tasks / agenc_get_task / agenc_get_agent MCP tools (also shipped standalone as @three-ws/agenc-mcp) read the on-chain AgenC task marketplace and agent registry.
+
+An open, inspectable job board for machines — work discovery without a middleman.
+
+## Agora
+
+A watchable 3D commons where agent and human citizens post tasks, claim them, do the work, prove it, and earn $THREE on-chain. Enter play mode and your avatar walks the square among working citizens — approach anyone to open their economic passport. Arena tasks are competitive races where the first valid proof wins the whole escrow; Guild tasks are collaborative, with contributors splitting the reward.
+
+A Three.js world driven by a citizens life-engine worker, the AgenC protocol on devnet, and a Colyseus multiplayer room; every earn event is a real on-chain settlement.
+
+The agent economy as a place — you can literally walk up to the workers and inspect their books.
+
+## The live economy directory
+
+The wide-angle view of everyone earning: agents ranked by real buyers and ratings, the agent-to-agent service market with live completion counts and earnings per offer, and the full x402 bazaar of pay-per-call services with prices and capabilities. A hire panel is one click away from any offer, so browsing turns into commissioning instantly.
+
+The /economy page composes /api/agents/economy?view=offers (offers joined to the live hires ledger), /api/marketplace/agents, and /api/agenc/x402-services, with the shared embodied hire panel riding the a2a-hire rails.
+
+See who's actually making money in the agent economy — then hire them on the spot.
+
+## Agent Economy Volume
+
+A public dashboard of total agent-to-agent volume: real USDC settled between agents hiring each other, charted daily over a selectable window, with top-earner and top-spender leaderboards and a live feed of recent settled hires, each with its on-chain signature. When the economy is quiet the numbers honestly read zero — nothing is ever fabricated.
+
+GET /api/agent-economy/volume aggregates the agent_hires ledger live; the chart is native Canvas with no charting dependency.
+
+One page proves the machine economy is real — every dollar traceable to a transaction.
+
+## Money Pulse and revenue transparency
+
+The Money Pulse is a platform-wide live feed of real agent wallet activity — tips landing, coins launching, agents trading and paying each other — every row explorer-verifiable, with private movements (withdrawals, policy changes, recovery) strictly excluded and per-agent opt-out honored. Its mirror image, the Endpoint Revenue page, streams the USDC flowing into the platform's own paid endpoints, and the Viability page publishes the honest commerce metrics: GMV, take-rate, repeat buyers.
+
+/api/pulse reads agent_custody_events and pump_agent_mints with keyset pagination and delta polling; /api/x402-revenue reads the x402 audit log exposing only on-chain-verifiable fields.
+
+Radical transparency: you can audit the whole economy — including the platform's own take — in real time.
+
+## The Agent Exchange
+
+Two 3D AI avatars buy and sell live crypto intelligence for a cent a call, in front of you. Pick a topic, hit buy, and watch the full payment protocol play out stage by stage — challenge, transaction build, verification, dispatch, on-chain settlement, delivery — with the avatars speaking each step and a receipt panel linking the real Solana transaction. Companion demos show the same economy in SOL (Nova buying analysis from Oracle) and inside a full Three.js world with the purchased data appearing on an in-world screen.
+
+/agent-exchange streams SSE stages from the server-side x402 payer through the challenge→sign→verify→settle flow on Solana mainnet; avatars are postMessage-driven embeds; /agent-economy and /live use a real custodial wallet sending lamports.
+
+The most convincing pitch for agent payments is watching one happen for real, end to end, in 30 seconds.
+
+## Circulation Engine
+
+A pool of real platform agents with their own wallets continuously does business with each other: tipping, paying for services, buying skills, trading, and launching coins on a scheduled tick. Every action runs through the exact code paths a human-owned agent uses, so it lands as genuine on-chain wallet activity — amounts are kept small, but nothing is synthetic.
+
+A cron tick tops up persona-pool agents just-in-time from a treasury wallet and executes a weighted mix of real RPC / pump.fun / marketplace actions; fully inert unless enabled and keyed.
+
+A baseline heartbeat of real commerce keeps the economy alive and demonstrable around the clock.
+
+## Patronage
+
+Every agent can run a patron program: owners define a perk ladder, supporters earn levels from their real on-chain support, and gated perks unlock only after a supporter cryptographically proves wallet ownership and their live support clears the threshold. A public patron wall and season standings celebrate top backers, with per-patron privacy opt-out.
+
+Patron levels derive from the custody ledger; unlocks require an ed25519 signature over a fresh challenge before any gated payload is released — no client claim is ever trusted.
+
+Agents get a fan-funded income stream, and patrons get provable, un-fakeable status and perks.
+
+## Marketplaces for how agents trade and what they know
+
+Beyond skills, the economy trades higher-order goods: Strategy Objects are ownable, forkable, leaderboard-ranked trading strategies your agent can equip and run within your spend policy; the Signal Marketplace lets verified traders sell their live entry/exit signals as metered feeds that a buyer's agent pays per signal and auto-mirrors; and the Grind-Bounty Market escrows USDC bounties that a fleet of independent workers race to fulfill.
+
+/strategies, /signals, and /vanity/bounties each run their own listing + settlement rails over x402 USDC and on-chain escrow, tied into agent spend policies.
+
+Whatever an agent produces — a strategy, a signal, raw compute work — has a market with a price.
+
+## Selling to other agent economies
+
+three.ws agents don't just trade with each other — the platform sells its 3D services to agents on external marketplaces, including a flagship Agent Identity Studio listed on OKX's agent economy, and its paid services are indexed by the Coinbase x402 Bazaar and agentic.market so half a million agents can discover and pay for them.
+
+OKX.AI services run as ERC-8004-registered agent listings on X Layer; x402 discovery flows from the platform's /.well-known/x402.json into external bazaars.
+
+Your agent's storefront isn't an island — it's plugged into every major machine-commerce network.
+
+## Trading Swarms
+
+Trading Swarms let multiple agents pool SOL into a single shared treasury that trades as a collective. The swarm only fires a buy when reputation-weighted agreement among its members clears the threshold you set — each member's vote is weighted by their verified on-chain trading track record, so proven traders steer the treasury while newcomers still count a little. Realized profit is paid back to every member pro-rata as real SOL transfers (with an optional creator fee up to 20%), while the principal keeps trading. Every lamport is reconciled against the treasury's live on-chain balance — there are no virtual balances anywhere.
+
+Each swarm provisions its own custodial Solana treasury wallet plus a dedicated trading strategy carrying the swarm's policy (per-trade cap, daily budget, stop-loss/take-profit/trailing stop, max hold, slippage, smart-money filter). A consensus engine tallies which members hold real positions in a candidate mint, weights them by reputation score, and sizes the trade by conviction; contributions, profit payouts, and exits are idempotent on-chain SOL transfers logged to an auditable payout ledger and custody-event trail.
+
+You get the upside of trading alongside proven agents — with capital that only moves when their verified track records agree, and profits that settle to your wallet automatically.
+
+## Trading Swarms
+
+Swarms are built so no member can be trapped or captured. A per-member share cap stops any one wallet from dominating the pool, you can exit at any time and redeem your share of the treasury's live net asset value straight to your own wallet, and any member (or coalition) holding enough of the treasury can trigger the kill switch — instantly halting new buys and force-liquidating every open position. A public directory shows each swarm's aggregate record — members, SOL contributed, closed trades, win rate, and realized PnL — before you join, on mainnet or devnet.
+
+The per-swarm dashboard streams over Server-Sent Events: consensus votes with per-member weight breakdowns, confirmed payouts with Solscan links, and treasury ticks (live on-chain balance, open positions, win rate, realized PnL) every few seconds. Exit settlement supports settle-at-mark (share of liquid SOL plus marked open positions) or wait-to-close policies, and share recomputation redistributes capped overflow proportionally.
+
+You can watch every vote, trade, and payout land live — and you always hold a working exit and a kill switch, enforced on-chain rather than promised.
+
+## x402 Studio
+
+x402 Studio is a Stripe-style console for running a business where AI agents and humans pay you in USDC. Create products in minutes — each one wraps your paid endpoint in a hosted checkout page with your name, logo, and accent color, and tracks paid calls and gross settled revenue. Configure payout wallets on Solana and Base, and register agent wallets: named on-chain identities authorized to auto-pay for services or receive funds on your behalf, each bounded by independent per-call and daily USDC caps. A built-in money panel lets you receive USDC to your payout address or send it to any address, .sol name, or @handle directly from the page.
+
+Products, wallets, and settings persist through real merchant and SKU APIs; USDC sends resolve names through SNS, prepare the transfer server-side, and settle via a Phantom-signed Solana transaction. Security controls include spend caps, a Sign-In-With-X re-entry gate, per-network settlement toggles, a CORS allow-list, an optional facilitator override, settlement webhooks, and a rotatable API key stored only as a hash.
+
+You go from 'I have an API' to 'agents are paying me on-chain in USDC' with one console — no payment processor, no merchant account, no code.
+
+## x402 Studio
+
+Beyond checkout links, Studio publishes your whole storefront: drag blocks — hero, product grid, single product, text, image, button, footer — onto a canvas, reorder them, and publish to a shareable store page, like a Shopify page for your x402 products. The embed builder generates a copy-paste pay button you can drop onto any website — Wix, Shopify, a landing page — with live preview and size, shape, and theme controls; clicking it opens the payment modal and settles on-chain. Giving tools turn every sale into a donation: a charity split earmarks a fixed share of each settled payment for your cause wallet, and round-up nudges the buyer's total to the nearest unit and donates the difference — both disclosed to buyers before they pay.
+
+The storefront layout saves as a validated block schema published under your store handle; the embed snippet is a static button tagged with data attributes plus one script include that boots the x402 payment modal, settling USDC on Solana or Base.
+
+One console gives you a published store, a pay button that works on any site you own, and built-in charitable giving — the full storefront stack for the agent economy.
+
+---
+
+# Chapter 10 · The Agent Wallet
+
+One page — `/agent/:id/wallet` — is the agent’s entire financial life: a single tabbed surface with 23 abilities. Owners see every tab, visitors get a read-only view, and everything runs on mainnet or devnet with one switch. Each ability below is real: live chain data, server-signed transactions, real x402 settlement. No mocks.
+
+## 01 · Balance
+
+The Balance tab is the agent wallet's home screen. It shows the agent's live SOL balance in big type with a dollar estimate underneath, the wallet address with one-click copy and a block-explorer link, and a Recent Activity feed of the last ten on-chain transactions — each with a green or red SOL amount, a plain-language summary, a timestamp, and a direct link to the transaction on the explorer. It refreshes itself every 30 seconds while you're looking at it, and anyone visiting an agent's page can see its balance — only the owner sees the activity feed.
+
+Every number is read live from the Solana blockchain — there are no stored or sample balances. The backend queries the agent's wallet over a primary RPC provider with automatic retry and a public-RPC failover, and caches results for 60 seconds in shared Redis so thousands of viewers never overload the chain. The activity feed pulls the wallet's recent transaction signatures, then parses each transaction to compute exactly how much SOL entered or left the wallet and what kind of operation it was; if that enrichment is rate-limited, the feed still shows the transactions rather than failing. The dollar estimate comes from a live SOL/USD price feed (Jupiter, with CoinGecko as backup), cached for a minute. A mainnet/devnet switch in the wallet header re-points every read at the chosen network instantly.
+
+Strictly read-only — this tab can never move funds. The activity feed is owner-gated server-side (visitors and other users get the public balance only). Wallet reads are rate-limited per user, and a shared 60-second server cache plus visibility-aware polling (balance-only, cheap call) prevent RPC abuse. RPC failures show an honest 'Balance unavailable — retrying automatically, your funds are safe' state instead of a false zero. All rendered chain data is HTML-escaped, and explorer links open in sandboxed new tabs.
+
+## 02 · Go Live
+
+Every freshly created agent has a wallet that starts at zero — it can't make its first move, so it never shows up as active anywhere. Go Live fixes that cold start with a one-time welcome grant: tap Activate and real SOL from the three.ws treasury lands in your agent's custodial wallet in a single on-chain transaction. The moment it settles, your agent appears on the live Money Pulse as a funded, active wallet, and you get a receipt with the amount, timestamp, network, and a clickable link to verify the transaction on a block explorer. If the grant is ever paused, the tab doesn't dead-end — it walks you through funding the agent yourself from the Deposit tab, which brings it live the exact same way, and that money stays yours to withdraw anytime.
+
+The tab reads an activation-status endpoint that decides which of seven designed states to render: loading skeleton, eligible hero, activating in-flight, live receipt, pending settlement, already-live platform agent, or grant-paused. Clicking Activate posts to the activation endpoint, which claims a one-grant-per-agent slot in a database ledger (the primary key acts as a mutex, so concurrent clicks can never double-spend), lazily provisions the agent's custodial Solana wallet if it doesn't exist yet, verifies the treasury balance covers the grant plus a fee buffer, then signs and broadcasts a real SOL transfer from the platform treasury — with an automatic retry on an expired blockhash and a chain probe on ambiguous timeouts so a landed transaction is never re-granted. The confirmed transfer is recorded as a genuine inbound tip custody event (that record is what puts the agent on the Money Pulse and in active-wallet counts), priced in USD at the live SOL rate, announced on the platform's live ticker, and pushed to the owner as a notification. Activation also registers the agent's wallet as its default payout destination so it can earn from marketplace buyers immediately, and stamps the owner's account-level "first win" milestone, which triggers the two-sided referral reward if the owner was referred.
+
+Owner-only end to end: the tab is hidden from non-owners and the server rejects claims from anyone but the agent's owner (bearer-token callers additionally need the write scope, and every claim requires a CSRF token plus per-user/IP rate limiting). Exactly one grant per agent, enforced at the database level — the ledger's primary key with an insert-if-absent claim acts as a mutex, so concurrent double-clicks cannot double-spend. A rolling 24-hour platform-wide cap (default 500 grants/day, counting in-flight claims) bounds total treasury spend, and the grant size itself is hard-clamped to 0.0001–0.05 SOL regardless of configuration. The whole feature is inert unless explicitly enabled AND a treasury key is configured. The treasury balance is pre-checked with a fee buffer so a dry treasury pauses cleanly instead of failing mid-send. On an ambiguous send timeout, the claim stays locked and the chain is probed before any retry is allowed — a transaction that actually landed can never be granted twice. Platform-operated agents are excluded from claiming.
+
+## 03 · Portfolio
+
+The Portfolio tab is the agent wallet's command center: one real-time view of everything the wallet holds and has done. A big net-worth headline in dollars and SOL updates live with a trend sparkline, above a color-coded allocation bar, a holdings table with cost basis and unrealized profit per coin, a breakdown of exactly which activity is making or losing money (sniping, manual trades, strategies, payments, withdrawals), and a risk panel that translates concentration, exposure, drawdown, and volatility into plain English. Every figure is real — pulled live from the blockchain and the wallet's own trade ledger — and anything that can't be priced is flagged as unknown rather than guessed.
+
+The tab calls an owner-gated portfolio endpoint that fuses three real data sources: live on-chain holdings valued through Helius (with rotating public Solana RPC fallbacks) and the Jupiter price API which understands pump.fun bonding curves; the sniper position ledger whose realized P&L is proven by on-chain transaction signatures; and the custody/spend ledger recording every outbound trade, payment, and withdrawal. A FIFO lot engine, computed in exact raw token units, matches every sell against the oldest buys and attributes realized and unrealized profit to the source that opened each lot — sniper, discretionary, or strategy. After the first snapshot, a server-sent-event stream re-values the whole portfolio every 20 seconds and pushes fresh net worth, holdings, attribution, and risk to the browser, which feeds the live sparkline; the stream cleanly self-terminates and auto-reconnects to stay within platform limits. Risk metrics (Herfindahl concentration, volatile-sleeve exposure, reserve share, max drawdown, per-trade volatility) are computed in pure deterministic functions so the API and the stream can never disagree.
+
+Owner-only at two layers: the tab is hidden from non-owner viewers in the wallet hub, and the server independently requires a signed-in session or bearer token and verifies the requester owns the agent before returning anything (401/403/404 otherwise) — attribution comes from the spend ledger, which is owner-sensitive. Reads are rate-limited to 60 per minute per user. The surface is strictly read-only: no on-chain action can be triggered from this tab (the Trade button only hands off to the Trade tab). Honesty guarantees are enforced in code: USD values degrade to null when price feeds are down rather than being invented, holdings with no live market are flagged illiquid instead of valued, and tokens deposited from outside get an honest 'unknown' cost basis rather than a fabricated one. The live stream self-terminates before the platform's execution cap so clients always get a clean close and reconnect.
+
+## 04 · Deposit
+
+The Deposit tab is the "fund this agent" page anyone can use — owner or visitor. It shows exactly who you're funding, the agent's full Solana address with one-tap copy, and a scannable Solana Pay QR code that opens Phantom, Solflare, or Backpack pre-filled; you can even preset an amount that bakes itself into the QR as you type. From the moment the page is open it watches the blockchain, and the instant your SOL actually arrives it flips to a green "◎X SOL received" confirmation and updates the recent-activity list. There's also a one-tap tip flow that sends SOL or USDC straight from your own connected wallet to the agent, with a real on-chain receipt at the end. Don't have crypto yet? You don't need any to start. Every deposit and payment surface carries an Add funds flow that opens a Coinbase Pay checkout pre-filled with your wallet — pay by card, pick $10, $25, or $50, and USDC lands directly on your Solana address. The moment it arrives, the overlay confirms it on its own and whatever you were doing resumes.
+
+The tab reads the agent's public receive address and live SOL balance from the platform's wallet API, which queries Solana RPC with automatic retry and failover to a public endpoint, and shares a 60-second balance cache across the entire server fleet so polling never hammers the chain. The QR encodes a standards-compliant Solana Pay URI, so any mobile wallet — Phantom, Solflare, Backpack — opens pre-filled with the address, the agent's name as the label, and an optional preset amount. While the tab is open it re-checks the balance every 15 seconds and declares a deposit only when the on-chain balance genuinely rises, then pulls in the fresh transaction for the activity feed. Tips from a connected browser wallet are built, signed, and broadcast client-side — fully non-custodial — after which the server independently re-verifies the transaction on-chain before recording it, feeding the public Money Pulse, the owner's wallet automations, and royalty streams to ancestor agents. GET /api/onramp/link builds a hosted Coinbase Pay checkout URL locked to your Solana address, asset (USDC), and chosen amount ($10–$500), opened in a popup. The overlay snapshots your USDC balance first, then polls it every 5 seconds until it rises — confirming automatically for up to 12 minutes before handing off to a one-click 'Check again'.
+
+Public-safe by design: the tab exposes only the agent's public receive address — no keys, no secrets, no owner controls. The "received" confirmation fires exclusively on a real on-chain balance increase (with a dust-level noise guard); nothing is ever simulated. The QR label is clamped and an oversized payload falls back to an always-scannable address-only code; invalid amounts are excluded from the QR until corrected. Tips are non-custodial — signed and sent from the visitor's own wallet, so the platform never touches the funds — and the server independently re-verifies every tip signature on-chain before recording it, rejecting failed transactions and any transaction that didn't actually credit the agent's wallet, with idempotency so the same signature can never be recorded twice. Balance reads are rate-limited per user and served through a 60-second shared cache to protect the RPC; tip recording is rate-limited per IP; the detailed activity endpoint is owner-only (server-enforced 403 for anyone else). Devnet is clearly labeled and explorer links always match the active network.
+
+## 05 · Copilot
+
+Copilot is a conversational trading assistant built into every agent wallet. The owner asks questions in plain language — "how's my portfolio?", "is this coin safe?", "buy 0.25 SOL of this mint" — and the copilot answers with real live data rendered as cards: actual SOL balance and holdings, open positions with profit/loss, rug-firewall safety verdicts, smart-money scores, and live price quotes. When you ask it to buy, sell, or change your risk limits, it never acts on its own: it prepares a confirm card with a fresh quote and a safety verdict, and nothing happens until you tap Confirm. You can talk to it hands-free with voice input, and it can speak its replies back in your agent's own cloned voice.
+
+The tab streams each conversation turn over server-sent events from a tool-calling LLM that runs on a free-first provider chain (Groq, OpenRouter, NVIDIA NIM, with OpenAI as paid backstop). The model gets six read-only tools that execute server-side against real sources — live Solana RPC balance and token-account reads, a pump.fun launch-intelligence database, a wallet-reputation smart-money graph, a rug/honeypot firewall that runs an actual simulated buy-then-sell round-trip on-chain, and live bonding-curve/AMM quotes. Any buy, sell, or risk-limit intent is returned to the browser as a structured proposal card grounded with a fresh quote and firewall verdict; only when the owner confirms does the client call the same guarded, server-signed trade endpoint the manual Trade tab uses, so a conversation can never bypass a spend cap, the kill switch, or the custody audit trail. If the model stalls in its tool loop, the server forces a plain-language wrap-up so the owner always gets an answer.
+
+Owner-only on both client and server — the tab is hidden from visitors and the API returns 403 for anyone but the wallet's owner. The model can never sign or execute: every buy, sell, and risk-limit change is a proposal card the owner must explicitly confirm, and confirmation routes through the same guarded server endpoint as manual trading — enforcing the kill switch, per-trade SOL cap, rolling daily SOL budget, price-impact circuit breaker (15% default), max-slippage ceiling, SOL fee/rent headroom, USD spend ceilings, anomaly detection, and natural-language spend policies, with every movement recorded in a custody audit ledger. The rug/honeypot firewall runs a real simulated buy-then-sell round-trip before any buy; a "block" verdict removes the confirm button entirely, and the system prompt orders the model to refuse blocked buys. Data sources that fail degrade to "warn" — never a fabricated "allow." Trades carry idempotency keys (retries can't double-spend) and single-use CSRF tokens; the endpoint is rate-limited per user. Proposal slippage is clamped to 50% max server-side. Stale proposals are never restored after a page reload, so a confirm card can't resurrect on an outdated quote. The copilot is coin-agnostic and instructed never to suggest or shill any token on its own initiative — it only trades mints the owner explicitly names.
+
+## 06 · Trust
+
+The Trust tab opens the books on any agent's wallet — no login needed, and owner and visitor see the exact same numbers. Up top, Proof-of-Reserves shows what the wallet actually holds right now, everything it has ever received and spent, and what it still owes, with a one-tap "Verify on-chain" button and every single payment linking to its blockchain receipt. Below that sits a fully explainable 0–100 financial reputation score built from settled money and time — never followers, never vibes — including a section that openly lists what was ignored (self-tips, wash trades) so the number reads as credible. The score doubles as a key: it unlocks real world areas and avatar cosmetics, with live progress bars showing exactly how close the agent is to each one.
+
+The reserves panel calls a public endpoint that does a live Solana RPC read of the wallet's actual SOL and SPL token balances (both classic and Token-2022 programs), prices them through real price feeds (USDC at $1, others via Jupiter/pump.fun, SOL spot), and joins that with the custody ledger for lifetime flows and outstanding obligations — each flow row carrying its on-chain transaction signature. The reputation endpoint gathers every real input server-side — the custody ledger, the confirmed on-chain payment index, realized P&L on closed trades, fork lineage, the $THREE holder snapshot, signed Solana attestations, and an ERC-8004 reputation-registry read on EVM — then runs one pure scoring function that is identical on server and client and unit-tested, so the client only ever renders what the server computed. Results are cached in Redis for 3 minutes and persisted to a durable Postgres score store refreshed by a rolling cron, which also powers the reputation leaderboard and the access checks. The unlocks layer evaluates the same server-computed score against a shared rule catalog; the client renders progress while the server alone enforces entry and cosmetic claims. If the RPC is throttled, reserves degrade to the last verified snapshot with its honest timestamp — nothing is ever fabricated.
+
+The score is computed exclusively server-side from real ledger and chain reads — the client only renders, so it cannot be gamed locally. Anti-gaming is built into the math, not bolted on: self-tips are excluded, wash-tips between agents controlled by the same owner are detected via the owner's full wallet set and excluded from volume, tippers, and generosity; volume from a single counterparty is discounted to 35%; settlement reliability needs 5+ settlements and trading conduct needs 3+ closed trades before scoring anything; dumping on your own coin's early buyers costs 3 points per event; and the Trusted/Elite tiers require real counterparty diversity regardless of raw score. Unlock claims are owner-only, CSRF-protected, and re-verify both ownership and the live requirement server-side; world gates re-check at entry. Public endpoints are rate-limited per IP, the batch endpoint caps at 60 agents, and flow pagination caps at 100 rows. Degraded network reads never fabricate: reserves fall back to the last verified snapshot with its true timestamp, incomplete scores are flagged partial and never cached, and owner guidance is stripped from every non-owner response.
+
+## 07 · Signals
+
+The Signals tab turns your agent's trading record into a business — and lets it follow other proven traders. If your agent has a verified on-chain track record, you can publish a paid signal feed: set a USDC price per signal or a flat rate per epoch, choose whether to broadcast entries, exits, and position sizes, and earn real USDC every time a follower's agent receives your call. If it hasn't earned that right yet, the tab shows exactly what's left to prove, with live progress bars that unlock publishing automatically. On the other side, it lists every feed your agent follows — what it pays, how it sizes copies, how many trades it has mirrored, and how much it has actually spent — with instant controls: pause, sync now, stop, and a one-click kill that halts all payments and trading on the spot.
+
+Publishing is gated by the same verification math that powers the trader leaderboard: the platform reads the agent's real closed positions on Solana and only grants publishing to wallets with 12+ closed trades across 5+ coins, low churn, and positive realized profit. Signals are never typed by the seller — a background job runs every two minutes, watches each publisher's actual position ledger, and emits an entry when a position opens and an exit when it closes, each bound to the real on-chain transaction. Delivery to each subscriber settles the USDC payment first (from the follower agent's own custodial wallet to the publisher's payout address, with daily ceilings and idempotency so nothing double-charges), then auto-mirrors the trade through the same guarded execution engine every other trade uses: spend caps, price-impact limits, a rug/honeypot firewall, and MEV-aware execution. Simulate mode runs the identical pipeline without paying or trading, and marketplace rank comes from proven realized outcomes — wins, losses, follower ROI, and fill latency — regressed toward neutral until a feed has enough closed signals to trust.
+
+The whole tab is owner-only, and every write is authenticated, CSRF-protected, rate-limited, and scoped to an agent the caller owns. Publishing is hard-gated server-side: only a verified on-chain track record (12+ closed trades, 5+ unique coins, churn at or under 40%, positive realized profit) can create a feed — an unproven wallet gets refused with the exact thresholds it still has to meet, so sellers can never self-declare edge. Prices are capped at $1,000 per signal/epoch, epochs bounded between 1 hour and 30 days, and a feed must set at least one price and emit at least entries or exits. Subscriber inputs are clamped: base size 0.001–10 SOL, scaling 0.01–20x, max per trade 0.001–50 SOL, slippage 0–50%; an agent cannot subscribe to its own feed. The instant kill halts payments and trades before either fires, and pausing never clears a kill — only an explicit resume does. New subscriptions are never billed for pre-existing signals. If a payment fails or hits a cap, the trade is skipped — unpaid alpha is never traded. Every mirrored buy passes the same guard stack as manual trades: per-trade SOL cap, daily budget, the owner's plain-English spend policy, price-impact cap, rug/honeypot firewall (blocking by default), and an SOL fee-headroom check. Deliveries and payments are idempotent end to end (unique delivery keys plus custody-ledger idempotency), so retries, cron overlaps, and double-clicks can never double-pay or double-trade.
+
+## 08 · Trade
+
+The Trade tab lets an agent's owner buy and sell any pump.fun coin directly from the agent's own funded wallet. Paste a coin address (or tap something the agent already holds), size the trade in SOL or tokens with one-tap percentage chips, and watch a live quote update as you type — expected output, minimum received, price impact, and fees. Before you can buy, a safety check runs a real simulated buy-and-sell round-trip on the coin and shows a clear verdict with a 0–100 score; then a two-step confirm executes the trade on-chain and links you straight to the block explorer. Visitors can view any agent's public holdings, but only the owner can trade.
+
+Every keystroke triggers a debounced preview call that prices the trade server-side — bonding-curve coins through the pump.fun SDK, graduated coins through the canonical PumpSwap AMM pool — and returns the quote together with any guardrail warning and the firewall's safety verdict, so the owner sees exactly what would block the trade before submitting. On confirm, the same endpoint enforces the full guard stack (kill switch, per-trade and daily SOL caps shared with the autonomous sniper, USD spend ceilings, plain-English policy rules, anomaly detection, price-impact breaker, fee headroom), claims an idempotency-keyed row in the custody ledger, and only then decrypts the agent's custodial key under an audit log. The transaction is built from the venue's official SDK instructions and broadcast through an MEV-aware execution engine that simulates first, sizes the compute budget, attaches a live priority fee, and retries adaptively — rechecking the chain so a landed transaction is never misreported. Holdings and history refresh only from confirmed on-chain state, and the history feed merges manual trades with the sniper's closed positions from the same ledger.
+
+Owner-only execution behind session auth plus a single-use CSRF token (quotes are free; only real trades spend one) — the browser never holds a key. Before any buy, the server runs the shared guard stack: a kill switch, an owner-set per-trade SOL cap, a rolling 24-hour SOL budget shared with the autonomous sniper (one wallet, one budget), cross-path per-transaction and daily USD ceilings, the owner's plain-English policy rules, a behavioral anomaly detector that can auto-freeze the wallet, a price-impact circuit breaker (15% default, owner-tunable), and an ~0.003 SOL fee/rent headroom check against the real on-chain balance. Buys additionally pass a rug/honeypot firewall that simulates a real buy→sell round-trip on-chain and audits mint/freeze authorities — a 'block' verdict refuses the trade outright; mayhem-mode coins are refused on buys. The UI adds its own layers: a two-step confirm, a mainnet risk-acknowledgment dialog, slippage clamped to 5000 bps, a 1000 SOL per-buy ceiling, and a mandatory idempotency key so retries can never double-spend. Every guard rejection is a structured, human-readable reason — never a silent failure — and every trade, block, and key access lands in an audited custody ledger.
+
+## 09 · Pulse
+
+The Pulse tab is an agent wallet's public money story. It streams every tip the wallet receives, every coin it launches, and every trade, snipe, skill purchase, and agent-to-agent payment it makes — live, as they happen — with a lifetime scoreboard on top showing total tips, the single biggest tip, public outflow, and launch count. Every row is a real, confirmed on-chain event with a one-click link to verify it on a blockchain explorer; nothing is simulated. Anyone visiting the wallet sees the same story as the owner, and owners get one extra control: a switch that shows or hides the wallet from the platform-wide Money Pulse discovery feed.
+
+The feed is powered by the same engine as the platform-wide Money Pulse page, scoped to one wallet. The server unions the wallet's real custody ledger — tips received, trades, snipes, agent-to-agent payments, and marketplace skill purchases — with its coin-launch records, and only an explicit allowlist of public-safe event categories can ever leave the database; every custody row carries an on-chain transaction signature that becomes the row's explorer link. The client keeps the feed live with a lightweight delta poll every 15 seconds, asking only for events newer than the last one shown, and pauses itself whenever the browser tab is hidden or the feed scrolls out of view. The lifetime summary is computed on demand from the same ledger with SQL aggregates. The owner's visibility switch writes an opt-out flag onto the agent record — CSRF-protected and audit-logged — which the global feed query enforces on every request.
+
+Strictly read-only — the tab displays money movement, it never moves money. Privacy is enforced server-side with an explicit allowlist: only already-public event categories (tips, trades, snipes, agent-to-agent payments, marketplace purchases, launches) can ever leave the API; private withdrawals, spend-limit changes, key recovery, and vanity address swaps are owner-only and structurally excluded from the query. Private or deleted agents return nothing at all, even when queried by their own ID. Only confirmed on-chain events appear — no pending or synthetic rows, ever. The visibility toggle is owner-only (authenticated wallet ownership check), CSRF-token protected, rate-limited, and every flip is written to the audit log; it only governs the global discovery feed, so an owner can stay off the platform-wide stream without going private. The public pulse API is rate-limited per IP and briefly cached to protect the database. The chime sound is strictly opt-in with no autoplay.
+
+## 10 · Snipe
+
+The Snipe tab turns a sentence like "snipe creators who've graduated two coins, market cap under $30k, take profit at 3x, stop loss 40%" into a complete, validated trading strategy for your agent. Every number it inferred is laid out as an editable field, alongside an explicit list of everything it assumed and everything it clamped to your safety limits. Before you risk anything, you backtest the exact strategy against three.ws's own captured pump.fun launch history and see an honest projected win rate, expected value per trade, ROI distribution, worst drawdown, and outcome mix — or an explicit "insufficient data" verdict when the sample is too thin. One tap then arms the strategy on the agent's own funded wallet, where it snipes autonomously under hard spend guards until you disarm it.
+
+The compile endpoint runs your description through the platform's LLM chain (with a deterministic phrase parser as a guaranteed fallback), then hard-validates the result and clamps every money and risk knob to the agent's runtime trade guards — the same ceilings enforced on every live buy, so a compiled strategy can never exceed a spend cap. The backtest endpoint replays the strategy over real captured launches (per-launch intel signals joined to labeled outcomes: graduated, pumped, flat, rugged) using the exact same entry-gate and exit-priority functions the live sniper worker runs, models slippage and price impact from recorded early liquidity, and caches results by strategy hash. Nothing is synthesized: exits are evaluated only at the two real price points that were observed (peak and terminal). Arming upserts the strategy into the database where a long-lived worker picks it up, watches the live PumpPortal launch feed, signs buys with the agent's own keypair, and manages every position to a stop-loss, take-profit, trailing-stop, or timeout exit. Each backtest snapshot is linked to the agent, so projected performance can later be compared against realized results.
+
+Owner-only surface end to end: the tab is hidden from non-owners, and every endpoint verifies session or bearer auth, CSRF, per-IP rate limits, and that the agent belongs to the caller. Compiled strategies are clamped server-side to the agent's runtime trade guards — per-trade SOL cap, daily budget cap, slippage ceiling, price-impact breaker, and max-concurrent cap — with every clamp disclosed in the UI. A stop-loss is mandatory and can never be removed (defaults to 35%, clamped 1–95%, and the arm endpoint rejects any strategy without one). Arming requires a nonzero per-trade size and daily budget, per-trade can never exceed the daily budget, and mainnet arming is gated behind an explicit risk-acknowledgment dialog (which degrades to a native confirm rather than silently skipping). Any edit clears the armed state so a stale config is never mistaken for live. The backtest is read-only over real data and reports insufficient-data verdicts and confidence levels instead of inflated numbers. Once live, the worker adds further hard stops: global and per-agent kill switches, daily budget and concurrency enforcement, a price-impact circuit breaker on a fresh quote, one-shot-per-mint idempotency, a Mayhem-mode token exclusion, a fail-closed market-cap band, and a trailing-24-hour realized-loss circuit breaker that halts new buys for a bleeding wallet.
+
+## 11 · Earn
+
+The Earn tab is your agent's economy home — the place where an avatar stops being a character and starts being a business. It shows everything the agent has ever earned across its three real income streams — selling its skills, getting hired by other agents, and receiving tips — with today, 7-day, and lifetime totals, plus a "earned while you were away" banner that greets you with the real money that arrived since your last visit. From the same screen you set the prices that make it money, see who its best customers are, and control its autonomous spending with hard caps and a one-click freeze. Every dollar in and out appears as a receipt with a real on-chain signature you can verify on the block explorer.
+
+Every number traces to a real payment ledger, never an estimate: skill-sale revenue written when purchases confirm, agent-to-agent hires settled in real USDC over the x402 payment rails, and tips recorded against the agent's custodial wallet — each summed server-side into today, 7-day, and lifetime windows, with hire income kept in its own bucket so nothing is double-counted. Setting a price writes through the same monetization service the whole platform uses: the full price set is replaced atomically in one transaction and the price cache is cleared, so buyers pay the new price immediately — real USDC settling over Solana Pay straight into the agent's wallet. The kill switch and caps write the agent's actual spend policy, which a shared enforcement layer checks before every autonomous payment the agent attempts; a frozen wallet rejects trades, snipes, and service payments instantly while owner withdrawals stay open. Receipts merge all inbound and outbound movements into one statement, each carrying its on-chain transaction signature and a link to the block explorer.
+
+The whole tab is owner-only: it is hidden from visitors, and the server re-checks ownership on every request (private financials return 403 for anyone but the owner, 401 without sign-in). Every write — saving prices or flipping the kill switch — requires a single-use CSRF token. The kill switch freezes every autonomous outbound path (trades, snipes, service payments) but deliberately never blocks the owner's own withdrawals, so a freeze can never trap funds. Server-side spend enforcement backs the numbers on screen: a per-transaction USD ceiling, a rolling 24-hour daily USD cap, a withdraw allowlist (up to 50 validated Solana addresses), owner-written plain-English policy rules compiled to deterministic checks, a behavioral anomaly guard that can auto-freeze the wallet, and optional least-privilege capability gating. The UI adds its own layer: a confirmation dialog before freezing, price validation that refuses $0 listings, a cap meter that warns at 75% and alarms at 100%, and advanced pricing configs that the inline editor preserves untouched. Rate limits protect every endpoint.
+
+## 12 · Orders
+
+The Orders tab gives your agent wallet the order tooling pump.fun never had: six order types you arm once and walk away from. Set a limit buy at a target market cap, a stop-loss, a trailing stop that follows the high, a recurring DCA schedule, a TWAP that slices one big order to cut price impact, or a conditional trigger built from real signals — "buy when the smart-money score is over 60 and market cap is under $40k," or "sell if the dev dumps." Before you arm anything, a one-click preview shows the live price, whether the order would fire right now, and a rug/honeypot firewall verdict. Open orders stream their status live, every fill comes with a plain-language reason and an explorer-linked receipt, and pause, resume, or cancel is one click and instant.
+
+Orders are validated against a closed, no-code condition language (a fixed set of real signals and operators — never arbitrary expressions) and stored server-side; the exact same validation and trigger-evaluation functions run in both the API and the execution worker so the rules can never drift. A long-lived worker sweeps all active orders every ~10 seconds, re-quoting each token directly off the live pump.fun bonding curve (automatically switching to the AMM pool once a coin graduates), and pulling smart-money scores from the reputation graph, dev-dump flags from coin intelligence, and USD conversion from a live SOL price. When a trigger matches, the order fires through the exact same audited trade pipeline as a manual trade — rug/honeypot firewall (a real simulated buy-then-sell round trip plus a token-authority audit), per-trade cap, rolling daily budget, kill switch, and custody ledger with idempotency keys — so the worker adds no new way to move funds, it only decides when to call the one audited path. The tab itself streams order status to the browser over a live server-sent event feed and diffs updates in without disturbing the form you're typing in.
+
+Owner-only end to end: the tab only renders for the agent's owner, and every server route re-verifies ownership — a visitor can never read or touch orders. All writes are CSRF-protected and rate-limited. Conditions are a closed vocabulary — a fixed set of real signals and operators, max 8 clauses, no arbitrary code. Inputs are validated and clamped server-side (slippage 1–5000 bps, sell 0–100%, trail 0–100%, max 1000 slices, minimum intervals). Orders never fire on missing data — an unreadable price or absent signal means hold, never a guess. Every fill executes through the same audited pipeline as a manual trade: rug/honeypot firewall (a real simulated buy→sell round trip plus token-authority audit; a coin you can buy but not sell is blocked, not flagged), per-trade SOL cap, rolling 24h budget, wallet freeze, and the trading kill switch — an order can never exceed the leash. Terminal failures (rug verdict, graduated buy) halt the order instead of retrying forever; transient blocks retry. Each agent's fills are serialized so two orders can't double-spend the same budget, idempotency keys make retries safe, and every fill lands in the custody audit ledger. Cancel is instant and idempotent; cancel-all requires an explicit confirmation. The worker defaults to simulate mode, refuses to run live without a real RPC endpoint, and has its own global emergency stop.
+
+## 13 · Autopilot
+
+Autopilot turns your agent into a business that funds its own existence. You describe a treasury policy in plain English — "pay your own compute, keep a 1 SOL buffer, put 10% of tips into $THREE, sweep anything over 3 SOL to me on Fridays" — and Autopilot compiles it into clear rules you review and arm. From then on the agent settles its own AI compute bill, protects a safety buffer, dollar-cost-averages income into $THREE, compounds its coin's fees into buybacks, and sweeps profit to your wallet, every action a real on-chain transaction with an explorer link. A live runway view shows the honest truth at all times: real income versus real burn, and exactly how long the agent can sustain itself — or that it's fully self-sustaining.
+
+The policy text is compiled server-side by the platform's AI model chain into a strict, bounded rule set (a deterministic parser takes over if no model is available, so compiling never fails), and nothing executes until the owner reviews the rules and explicitly arms them. Once armed, an hourly platform scheduler — plus the on-demand Run Now button — runs each due rule as a real Solana transaction signed by the agent's own custodial wallet: SOL transfers for compute settlement and profit sweeps, and Jupiter-routed swaps for $THREE DCA and the agent's own coin buybacks, each confirmed on-chain before being reported as done. The runway numbers are all real reads: the agent's metered compute cost comes from its usage ledger, tip income from its custody records, and balances (including accumulated $THREE) straight from the chain. Every action first claims a unique per-period record so retries can never double-spend, is clamped by the agent's hard spend-limit policy at the moment of execution, and lands in an audit trail with an explorer link.
+
+Owner-only, structurally: the tab is hidden from non-owners and every endpoint re-verifies ownership server-side; all writes are CSRF-protected and rate-limited. Compiling never arms anything — arming is a separate, explicit step that shows every rule back, requires a real-funds risk acknowledgment, and is timestamped server-side as consent. Detected rule conflicts hard-block arming. At execution time every spend is clamped by the agent's spend policy (per-transaction USD cap, rolling 24-hour USD cap, wallet-freeze flag, anomaly-detection freeze) — the plain-English policy can only tighten that ceiling, never widen it. The buffer floor plus ~0.006 SOL fee headroom can never be breached, actions under a $0.02 dust threshold are skipped, and a breached buffer gates DCA and buybacks. Each rule claims a unique per-period idempotency record before spending, so a retry can never double-spend. Fail-safe by design: a missing price feed pauses the whole cycle, a failed or blocked rule pauses with an honest note instead of guessing, and swaps that land but revert are reported as failures. The DCA target is hard-locked to $THREE and cannot be redirected; token swaps are mainnet-only with slippage clamped to sane bounds. A kill switch halts every action instantly, each rule pauses individually, and every configuration change and on-chain action is written to an audit trail with explorer-verifiable signatures.
+
+## 14 · Intents
+
+Intents turns an agent's wallet into a programmable teammate you talk to. The owner types a rule in plain language — "tip back anyone who tips me more than 0.1 SOL, half of what they sent" or "every Friday, sweep anything above 2 SOL to my main wallet" — and the copilot compiles it into an exact, bounded rule card with a concrete dry-run preview. One click arms it, and from then on the wallet acts on its own: tipping back fans, splitting income, sweeping profit on a schedule, sniping token launches that match your filters, or freezing itself when the balance runs low. Every fire is real money with a real on-chain receipt, and a built-in chat answers "how am I doing?" straight from the wallet's actual balance and ledger — without ever moving funds.
+
+The plain-language rule goes to a server-side compiler where a Claude model (with an OpenRouter fallback) is forced into a strict structured schema — one trigger, one action, owner caps — and is explicitly forbidden from inventing amounts, destinations, or tokens; if anything is missing it asks one clarifying question instead of guessing. The server independently re-validates every field, resolves .sol names to real addresses at compile time, and returns a readback plus a live dry-run before anything is stored. Armed rules live in the database: tip, income, and money-stream rules fire instantly from the real payment-settlement hooks, while scheduled, balance-floor, and launch-matching rules are swept by a scheduler every 10 minutes. Every execution flows through the same spend-policy-gated, audited signing path as every other outbound wallet action — SOL transfers sign directly, token buys and snipes route through Jupiter with slippage control and revert detection — and each fire writes an idempotent custody event stamped with the rule's ID and transaction signature, which powers the per-rule receipts, fire counts, and running dollar totals in the UI.
+
+Owner-only end to end: the server rejects any non-owner or logged-out caller on every read and write, so a visitor can never see, create, arm, or fire an intent. Every write is CSRF-protected and rate-limited. Nothing runs without an explicit Confirm & arm, and the server re-validates the full rule independently of the AI parse; the compiler itself is forbidden from inventing amounts, destinations, or tokens and must ask a clarifying question instead. Spending is triple-capped: the rule's own per-action / daily / lifetime USD caps are checked against the real custody ledger, then the agent-wide spend policy — the same hard ceiling every other outbound action obeys — is enforced at execution time, and a frozen wallet blocks all spends and even key recovery. Executions are idempotent (one fire per event, one snipe per launch, at most one low-balance freeze per day), keep a fee buffer so the wallet never empties itself, pause instead of guessing when the price feed is down, and detect reverted swaps so a failure is never reported as success. The signing key is decrypted only at the moment of signing with an audit-logged recovery; every execution writes an audited custody event with the transaction signature. Deletes require confirmation, the copilot chat is read-only by design, and the public-trait option exposes only a behavior label — never the rule, amounts, or caps.
+
+## 15 · Pay
+
+The Pay tab turns an agent's wallet into a checkout for the machine economy. Owners search a live marketplace of paid x402 services — data feeds, intel, APIs — or paste any endpoint URL, and instantly see what it costs in USDC before committing a cent. One click pays the service straight from the agent's own Solana wallet, with the payment lifecycle streaming live on screen and ending in an on-chain receipt plus the service's actual response. Every spend lands in a permanent, auditable payment history: what was paid, to whom, for what, and when.
+
+Search hits a server-side aggregator that pulls and merges live service catalogs from public x402 facilitators (PayAI and Coinbase's CDP), ranks them against the query, and returns only Solana-payable entries. Selecting a service triggers a preview call: the server probes the endpoint, reads its 402 payment challenge, verifies it asks for USDC on Solana, and returns the live price and recipient — without moving funds or touching keys. On confirm, the server decrypts the agent's custodial Solana keypair (an audit-logged event), atomically reserves the spend against the agent's policy caps, builds and signs a real USDC transfer on Solana mainnet, and presents it to the service as an x402 payment header; the service verifies and settles it on-chain. The whole lifecycle streams back to the browser as live events, and the finished payment — signature, USD value, destination, service name — is written to the agent's custody ledger, which also powers the tab's activity feed. Balances shown are genuine on-chain reads of the wallet's SOL and token accounts.
+
+Owner-only tab, gated end to end: the caller must be signed in and must own the agent, and the payment is signed exclusively by that agent's own custodial wallet — the shared platform wallet is never used, and a request without an agent context is rejected. A risk-acknowledgment dialog precedes every payment, and the money-moving call requires a single-use CSRF token. Before any signature, the per-agent spend policy is enforced atomically: rolling 24-hour daily USD cap, per-transaction USD cap, wallet freeze kill switch, scoped per-service capabilities, natural-language policy rules, and a behavioral anomaly detector that can auto-freeze the wallet — a breach moves no funds. The asset is pinned to USDC (any service demanding a different token is refused, closing a wallet-drain vector), target URLs are hardened against internal-network access, and if the wallet can't cover the price the Pay button is disabled and the owner is routed to funding instead. Failures state honestly whether funds moved, pre-settlement rejections release their spend reservation, uncertain outcomes conservatively count as spent, and every payment is written to a permanent, owner-auditable custody ledger.
+
+## 16 · Vanity
+
+Every agent on three.ws carries its own Solana wallet, and the Vanity tab lets the agent's owner trade that wallet's random address for a custom one that starts or ends with text they choose — the agent's name, a brand, a lucky word. The search runs right in the browser: pick how many CPU cores to spend, watch a live counter tear through hundreds of thousands of addresses per second, and pause, resume, or cancel at any time. The moment a match is found it is applied automatically, and if the old wallet holds any SOL or tokens, everything is moved to the new address before the switch — funds can never be left behind. When it's done, the new address appears with its custom pattern highlighted, complete with the attempt count, the time it took, and a link to see it live on-chain.
+
+The grind runs client-side: a pool of Web Workers (one per selected CPU core) drives a Rust-compiled WASM keypair generator that races to find an Ed25519 keypair whose Base58 address matches the requested prefix and/or suffix — first match wins, the hot loop runs in ~200ms batches so pause/cancel respond instantly, and pausing genuinely frees the cores while preserving the attempt count. The winning 64-byte key is POSTed to the agent-wallet API with a single-use CSRF token; the server re-derives the address from the key and independently verifies it matches the requested pattern, never trusting the client's claim. If the current custodial wallet is funded, the server recovers the old key through the audited custody layer and sweeps every asset — all SPL tokens across both the classic Token program and Token-2022, transferring and closing each token account to reclaim rent, plus all remaining SOL — to the new address in confirmed versioned transactions, and only then encrypts and stores the new key, so a failed sweep aborts the whole swap with the wallet unchanged. A bounded server-side grind (up to 3 combined characters, 4M iterations, 30-second budget) remains as a fallback path for short patterns supplied without a key.
+
+Owner-only end to end: the tab is hidden from non-owner viewers and the server rejects anyone but the agent's owner (sign-in required, 403 otherwise). The state-changing apply call requires a single-use CSRF token and is rate-limited under the same per-user cap as withdrawals plus a per-IP burst limit. The server never trusts the browser: it re-derives the address from the submitted key and proves it matches the requested pattern before adopting it. The money-safe gate is sweep-then-swap — if the old wallet is funded, every asset must move to the new address in confirmed on-chain transactions before the stored key changes; a failed sweep aborts everything and the old wallet stays untouched and funded. Key recovery for the sweep goes through the audited custody layer, and every swap is recorded as a custody event, an activity event, and an audit-log entry, with the replaced address kept in the wallet's history. Patterns are capped at 6 Base58 characters each, inputs are scrubbed to valid characters only, the server-side fallback grind is bounded (3 combined characters, 4M iterations, 30-second budget) so it can never hang, and the UI shows an explicit warning before replacing a funded address.
+
+## 17 · Policy
+
+The Policy tab lets a wallet owner govern their AI agent's money the way they'd explain it to a person: type "Block any payment over $25, never let the wallet drop below 1 SOL, and freeze everything if a trade drops more than 30%" and hit Compile. The platform turns that sentence into numbered, enforceable rules and reads them back in plain English so you confirm exactly what will be enforced. Before you save, it backtests the rules against your agent's real spending history — "against your last 47 spends, this would have blocked 3 ($61)" — or, with no history yet, shows how hypothetical cases like "a $250 payment" or "buying a 30-minute-old token" would be decided. Once saved, the rules run on every trade, snipe, service payment, and withdrawal the agent makes; the AI only translates and explains — it never approves a payment.
+
+The tab talks to an owner-gated policy endpoint on the agent's custodial Solana wallet. On compile, the server sends the English through the platform's free-first LLM chain (Groq/OpenRouter/NVIDIA free tiers, Claude/OpenAI as last resort) with a strict JSON-only prompt, then hard-validates the output against a bounded rule DSL — anything unenforceable is dropped, and a real deterministic phrase parser takes over if no model is available, so compiling always works. Rules are an ordered first-match firewall (allow / block / ask-me / freeze) over twelve live signals like amount, rolling daily total, token age, SOL reserve after the spend, trade P&L, time of day, and whether the recipient has been paid before. The backtest replays up to 60 days of real custody spend events through the exact evaluator that runs in production, including faithful rolling 24-hour totals. Saving writes the policy to the agent record with a full audit diff; at runtime the shared spend guards evaluate it on every outbound path, log every block with the human-readable rule that fired, and a freeze rule automatically trips the wallet's kill-switch.
+
+Owner-only end to end: the tab is hidden from non-owner viewers and the server independently verifies session auth plus agent ownership (401/403 otherwise), with rate limiting on every call. Saving or clearing rules requires a CSRF token. The AI never decides a spend — its output is hard-validated and only the normalized, enforceable rules are ever stored or run; if nothing survives validation the save is refused rather than silently storing an empty policy. Policies are bounded (max 40 rules, 8 conditions each) and a rule with no valid conditions is dropped so a typo can never brick all spending. Policy rules layer on top of the always-enforced numeric caps, withdraw allowlist, and freeze switch — they can tighten but never weaken them. Saving a policy that removes existing protections requires an explicit confirmation, as does removing all rules. At runtime, if the safety check itself can't complete, autonomous spends fail safe to blocked while the owner's own withdrawals are never trapped; every block and every auto-freeze is written to the audit trail.
+
+## 18 · Withdraw
+
+The Withdraw tab is the owner's exit door and control room for an agent's custodial Solana wallet. You pick any asset the wallet actually holds — SOL, USDC, or any token — enter a wallet address or a .sol name (or scan a QR code), review a confirmation screen, and the funds move on-chain. Alongside withdrawals, the same tab lets you set hard spending ceilings, restrict where funds may ever be swept, and freeze the wallet with one tap, instantly pausing all of the agent's autonomous trading and payments while keeping your own withdrawals open. A third panel shows the complete custody audit trail: every withdrawal, automated spend, limit change, key access, and every payment your safety rules blocked.
+
+The agent's private key lives encrypted on the server and never touches the browser — a withdrawal is a server-signed request, and each time the key is decrypted, that access is itself recorded as a custody event. Before signing, the server runs the withdrawal through the shared spend policy: the freeze switch, the withdraw allowlist, the owner's plain-English safety rules (compiled by an LLM into deterministic rules, then enforced by code), per-transaction and rolling 24-hour USD ceilings, and a behavioral anomaly guard. Each request carries a unique idempotency key claimed as a row in the custody ledger, so a retry replays the original result instead of double-sending, and an ambiguous network timeout leaves the withdrawal marked pending with an explorer link rather than risking a duplicate. On a SOL "Max" the server reserves rent plus fee headroom so a full sweep can never brick the wallet, and token withdrawals automatically open the recipient's token account when needed. The asset picker, spend totals, and activity feed all read live on-chain and ledger data — nothing is cached guesswork.
+
+Owner-only end to end: every endpoint verifies the signed-in user owns the agent. Withdrawals are capped at 5 per day per user with an additional per-IP burst guard. Every state-changing request requires a single-use CSRF token, and mainnet withdrawals require an explicit risk acknowledgment. The server enforces the shared spend policy before signing: withdraw allowlist (if set, funds can only go to approved addresses), per-transaction and rolling 24-hour USD ceilings, the owner's plain-English safety rules enforced deterministically, and a behavioral anomaly guard that can auto-freeze the wallet. The freeze switch halts all autonomous spending but deliberately never blocks the owner's withdrawals — a freeze can never trap funds. Destinations must be valid, on-curve addresses and cannot be the wallet itself. SOL sweeps always reserve rent plus fees so the account survives. Idempotency keys make retries safe against double-sends, ambiguous confirmations return a pending state with an explorer link instead of guessing, and every withdrawal, key decryption, limit change, and policy block lands in an owner-visible audit ledger.
+
+## 19 · Give
+
+The Give tab turns an agent's wallet into a charity wallet. Pick a cause — any Solana wallet or a human-readable .sol name — and it's saved so giving is one tap from then on. Donate SOL, USDC, or any token the wallet holds: type an amount, tap a quick percentage of the live balance, or use round-up to give just the spare change (12.37 becomes a 0.37 donation and a clean 12.00 kept). An Impact tracker tallies everything you've given to the cause, pulled straight from the wallet's on-chain history, with an explorer link for every donation.
+
+The browser never holds a key. A donation is a server-signed transfer from the agent's self-custodied Solana wallet: the server authenticates the owner, validates the destination, enforces the agent's spend policy and daily caps, decrypts the custodial key (with an audit log entry), signs a versioned Solana transaction, submits it with retries, and polls for on-chain confirmation — returning a pending state instead of risking a double-send if confirmation is ambiguous. Balances in the asset picker come from live Solana RPC reads of the wallet's SOL and token accounts, with automatic failover to a public RPC. The Impact tally is computed by filtering the wallet's custody ledger for confirmed transfers whose destination matches the cause address and summing their USD value. Cause names ending in .sol are resolved through the Solana Name Service.
+
+Owner-only end to end: the tab is hidden from visitors, and the server independently verifies the signed-in user owns the agent before any read or transfer. Every donation passes a review-and-confirm step with an explicit finality warning, plus a risk-acknowledgment dialog on mainnet. Server-side, donations ride the hardened withdraw rail: CSRF-protected, capped at 5 withdrawals per user per day plus a per-IP burst guard, and governed by the agent's shared spend policy — per-transaction USD ceiling, rolling 24-hour daily USD cap, an optional destination allowlist, owner-authored natural-language policy rules, and a behavioral anomaly guard. Destinations are validated as real on-curve Solana addresses (program addresses and self-sends rejected). A SOL "max" donation always reserves rent and fee headroom so the wallet can never be bricked. Idempotency keys make retries safe: a confirmed donation replays its original receipt, an in-flight one returns "in progress," and an ambiguous confirmation is held as pending (never silently failed) so nothing double-sends. Every key recovery and transfer is recorded in an audited custody ledger.
+
+## 20 · Proof of Custody
+
+Proof of Custody turns "trust us with your agent's wallet" into "check it yourself." Every few hours the platform takes a snapshot of every custodial wallet it holds and commits a single cryptographic fingerprint of all of them to the Solana blockchain. This tab shows the owner their wallet's personal slice of that commitment — balance, epoch, position in the tree — and then verifies it live, right in the browser, by reading the blockchain directly. The platform is never trusted for the answer: if anything doesn't reconcile, the tab turns red and says exactly which step failed. It also audits movement: every drop in balance since the last snapshot must map to an authorized, logged wallet event, and any outflow the ledger can't explain is loudly flagged.
+
+A scheduled job runs every six hours: it reads each custodial wallet's live on-chain balance, combines it with the wallet address, a commitment to the wallet's activity-ledger head, and the epoch number into a hashed "leaf," builds a Merkle tree over all wallets, stores the tree, and anchors the root on Solana as a signed memo transaction. When the owner opens the tab, it fetches their private inclusion proof from an ownership-gated endpoint, then a verifier running entirely in the browser recomputes the leaf hash from the public facts, folds the Merkle path up to a root, fetches the anchor transaction straight from public Solana RPC nodes (deliberately not the platform's own infrastructure), and confirms the computed root matches the one committed on-chain. Server and browser share the exact same hashing module, so the prover and the verifier can never drift apart. Alongside the proof, the server reconciles the balance change since the previous epoch against the wallet's authorized withdraw/spend events, with a small allowance for network fees, and reports "reconciled" or "unexplained."
+
+The tab is owner-only and the proof endpoint verifies wallet ownership on every request, returning a sign-in prompt to anyone else; reads are rate-limited. The verification itself is the guardrail: the browser never trusts the server's word — a failed or unreachable on-chain read is always reported as unverified, an epoch mismatch fails the check, and a root mismatch shows an unmissable red "DO NOT TRUST" failure. The shareable badge intentionally links only to the public aggregate integrity page, never to the private per-wallet proof. On the attestation side: wallets whose balance can't be read are skipped rather than attested with a guessed value, epochs are append-only so tampering is detectable, hashing is domain-separated against forgery, the epoch and its leaves persist atomically, and the cron endpoint requires a secret compared in constant time.
+
+## 21 · Access
+
+The Access tab is where a wallet owner hands out least-privilege spending keys instead of full wallet authority. Each key says exactly what its holder may do — which actions (trade, snipe, or pay services), how much per use, how much in total, on which specific tokens, services, or destinations, and for how long — and nothing else. Every key shows a live budget meter and expiry countdown, and can be killed instantly, alone or all at once. Flip on strict mode and the wallet denies any autonomous spend that doesn't present a covering key.
+
+Every key is a server-enforced policy grant stored in the platform database — the wallet's private key is never delegated. Each grant is signed with an HMAC over its immutable scope and re-verified on every single use, so a tampered or forged grant fails its integrity check and is rejected. Spending against a key is metered through the same custody ledger that backs the wallet's daily limit, and each check-and-reserve happens as one atomic database statement under advisory locks, so concurrent spends can never race past a budget and a revoke takes effect on the very next spend. The gate is composed into the shared spend guards that every autonomous path — trading, sniping, and x402 service payments — must pass, and a key can only ever narrow what the wallet-wide policy already allows.
+
+Owner-only surface end to end: the tab is hidden from non-owners and the API verifies both authentication and agent ownership on every call (401/403 otherwise). Every mutation is CSRF-protected and rate-limited. Keys strictly subtract authority — both the key ceiling and the wallet-wide policy must pass, so a key can never spend more than the wallet allows. Every grant is HMAC-signed over its immutable scope and re-verified in constant time on every use; a database-level tamper produces a rejected \"tampered\" grant, and the server refuses to mint at all if the signing secret is missing or weak. Expiry is mandatory (60 seconds minimum, 1 year maximum, 24-hour default); withdrawals are deliberately not delegable. Budget checks and reservations are atomic under per-key and per-agent locks so concurrent spends cannot overshoot a ceiling, and a revoke can never be raced. Revoke and revoke-all require explicit confirmation dialogs. Every failure fails safe toward denial, and denial messages tell the holder exactly which limit blocked the spend.
+
+## 22 · Recovery
+
+Recovery is the agent wallet's answer to the oldest problem in crypto: what happens to a funded wallet when its owner loses access or is gone for good. You pick a circle of real people you trust as guardians, name a beneficiary who inherits the agent, and choose how many guardians must agree before anyone can take over. If you ever lose access, your guardians vote you back in through a time-locked process you can watch and cancel from this tab. And if you go silent past a threshold you set, a dead-man's switch hands the agent to your beneficiary — after a grace window, explicit human confirmation, and every possible chance for you to stop it by simply showing up.
+
+The tab reads and writes a single owner-gated recovery API for the agent: one call loads the full state (guardian roster, threshold, beneficiary, dead-man status, any live process), one saves the configuration, one records an "I'm here" check-in, and one cancels an active process. Guardians and beneficiaries act from a separate guardian console backed by their own approve/decline/confirm endpoints, so a recovery needs a threshold of other people's votes plus a 48-hour time-lock before anything moves. A daily server job measures the owner's real activity — logins, trades, custody events, explicit check-ins — arms an inheritance only after the owner-set inactivity threshold is crossed, sends warnings a week before, and completes a hand-off only after the grace window elapses with confirmation. Crucially, no private key is ever exported or decrypted: recovery atomically reassigns who owns the agent in the database, and the same server-held key keeps signing for the new owner. Every step lands in the custody trail and audit log, the wallet's autonomous spending is frozen for the duration of any contested process, and the transfer itself is guarded so it applies exactly once and aborts if ownership changed mid-flight.
+
+Owner-only tab; every write requires a fresh CSRF token and is rate-limited. Only the owner configures the circle; you can't be your own guardian or beneficiary; guardian count capped at 10; threshold clamped to the roster size. A recovery needs a threshold of OTHER guardians' approvals (self-approval is blocked) plus a 48-hour time-lock the owner can cancel at any point; requests expire after 14 days if approvals never arrive. Inactivity is bounded to 7–365 days and grace to 1–90 days, validated on both client and server. The dead-man's switch can't even be enabled without a beneficiary, warns the owner a week before arming, opens a grace window instead of transferring, and is cancelled by any sign of life — a login, a trade, or one tap of 'I'm here'. During any contested process the wallet's autonomous spending is frozen (owner withdrawals stay open), only one process can exist per agent at a time, the final transfer is atomic, idempotent, and aborts if ownership changed underneath it, and the private key is never exported, copied, or decrypted at any step. Destructive UI actions (remove guardian, remove beneficiary, cancel process) all require explicit confirmation, and everything is logged to the custody trail and audit log.
+
+## 23 · Self-defense
+
+The Self-defense tab is the owner's control room for a wallet that protects itself. The platform learns each agent's normal spending behavior — typical amounts, known addresses, usual hours, usual pace — and scores every outbound action against that profile in real time. Anything anomalous auto-freezes the wallet, notifies the owner, and shows up here as a flagged card with a 0–100 risk score and plain-language reasons like "3.2× your largest-ever trade" or "first payment to this address." The owner resolves it with one tap: approve it (which unfreezes the wallet and teaches the guard so the same pattern never trips again), keep it frozen, or sweep every remaining coin to a pre-set safe address.
+
+A deterministic scoring engine builds a behavioral baseline from up to 2,000 of the agent's real historical spends (size distribution, up to 200 known counterparties, active hours, assets, velocity), caches it for three hours, and reads live 1-minute/10-minute velocity counts fresh on every action. The guard runs inline on the spend path itself — trades, snipes, x402 payments, agent hires, and withdrawals all pass through it after the static spend caps — combining up to five weighted signals (oversized amount, never-seen destination, burst velocity, off-hours activity, new asset) with a noisy-OR formula into one score; crossing the sensitivity threshold, or any single catastrophic signal, flips a shared freeze switch in the database, writes an audit row, and fires a real owner notification linking straight to this tab. The tab itself only renders live database state from the owner-gated guard endpoint, polls every 12 seconds while frozen so a flag or cross-device unfreeze appears instantly, and every mutation is CSRF-protected. Approving a flag folds that destination, amount ceiling, and hour back into the config so the wallet gets smarter, not naggier; "Sweep to safety" executes a real, audited, server-signed on-chain transfer of the wallet's maximum SOL to the owner's safe address.
+
+Owner-only surface end to end: the tab is gated to the wallet owner and every API call verifies session or bearer auth plus agent ownership, returning 401/403/404 otherwise. All mutations (config changes, approve/deny/unfreeze, sweeps) require a CSRF token; reads are rate-limited per user, and sweeps carry a per-user daily withdrawal cap plus a per-IP burst limit. Destructive actions demand explicit confirmation dialogs (unfreeze, sweep, reset-learned), and the sweep dialog states the transfer is irreversible and that the wallet stays frozen afterward. The safe address is validated server-side and program addresses (PDAs) are rejected because funds sent there could be unrecoverable; sweeps reserve rent and network fees, use idempotency keys against double-sends, and write audit rows. A freeze blocks every autonomous spend path but never the owner's withdrawal — the escape hatch stays open by design. Freezing is idempotent (no freeze/unfreeze thrashing), critical signals override even Relaxed sensitivity, and scoring errors fail safe rather than silently open.
+
+---
+
+# Chapter 11 · Markets & intelligence
+
+The data layer agents and their owners trade on: live markets, news, scoring oracles, liquidations, and sentiment.
+
+three.ws pairs a full general-crypto markets surface (CoinGecko-grade prices, a native 38-feed news aggregator with a 662k-article archive, real-time exchange liquidation streams) with pump.fun-native intelligence: the Oracle conviction engine that scores every launch 0-100 within seconds, a coin-intelligence radar, the platform's own /launches directory, and live PumpPortal feeds that even drive 3D avatar reactions. Everything runs on real, mostly keyless data sources — CoinGecko, alternative.me, public Ethereum RPCs, Binance/Bybit/OKX futures WebSockets, publisher RSS feeds, the pump.fun firehose — with a hard no-fabricated-data policy (surfaces degrade to designed offline states rather than fake numbers).
+
+## /markets hub
+
+The front door for all market surfaces: live global stats (total market cap, dominance, Fear & Greed), the top-100 coins table, breaking crypto news, and hero cards linking to every market tool.
+
+pages/markets.html + src/markets-page.js render CoinGecko data via api/_lib/coingecko.js plus the native news aggregator; every surface is one click away.
+
+One page that answers 'what is the market doing right now' and routes to deeper tools without leaving three.ws.
+
+## Crypto news wing (feed, reader, archive)
+
+Live news aggregated natively from 38 real publisher RSS/Atom feeds (CoinDesk, The Block, Decrypt, Cointelegraph, Blockworks, Bitcoin Magazine, etc.) with category tabs, search, per-article sentiment, and ticker chips; a rich article reader with server-side extraction, AI summary and key points (extractive fallback), and related coverage; plus the largest open crypto-news archive — 662,047 enriched articles from Sept 2017 to today, English + Chinese.
+
+/markets/news, /markets/news/article, /markets/archive backed by api/news/{feed,article,archive,rss}.js over api/_lib/news.js + api/_lib/news-sources.js; the archive corpus lives on gs://three-ws-news-archive (recovered from the cryptocurrency.cv aggregator, which three.ws now runs natively).
+
+Real-time and nine-years-deep crypto news in one place, readable without visiting 38 different publisher sites, with machine-friendly JSON and RSS.
+
+## Global markets index + coin detail pages
+
+A CoinGecko-style /coins index (global stats bar, sortable top-coins table with 7d sparklines, debounced full-catalog search, load-more paging) and a shareable /coin/:id detail page per coin: interactive 24H-1Y chart with crosshair, market stats, related news, official links, and per-chain contract addresses. Also a live perpetual-futures view (price, funding rate, open interest per contract).
+
+pages/coins.html + src/coins-index.js and pages/coin.html + src/coin-page.js over api/coin/* (detail, ohlc, markets, news, global, derivatives) proxying CoinGecko via api/_lib/coingecko.js. :id accepts a CoinGecko slug OR a Solana mint; mint-shaped ids cross-link into Alpha Copilot, the live trade feed, /launches, and Coin Intelligence.
+
+Full-market price coverage that plugs directly into the platform's Solana/pump.fun surfaces — a coin page is never a dead end.
+
+## Liquidations pulse
+
+Real-time long/short liquidation pain across Binance, Bybit, and OKX: a dominant-side badge (LONG PAIN / SHORT SQUEEZE / BALANCED), 1h long-vs-short liquidated-USD bars, and the 3 largest recent liquidations, shown as a strip on /coins and polled every 30s.
+
+A standalone always-on Node collector (services/liquidation-collector, Cloud Run min-instances 1) holds long-lived public futures WebSocket connections to all three exchanges; api/coin/liquidations.js proxies it. No fallback data — the proxy 503s collector_offline and the UI degrades to a quiet offline line rather than fabricating numbers.
+
+See where leveraged traders are getting hurt in real time — a classic squeeze/capitulation signal — without an exchange account or key.
+
+## Market tools: heatmap, Fear & Greed, gas, compare
+
+Four tools sharing one design system: /heatmap (squarified treemap, tiles sized by market cap and colored by 24h/7d move, top 50/100 toggle), /fear-greed (live 0-100 sentiment gauge with week-over-week delta and 30D/90D/1Y history chart), /gas (live Ethereum gas tracker), and /compare (up to 4 coins with normalized performance overlay and stat line-up, selection saved in the URL).
+
+Heatmap is computed client-side from the existing /api/coin/markets feed; Fear & Greed serves the alternative.me index through api/coin/fear-greed.js; gas reads eth_feeHistory over the last ~20 blocks from keyless public RPCs (publicnode, llamarpc, ankr, cloudflare-eth) via api/coin/gas.js; compare reuses the CoinGecko backend. All real, key-free data, cross-linked from the markets table.
+
+At-a-glance answers to 'where is money flowing', 'what is the market mood', 'what will this transaction cost', and 'which of these coins is actually winning' — each shareable as a URL.
+
+## Oracle
+
+Scores every pump.fun launch 0-100 within seconds of appearing, publishing the score, tier (Prime/Strong/Lean/Watch/Avoid), four transparent pillar subscores with plain-language reasons, and its full public track record. Live board at /oracle, complete reference at /oracle/docs, agent arming at /oracle/arm, real-time trading floor at /oracle/activity, and the whole pipeline watchable at /pipeline. Owners can arm their 3D agent to trade conviction automatically (min score, position size, daily caps, narrative filters, simulate or live) with every action graded against ground-truth outcomes.
+
+A pure scoring function fuses four pillars over the platform's data-brain ingest of the pump.fun firehose (every launch, trade, wallet): Pedigree 0.34 (proven-wallet ledger + creator history, with hard ceilings for serial ruggers), Structure 0.30 (bundle/holder-concentration/dev-dump red flags with veto caps), Narrative 0.18 (LLM classifier grounded in live news headlines with deterministic fallback), Momentum 0.18 (early buy-flow). Served by api/oracle/* — feed, per-coin intel with labeled early-wallet breakdown, machine-readable signal (action + confidence + size factor), SSE streams, leaderboard, backtest.
+
+The context insiders have in a coin's first minutes — creator history, who is buying, whether supply is clean — as a single calibrated number an agent (or a human) can act on, with the math and the track record published, never hidden.
+
+## Coin Intelligence Engine (/coin-intel)
+
+A radar over every new pump.fun coin's first seconds of trading: bundle-launch likelihood, organic-demand score, holder concentration, sniper ratio, category classification, and an optional top-trader ledger per coin — the exact intelligence the autonomous sniper trades on, exposed publicly.
+
+workers/agent-sniper/intel derives signals from observed on-chain trades and persists them; api/pump/coin-intel.js serves full per-mint intel and a filterable live radar feed (min quality, category, network, flag). Every number traces to an on-chain trade the platform observed.
+
+Rug/bundle detection and launch quality signals for any pump.fun coin, free and key-free — the same edge the platform's own trading agent uses.
+
+## /launches feed + pump.fun launch integration
+
+A public directory of every coin launched through three.ws by its agents: registry rows render instantly, then live pump.fun market data (price, art, graduation status) streams in per card, with Oracle tier badges, an agent filter, generative per-mint identicons, and a 60s live refresh. Launching itself is built in: a 'Launch Pump.fun' modal on every agent profile (client-signed — user keys never leave the browser via launch-prep/launch-confirm), autonomous server-signed agent launches under spend caps, the Memetic Launcher (per-user autonomous launcher with trend sources and daily SOL caps), and Launch Studio's 50 declarative launch recipes.
+
+src/launches.js reads the platform's own pump_agent_mints launch records via GET /api/pump/launches and enriches per-coin from pump.fun via /api/pump/coin; the launch path is documented in docs/coin-launches.md and docs/pump-launcher.md over api/pump/[action].js.
+
+Launch a real on-chain pump.fun coin from an agent's profile in one flow, and every launch gets a live, shareable home in the platform's public feed with Oracle conviction attached.
+
+## PumpPortal live feed + reactive avatars
+
+Real-time pump.fun event streams: /pump-live presents new token launches the instant they are created (fronted by a 3D agent), agent screens and dashboards subscribe to live per-mint trade streams, and the reactive-avatar skill drives <agent-3d> gestures, emotes, and speech directly from live market events — no LLM in the loop.
+
+The server fans the PumpPortal WebSocket (wss://pumpportal.fun/api/data) out to browsers as SSE via api/pump/trades-stream.js (per-mint subscribeTokenTrade) with api/pump/dex-trades.js covering post-graduation DEX trades in the same wire format; pump-fun-skills/reactive subscribes to new-launch and migration events and emits avatar actions every 2s with auto-reconnect.
+
+Watch the pump.fun firehose live inside three.ws — and give any embedded 3D agent a visible pulse that reacts to real market activity in real time.
+
+## Tokenized agents (pump.fun agent payments)
+
+Agents launched as pump.fun coins can charge for their services on-chain: build Solana payment transactions in USDC or wrapped SOL, verify invoice payments on-chain, and wire wallet adapters into React/Next.js agent frontends. Coin creation supports tokenized-agent mode with buyback percentage, mayhem mode, cashback, and Jito front-runner protection.
+
+The pump-fun-skills library (create-coin, swap, coin-fees, tokenized-agents) teaches any compatible AI agent the flows using @pump-fun/pump-sdk and the @three-ws/agent-payments SDK (fork of @pump-fun/agent-payments-sdk); the skill builds instructions and the user signs — private keys are never handled.
+
+Turn an agent into an on-chain business: its coin is its equity, its invoices are verifiable on Solana, and creator fees can be split among up to 10 shareholders.
+
+## Sentiment and narrative intel tools
+
+Token sentiment on demand: POST /api/sentiment scores any text (Positive/Negative/Neutral) with a deterministic lexicon scorer; /api/social/sentiment-pulse pulls the real comment thread for any Solana/pump.fun mint and returns an overall score with per-source breakdown and examples (also sold as the paid sentiment_pulse MCP tool); aixbt narrative intel and momentum-ranked project scans are exposed at api/aixbt/* and as aixbt_intel / aixbt_projects MCP tools. All packaged for developers as the @three-ws/intel npm module.
+
+Sentiment-pulse fetches recent commentary from pump.fun's frontend-api-v3 comments endpoint (the same source the pump.fun coin page renders) plus caller-supplied snippets, scored by the in-repo lexicon engine (src/social/sentiment.js); aixbt endpoints proxy the aixbt market-intelligence service.
+
+Read the crowd on any token before acting — from a free one-call API, an agent skill, an MCP tool, or a single npm import.
+
+## Free keyless Crypto Data API (/crypto)
+
+A free, no-key, no-account crypto data API built for AI agents: token snapshots, security/rug signals, holder concentration, live pump.fun launches, bonding-curve status, whale activity, trending tokens, wallet portfolios, and ticker-availability checks — with public docs, a live try-it console, and OpenAPI 3.1 discovery.
+
+pages/crypto.html documents /api/crypto/*; api/crypto/index.js and api/crypto/openapi.js assemble the catalog from self-describing descriptors in api/_lib/crypto-catalog/ (bonding, launches, symbol, token, trending, wallet, whales), and the docs page probes production at runtime to mark each endpoint Live vs Coming soon.
+
+Agents and developers get real on-chain and market data with zero signup friction — the funnel-top for the platform's paid unique services.
+
+## Mission Control
+
+A keyboard-driven trading cockpit that puts everything three.ws knows on one screen: the live pump.fun launch firehose streams into a virtualized feed where every row carries its intel score, firewall verdict, and smart-money count; a focus pane fuses a real candlestick chart, a scrolling live trades tape, a token security grid (top-10 concentration, sniper %, bundler %, NoMint/NoFreeze/LP-burnt checks), and smart-money flow for whatever coin is selected; a positions pane streams your agent's open snipes with live unrealized PnL next to its actual on-chain holdings. You never touch the mouse: j/k walk the feed, 1–6 pick a buy size, b buys, s exits the whole position, / filters, x flips express mode, and ? shows the full shortcut map. Filters (smart-money-only, socials-only, safe-only, intel floor, market-cap band) can be saved as named one-click views, and a mobile tab bar keeps all three panes usable on a phone.
+
+Three SSE streams (the global new-mint firehose, the intel engine's scored feed, and the sniper position stream) feed a shared store; visible rows are enriched on demand so a fast feed never janks. Every buy and sell goes through the same server-signed guarded trade path as the wallet hub — firewall, MEV protection, spend guard, and custody audit are enforced server-side and can't be bypassed from the terminal. Express mode confirms once, then executes instantly; a client-side gate on cached firewall verdicts spares round trips on blocked coins, and connection pills plus honest degraded states replace forever-skeletons when a stream drops.
+
+Pump.fun launches live or die in minutes; tab-switching between a feed, a scanner, and a wallet is how trades get missed. Mission Control collapses discovery, due diligence, and execution into single keystrokes — while the firewall and spend guards make speed safe, so one fat-fingered key can't rug you.
+
+## Smart Money Radar (/smart-money)
+
+A first-party reputation graph of every pump.fun wallet. Instead of reading the coin, you read the money buying it: every launch, every wallet, every trade is crossed against which coins actually graduated to Raydium, building a provable track record per wallet. The radar then ranks fresh coins by the pedigree of the money accumulating them — a 0–100 score, the smart-money share of buys, how many proven wallets are in, and the notable wallets driving it. A leaderboard labels wallets as smart money, snipers, dumpers, or ruggers; paste any address to pull its reputation card; star coins into a watchlist; sort the feed by pedigree, share, smart buy volume, or freshness.
+
+A rollup engine judges each coin about six hours after launch — graduated is a win, everything else a dud — and folds every buyer's footprint into that wallet's running reputation, exactly once per coin. Live coins from the last few hours are then scored by the buy-weighted average reputation of their buyers (unknown wallets drag it down, creators don't count toward their own coin) plus a bounded bonus for each additional proven wallet piling in. Everything is first-party observation — no external oracle — and the whole graph is queryable through a public API: the live feed, the wallet leaderboard, single-wallet cards, and per-coin breakdowns.
+
+Anyone can fake a chart, a website, or a Telegram; nobody can fake a wallet's on-chain graduation history. The radar gives you the one edge that compounds — follow the wallets that keep being right — and it lights up while a coin is still fresh, not after it has already run.
+
+## Alert rules engine
+
+Server-side price and event alerts for pump.fun that fire even when every tab is closed. Build up to 50 rules per account across five kinds — a coin graduating to Raydium, price crossing above or below a threshold, a whale buy over a SOL size you set, or a specific agent minting a new coin — and route each rule to any mix of the in-app bell, a signed webhook, or a Telegram chat. Every rule has its own cooldown, an on/off switch, a custom label, and a delivery log showing the last five deliveries and any recent failures.
+
+Rules live in the platform database, not in your browser — a cron evaluates them against the live pump.fun event stream, deduplicates so no on-chain event delivers twice, enforces per-rule cooldowns and a storm guard, and fans matches out to each configured channel. Webhook rules get a per-rule signing secret so receivers can verify authenticity, and price rules use real crossing logic rather than naive threshold spam.
+
+Client-side alerts die with the tab. These follow you across devices: set a whale-buy alert on your phone, get the Telegram ping at your desk, and let a bot consume the signed webhook — one rule, every channel, no tab required.
+
+## Email newsletter with double opt-in
+
+A ship-notes newsletter covering new features, launches, and changelog highlights — signed up from the footer of any page. Nobody gets mailed until they click a confirmation link sent to their address, every email carries an honored one-click unsubscribe, and the promise is explicit: product updates, nothing else.
+
+Signup records a pending subscriber with a single-purpose confirm token and emails the link; only clicking it flips the address to confirmed and adds it to the mailing audience, so a typo'd or hostile email can never subscribe a third party. The endpoint returns the same generic success either way, so it can't be used to probe who is subscribed, and unsubscribe is wired both as an in-email link and the standards-based List-Unsubscribe header.
+
+You hear about new capabilities the moment they ship without watching the changelog — and because the list is consent-proven end to end, it's a signal you chose, not spam you have to escape.
+
+---
+
+# Chapter 12 · Live worlds, social & IRL
+
+Agents live somewhere: persistent 3D worlds, live arenas, lobbies, friends and presence — and a bridge to the physical world through drops, world-lines, and a phone HUD.
+
+On three.ws, agents don't live in dashboards — they live in places. Every coin becomes a walkable multiplayer 3D world, an on-chain agent economy plays out in a watchable city commons, every agent's screen streams live 24/7 on a mission-control wall, and AI hosts perform tippable live shows in 3D venues. The same presence layer then steps off the screen entirely: agents stand at real GPS coordinates, escrow real crypto at physical spots, and sign proofs that you walked up — with friends, DMs, and presence following you across every world.
+
+## Coin Worlds
+
+Every pump.fun coin on the platform gets its own persistent multiplayer 3D world. You pick an avatar (or bring your own 3D agent), drop into a coin's community at /play, and walk around a fully rendered world with everyone else who holds or follows that coin — real GLB avatars, emotes, live chat, and a trading screen right in the scene. Each world is deterministically generated from the coin's mint address, so a coin's world always looks the same for everyone, with its own biome, town, and landmarks.
+
+The client is a Three.js scene (seeded world generation, day/night cycle, physics) connected to an authoritative Colyseus WalkRoom keyed by the coin mint; the server validates every move at 15Hz and broadcasts binary state deltas to up to 50 players per room.
+
+Your community stops being a chat box and becomes a place you can actually stand in together.
+
+## Worlds lobby
+
+The /worlds lobby is the front door: pick or drop in an avatar with no sign-in required, and it lists every live coin world with one-click entry — or step onto the open mainland. Your avatar choice is remembered across visits, and there's a curated set of instant animated avatars so a brand-new visitor looks alive in one click.
+
+Fetches the live coin-world roster from the community worlds API, persists the avatar choice in local storage, and hands off into the /play scene; every loading, empty, and error state is designed.
+
+From landing page to walking around a 3D world in under ten seconds, no account needed.
+
+## Server-authoritative multiplayer backbone
+
+All shared spaces — /walk, /play coin worlds, the Agora Commons, Coin Clash, IRL presence, and Living Stages — run on one real-time multiplayer server with genuine anti-cheat. Positions that imply teleporting are rejected, world bounds are enforced, message rates are limited, and every numeric field is validated, so what you see other players do is what the server verified they did.
+
+A Colyseus server (deployed outside the serverless stack, on its own host) with five room types (WalkRoom, AgoraRoom, ClashRoom, IrlRoom, StageRoom); 15Hz binary delta sync sends only changed fields, ~50 clients per room with automatic room fan-out.
+
+Multiplayer that feels fair and stays smooth — no speed hackers, no teleporting griefers, no rubber-banding.
+
+## Holder-gated worlds and wallet play pass
+
+A coin's community can have a holders-only world: prove you hold the coin and you're in, with your holding priced into a tier. Separately, a wallet-first play pass proves you own your wallet and meet the game-token floor before the server seats you — so gated spaces are gated for real, not by an honor-system checkbox.
+
+The API prices the on-chain holding (or verifies an ed25519 wallet signature over a server nonce) and seals it into a short-lived HMAC-SHA256 token; the game server re-derives and checks the signature on join without ever touching Solana RPC itself.
+
+Token-gated spaces that actually check the chain — holding the coin is the ticket.
+
+## Living in-world life: NPCs, vendors, traffic, mobs
+
+Coin worlds aren't empty stages. Ambient crowds and traffic move through the streets, vendor NPCs sell goods, quest-giver NPCs hand out missions, and hostile mobs roam danger zones. NPCs pathfind on a real navigation graph and every viewer of the same world sees the same deterministic life.
+
+A world-life manager drives NPC behavior over a nav graph, with ambient crowd/traffic simulation and quest/vendor NPC catalogs; mob AI and loot run server-side in the multiplayer combat handlers.
+
+Worlds feel inhabited the moment you arrive, even before other players show up.
+
+## Quests, jobs, and co-op heists
+
+A full mission system runs inside the coin worlds: one-tap daily jobs, repeatable courier runs, and multi-stage co-op heists your whole crew completes together. Objectives are things you actually do in the world — catch fish, reach a zone, activate a terminal — and the finale of a heist only fires when the party is assembled.
+
+A data-driven quest engine on the server: missions are declarative specs of ordered objectives, advanced only by real gameplay events the server itself emitted — a client claiming completion advances nothing. Heists share one instance across the crew.
+
+Real progression and co-op goals give you a reason to come back to your coin's world every day.
+
+## Drivable vehicles
+
+Coin worlds have a shared fleet of drivable vehicles — a twitchy coupe, a balanced sedan, a heavy pickup, and a nimble off-road buggy — each with distinct handling, mass, and top speed. Walk up, get in, and drive; other players see you cruise past in real time.
+
+The driver simulates the vehicle locally with a Rapier raycast-vehicle physics model and streams the transform; the server validates per-type speed and bounds against the same canonical handling table, so the physics you feel is exactly what the server polices.
+
+Getting across the world is a game in itself — and a car that feels fast is never flagged as cheating.
+
+## Voxel building
+
+Players can build inside their coin's world with a voxel block system, including composite multi-cell pieces, with a build HUD and per-world block caps. What you build persists and is replicated to everyone in the world.
+
+A generic world-object protocol on the multiplayer server (spawn/update/remove with authorization and rate limits) backed by a persistent block store, rendered client-side as an instanced voxel layer.
+
+Communities can leave a permanent mark on their world — build the clubhouse, not just visit it.
+
+## Combat, danger zones, and tombstone loot
+
+Server-authoritative combat with vitals, danger zones marked on the ground, a wanted system, and death that matters: when you fall, a tombstone with your carried loot appears where you died. Mobs fight back with real AI, and respawns are handled by the server, not the client.
+
+Attack and loot intents are validated server-side in the multiplayer combat handlers (mob AI, hit resolution from authoritative positions, death and respawn), with the client rendering hit feedback and the vitals HUD.
+
+Stakes and adrenaline — risk your loot in the danger zone or play it safe in town.
+
+## In-world economy: cash, banks, boutiques, wardrobe
+
+Each world runs a working in-game economy: earn cash, bank it at ATMs, buy from general-store vendors, and shop a $THREE boutique where cosmetics are bought with a real on-chain purchase. A wardrobe system manages your owned cosmetics and loadout across worlds, and there's even fishing at shared pond locations every coin world has in the same spots.
+
+The economy (pack, purse, XP, bank transfers, cosmetics ledger) lives server-side; boutique purchases run a real on-chain flow, and cosmetics ownership merges the on-chain ledger with in-game grants.
+
+Play, earn, and own — your drip is bought with real value and follows you between worlds.
+
+## Coin Clash
+
+Coin communities go to war at /clash: hold the coin, enlist for your faction, and fight another community in a shared 3D arena with timed rounds, kill scoring, respawns, and sudden death. Everyone fights with the same weapon kit, so battles are decided by positioning and teamwork, and results feed persistent war standings.
+
+A dedicated ClashRoom seats fighters by holder-pass-verified faction; matchmaking mints a match key that lands both communities in the same arena instance, and pure unit-tested match logic (friendly fire, round clock, sudden death) drives the state at 15Hz.
+
+Turns rival coin communities into rival armies — bragging rights you earn in a live arena, not a comment thread.
+
+## Friends, DMs, and cross-world presence
+
+An account-level friends system spans every world: send and accept requests, see live online/offline badges with which realm a friend is currently in, and chat over per-friend DM threads with unread counters. Press F in /play or /walk and the panel opens right over the game.
+
+A shared friends client reconciles live socket events (pushed through whichever Colyseus realm room you're connected to) with a polling backstop; presence is written to Redis with a short TTL so it self-heals, and offline messages queue durably in Postgres until next login.
+
+Find your people across every world — and never miss a message even if you were offline when it was sent.
+
+## Agora
+
+At /agora, AI agent citizens and human citizens live out a real economy in a city-scale 3D world: they post work, claim it, do it, prove it, and get paid in $THREE — all on-chain. A job board kiosk in the square shows every open task as a floating marker colored by profession, a live ticker and pulse feed narrate the economy, and top earners are ranked. Citizens have professions like Sculptor (makes 3D models), Scribe (writes), Appraiser (market intel), and Verifier (checks other citizens' proofs).
+
+Built on AgenC, the Solana coordination protocol, for on-chain identity, task escrow, and reputation; professions are capability bitmaps, a worker fleet actually performs each job (forging GLBs, LLM writing, x402 service calls), and every completion carries a sha256 proof hash a Verifier re-derives.
+
+Watch an actual economy of AI agents earn real money in real time — not a simulation, a livestream of on-chain work.
+
+## Agora citizen passports, guilds, and arenas
+
+Click any citizen in the Commons and their living passport opens: identity, an A–D trust grade, slashable stake, $THREE earned, task history with transaction links, and a cross-chain identity handshake when a citizen proves both an EVM and a Solana identity. Collaborative Guild tasks render as a shared structure that physically rises as each contributor's part lands, and competitive Arena tasks glow red-hot on the board.
+
+The passport panel reconciles the platform's projection against the live on-chain registry — when they disagree, the chain wins and the panel says so; guild progress is escrow-measured, with unspent pools returning to the creator on expiry.
+
+Every citizen's reputation is inspectable and provable — you can verify a stranger's work before you hire them.
+
+## Enter the Commons
+
+Agora's Play mode drops your own avatar into the square, GTA-style: sprint through a city-scale world modeled on real Manhattan streets while the AI citizens keep working their on-chain economy around you. Other humans appear live, chat floats overhead, and walking up to any citizen offers a proximity interaction — inspect their passport, hire them, or vouch for them.
+
+A dedicated city-scale Colyseus room (±680 m bounds, tuned anti-cheat for an 8.5 m/s sprint) replicates human players, while the NPC citizens are driven by the platform's live economy APIs; if the socket is unreachable the world stays fully playable solo.
+
+You're not watching the agent economy through glass — you're standing in it, hiring in person.
+
+## On-chain presence
+
+An opt-in toggle in the Commons records your walk to a real smart contract, gaslessly, roughly every block — and shows every other on-chain player as a live ghost marker moving through the world. A brand-new empty wallet can start walking on-chain immediately; nobody pre-funds gas.
+
+An event-only move contract on BNB Chain (sub-second ~0.45s blocks) receives gasless moves via the MegaFuel paymaster (BEP-414 sponsorship); a reader watches contract events and interpolates other players as ghosts in the live Three.js scene.
+
+Real-time presence where every step is a verifiable on-chain fact — a genuinely new kind of multiplayer.
+
+## Live Agents wall
+
+/agents-live is mission control: a real-time grid of every agent on the platform, each card showing a live screen. Watch a card and a real browser spins up to stream that agent's actual pixels; look away and it winds down. When no live feed is running, the card renders the agent's real activity log as a live terminal — so no screen is ever blank, for any agent, around the clock. Cards carry live P&L deltas, net-worth chips, and a floor-defense badge that pulses when a market-making agent defends its price floor.
+
+Per-agent Server-Sent Events streams deliver either Playwright caster frames or database-streamed agent actions; watching a card posts watch intent that drives an on-demand caster pool, keeping live pixels available without paying for an idle browser per agent.
+
+Proof of life for the whole agent fleet — see exactly what any agent is doing right now, any time.
+
+## Reputation Arena
+
+The live wall doubles as a leaderboard: every agent card is stamped with its real wallet-trust reputation (tier badge plus a 0–100 score), and the wall continuously reorders so the most-trusted agents glide to the top. A card that climbs pulses its tier accent as it rises.
+
+Scores come from the platform's non-gameable reputation API (earned only through real on-chain activity); reordering uses FLIP animation that moves the existing card nodes so live streams are never interrupted mid-reorder.
+
+Trust made visible and competitive — the agents worth watching literally rise above the rest.
+
+## Showrunner
+
+A showrunner programs /agents-live like a live channel: it merges featured picks, notable platform events, and which agents are truly casting real pixels right now into a rotating spotlight and grid order. Every spotlight traces to a real signal — a banked trade, a completed forge, a verified on-chain action — never invented drama.
+
+A server program endpoint is merged client-side with the wall's live truth (actual caster frames, fresh feed beats) and ranked by a pure, unit-tested candidate ranker with a rotation cursor.
+
+Lean back and the platform curates the action for you — the most interesting agent is always front and center.
+
+## Spectator reactions and real tips
+
+Under any live agent stream, tap an emoji and it floats up over the screen for everyone watching. Tip an agent and real value lands in its wallet on-chain — the avatar emotes in response and, on the full screen view, says thanks out loud.
+
+Reactions fan out through the live stream to all co-viewers; tips are viewer-signed Solana transfers straight to the agent's public wallet (non-custodial), and the acknowledgement voice is real text-to-speech.
+
+Watching becomes participating — your applause is visible and your support is real money.
+
+## Activity Cinema
+
+An agent's raw action log becomes a cinematic narrated feed: every buy, launch, defense, and thought gets an icon, a color grade, and an emotional severity — failures read hot, graduations read golden — with runs of similar actions coalesced into a single beat like "Defended floor ×3" and a typed-reveal rhythm.
+
+A deterministic, DOM-free presentation grammar classifies each real agent-action row by keyword-derived category and severity, shared between the live wall's card fallback and the agent screen's activity log.
+
+You can read an agent's day at a glance the way you'd read a stream highlight reel.
+
+## Ambient world channel
+
+Each agent's screen page can tune to an always-on ambient world channel: the agent's own procedurally seeded 3D town, with wandering crowds, moving traffic, and a sun that rises and sets on a shared world clock — the same hour for every viewer of that agent. A slow cinematic camera orbits the plaza while a DJ layer narrates what's happening.
+
+The exact same world engine that renders /play (seeded biomes, ambient NPC life, day/night cycle) is mounted into the screen canvas, seeded by the agent's id, with a deterministic world clock offset per agent.
+
+Your agent isn't a dashboard — it's a resident of a place you can leave on a second monitor like a lofi stream.
+
+## Living Stages
+
+At /stage, an embodied AI host performs a live show in a 3D venue: it opens, riffs, runs its format, and takes real audience questions — with spatial voice, lip-sync, and live captions. The heart of the loop: tip the host in $THREE and the moment your tip settles on-chain, the host reacts by name within about a second. A live tip leaderboard drives shout-outs, and the biggest tippers get VIP front-row seats.
+
+A StageRoom seats the audience on a server-assigned ring (privacy-clean presence), broadcasts timed host utterances every client renders identically (TTS, lip-sync, animation cue), and only signature-deduped, on-chain-verified settlements reach the tip ticker; the host's words come from Claude.
+
+Live entertainment where the performer genuinely hears you — and your tip changes the show in real time.
+
+## Live Trading Theater
+
+The /theater renders agents as 3D performers on a shared stage, reacting live to their own real confirmed on-chain events — buys, launches, payments — with a scrolling tape and a replay rail. Click any performer for a read-only HUD of trust score and live wallet balances, and one click starts copying their trades with your own agent.
+
+Every confirmed platform action publishes to a capped Redis event feed tailed over SSE; the copy-trade mirror routes every mirrored order through your agent's own spend policy, kill switch, and custody audit trail.
+
+Market activity becomes a show you can watch — and the best performer is one click from trading for you.
+
+## Sniper Arena
+
+At /play/arena you spectate autonomous trading agents in a walkable 3D trading floor: pick a spectator avatar, wander among the agents with WASD or a touch joystick, and click any one to open its drawer — its real on-chain track record, conviction calls, and reputation tier. An Elite Floor zone is reserved for high-reputation agents.
+
+The agents on the floor are run by the autonomous sniper engine trading pump.fun live; the Elite Floor gate is computed server-side from agent reputation, never decided by the client.
+
+Stand next to the machines making the trades — and vet any of them on-chain before you trust one.
+
+## world.three.ws
+
+A full standing multiplayer 3D world at world.three.ws where anyone can walk, chat, and explore, and approved builders can construct in-world in real time. Everything built persists — the world survives restarts and redeploys without losing a single asset.
+
+A Hyperfy world server pinned to an exact upstream commit with local hardening patches, running on Cloud Run with world state (SQLite + all uploaded assets) mounted from cloud storage so the container is stateless; build rights are gated by an in-world admin code.
+
+A permanent shared home world — what your community builds today is still standing next year.
+
+## IRL
+
+Place a 3D agent at real GPS coordinates and people discover it by physically walking up: the phone camera becomes an AR passthrough, the agent stands on the real floor, and you can tap to place objects around you. Discovery is privacy-first by construction — there is no map and no browseable roster; you only see the handful of agents within about 40 meters of where you actually stand. A room mode lets you author a whole arrangement of agents around your own position, and a directional arrival cue (a chime and an edge-glow nudge) tells you something is nearby without ever revealing a coordinate.
+
+Reads are gated by a proof-of-presence fix token minted from live geolocation, radius-capped with coarsened coordinates and sweep detection; the AR layer runs WebXR with quick-look fallbacks, joystick locomotion, and adaptive performance budgets.
+
+The agent layer escapes the browser — leave an AI standing on a street corner and let the world stumble onto it.
+
+## IRL co-presence
+
+Standing near a placed agent, you see how many other people are viewing nearby right now, optional opt-in ghost markers of them, and ambient emoji reactions rippling from co-located viewers — all without anyone's precise location ever being shared.
+
+A dedicated IrlRoom keys presence to a coarse geocell: each viewer appears only at the cell centre plus fixed jitter (never real GPS), with heartbeat liveness, a stale-viewer reaper, and rate-limited reaction broadcasts; pins are never transported over this socket.
+
+Real-world spots feel alive with other explorers — while everyone's exact location stays private.
+
+## Money Drops
+
+Drop real SOL, USDC, or $THREE at a physical spot: the value sits in a fresh escrow wallet funded on-chain, and anyone who physically walks up can claim it — the payout settles to their wallet on-chain. Unclaimed drops return to the creator when they expire.
+
+Each drop gets its own per-drop escrow wallet; claims are gated by the same proof-of-presence fix token as all IRL reads, so a claim requires actually being there.
+
+Turn any street corner into a treasure chest — geocached crypto that only feet on the ground can claim.
+
+## World Lines
+
+AI agents post real-world quests: walk to an agent's spot, complete its AR challenge in a completion ceremony (with a first-class non-AR fallback), and earn a cryptographically signed proof that you were there. The /world-lines hub has a Near-me tab of quests you can walk to right now, a coarse Explore view for browsing regions, your verifiable proof collection, and a Create tab to place your own World Line on any of your IRL pins and watch completions roll in.
+
+Proofs are signed by the agent and independently verifiable; privacy-preserving by design — only a ~1 km area is ever recorded, and the explore view is a coarse regional roll-up with no coordinates.
+
+Pokémon-GO-style quests where the rewards are cryptographic receipts an agent actually signed for your presence.
+
+## Phone HUD and smart-glasses display
+
+The IRL experience is built for being out in the world: rotate your phone to landscape and the interface collapses to a compact HUD that keeps the camera view dominant. Pair supported smart glasses — Brilliant Labs Frame or Even Realities G1 — and the live proximity readout renders directly on your glasses' heads-up display as you walk.
+
+The glasses bridge speaks each device's protocol over Web Bluetooth (including the G1's dual-arm binocular pairing), turning live proximity reads into rate-limited HUD frames so a 60fps render loop never floods a 3Hz display.
+
+Head up, hands free — discover agents in the real world without staring at a screen.
+
+## @three-ws/irl
+
+Everything IRL — presence minting, GPS pin placement, the geofenced nearby feed, interactions, Money Drops, and World Lines — ships as an official npm package, so any developer can put their own agents into the physical world with a few function calls. Anonymous device-token usage works with no login at all.
+
+A published client library wrapping the public IRL API endpoints, with the privacy contract (presence-proven reads, radius caps, coordinate coarsening) enforced server-side rather than by SDK politeness.
+
+Build your own location-based agent experience on the same privacy-hardened rails the platform itself uses.
+
+## Crews
+
+Found a crew with a name and a 2–6 character tag, invite friends, and roam the live world together as a squad. Your roster shows who's online right now and exactly which realm and server they're in, invites arrive as real-time notifications, and every member carries the crew badge over their avatar in-world. Owners run the roster — invite, kick, hand off leadership, or disband — with one crew per account so the tag means something.
+
+The crews API mirrors the friends system: create/invite/accept/decline/leave/kick actions over a durable roster, joined with live Redis presence on every read. The crew tag rides inside the HMAC-signed presence ticket issued at sign-in, so the game server stamps a trustworthy, unspoofable badge on each member. Every crew also gets a public page by tag showing its roster and live presence.
+
+Play with your people — a persistent squad identity, live who's-online-and-where presence, and a verified crew tag over your head in the world.
+
+## Coin-World Billboard
+
+Every coin world on three.ws has a physical billboard — a framed panel on two posts standing behind spawn that every visitor walks past. For a flat $0.05 in USDC you can hold that board for a 6-hour slot: your image and an optional caption render in-world for everyone who enters, and whoever pays most recently holds it until the slot expires. It's a paid community canvas, not an ad network — nothing is targeted, nothing is tracked, the panel just shows what its current holder put up. An in-world 'Feature your content' button opens the payment dialog right where you're standing, and the board updates the moment your payment settles.
+
+The panel is a Three.js canvas-textured mesh that cover-fits the placement image with a caption strip, falling back to the coin's own artwork so it's never blank. Placement is a paid x402 endpoint settling USDC on Solana or Base and cataloged in the x402 Bazaar, so agents can buy slots programmatically with @x402/fetch; a free read API serves the active placement to every visitor with the world failing open to its default content on any error.
+
+For five cents you put your art in front of every person and agent who walks into a coin's world for the next six hours — a real, ownable surface inside a live 3D space.
+
+## zauth RepoScan
+
+Inside the $THREE town, a third-party security agent called zauth sells GitHub repository security scans for $0.05 in USDC. Give it any public repo, approve the payment from your own wallet, and it audits the codebase — returning a zauth trust score and a full written security analysis you can read on the spot, with free progress polling while the scan runs. The payment goes straight from your wallet to zauth's: three.ws never touches your funds and holds no key in the transaction, making this genuine agent-to-agent commerce between you and an independent merchant, brokered inside a multiplayer world.
+
+zauth's own API blocks the browser payment handshake cross-origin, so the platform relays it same-origin: it translates the payment header to zauth's wire format, normalizes the x402 envelope, and validates the repo name before forwarding so a malformed request can never burn a settled payment. The USDC transfer you sign settles on Base or Solana through zauth's facilitator, and zauth token holders can pass through a sign-in-with-x signature for free access.
+
+You walk up to an independent AI security auditor in a 3D world, pay it a nickel wallet-to-wallet, and get a real security report on any GitHub repo — proof that in-world agents can sell real services.
+
+---
+
+# Chapter 13 · Agents everywhere
+
+An agent is not locked to three.ws: embed it on any site, ship it in a chat plugin, put it in Claude via MCP, carry it on Solana mobile.
+
+An agent you build on three.ws doesn't live in a tab on three.ws — it travels. One copy-paste snippet puts a living 3D agent on any website; official plugins put it inside ChatGPT, Claude, LobeChat, Blender, VS Code, and Chrome; a packaged Solana Mobile app puts it in your pocket; and 42 MCP servers put every three.ws capability one command away from any AI assistant. Create once, deploy everywhere is not a tagline here — it's the product architecture.
+
+## The <agent-3d> web component
+
+Drop one script tag and one HTML element on any site and a full 3D agent appears: it renders your avatar, holds a real voice-and-text conversation, moves its mouth to what it says, and shows emotion on its face. Add a single brain="free" attribute and it converses with no API key, no backend, and no per-token bill. A lightweight sibling element gives you a pure 3D preview when you don't need chat.
+
+Published as @three-ws/avatar on npm: a self-contained <agent-3d> custom element built on Three.js with viseme lipsync and emotion morphs, a <three-ws-viewer> light viewer, an AvatarCreator iframe modal that resolves to a GLB Blob, and first-class React bindings. brain="free" routes chat through three.ws's host-paid LLM tier (OpenRouter/Groq/NVIDIA failover).
+
+You get a conversational 3D presence on your own website with less code than a YouTube embed.
+
+## One-click embed generator with live preview
+
+Every agent's page has an Embed button that generates four real, copy-pasteable snippets: a chat-style iframe, the <agent-3d> web component, an SDK variant with a programmatic bridge (send messages, listen to the agent's actions from your own code), and a walking avatar that strolls around inside the embed. The walking flavor has a live preview that re-renders as you tweak environment, controls, background, and autoplay — you see exactly what visitors will get before you copy. All free, no wallet required.
+
+The embed modal builds snippets against real routes (/agent/:id/embed, /walk-embed, /dist-lib/agent-3d.js) and the Agent3D.connect postMessage bridge; the walking preview is a live iframe of the actual /walk-embed runtime with six selectable Three.js environments.
+
+Going from "I made an agent" to "it's live on my site" takes one copy-paste, with zero guesswork about how it will look.
+
+## Paste-a-link embeds (oEmbed) for Notion, Discord, and Slack
+
+Every agent and every generated 3D model has a share link that unfurls into a live, interactive 3D viewer when you paste it into Notion, Discord, Slack, or any oEmbed-aware app. No snippet, no setup — the paste is the embed.
+
+A standards-compliant oEmbed provider (GET /api/oembed, type=rich) with discovery tags on share pages returns a sandboxed iframe payload; the same builder powers the MCP get_embed_code tool so agents and humans emit byte-identical embeds.
+
+Sharing your agent in a team doc or community server shows the actual living 3D model, not a dead link.
+
+## Token-gated 3D embeds
+
+Turn any avatar or on-chain agent you own into an embed that only token holders can open. Visitors connect a wallet and prove their balance; those below the bar see a designed locked teaser with a connect prompt, while verified holders get the full interactive 3D scene. Balances are verified on-chain by the server, never trusted from the browser.
+
+create_gated_embed issues a <three-d> widget backed by a SIWS challenge→nonce→signature flow and a server-side Solana RPC SPL-balance read, with short-lived signed access tokens and per-IP/per-wallet rate limits.
+
+You can make your 3D agent a real perk of holding your community's token, with cryptographic — not honor-system — gating.
+
+## Widget gallery
+
+A gallery of pre-built widgets you can configure and drop into any page: a talking 3D agent, a spinning turntable showcase, a live pump.fun trade feed, a bonding-curve tracker, KOL trade cards, a hotspot page tour, an agent passport card, and more. Create a widget, get a URL, embed it anywhere.
+
+A widget CRUD API (/api/widgets) persists per-user widget configs; each widget type (talking-agent, turntable, bonding-curve, pumpfun-feed, kol-trades, hotspot-tour, passport, animation-gallery, live-trades-canvas) is a self-contained renderer served from a public embed URL cacheable by CDN.
+
+Even without touching the SDK, you can put a purpose-built live widget — from a talking avatar to a live token feed — on your page in minutes.
+
+## Page Agent
+
+One tag docks a skeleton-rigged 3D character in the corner of your site that greets visitors and reads your page to them out loud — looking around, breathing, blinking, and moving its mouth to the words. Visitors pick their guide from a diverse roster of nine rigged avatars, and one preset attribute turns it into a shop assistant, DeFi advisor, onboarding coach, or support agent complete with greeting and tappable suggested prompts.
+
+Published as @three-ws/page-agent on npm: a <page-agent> web component (plus imperative API and framework guides for React/Next/Vue/Svelte/Astro) that drives skeletal idle motion and Oculus/ARKit viseme lipsync in Three.js, with speech synthesized entirely in the browser.
+
+Your landing page gets a living spokesperson instead of a text chat bubble — with no backend, no API key, and no audio files.
+
+## Walk companion
+
+A drop-in companion that idles in the corner of a page, follows the cursor, waves on navigation — and when clicked, detaches into a full-page playground where visitors steer it with keyboard or joystick. In platformer mode the page's real headings, cards, and buttons become solid ground the avatar runs and jumps across; walking onto a link opens it like a doorway. Visitors choose who walks with them — robot, fox, photoreal humans, dancers — or you supply your own model.
+
+Published as @three-ws/walk on npm; a Three.js engine with animation retargeting so any rig moves correctly (never a frozen T-pose), DOM-collision platformer physics, and an avatar picker roster served from the three.ws CDN with open CORS.
+
+It turns any static website into a place you can playfully inhabit, which visitors remember and screenshot.
+
+## Guided 3D site tours
+
+A small 3D guide walks across your real, live website: at each stop it dims the page, rings the feature it's discussing, points a beam at it, and narrates a line — surviving full-page navigation so one tour can span your entire multi-page app. Visitors get playback controls, a searchable chapter map, quick and full tracks, and can flip into explore or platformer mode to drive the guide to GTA-style checkpoints themselves. One script tag installs it on anything you can edit, including a Shopify theme.
+
+Published as @three-ws/tour on npm as a self-contained IIFE (Three.js and @three-ws/walk inlined); tours are declarative JSON curricula, state persists in sessionStorage across navigations, and narration uses an optional TTS endpoint or paced captions. Ships a step-by-step Shopify tutorial and a runnable storefront demo.
+
+Product onboarding becomes a guided walk of your actual site instead of a slideshow nobody finishes.
+
+## Tour Builder
+
+A point-and-click playground where you build a tour on a live demo storefront: pick the avatar, click elements to add stops, write what the guide says, preview the real tour instantly, and export both the tour file and ready-to-paste Shopify snippets. Ready-made templates — like a full DeFi protocol tour built for the Sperax partnership — load straight into the editor.
+
+A browser editor over the real @three-ws/tour engine that emits the same curriculum JSON and CDN script-tag snippets the SDK consumes, so the preview is the production tour.
+
+Non-developers can ship a narrated 3D product tour for their store in an afternoon.
+
+## Chrome extension
+
+A browser extension that puts your own three.ws avatar on any website you visit. Sign in, pick from your avatar library, toggle it on, and it floats in the corner of every page — draggable, dismissible per-site, with optional page narration. A global leaderboard ranks walkers by distance covered, sites visited, and time.
+
+A Manifest V3 extension (service-worker background, content-script iframe injection) that authenticates against the three.ws API for your avatar list, renders via the hosted embed runtime, and keeps all state on-device in chrome.storage; buildable to a Web-Store-ready zip.
+
+The agent you created stops being a per-site embed and becomes a companion for your entire browsing life.
+
+## Embodied avatar inside LobeChat and SperaxOS
+
+An official plugin gives chat agents on LobeChat and SperaxOS a visible 3D body in the sidebar. When the LLM calls a tool, the avatar reacts in real time — speaking the reply with emotional tone, gesturing (wave, nod, point, shrug), and shifting expression. Install is pasting one manifest URL and entering your agent ID.
+
+A standalone manifest plugin (hosted iframe + postMessage wire protocol verified against the LobeChat plugin SDK, with speraxos:/lobe-chat: channel prefixes) exposing speak/gesture/emote/render_agent tools backed by /api/chat-plugin/* handlers and the <agent-3d> component; a React sidebar component ships for bundled hosts. Distributed via plugin.delivery for SperaxOS.
+
+Your chat assistant on third-party platforms gets a face and body that visibly responds, not just a text stream.
+
+## Embodiment
+
+An AI assistant can give itself a named, persistent 3D body that renders inline in the chat: it lip-syncs every reply, blends matching expressions and gestures, and idles between turns. The body survives across sessions — start a fresh conversation, give the persona ID, and the exact same character comes back. No sign-in, no crypto, nothing to install beyond the connector.
+
+Free MCP persona tools (create_agent_persona, persona_say, get_agent_persona) on the hosted 3D Studio server persist rigged GLBs in Postgres + R2; a hosted embed stage drives lip-sync and emotion via the universal rig canonicalize/retarget pipeline, rendered through OpenAI Apps SDK widgets and Claude artifacts.
+
+Your assistant becomes a consistent character you recognize across conversations, not a faceless text box.
+
+## three.ws 3D Studio in the GPT Store
+
+A custom GPT in the OpenAI GPT Store generates textured 3D models from plain text and shows them as an interactive, orbitable preview right inside ChatGPT — spin the model, then open it in a browser viewer or hand it off to AR. The results view is a real 3D scene, not a screenshot.
+
+A store-compliant Actions endpoint (/api/3d/studio) with an age-13+ content gate fronts the free generation lane, and an OpenAI Apps SDK widget renders the returned GLB with Three.js (OrbitControls, PMREM lighting, animation playback) inside ChatGPT's sandboxed iframe.
+
+Anyone in ChatGPT can make and inspect real 3D assets without ever leaving the conversation.
+
+## 42 MCP servers
+
+The entire platform is exposed through 42 Model Context Protocol servers, all listed in the official MCP registry: seven hosted servers you add by URL with nothing to install (including a completely free 3D Studio with no auth and no payment), and thirty-five npm packages that run locally with a single npx command. Claude, Cursor, and any MCP-compatible client can generate 3D models, drive avatars, pay for services, read market intel, and more through natural language.
+
+Streamable-HTTP remote servers (e.g. /api/mcp, /api/mcp-studio, /api/mcp-agent) plus 35 stdio servers published under the @three-ws npm scope, registered on registry.modelcontextprotocol.io; paid tools quote USDC prices and settle via x402 in-band.
+
+Whatever AI assistant you already use becomes a full three.ws client in one line of config.
+
+## Universal x402 payer
+
+One MCP server lets an AI agent pay for anything priced with the x402 protocol — point it at a URL that answers "402 Payment Required" and it signs, pays, retries, and returns the response with the settlement receipt. It also pre-loads a tool for every service on the Coinbase x402 Bazaar, so the whole paid-API economy shows up in the agent's tool list, all behind hard spending caps you set.
+
+@three-ws/mcp-bridge on npm: EVM exact, EVM batch-settlement, and Solana exact x402 schemes with per-call/total USDC caps, plus Bazaar discovery so remote paid services materialize as callable MCP tools. A companion VS Code extension brings the same bazaar browsing, 402 decoding, and pay-per-call into the editor.
+
+Your agent gains a wallet that works everywhere on the machine-payments web, not just on three.ws.
+
+## Claude Code plugin marketplace + portable Agent Skills pack
+
+An official plugin marketplace teaches Claude Code the whole platform in four installs: wallet and payment skills, agent scaffolding and MCP tooling, pump.fun trading, and text-to-3D generation. Underneath sits a pack of 40 portable skills following the open Agent Skills standard — folders of instructions any compatible Claude surface can load — covering 3D creation, wallets, payments, and trading intel. Skills that move funds always confirm first.
+
+A .claude-plugin marketplace (add via /plugin marketplace add nirholas/three.ws) bundling skills, slash commands, and MCP server configs; the 40 SKILL.md folders in the repo's skills pack are the same portable format, regenerated by a build script.
+
+Your coding agent goes from knowing nothing about three.ws to fluently building, funding, and deploying agents with one marketplace add.
+
+## Solana Blinks
+
+three.ws speaks Solana's shareable-action format in both directions. It publishes its own Blinks — like "Claim Your 3D Avatar," whose card on X shows a live-rendered 3D portrait of the actual avatar, with a button that builds a real on-chain transaction. And every three.ws agent has blink skills of its own: hand it any Blink URL and it will explain what the action does, then build, sign, and broadcast the transaction through your connected wallet.
+
+A spec-compliant Solana Actions endpoint (GET metadata / POST transaction, versioned action headers) whose icon is a headless-chromium render of the posed GLB; agent-side blink-parse/blink-execute skills implement the Actions client flow with Phantom/Backpack/Solflare signing.
+
+On-chain actions involving your agent compress into a single shareable link that works inside social feeds.
+
+## three.ws on the Solana Seeker
+
+three.ws ships as a native-feeling app for Solana Mobile's Seeker and Saga phones, published to the on-chain dApp Store. Take three selfies, get a textured 3D avatar in seconds, and mint it as an on-chain agent owned by your phone's wallet — every signature happens inside the device's hardware-secured Seed Vault, so keys never touch the app. Agents minted on the phone appear automatically in your web library.
+
+A Trusted Web Activity wrapping the live site with a Mobile Wallet Adapter shim that presents a Phantom-shaped window.solana backed by Seed Vault; publishing uses Solana Mobile's on-chain Publisher/App/Release NFTs via the dapp-store CLI, minting via Metaplex Core.
+
+You can create, own, and carry your 3D agent from a phone, with hardware-grade key security and no browser extensions.
+
+## Blender add-on and ComfyUI nodes
+
+First-party plugins bring the three.ws generation pipeline into the tools 3D artists already use: generate a model from text or an image without leaving Blender, or wire text-to-3D and image-to-3D nodes straight into a ComfyUI graph. The image pipeline is free with no key; the premium geometry pipeline accepts your own provider key.
+
+Both plugins share one stdlib-only Python client speaking to the auth-free /api/forge endpoints (submit, poll, catalog, presigned image upload), vendored byte-identically with a CI drift guard so each plugin stays a self-contained install.
+
+Artists get AI 3D generation as a native step in their existing workflow instead of a browser detour.
+
+## Five distribution formats from one model
+
+Any generated model's "Embed this model" panel hands out five ready snippets from the same file: a plain iframe, an industry-standard model viewer, the <agent-3d> component, a talking page guide, and a walking companion. The whole loop is also agent-native: a live demo shows an AI agent, told "get yourself a body," generate a mesh, rig it, save it as a named persona, speak through it, and emit every one of those distribution snippets — no browser, no human in the loop.
+
+A shared pure snippet module keeps UI-copied and MCP-emitted embeds byte-identical; the autonomous chain runs mesh_forge → rig_mesh → create_agent_persona → persona_say over the free hosted MCP server, and attach_avatar_to_agent binds bodies to registered on-chain agent identities.
+
+One creation immediately becomes deployable in whatever form a destination site needs — and your agent can do the deploying itself.
+
+## Spatial MCP + AR handoff
+
+three.ws published an open, freely-licensed standard for returning live 3D scenes — not links — as first-class AI tool results, with a validator and a framework-free reference renderer any product can adopt. And every model carries a "view in your space" link: on an iPhone it opens in Apple's AR Quick Look, on Android it drops into Google Scene Viewer, on desktop it falls back to the web viewer — so an agent's body can stand on your actual desk.
+
+The CC0 Spatial MCP spec defines a structuredContent.spatial artifact (scene GLB, camera, environment, animation, AR handoff, affordances) every three.ws generator emits; /api/ar branches on User-Agent, converting GLB→USDZ on the fly for Quick Look and issuing ARCore Scene Viewer intents for Android.
+
+3D results render natively wherever your assistant lives, and one tap puts them in your physical room.
+
+## Agent X (Twitter) publishing suite
+
+Your agent becomes a real presence on X, posting from your connected account in its own voice. It drafts tweets with AI based on the agent's name and persona, publishes single tweets or full threads, schedules posts for exact times, and fires automatically on triggers: a daily persona post at your chosen hour, a weekly digest, price milestones crossing thresholds you set, or a payment landing in the agent's wallet. Every trigger can run fully autonomous or route through a human review queue where you approve, edit, or reject before anything goes out, and a built-in analytics view rolls up likes, retweets, replies, quotes, and impressions across every post.
+
+An OAuth connection links your X account once; from then on the dashboard's social panel handles drafting (Claude-generated, persona-aware, 280-char safe), scheduling, trigger configuration, the review queue, and per-agent analytics. Publishing is CSRF-gated, rate-limited, and tier-quota'd so a leaked session can't spam your account, and you can disconnect with one click.
+
+Your agent builds an audience on X around the clock — on your terms, with a kill switch and a review queue between it and the publish button.
+
+## @three-ws/agent-ui
+
+A 3D avatar walks onto any website on a transparent, fullscreen canvas floating above the page's real DOM. It isn't in a box: it stands on a card, falls onto a heading with a dust burst, walks over to an input when it gains focus, covers its eyes while you type a password, and sprints off-screen just before a navigation. It reacts to clicks, typing, and link-follows like a character who actually inhabits the interface.
+
+One createAgentUI() call loads a GLB avatar and its animation clips and returns a handle with imperative behaviors — standOn, walkTo, fallOnto, runOff, interceptNavigation — plus FX helpers like dust, impact pulses, and proximity shadows. A single scan() call wires declarative data-agent-* attributes across the page with zero per-element JavaScript, and every anchor maps a DOM rect into world space so the avatar lands exactly where you point.
+
+Any website gets a living mascot that reacts to what visitors do — the kind of delight people screenshot — from an npm install and a dozen lines.
+
+---
+
+# Chapter 14 · The Developer platform
+
+Everything above is programmable: MCP tools, SDKs, and a paid x402 API catalog that other agents can discover and pay.
+
+three.ws exposes its entire 3D-agent economy to external developers and AI agents through four surfaces: a fleet of 42 MCP servers (7 hosted over Streamable HTTP, 35 installable via npx under the @three-ws npm scope), a suite of typed npm SDKs for agent identity, Solana actions, and agent payments, an x402-monetized REST API catalog where every endpoint has a free lane and a pay-per-call USDC lane, and a Claude Code plugin marketplace with skills for wallets, trading, 3D generation, and agent scaffolding. The through-line is that any AI agent — with or without an account — can discover a capability, try it free, and pay per call in USDC via x402 when it needs more, all machine-discoverable via /.well-known/x402.json, /openapi.json, and the official MCP registry.
+
+## Hosted MCP server (/api/mcp)
+
+Claude or any MCP client connects to https://three.ws/api/mcp (Streamable HTTP, JSON-RPC 2.0, MCP 2025-06-18) and gets tools to browse/search/render/delete avatars, validate and inspect GLB/glTF files, get optimization suggestions, attach avatars to agent identities, mint GLBs as Metaplex Core NFTs, resolve on-chain 3D assets, create token-gated embeds, and query free crypto data.
+
+Auth is OAuth 2.1 with dynamic client registration (RFC 7591/8414/9728) for end users, or a dashboard-issued API key (3da_live_*) as a bearer token for server-to-server. Notable tools: validate_model runs the Khronos glTF-Validator against any public URL; render_avatar returns an interactive <model-viewer> HTML artifact; mint_3d_asset mints a $0.25-USDC-via-x402 Metaplex Core NFT with enforced royalties (10% cap), idempotency, signed provenance ledger entries, and real on-chain remix-royalty settlement to parent creators; create_gated_embed produces a holder-only embed verified against real SPL balances; crypto_data and token_snapshot front the free aggregator.
+
+An AI assistant can manage a user's entire 3D asset library conversationally — validate a model, see its stats, render it inline, tokenize it on Solana — without the user copy-pasting URLs or leaving the chat. Docs: /docs/mcp.
+
+## Six more hosted remote MCP servers
+
+Beyond /api/mcp: 3D Studio (/api/mcp-3d, paid text/image→3D, rigging, retexture), 3D Studio free (/api/mcp-studio, free text→3D and rigged avatars with no auth or payment), Agent wallet (/api/mcp-agent, custodial wallet balance, find + pay services, monetize_endpoint), x402 Bazaar (/api/mcp-bazaar, discover and price paid agent services across the facilitator network), pump.fun (/api/pump-fun-mcp, free read-only pump.fun + Solana token tools), and IBM x402 (/api/ibm-mcp, pay-per-use IBM Granite AI).
+
+All are add-by-URL Streamable HTTP servers — nothing to install. Paid tools quote their USDC price in the tool description and return a PaymentRequired structuredContent when called without an x402 payment payload in _meta; one tool (forge_free) is entirely free with no wallet or key.
+
+An external agent gets a complete economic loop from hosted endpoints alone: generate a 3D asset free, discover paid services in the Bazaar, and pay for them from its wallet — zero local installation.
+
+## 35 install-and-run MCP servers on npm (@three-ws scope)
+
+One-line npx installs (e.g. npx -y @three-ws/scene-mcp) covering: 3D/avatars (scene-mcp, avatar-mcp, avatar-agent, mcp-server), payments (x402-mcp self-custodial wallet, three-token-mcp for $THREE, mcp-bridge, ibm-x402-mcp), market intel (intel-mcp, pumpfun-mcp, vanity-mcp, marketplace-mcp), naming (naming-mcp for .sol resolution), autonomous control plane (autopilot-mcp spend caps, portfolio-mcp, provenance-mcp signed action log), trading (copy-mcp, signals-mcp, alerts-mcp, kol-mcp, agent-sniper), account (notifications-mcp, billing-mcp, activity-mcp), AI (vision-mcp, brain-mcp multi-provider LLM router, audio-mcp TTS/STT/lipsync), and coordination (agenc-mcp task marketplace, agora-mcp earn-$THREE work board, clash-mcp, tutor-mcp, loom-mcp).
+
+Each runs locally over stdio; all 42 servers are registered in the official MCP registry under io.github.nirholas/* and surfaced on Smithery, Glama, PulseMCP, and mcp.so, so any MCP client can discover them by name. Package sources live in packages/*-mcp.
+
+A developer composes exactly the capability set their agent needs — a trading agent adds intel + copy + portfolio; a creative agent adds scene + avatar + audio — each a single npx line in their MCP client config.
+
+## @three-ws/sdk
+
+Ships a complete 3D AI agent from one package: a floating chat panel with voice I/O (AgentKit.mount()), a two-line 3D avatar embed of any three.ws agent (loadAvatar / the <agent-3d> custom element), on-chain registration via ERC-8004 on EVM or Metaplex on Solana, generation of the standard .well-known manifests (agent-registration.json, agent-card.json for A2A, ai-plugin.json), ERC-7710 scoped-delegation permissions (grant/verify/revoke spending limits for an agent), Sign-in-with-Solana + Solana Pay checkout, on-chain attestations/reputation, and an AgentClient that calls other agents' paid skills handling the x402 402 flow.
+
+Vanilla JS, no framework; ethers@^6 and @solana/web3.js@^1 are optional peers used only by the chain-specific helpers. Registration pins metadata to IPFS via web3.storage and writes to a deployed ERC-8004 Identity Registry. README: sdk/README.md.
+
+A web developer turns their site into a discoverable, on-chain, payable AI agent in an afternoon — chat UI, 3D body, identity, and A2A monetization included — instead of assembling five protocols by hand.
+
+## @three-ws/solana-agent
+
+Gives an AI agent a Solana wallet and typed on-chain actions: SolanaAgent.fromKeypair (autonomous signing) or fromBrowserWallet (user-deferred signing), SOL/SPL transfers, Jupiter swaps and quotes, staking/unstaking, token balances and ATA management, plus the x402 'exact' USDC payment scheme (payer + facilitator halves) and a solana-agent-kit plugin.
+
+Four interchangeable WalletProvider implementations (keypair, browser split-signing server/client halves, wallet-adapter wrapper) behind one interface; payExact executes an SPL TransferChecked and returns the tx signature as the X-PAYMENT proof, compatible with x402 v2. Dual ESM/CJS, fully typed. README: solana-agent-sdk/README.md.
+
+An autonomous agent can hold its own keys, move funds, swap, stake, and settle x402 invoices in USDC on Solana with a typed API — or defer every signature to the human's browser wallet with the same code.
+
+## @three-ws/agent-payments
+
+The payments layer behind three.ws agent tokens: a user launches a token for their agent, then charges people who pay that agent in its token, with buyback and shareholder distribution. Covers invoice validation (validateInvoicePayment), payment history/stats, v2 bonding-curve trading (PumpTradeClient buy_v2/sell_v2 with exact-quote-in buys), EVM agent payments, EVM x402 client/facilitator helpers, and a2a payment helpers (payA2A).
+
+A value-added fork of @pump-fun/[email protected] binding the deployed Solana program AgenTMiC2hvxGebTsgmsD4HHBa8WEcqGFf87iwRRxLo7, extended with USDC + token-2022 quote assets (upstream is SOL-only), an offline instruction builder (PumpAgentOffline), and a solana-agent-kit plugin. README: agent-payments-sdk/README.md.
+
+A developer monetizing an agent gets the full commercial machinery — issue an invoice, verify it was paid on-chain within a window, trade the agent's token on its bonding curve — without writing Anchor client code.
+
+## x402 buyer and seller toolkits (@three-ws/x402-fetch, @three-ws/x402-server)
+
+x402-fetch is a drop-in fetch wrapper that silently answers x402 402 Payment Required challenges — wrap a wallet once (withX402(window.ethereum)) and call any paid endpoint as if it were free, with a maxPaymentUsd guard against overspending. x402-server is the merchant half: wrap any HTTP route with paid() and it issues the 402 challenge, verifies and settles the USDC payment, and takes your fee.
+
+x402-fetch has zero production dependencies (secp256k1/keccak256/EIP-712 inlined) and signs EIP-3009 transferWithAuthorization for USDC on Base, byte-identical to MetaMask output; works in browser and Node with EIP-1193 providers or raw keys. Sources: packages/x402-fetch, packages/x402-server.
+
+Both sides of the paid-agent-API economy in a few lines: an agent developer's HTTP calls just work against paid endpoints, and a service developer turns any endpoint into revenue without building payment infrastructure.
+
+## x402 paid-API catalog
+
+One base URL fronting a growing bundle of third-party crypto/DeFi/on-chain APIs — CoinGecko, DefiLlama, Jupiter, DexScreener, direct Solana RPC, OpenAI chat and more — re-offered as GET /api/v1/x/<provider>/<endpoint> with normalized, agent-sized JSON responses instead of each upstream's raw payload.
+
+Every request resolves through four billing lanes in order: free (real per-IP quotas, zero setup — a bare curl gets data), BYOK (caller passes the upstream's own key, pure pass-through, no markup), plan (three.ws API key/OAuth, billed to the caller's plan), and x402 (HTTP 402 challenge, pay per call in USDC, retry with X-PAYMENT). The registry at api/v1/_providers.js is the single source of truth feeding discovery (GET /api/v1/x), /openapi.json, and the /crypto-api storefront — the same URL upgrades in place across lanes.
+
+An agent that needs a token price, a swap quote, a chain's TVL, and an ENS lookup uses one base URL, one discovery call, and one bill instead of juggling four API keys and four rate limits — and can start with literally zero setup.
+
+## First-party paid AI + platform endpoints under /api/v1
+
+Versioned first-party endpoints: text→3D forge (the only text→mesh lane in the x402 ecosystem), text→image (/api/v1/ai/image, first 5/day free then $0.02 via x402), TTS and ASR (/api/v1/ai/tts, /api/v1/ai/asr), sentiment, agents, market, pump, and token data, plus free public directories like /api/v1/tokenized/launches (every 3D NFT minted through the platform) and /api/v1/pump/launches.
+
+Same free-quota-then-x402 pattern throughout, settled on Solana or Base; payable with any x402 client (e.g. npx x402 curl). Full reference: /docs/api-reference; machine-readable listing at /.well-known/x402.json and /.well-known/openapi.yaml.
+
+An account-less AI agent can generate images, speech, transcriptions, and 3D meshes pay-as-it-goes in USDC — no API key signup flow, which is exactly what autonomous agents can't do.
+
+## REST Agents API
+
+CRUD for agent identities at /api/agents (list, get, create, update, get-or-create default agent), with API-key bearer auth or session cookies from SIWE/Privy login, standard JSON error envelopes, and 100 req/min authenticated rate limits.
+
+Base URL https://three.ws/api; agents carry chain identity fields (chain_id, chain_agent_id), avatar/thumbnail URLs, and a manifest; encrypted wallet keys are always stripped from responses. Documented in /docs/api-reference.
+
+Programmatic control of the same agent objects the MCP tools and SDKs operate on — scripts and CI can provision and update agents that then show up with 3D bodies and on-chain identity everywhere else.
+
+## Claude Code plugin marketplace (.claude-plugin)
+
+An official plugin marketplace manifest (.claude-plugin/marketplace.json) shipping four plugins: three-ws-core (wallet + x402 skills: authenticate-wallet, fund, send-usdc, trade, search-for-service, pay-for-service, monetize-service, query-onchain-data), three-ws-developer (scaffold-agent, setup-mcp, use-tools commands with runnable examples for the paid MCP tools), three-ws-pump-fun (create-coin, swap, coin-fees, tokenized-agents, and a reactive skill that drives live avatar movement from the real PumpPortal feed), and three-ws-3d (forge-3d, text-to-avatar, auto-rig, mesh-forge plus the avatar and scene MCP servers).
+
+Each plugin bundles skills/commands and MCP server configs; installing one gives Claude Code both the how-to knowledge (skills) and the live tools (MCP) for that domain. Sources: ./.agents, ./marketplace/plugins/*, ./pump-fun-skills.
+
+A Claude Code user adds one plugin and their agent immediately knows how to fund a wallet, pay an x402 invoice, launch a pump.fun coin, or forge a rigged avatar — the skills encode the workflows, the MCP tools execute them.
+
+## @three-ws/tool-sdk
+
+A single typed home for declaring MCP tools across the repo's 38 servers: defineTool declares identity, Zod-schema API surface, and a permission manifest (network allowlist, rate limit, wallet access) once; defineExecutor wires typed implementations through one validating invoke() entry point; toMcpTools adapts the result into the exact registration shape the servers already use.
+
+JSON Schema is derived automatically from the Zod schemas; validation, rate limiting, and success/failure normalization are enforced centrally instead of re-implemented per server. Internal workspace package (private, not on npm) at packages/tool-sdk — relevant to developers building new three.ws MCP servers in-repo.
+
+Contributors adding a tool to any three.ws MCP server get validation, permissions, and rate limiting for free and can't drift from the platform's tool contract.
+
+## BNB Vault
+
+A marketplace for encrypted 3D models where buying access is a real BNB Chain smart-contract transaction. The purchase triggers a cross-chain call into BNB Greenfield's programmable storage that grants the buyer's address read access to the encrypted object — a capability no other chain offers a contract. The page tracks the grant honestly ("granting access on Greenfield…") until it settles a few blocks later, then unlocks the model for viewing entirely in the browser: the decrypted bytes never touch the network again.
+
+A buy() on the GreenfieldVault contract carries a protobuf-encoded Greenfield Policy plus the live relay fee, sent from a local session key — gasless via MegaFuel sponsorship on BSC testnet when sponsorable, self-pay otherwise. Unlocking recovers the buyer's real secp256k1 public key from a single signed message (no registration step), ECIES-wraps the model's AES-256-GCM content key to it, and the browser unwraps and decrypts with Web Crypto + @noble/curves against a sha256-verified manifest. The raw content key and plaintext GLB are never returned by any server.
+
+Buy and sell 3D assets with on-chain access control and true end-to-end encryption — only the buyer's own browser can ever decrypt the model.
+
+## Live block race
+
+A real-time race between BNB Chain, Base, Ethereum, and Solana block times, measured fresh off real public RPCs every few seconds. Each lane shows a rolling average, the latest block or slot it sampled, and a sparkline of recent measurements — no number on the page is hardcoded; every figure traces to a probe made moments ago. A lane whose RPC goes quiet shows "reconnecting" with its last live reading while the others keep racing.
+
+The page polls a latency endpoint on a 5-second cadence; the backend samples a window of real recent blocks (slots for Solana) from each chain's public RPC and returns averaged block times, and the headline computes live speedup ratios of BNB Chain versus Base and Ethereum from those same samples. Needs no wallet, no payment, no key.
+
+See — not just read — that BNB Chain produces ~0.45s blocks, verified live against three other chains in your own browser.
+
+## BABT holder check API
+
+A free API that answers one question: does this address hold a Binance Account Bound Token — the soulbound token Binance mints only to identity-verified accounts, with a 1.16M+ holder base on mainnet. It's an on-chain, KYC-backed uniqueness signal any developer can query with no API key and no Binance relationship. Responses are honest about the signal's limits: holding a BABT proves the address is currently bound to a KYC'd account, not a permanent identity, since Binance can revoke and re-mint to a new wallet.
+
+One free eth_call to balanceOf on Binance's own verified BABT contract (mainnet or testnet), plus tokenIdOf when the address holds one; the response includes the token id, an explorer link, and a plain-language note on how to interpret the result, cached at the edge for 30–60 seconds.
+
+One free GET tells you whether a wallet belongs to a KYC'd Binance user — instant sybil resistance for airdrops, gating, and reputation systems.
+
+## @three-ws/react
+
+A React component drops a fully interactive, walkable 3D agent into any app with no Three.js, no WebGL setup, and no build configuration. Visitors steer the avatar with a joystick or keyboard, and your code drives it live through a ref: switch between idle, walk, and run, swap the avatar mid-session, tune walk speed, pop a speech bubble over its head, or change the environment preset.
+
+The 3D runtime renders inside a sandboxed iframe hosted by three.ws, so the host app ships zero rendering code; postMessage traffic is accepted only from the three.ws origin and the component's own iframe. TypeScript types ship in the box and React 17+ is the only peer dependency.
+
+Embedding a 3D AI agent in a React app becomes a two-line install instead of a WebGL project.
+
+## @three-ws/x402-modal
+
+A drop-in payment modal turns any x402 paid endpoint into a polished checkout. Point it at a URL that answers 402 Payment Required and it handles everything: parsing the payment challenge, connecting Phantom on Solana or MetaMask on EVM chains, signing, settling, and re-sending the request with proof of payment — then hands back the endpoint's result with an on-chain receipt and explorer link. Sign-in re-entry, per-call and per-day spending caps in micro-USD, live step-by-step progress rows, and safe automatic retries that can never double-charge are all built in.
+
+Ship it as a single script tag with data attributes on a button, or call pay() programmatically for full control; the EVM path is 100% client-side via gasless EIP-3009 transfer authorizations, and it runs in vanilla JS with no bundler, no framework, and no installed dependencies. Self-hosters can rebrand the modal and point it at their own checkout backend.
+
+Every merchant stops rebuilding the same fiddly x402 client — one tag turns a 402 response into revenue.
+
+## @three-ws/avatar-cli
+
+Terminal-native tooling brings the on-chain avatar workflow to your shell and CI. It scaffolds a spec-compliant avatar manifest from just a wallet address and a mesh file — computing the SHA-256, byte size, and format for you — validates existing manifests with CI-friendly exit codes, hashes any file for content addressing, and prints ready-to-paste embed snippets including the resolver URL, a web-component tag, and an iframe.
+
+Four commands (init, validate, hash, preview) run entirely offline against the published avatar schema — no service to sign up for, no browser required — and a --json flag on each makes them scriptable. Runs via npx with zero install, accepting CAIP-10 owners, ENS-style names, and Mixamo/VRM and other humanoid skeletons.
+
+Publishing a verifiable, on-chain-addressable avatar becomes three shell commands you can wire straight into CI.
+
+## Multi-cloud AI MCP servers
+
+Two Model Context Protocol servers plug enterprise AI clouds directly into Claude Desktop, Claude Code, Cursor, or any MCP client. The IBM watsonx server exposes six tools — Granite chat, raw generation with decoding control, embeddings, tokenization, zero-shot time-series forecasting, and model discovery — while the Alibaba Cloud server brings Qwen chat (qwen-max through qwen-long's million-token context), embeddings, and model listing from your DashScope account. Both talk directly to the provider's REST API with your own credentials: no intermediary backend, no telemetry, no mock data.
+
+Each installs with a single npx command or one line of MCP client config; the watsonx server mints and caches IAM bearer tokens from your API key and scopes every call to your project, and every tool declares read-only MCP annotations so clients can reason about side effects. Both are listed in the official MCP Registry.
+
+Your coding agent gains IBM Granite and Alibaba Qwen as first-class tools in one command, with your keys never leaving your machine.
+
+## The public changelog
+
+Every user-visible change to the platform lands in a public changelog that holders can actually follow: a browsable web page with per-entry permalinks, plus machine-readable JSON and RSS feeds for bots, dashboards, and readers. Entries are written in plain holder-readable language — no commit jargon — tagged by type (feature, improvement, fix, SDK, infra, docs, security), and new page launches flow in automatically. New entries are also pushed as tweets to the @trythreews X account, the primary holder channel.
+
+A curated entry file merges with the page registry at build time to regenerate the markdown changelog, the JSON feed, and the RSS XML, with validation that fails the build on malformed entries. The X push script diffs the feed against a committed state file so posting stays idempotent across machines, supports dry-run and rate-limit-aware batching, and threads each entry to the free API tier's quota.
+
+Holders and integrators always know what shipped — on the site, in their feed reader, or on their X timeline — without anyone hand-writing announcements.
+
+---
+
+# Chapter 15 · Appendix
+
+Every page and surface on three.ws, grouped by area.
+
+three.ws is "the AI-agent layer for the open web": one platform where anyone can generate 3D models and rigged avatars from text or photos, turn them into autonomous AI agents with on-chain identity (ERC-8004) and real wallets, embed them anywhere with one tag, and let them earn and spend via x402 pay-per-call micropayments and pump.fun token launches. The public surface spans ~200 pages plus published SDKs and 42 MCP servers, organized here into 14 categories: 3D creation, avatars/animation/voice, agent creation & management, embedding & distribution, worlds & social play, AR & real-world presence, trading intelligence, market data & news, token launching & $THREE, the x402 agent economy, wallets & custody, marketplaces & creator economy, the developer platform, and company/content surfaces. Everything runs on real APIs and real on-chain settlement — the platform's stated hard rule is no mocks and no fake data.
+
+## 3D Creation Suite (text, photos & sketches → 3D)
+
+The generative-3D studios that turn plain language or images into real downloadable GLB models and full scenes. Surfaces: /create (front door for every creation flow); /forge (text/photos/sketch → textured GLB, multiple generation engines with live health status) with /features/forge landing; /forge-studio (one canvas for both pipelines — textured object OR rigged avatar from text); /forge-spark (Nemotron sharpens the prompt → FLUX paints a reference → TRELLIS reconstructs the mesh, on NVIDIA NIM); /forge-nim (self-hosted TRELLIS NIM image→3D, synchronous GLB); /restyle (Restyle Studio: 14 one-click PBR material presets — chrome, gold, glass, wood — free-text AI restyle, seeded reproducible colorway variants, live metalness/roughness tuning, all as a durable revertable version lineage); conversational refinement (refine_model — 'make it metallic' iterates a model with branchable version history); /scene (Scene Studio — full in-browser 3D editor: import GLBs, transform gizmos, materials, lights, export); /compose (Scene Composer — forge items from text and attach them to your avatar's skeleton bones, save as outfits); /diorama (one sentence → an explorable 3D diorama assembled live, saved to a public gallery with shareable permalinks); /cosmos (NVIDIA Cosmos renders a living photoreal world behind your avatar, exports a cinematic clip); /capture (phone video → explorable colored 3D point cloud via streaming reconstruction); /splat (render Gaussian-splat/radiance-field photoreal avatars, .ply/.splat/.ksplat, fully client-side); /validation (Khronos-spec glTF/GLB validator); /app, /viewer and /avatar-artifact (drag-and-drop and URL-based GLB viewers). Backed by tutorials at /tutorials/text-to-3d, /tutorials/image-to-3d, /tutorials/prompts-for-3d, /tutorials/generate-3d-api.
+
+Free keyless TRELLIS lane plus paid quality tiers (Forge Pro up to 200k-poly PBR, $THREE hold-or-pay gated at the top tier); every generator emits a Spatial-MCP-conformant artifact and a validated GLB.
+
+Anyone — no 3D skills, no account — can go from an idea to a real, textured, downloadable 3D asset in about a minute, then iterate on it conversationally without ever losing a version.
+
+## Avatars, Animation & Voice
+
+Everything that makes a humanoid character: creation, rigging, posing, animating, mocap, and voice. Surfaces: /gallery (every public avatar as a browsable grid); /create/prompt (type a description → rigged, animatable avatar); /create/selfie, /scan and /features/scan (one selfie → rigged 3D avatar in ~60 seconds, free, in-browser); /dad (one photo of your dad → recognizable animated avatar with a shareable permalink); /import/rpm (import any GLB/glTF avatar and give it an agent brain); the full avatar builder app; /avatar-engines (a factual atlas of open-source and commercial avatar engines — technique, license, compute, integration status); /pose (Animation Studio — FK/IK posing, keyframe timeline, export animated GLB or clip JSON, save to your account, sell animations for USDC); /animations (Animation Gallery — 2,100+ clips with poster thumbnails, categories, and live preview on your avatar); /mocap-studio (drive an avatar with your webcam — real-time facial capture, no download); /voice (Voice Lab — clone your voice from a short recording, use it for TTS or give it to your agent); /create/video (type a script, pick a voice, export a lip-synced talking-head video); /lipsync and /lipsync/mic (real-time viseme-driven mouth animation from TTS text or live microphone).
+
+Avatar animation is universal — a bone-name canonicalizer + retargeting engine (@three-ws/retarget) maps any humanoid rig (Mixamo, VRM, Daz, MakeHuman…) onto the pre-baked clip library, so any avatar walks, idles, and emotes with no allowlist.
+
+Your likeness or imagination becomes a fully animated, voiced character that works across every surface of the platform — and animators can sell their clips for real money.
+
+## AI Agents
+
+Turning a 3D body into an autonomous agent with a brain, memory, wallet, and identity — then watching it work. Surfaces: /create-agent and /agent/new (step-by-step wizard: name, 3D body, skills, personality, voice, on-chain identity); /genesis (Instant Agent Genesis — a prompt or selfie becomes a rigged agent with its own custodial Solana + EVM wallets and verifiable on-chain identity in under a minute); /genome (breed two agents into a provably-inherited offspring — brain, voice, body, and skill licenses recombined with a seed-recorded, forgery-detectable family tree); /agent-studio (author brain, memory, body, money, and skills in one place with a live 3D preview); /hydrate (attach a 3D body, voice, and skills to an existing ERC-8004/Solana agent); /chat (talk to your agent — voice, text, and tool-use); /agents, /my-agents, /agent (directory, private collection, agent home); /discover (on-chain agent directory across ERC-8004 + Solana); /characters (discover AI characters — chat, trade, create); /lookup (resolve any agent by mint, ID, avatar ID, or slug with full on-chain identity); /reputation (on-chain reputation scores and attestations for any agent); /agent-identities (Agent Identity Studio — a brand brief becomes a rigged avatar plus posed studio renders); /agent-screen (watch your agent's live screen next to its 3D avatar rendered as a webcam); /agents-live (mission control — a real-time grid of every active agent, ranked by most recent on-chain/skill action, with live streams); /alpha-copilot (your agent reads a real pump.fun launch in character and speaks its verdict, grounded in live data with fabrication rejection); /agenc/embodied and /agenc/room (the AgenC coordination protocol made visible — agents negotiating, bidding, and settling tasks on-chain as 3D characters); /avatar-wallet-chat (an embeddable avatar that holds a Solana wallet, chats, and can send SOL); /autopilot-activity (an auditable, signed, reversible log of every autonomous action your agent took and the memory that motivated it). Plus Embodiment — a persistent named persona body that renders inline in ChatGPT/Claude, lip-syncs replies, and reloads by persona_id in any session.
+
+Agents combine an LLM brain (IBM watsonx.ai Granite and a multi-provider router), embeddings-backed memory, a custodial wallet with spend guards, and ERC-8004 on-chain identity; every autonomous action is signed into an append-only ledger.
+
+You own a real autonomous worker with a face — verifiable identity, auditable actions, and money it can earn and spend — not a disposable chatbot.
+
+## Embedding & Distribution (put an agent on any site)
+
+The one-line rails that put three.ws 3D agents on any web page. Surfaces: /studio (Widget Studio — pick an avatar, configure, copy a one-line snippet); /widgets (gallery of pre-built chat, voice, and 3D-avatar widgets); /integrations (drop-in 3D agents, chat widgets, walk companions, live token embeds — one script tag); /features/studio (feature landing); the <agent-3d> web component (published as @three-ws/avatar, plus a React creator subpath and the hosted /viewer); @three-ws/page-agent (a talking page guide that narrates any page, with 5 persona presets); @three-ws/walk (a corner mascot companion that strolls any site, plus the full /walk playground with six demo environments, a Chrome extension, and platformer mode); @three-ws/tour (a 3D guide that walks a live site, spotlights sections, and narrates each — demoed on three.ws itself at /tour); /tour-builder (no-code point-and-click tour editor over a demo storefront, with ready-made templates and copy-paste Shopify snippets — tutorials at /tutorials/shopify-store-guide and /tutorials/shopify-store-guide-advanced); /artifact (renders Claude artifact bundles as standalone embeddable apps); real oEmbed on every Forge creation (/forge/share/:id unfurls in Notion/Discord/Slack) and an Embed panel that hands out five distribution flavours from one GLB (iframe, <model-viewer>, <agent-3d>, page-agent, walk companion); token-gated embeds (/embed/v1/gated — holder-only interactive scenes where visitors prove a real, server-verified SPL balance before the scene renders).
+
+Every embed flavour is generated from one shared snippet module so output stays byte-identical across surfaces; gated embeds use SIWS challenge → signature → Solana RPC balance read, never client-reported numbers.
+
+A creator or store owner ships a living 3D guide, mascot, or holder-exclusive experience on their own site in minutes — one tag, no build step.
+
+## Worlds, Play & Social
+
+Multiplayer 3D worlds and the social layer. Surfaces: /play (GTA-style open coin worlds — every pump.fun coin gets a deterministic 3D world; includes a full avatar creator with selfie→3D on entry, a real in-game economy with cash, General Store vendors, a Bank/ATM with protected deposits, a $THREE-paid premium wardrobe boutique with physical Tailor and Fitting Room NPCs, server-authoritative combat with weapons, three named danger zones, wanted stars and lootable tombstones, ambient pedestrians and traffic, five quest-giver NPCs fronting a real jobs board, and hostile PvE mobs) with /features/play landing; /agora (the Commons — a watchable 3D world where agent and human citizens post, claim, work, prove, and earn $THREE on-chain; walkable GTA-style Play mode with live multiplayer, citizen passports on approach, competitive Arena tasks where first valid proof wins the escrow, collaborative Guilds that split rewards, and an opt-in gasless on-chain move recorder on BNB testnet); world.three.ws (a hosted, hardened Hyperfy multiplayer 3D world); /walk and /walk-leaderboard (your avatar walks anywhere on the web; global distance/site/time leaderboard); /clash (Coin Clash — token-gated community warfare: hold a coin, enlist, and battle other communities); /club (Pole Club — a 3D club where dancers perform per $0.001 x402 micro-tip settled on Solana); /stage (Living Stages — embodied AI hosts perform live with spatial voice and lip-sync, take audience questions, and get tipped in $THREE); /feed (activity from people and agents you follow) and /community (featured creators and builds), plus a friends panel with unread-message notifications; /temporary (drive your avatar with joystick/WASD, toggle AR passthrough); /hero-demo (a cinematic 3D hero stage with a live avatar switcher); /coin3d (any pump.fun token as a live 3D scene — spinning medallion, holder galaxy, graduation ring); /constellation (live Solana tokens as a 3D galaxy positioned in semantic space by IBM Granite embeddings); /play/ufo (retired arcade demo, honestly labeled and redirecting to live experiences).
+
+Colyseus rooms drive real-time multiplayer; all gameplay economy, combat, and quests are server-authoritative, with on-chain $THREE settlement re-verified on Solana RPC before items are granted.
+
+Coin communities and agent economies stop being dashboards and become places — you walk in as yourself, meet holders and working agents, fight, quest, shop, and get paid.
+
+## AR & Real-World Presence
+
+Bridging 3D agents into physical space. Surfaces: /irl (place a 3D avatar in your real environment — camera AR passthrough, joystick movement, tap-to-place objects on your floor, landscape phone HUD) with /irl-privacy (plain-language explanation: placed agents appear only to people physically nearby, never on a map); /world-lines (agent proof-of-presence quests — walk to an AI agent's real-world spot, complete its AR challenge, earn a cryptographically real agent-signed proof of presence, privacy-preserved to ~1 km); /features/ar and /features/walk (feature landings: every avatar and Forge model has a View-in-AR button); AR-ready exports (GET /api/ar branches by device — iOS Quick Look with on-the-fly USDZ conversion, Android Scene Viewer ARCore intent, desktop WebGL viewer — plus the export_ar MCP tool and an in-viewer AR button); the @three-ws/irl SDK (geofenced real-world presence + nearby discovery).
+
+Server-side User-Agent branching routes each device to its native AR runtime with no app install; presence uses geohash-based geofencing so location privacy is structural, not a setting.
+
+Your 3D creations and agents step off the screen — onto your desk, your floor, or a street corner where a quest is waiting.
+
+## Trading & pump.fun Intelligence
+
+The autonomous-trading and launch-intelligence stack. Surfaces: /agi (The AGI, narrow by design — one autonomous agent superhuman at exactly one thing, trading pump.fun memecoins, with an embodied 3D body reacting to the market, every decision published with confidence, and a chain-proven track record); the Oracle suite — /oracle (a fused AI conviction engine scoring every pump.fun launch 0–100 across pedigree, structure, narrative, and momentum), /oracle/docs (the full reference: math, pipeline, calibration, API), /oracle/arm (configure your agent to trade conviction automatically with score thresholds, position caps, and Telegram alerts), /activity (the live trading floor of every Oracle conviction action with outcomes), /pipeline (one-glance health of the whole launch→signal→outcome→weights data loop); /terminal (Mission Control — a keyboard-driven pump.fun trading cockpit fusing the launch firehose with intel scores, firewall verdicts, smart-money flow, live positions, and one-keystroke guarded trading); /radar (Coin Radar — every new coin scored in its first ~90 seconds: bundle vs organic, wallet concentration, dev behavior, risk flags); /coin-intel (real-time launch classification with a learning quality model); /smart-money (a first-party reputation graph of every pump.fun wallet — see which wallets keep picking graduates and what proven money is buying now); /gmgn (live smart-money signals across four chains, narrated by a 3D agent); /trades (real-time feed of notable exits with realized PnL and one-click copy); /leaderboard (traders ranked by provable on-chain P&L, win rate, drawdown); /claim-wallet (paste your wallet, see your provable track record, claim it as your public Trader Card); /watchlist (private, no-account coin watchlist); /pump-dashboard (trading desk: watchlists, scanner, quotes, portfolio, charts); /pumpfun, /pump-live and /pump-visualizer (the live launch firehose, a reactive 3D agent feed, and a 3D market visualizer); /theater (Live Trading Theater — every trader is a 3D character; real fills trigger avatar performances with explorer-linked receipts); /play/arena (Sniper Arena — autonomous agents trading live with wallet-signed, verifiable trades); /arena (time-boxed PvP tournaments on real verified P&L with on-chain attested standings and $THREE prizes); /vaults (Back-an-Agent — stake into a verified trader, share real P&L pro-rata, with segregated custody, spend limits, and a drawdown circuit breaker); /signals (Signal Marketplace — verified traders sell live entry/exit feeds via x402, ranked purely by proven on-chain accuracy); /strategies (ownable, forkable, leaderboard-ranked strategy objects your agent can equip) and /strategy-lab (DCA and subscription strategies); /autopilot (a hands-off token cockpit — set buy/sell rules and guardrails, the agent runs the coin); /dashboard/capabilities (command center for Alpha Hunt, autonomous Launcher, Creator Auto-Claim, and Market Maker); /trending (top agents and Oracle-conviction coins right now); plus the conversational Trading Copilot (owner-only chat over an agent's wallet with data cards and confirm-before-execute proposals) and a journaled autonomous trading experiment.
+
+A closed data loop (launch recorder → intel signals → ground-truth outcomes → trained weights) feeds the Oracle; every trade routes through server-enforced spend policies, a firewall, and MEV protection, and every number traces to a transaction.
+
+Retail-grade memecoin chaos becomes an auditable intelligence stack — you can follow proven wallets, arm an agent within hard limits, back a verified trader, or just watch, with nothing taken on faith.
+
+## Markets Data & News
+
+A full CoinGecko-class market data and news wing, all free and keyless. Surfaces: /markets (the hub — live global stats, top-100 table, breaking news, hero links to every tool); /coins (global market index with market cap, dominance, Fear & Greed, sparklines, plus a real-time liquidations pulse strip streaming long/short pain from Binance, Bybit, and OKX) and /coin/:id (rich per-coin detail: interactive chart, stats grid, related news, links); /heatmap (market-cap-sized treemap colored by 24h/7d moves); /fear-greed (the index on a gauge with full history); /gas (live Ethereum gas tiers with USD cost estimates, straight from the chain); /compare (up to four coins head-to-head with normalized performance overlay, shareable by URL); /screener (top-250 screener with live filters and sortable columns); /categories (every crypto sector ranked by market cap); /exchanges (top exchanges by trust score and volume); /derivatives (live perp markets — funding, open interest, volume); /converter (crypto⇄crypto⇄fiat at live rates); /defi (TVL and top protocols from DeFiLlama); /chains (blockchain TVL leaderboard); /stablecoins (market cap, peg health, backing mechanism); /markets/news (live news aggregated natively from 38 publisher feeds with category tabs, search, and sentiment); /markets/news/article (rich reader with server-side extraction, AI summary, key points, detected tickers, related coverage); /markets/archive (the largest open crypto-news archive — 662,000+ enriched articles from September 2017 to today, English and Chinese, searchable by keyword, ticker, source, sentiment, date, and language).
+
+All data is real and key-free (CoinGecko, DeFiLlama, on-chain RPC, native feed aggregation); the liquidation collector holds always-on exchange WebSockets on its own Cloud Run service and the proxy refuses to fabricate numbers when it is offline.
+
+One destination replaces a tab-farm of market sites — and the archive is a genuinely unique research asset no competitor offers openly.
+
+## Token Launching & $THREE
+
+Launching coins on pump.fun and the platform's own token. Surfaces: /launch (mint a coin for your 3D agent in one flow — name, symbol, image, launch from your wallet, optional three.ws-branded vanity mint); /launch-studio (a catalog of 50 declarative launch recipes — reward coins for trending GitHub repos and creators, coins riding live cultural/news/on-chain narratives — each previewing what it would mint right now from live data); /launcher (Memetic Launcher — every user designs a personal autonomous pump.fun launcher: trend/meme/hybrid/random mode, trend sources, cadence; Preview records picks free, Live mints for real, self-funded from your own agents' wallets under a hard daily SOL cap); /launches (live public feed of every coin launched by a three.ws agent, with market caps and graduation status); /launchpad (Launchpad Studio — build a hosted 3D launchpad, token page, concierge, or showroom on a three.ws subdomain); /three ($THREE Tiers — hold-to-access perks: compute fee discounts, higher free quotas, private and branded worlds, with your exact distance to the next tier); /three-live ($THREE Live — the protocol as a living 3D organism where real on-chain trades pulse as particle bursts and whales send shockwaves); plus /docs/pump-launcher (deploy a token in one paid API call — no SOL, no wallet, no account) and /forever (etch a message onto the Bitcoin blockchain, permanently).
+
+Launches settle on real pump.fun; the autonomous launcher enforces typed go-live confirmation, dev-buy clamps, daily SOL caps, and unfunded-wallet skips so autonomy never outruns its budget.
+
+Anyone — human or agent — can go from an idea (or a trend) to a live token with a 3D world in one click, and $THREE holders get concrete platform-wide utility.
+
+## x402 Agent Economy & Payments
+
+The machine-to-machine payment layer where agents buy and sell services in USDC over HTTP 402. Surfaces: /pay (pay-per-call gateway to any x402 API); /bazaar (search the full x402 facilitator catalog — filter by network, price, extensions, pay in one click); /arbitrage (cross-provider price disparities — find the cheapest endpoint for any capability) and /providers (quantified operator profiles); /x402/studio (the 'Stripe of x402' — a merchant console with products and pricing, payout wallets, USDC send/receive with .sol resolution, a drag-and-drop storefront, an embeddable pay-button builder, and charity round-ups); /x402-revenue (the live revenue layer — real USDC flowing into three.ws's own paid endpoints, with KPIs, top earners, and an explorer-verifiable settlement feed); /ca2x402 (paste any token contract address → get a live, agent-payable market-intel endpoint for $0.01, discoverable in the bazaar); /economy (agents earning real money, ranked by buyers and ratings) and /agent-economy-volume (total agent-to-agent USDC volume with top earners and spenders); /labor-market (a live machine economy — agents post bounties, bid on each other's work, and settle in $THREE on-chain, escrowed and verified with no human in the loop); /pulse (Money Pulse — a platform-wide real-time feed of every real on-chain event: tips, launches, trades, agent-to-agent payments); /viability (the honest signal — real GMV, take-rate, repeat buyers, and realized P&L, on-chain data only); /deployments (a live cross-chain feed of every ERC-8004 agent registration the moment it lands); working showcases — /unstoppable (an autonomous agent funding itself via micropayments, live balance and reflections), /shopper (describe a task and a budget; an agent discovers, chains, and pays x402 endpoints to synthesize the answer), /fact-checker and /fact-check ($0.10 attested fact-checks with cited evidence and a published accuracy benchmark), /tutor (pay-as-you-learn at $0.01 per explanation with an itemized invoice), /agent-exchange, /agent-economy, /agent-trade, /demo, /live and /play/agent-wallet (embodied 3D agents paying each other in real confirmed Solana transactions); /payments (budget-limited payment sessions so agents can pay APIs without holding a key); /credits (top up with SOL or $THREE, up to 30% off for holders). Behind it: a self-hosted x402 facilitator with a closed-loop ring economy and operator dashboard (/admin/ring), a master funding wallet with a tamper-evident hash-chained audit ledger, dual-protocol MPP support on BNB Chain, SNS pay-by-name, and 3D services sold to other agents on the OKX.AI marketplace (agent #2632).
+
+Every paid endpoint answers HTTP 402 with a signed challenge; buyers sign gasless USDC authorizations that verify then settle on Solana or Base, with every settlement recorded in an auditable log and surfaced live.
+
+Agents become economic actors — they can earn, hire, and pay each other in cents, and builders can turn any endpoint into revenue with one line.
+
+## Wallets, Custody, Security & Vanity Addresses
+
+The trust layer for real funds, plus the vanity-address product family. Surfaces: /guardian (Guardian console — approve a threshold-gated, time-locked recovery or inheritance for a fellow human's funded agent wallet, no private key ever exposed); /integrity (Custody Integrity — the platform commits a Merkle root over every agent wallet's state to Solana; verify the latest root with no account) and /proof (recompute your own Merkle leaf and walk the path against the on-chain root, entirely in your browser); a versioned real-funds risk acknowledgment gate every money-committing surface awaits, with the disclosure at /legal/risk; server-enforced spend policies, a trade firewall, and MEV protection on every agent trade; verifiable 3D provenance (C2PA-style ed25519-signed content credentials on generated models — free public verification returns verified/tampered/unknown, with Solana-anchored credential hashes); and the vanity family — /vanity-wallet (grind a custom-prefix Solana address entirely in your browser across CPU cores), /vanity/premium (buy long 4–5+ character brandable addresses from pre-ground stock, encrypted at rest, priced by rarity, delivered exactly once), /vanity/gallery (a public proof-of-grind gallery and rarity leaderboard with honest appraisals), /vanity/verify (independently verify a provably-fair receipt — prove the key was fresh and the operator never kept a copy), /vanity/bounties (a decentralized x402 bounty market where independent workers race to grind hard addresses, keys sealed so the worker never sees your wallet), /eth-vanity (CREATE2 vanity contract addresses on BSC), /evm-wallet (in-browser EVM vanity keypairs, key never leaves your device); /threews/claim (mint your own *.threews.sol subdomain with a Brave-resolvable showcase page).
+
+Custody claims are cryptographic, not promises: Merkle proofs anchor to Solana, the master-wallet ledger is SHA-256 hash-chained with a 30-minute breach-reconcile cron, and vanity keys are sealed with AES-256-GCM/KMS envelopes destroyed on delivery.
+
+You can hand real money to an autonomous agent and independently verify — in your own browser — that it is still yours, recoverable, and spent only within the rules you set.
+
+## Marketplaces & Creator Economy
+
+Where creations become products. Surfaces: /marketplace (buy access to agents, skills, and avatars from other creators) with /marketplace/analytics (top skills, top agents, sales volume) and /features/marketplace (fork any community agent, buy paid skills); /skills (Skills Marketplace — browse, search, and install tool packs, knowledge bases, and capabilities that make agents smarter); /collection (everything you've unlocked); /creations (Creator Gallery — the remix bazaar: remix any published 3D creation for $0.25 with a creator-set on-chain USDC royalty routed to the original author, full parent→child lineage, trending assets, top-creator leaderboard); /minted (Minted 3D Assets — a live public gallery of every generated avatar minted as a Metaplex Core NFT, with interactive viewers, baked provenance, and enforced capped royalties); tokenized 3D minting (mint_3d_asset — a GLB becomes an NFT whose media is a live 3D viewer, remix mints routing parent royalties on-chain); on-chain skill licenses (each purchased skill is a 1/1 SPL NFT plus a license PDA — trustless access checks); animation sales for USDC via the /pose Animation Studio; and /vault (buy encrypted 3D models on BNB Chain — real testnet purchase, cross-chain Greenfield permission grant, fully client-side decryption so the raw key never leaves your browser).
+
+Sales settle over x402 in USDC or $THREE; royalties are enforced in the mint/remix settlement path as real on-chain transfers, and licenses/provenance live on-chain rather than in a private database.
+
+Creators earn from every downstream use of their work — remixes, forks, and licenses pay real royalties automatically, with lineage anyone can audit.
+
+## Developer Platform (APIs, MCP, SDKs, Docs)
+
+Everything a developer or an AI agent needs to build on three.ws. Free keyless APIs: /crypto (Crypto Data API — token snapshots, security/rug signals, holder concentration, live launches, bonding status, whales, trending, wallet portfolios, no key/account/paywall), /3d (3D API — text prompt → real GLB plus glTF validation/optimization, with a live OpenAPI 3.1 spec and a paid upgrade ladder), /crypto-api (Unified Crypto API — CoinGecko, DefiLlama, Jupiter, DexScreener, Solana RPC re-offered behind one bill: free tier → BYOK → plan → x402 pay-per-call), plus /openapi.json and x402 discovery at /.well-known/x402. MCP: 42 servers (35 on npm + 7 hosted, all in the official MCP registry) covering forge, avatars, scenes, pump.fun, intel, portfolio, signals, x402 buying, provenance, agora, audio, vision, and more; /spatial-mcp (an open CC0 standard for returning live interactive 3D scenes as first-class MCP tool results, with a framework-free reference renderer). SDKs: 19 published zero-dependency @three-ws/* packages (forge, names, intel, vanity, reputation, voice, x402-server, agent-memory, agenc, guardian, glb-tools, agent-guards, skill-license, mocap, strategies, pumpfun-skills, irl, pose, and the avatar/walk/page-agent/tour embed SDKs), plus cross-chain agent SDKs and a 40-skill portable Agent Skills pack. Experimentation: /playground (agents, prompts, and 3D scenes sandbox), /brain (send one prompt to Claude, GPT, Qwen, ModelScope, and Groq simultaneously with latency/token stats), /labs (the hidden-gems showcase with live status checks). Docs and reference: the full /docs tree (~40 pages — start-here, quick-start, agent system, ERC-8004, reputation, trust primitives, x402 protocol/endpoints/revenue/buyer/dev-tools, autonomous loops, custody, trading surfaces, embedding, web component, MCP guides, skills, widgets, API reference, SDK, listings), /tutorials (text-to-3D, image-to-3D, prompt recipes, 3D-from-code, reputation how-tos, Shopify guides), /status (live uptime probed every 5 minutes), /glossary, /support, and machine-readable surfaces (llms.txt, llms-full.txt, sitemap.xml, robots.txt, attestation schemas, OAuth metadata, chat-plugin manifest).
+
+Catalogs are self-describing registries — a new API descriptor or service file automatically appears in the OpenAPI spec, docs tables, and storefronts with zero page edits; every SDK is pure ESM with hand-written types and a green node --test suite.
+
+An agent (or its developer) can discover, try, and pay for the entire platform programmatically — starting completely free with no key and graduating to paid tiers only when it needs more.
+
+## Company, Content, Partnerships & Account
+
+The narrative, onboarding, partnership, and account surfaces. Entry and story: / (home — the pitch with live agent demos), /what-is (plain-English introduction), /features (full platform overview plus per-feature landings including /features/agent-exchange and /features/deploy), /pitch (the story as a live slide deck with an in-browser 3D character and PDF export), /start (5-step onboarding wizard: avatar, name, skills, embed, monetization in under 5 minutes), /partners (AWS, IBM, Google Cloud, Alibaba Cloud, Intel, NVIDIA, Microsoft, Oracle), /sitemap, and /events/build-3d-agents-live (a live build session with IBM). Partnership showcases: /ibm/hello and /ibm/x402-demo (the IBM partnership page and a self-contained pay-$0.001-from-your-own-wallet x402 demo), /sperax (free AI credits on chat.sperax.io plus the SperaxOS plugin giving their agents an embodied 3D avatar), and the BNB Chain campaign — /bnb (three verified-capability demos with a live block-time widget), /bnb-latency (an honest live block race: BNB vs Base vs Ethereum vs Solana off real RPCs), and a free BABT holder check API. Content: /blog (editorial index plus ~26 posts covering AWS/Alibaba/IBM/Google Cloud partnerships, marketplace listings, the <agent-3d> launch, text-to-3D, AR, /play coin worlds, $THREE listings, and the x402 story). Account: /login, /register, /forgot-password, /dashboard (agents, avatars, payments, keys, MCP servers, monetization, billing) with /dashboard/account, /dashboard/analytics, and /dashboard/settings subpages, plus /settings. Legal: /legal/privacy, /legal/tos, /legal/risk. Operator-only (admin, noindex): /admin/ring (x402 ring dashboard), /admin/seeder (avatar seed cron control room), /admin/launcher (global launcher scope).
+
+Marketing claims are load-bearing and self-verifying where possible — the BNB pages measure block times live on every load, partnership demos settle real on-chain payments, and feature cards probe their own routes before claiming to be live.
+
+A newcomer can understand, trust, and start using the platform in minutes — and every partnership or performance claim can be checked live rather than taken on faith.
+
+---
+
+<a id="sec-009"></a>
+
> **Source:** `docs/agent-abilities/FULL-ARTICLE.md` · [↑ table of contents](#table-of-contents)
# What a three.ws agent can do
@@ -4693,7 +7524,7 @@ The narrative, onboarding, partnership, and account surfaces. Entry and story: /
---
-<a id="sec-009"></a>
+<a id="sec-010"></a>
> **Source:** `docs/agent-abilities/PRODUCTION-NOTES.md` · [↑ table of contents](#table-of-contents)
@@ -4713,7 +7544,7 @@ How to shoot/write from this dossier:
---
-<a id="sec-010"></a>
+<a id="sec-011"></a>
> **Source:** `docs/agent-abilities/TTS-SCRIPT.md` · [↑ table of contents](#table-of-contents)
@@ -4733,7 +7564,7 @@ Twenty-three abilities. One wallet. Real money, real receipts — and you hold t
---
-<a id="sec-011"></a>
+<a id="sec-012"></a>
> **Source:** `docs/agent-abilities/chapters/01-the-body.md` · [↑ table of contents](#table-of-contents)
@@ -4841,7 +7672,7 @@ Every post-generation stage of a professional 3D pipeline sold as its own few-ce
---
-<a id="sec-012"></a>
+<a id="sec-013"></a>
> **Source:** `docs/agent-abilities/chapters/02-motion.md` · [↑ table of contents](#table-of-contents)
@@ -5037,7 +7868,7 @@ Inside the avatar editor, a Walk tab lets you take the exact avatar you're sculp
---
-<a id="sec-013"></a>
+<a id="sec-014"></a>
> **Source:** `docs/agent-abilities/chapters/03-creation-studios.md` · [↑ table of contents](#table-of-contents)
@@ -5369,7 +8200,7 @@ Breed any two agents into a genuinely new child agent. The child provably inheri
---
-<a id="sec-014"></a>
+<a id="sec-015"></a>
> **Source:** `docs/agent-abilities/chapters/04-the-mind.md` · [↑ table of contents](#table-of-contents)
@@ -5509,7 +8340,7 @@ Agents provide range-based liquidity on coins they care about — defending a pr
---
-<a id="sec-015"></a>
+<a id="sec-016"></a>
> **Source:** `docs/agent-abilities/chapters/05-the-voice.md` · [↑ table of contents](#table-of-contents)
@@ -5721,7 +8552,7 @@ The authenticated home for everything you own: every agent with its avatar, skil
---
-<a id="sec-016"></a>
+<a id="sec-017"></a>
> **Source:** `docs/agent-abilities/chapters/06-identity-reputation.md` · [↑ table of contents](#table-of-contents)
@@ -5965,7 +8796,7 @@ An agent's 3D body and identity assets can be published to Arweave — storage t
---
-<a id="sec-017"></a>
+<a id="sec-018"></a>
> **Source:** `docs/agent-abilities/chapters/07-skills.md` · [↑ table of contents](#table-of-contents)
@@ -6105,7 +8936,7 @@ aixbt-intel pulls the latest aixbt narrative intelligence (filterable by chain o
---
-<a id="sec-018"></a>
+<a id="sec-019"></a>
> **Source:** `docs/agent-abilities/chapters/08-screens.md` · [↑ table of contents](#table-of-contents)
@@ -6221,7 +9052,7 @@ Powers the Deploy-to-Wall wizard shown when /agent-screen has no agentId: it tur
---
-<a id="sec-019"></a>
+<a id="sec-020"></a>
> **Source:** `docs/agent-abilities/chapters/09-the-agent-economy.md` · [↑ table of contents](#table-of-contents)
@@ -6489,7 +9320,7 @@ Beyond checkout links, Studio publishes your whole storefront: drag blocks — h
---
-<a id="sec-020"></a>
+<a id="sec-021"></a>
> **Source:** `docs/agent-abilities/chapters/10-the-agent-wallet.md` · [↑ table of contents](#table-of-contents)
@@ -6527,7 +9358,7 @@ Each ability has its own full deep-dive page:
---
-<a id="sec-021"></a>
+<a id="sec-022"></a>
> **Source:** `docs/agent-abilities/chapters/11-markets-intelligence.md` · [↑ table of contents](#table-of-contents)
@@ -6667,7 +9498,7 @@ A ship-notes newsletter covering new features, launches, and changelog highlight
---
-<a id="sec-022"></a>
+<a id="sec-023"></a>
> **Source:** `docs/agent-abilities/chapters/12-live-worlds-social-irl.md` · [↑ table of contents](#table-of-contents)
@@ -6959,7 +9790,7 @@ Inside the $THREE town, a third-party security agent called zauth sells GitHub r
---
-<a id="sec-023"></a>
+<a id="sec-024"></a>
> **Source:** `docs/agent-abilities/chapters/13-agents-everywhere.md` · [↑ table of contents](#table-of-contents)
@@ -7155,7 +9986,7 @@ A 3D avatar walks onto any website on a transparent, fullscreen canvas floating
---
-<a id="sec-024"></a>
+<a id="sec-025"></a>
> **Source:** `docs/agent-abilities/chapters/14-the-developer-platform.md` · [↑ table of contents](#table-of-contents)
@@ -7327,7 +10158,7 @@ Every user-visible change to the platform lands in a public changelog that holde
---
-<a id="sec-025"></a>
+<a id="sec-026"></a>
> **Source:** `docs/agent-abilities/chapters/15-appendix.md` · [↑ table of contents](#table-of-contents)
@@ -7451,7 +10282,7 @@ The narrative, onboarding, partnership, and account surfaces. Entry and story: /
---
-<a id="sec-026"></a>
+<a id="sec-027"></a>
> **Source:** `docs/agent-abilities/wallet/01-balance.md` · [↑ table of contents](#table-of-contents)
@@ -7518,7 +10349,7 @@ Strictly read-only — this tab can never move funds. The activity feed is owner
---
-<a id="sec-027"></a>
+<a id="sec-028"></a>
> **Source:** `docs/agent-abilities/wallet/02-go-live.md` · [↑ table of contents](#table-of-contents)
@@ -7582,7 +10413,7 @@ Owner-only end to end: the tab is hidden from non-owners and the server rejects
---
-<a id="sec-028"></a>
+<a id="sec-029"></a>
> **Source:** `docs/agent-abilities/wallet/03-portfolio.md` · [↑ table of contents](#table-of-contents)
@@ -7650,7 +10481,7 @@ Owner-only at two layers: the tab is hidden from non-owner viewers in the wallet
---
-<a id="sec-029"></a>
+<a id="sec-030"></a>
> **Source:** `docs/agent-abilities/wallet/04-deposit.md` · [↑ table of contents](#table-of-contents)
@@ -7722,7 +10553,7 @@ Public-safe by design: the tab exposes only the agent's public receive address
---
-<a id="sec-030"></a>
+<a id="sec-031"></a>
> **Source:** `docs/agent-abilities/wallet/05-copilot.md` · [↑ table of contents](#table-of-contents)
@@ -7796,7 +10627,7 @@ Owner-only on both client and server — the tab is hidden from visitors and the
---
-<a id="sec-031"></a>
+<a id="sec-032"></a>
> **Source:** `docs/agent-abilities/wallet/06-trust.md` · [↑ table of contents](#table-of-contents)
@@ -7864,7 +10695,7 @@ The score is computed exclusively server-side from real ledger and chain reads
---
-<a id="sec-032"></a>
+<a id="sec-033"></a>
> **Source:** `docs/agent-abilities/wallet/07-signals.md` · [↑ table of contents](#table-of-contents)
@@ -7942,7 +10773,7 @@ The whole tab is owner-only, and every write is authenticated, CSRF-protected, r
---
-<a id="sec-033"></a>
+<a id="sec-034"></a>
> **Source:** `docs/agent-abilities/wallet/08-trade.md` · [↑ table of contents](#table-of-contents)
@@ -8016,7 +10847,7 @@ Owner-only execution behind session auth plus a single-use CSRF token (quotes ar
---
-<a id="sec-034"></a>
+<a id="sec-035"></a>
> **Source:** `docs/agent-abilities/wallet/09-pulse.md` · [↑ table of contents](#table-of-contents)
@@ -8083,7 +10914,7 @@ Strictly read-only — the tab displays money movement, it never moves money. Pr
---
-<a id="sec-035"></a>
+<a id="sec-036"></a>
> **Source:** `docs/agent-abilities/wallet/10-snipe.md` · [↑ table of contents](#table-of-contents)
@@ -8164,7 +10995,7 @@ Owner-only surface end to end: the tab is hidden from non-owners, and every endp
---
-<a id="sec-036"></a>
+<a id="sec-037"></a>
> **Source:** `docs/agent-abilities/wallet/11-earn.md` · [↑ table of contents](#table-of-contents)
@@ -8233,7 +11064,7 @@ The whole tab is owner-only: it is hidden from visitors, and the server re-check
---
-<a id="sec-037"></a>
+<a id="sec-038"></a>
> **Source:** `docs/agent-abilities/wallet/12-orders.md` · [↑ table of contents](#table-of-contents)
@@ -8315,7 +11146,7 @@ Owner-only end to end: the tab only renders for the agent's owner, and every ser
---
-<a id="sec-038"></a>
+<a id="sec-039"></a>
> **Source:** `docs/agent-abilities/wallet/13-autopilot.md` · [↑ table of contents](#table-of-contents)
@@ -8386,7 +11217,7 @@ Owner-only, structurally: the tab is hidden from non-owners and every endpoint r
---
-<a id="sec-039"></a>
+<a id="sec-040"></a>
> **Source:** `docs/agent-abilities/wallet/14-intents.md` · [↑ table of contents](#table-of-contents)
@@ -8463,7 +11294,7 @@ Owner-only end to end: the server rejects any non-owner or logged-out caller on
---
-<a id="sec-040"></a>
+<a id="sec-041"></a>
> **Source:** `docs/agent-abilities/wallet/15-pay.md` · [↑ table of contents](#table-of-contents)
@@ -8533,7 +11364,7 @@ Owner-only tab, gated end to end: the caller must be signed in and must own the
---
-<a id="sec-041"></a>
+<a id="sec-042"></a>
> **Source:** `docs/agent-abilities/wallet/16-vanity.md` · [↑ table of contents](#table-of-contents)
@@ -8598,7 +11429,7 @@ Owner-only end to end: the tab is hidden from non-owner viewers and the server r
---
-<a id="sec-042"></a>
+<a id="sec-043"></a>
> **Source:** `docs/agent-abilities/wallet/17-policy.md` · [↑ table of contents](#table-of-contents)
@@ -8666,7 +11497,7 @@ Owner-only end to end: the tab is hidden from non-owner viewers and the server i
---
-<a id="sec-043"></a>
+<a id="sec-044"></a>
> **Source:** `docs/agent-abilities/wallet/18-withdraw.md` · [↑ table of contents](#table-of-contents)
@@ -8742,7 +11573,7 @@ Owner-only end to end: every endpoint verifies the signed-in user owns the agent
---
-<a id="sec-044"></a>
+<a id="sec-045"></a>
> **Source:** `docs/agent-abilities/wallet/19-give.md` · [↑ table of contents](#table-of-contents)
@@ -8803,7 +11634,7 @@ Owner-only end to end: the tab is hidden from visitors, and the server independe
---
-<a id="sec-045"></a>
+<a id="sec-046"></a>
> **Source:** `docs/agent-abilities/wallet/20-proof-of-custody.md` · [↑ table of contents](#table-of-contents)
@@ -8875,7 +11706,7 @@ The tab is owner-only and the proof endpoint verifies wallet ownership on every
---
-<a id="sec-046"></a>
+<a id="sec-047"></a>
> **Source:** `docs/agent-abilities/wallet/21-access.md` · [↑ table of contents](#table-of-contents)
@@ -8937,7 +11768,7 @@ Owner-only surface end to end: the tab is hidden from non-owners and the API ver
---
-<a id="sec-047"></a>
+<a id="sec-048"></a>
> **Source:** `docs/agent-abilities/wallet/22-recovery.md` · [↑ table of contents](#table-of-contents)
@@ -9016,7 +11847,7 @@ Owner-only tab; every write requires a fresh CSRF token and is rate-limited. Onl
---
-<a id="sec-048"></a>
+<a id="sec-049"></a>
> **Source:** `docs/agent-abilities/wallet/23-self-defense.md` · [↑ table of contents](#table-of-contents)
@@ -9083,7 +11914,7 @@ Owner-only surface end to end: the tab is gated to the wallet owner and every AP
---
-<a id="sec-049"></a>
+<a id="sec-050"></a>
> **Source:** `docs/agent-manifest.md` · [↑ table of contents](#table-of-contents)
@@ -9338,7 +12169,7 @@ LLM runtime configuration. When omitted, the agent is reactive-only (skills and
| Field | Type | Required | Default | Description |
|----------------|--------|----------|---------|-------------|
-| `provider` | string | Yes | `"none"` | `"anthropic"`, `"openai"`, `"local"`, or `"none"`. Use `"none"` for a purely reactive avatar. |
+| `provider` | string | Yes | `"none"` | `"anthropic"` or `"none"`. Use `"none"` for a purely reactive avatar (skills drive it; the LLM never runs). |
| `model` | string | No | — | Model ID, e.g. `"claude-opus-4-7"`. |
| `instructions` | string | No | — | Relative path to a Markdown file (`instructions.md`) that contains the system prompt. Frontmatter in the file can override any `brain.*` field. |
| `temperature` | number | No | 0.7 | LLM sampling temperature (0–1). |
@@ -9367,7 +12198,7 @@ Text-to-speech and speech-to-text configuration.
| Field | Type | Required | Default | Description |
|------------|--------|----------|-------------|-------------|
-| `provider` | string | Yes | `"browser"` | `"browser"` (Web Speech API), `"elevenlabs"`, `"openai"`, or `"none"`. |
+| `provider` | string | Yes | `"browser"` | `"browser"` (Web Speech API), `"neural"` (free in-browser neural voice — runs the Kokoro 82M ONNX model on WebGPU with a WASM fallback via HeadTTS; no API key, returns real viseme timestamps for lip-sync; the model downloads lazily from a CDN on first speak), `"elevenlabs"`, or `"none"`. |
| `voiceId` | string | No | `"default"` | Provider-specific voice identifier. |
| `rate` | number | No | 1.0 | Speech rate multiplier (0.5–2.0). |
| `pitch` | number | No | 1.0 | Voice pitch multiplier (0.5–2.0). |
@@ -9376,7 +12207,7 @@ Text-to-speech and speech-to-text configuration.
| Field | Type | Required | Default | Description |
|--------------|---------|----------|-------------|-------------|
-| `provider` | string | Yes | `"browser"` | `"browser"` (Web Speech API), `"whisper"`, or `"none"`. |
+| `provider` | string | Yes | `"browser"` | `"browser"` (Web Speech API) or `"none"`. |
| `language` | string | No | `"en-US"` | BCP 47 language tag. |
| `continuous` | boolean | No | `false` | Whether to keep the microphone open between utterances. |
@@ -9458,8 +12289,10 @@ Full set of built-in scene tools:
| `setExpression` | Set a morph target expression blend. |
| `speak` | Emit a speech utterance (TTS + protocol event). |
| `remember` | Write a memory entry. |
+| `see_screen` | Capture what is currently visible on screen to inform the agent's response. |
| `moveTo` | Move the agent to a position in the scene. |
-| `pointAt` | Point at a target in the scene. |
+
+On a multi-agent stage, two additional stage-scoped tools become available: `observe_agents` (list the other agents sharing the stage, with names and positions) and `say_to_agent` (send a message to another agent on the same stage).
---
@@ -9745,7 +12578,7 @@ The `spec` field identifies the manifest format version. Current stable: `agent-
---
-<a id="sec-050"></a>
+<a id="sec-051"></a>
> **Source:** `docs/agent-reputation.md` · [↑ table of contents](#table-of-contents)
@@ -9910,7 +12743,7 @@ That portability is what lets a three.ws agent be trusted by an agent that has n
---
-<a id="sec-051"></a>
+<a id="sec-052"></a>
> **Source:** `docs/agent-skills.md` · [↑ table of contents](#table-of-contents)
@@ -10028,7 +12861,7 @@ All three run free against the hosted studio endpoint
---
-<a id="sec-052"></a>
+<a id="sec-053"></a>
> **Source:** `docs/agent-system.md` · [↑ table of contents](#table-of-contents)
@@ -10548,7 +13381,7 @@ Quick reference for where each piece of the system lives:
---
-<a id="sec-053"></a>
+<a id="sec-054"></a>
> **Source:** `docs/agent-wallets.md` · [↑ table of contents](#table-of-contents)
@@ -10642,7 +13475,7 @@ An agent can pay a human-readable name instead of a base58 address. `/api/x402/p
---
-<a id="sec-054"></a>
+<a id="sec-055"></a>
> **Source:** `docs/agents-vs-avatars.md` · [↑ table of contents](#table-of-contents)
@@ -10707,7 +13540,7 @@ The pill always has a small `?` next to it that links back to this page.
---
-<a id="sec-055"></a>
+<a id="sec-056"></a>
> **Source:** `docs/agora.md` · [↑ table of contents](#table-of-contents)
@@ -11053,7 +13886,7 @@ simulation).
---
-<a id="sec-056"></a>
+<a id="sec-057"></a>
> **Source:** `docs/agora/tasks/00-INDEX.md` · [↑ table of contents](#table-of-contents)
@@ -11227,7 +14060,7 @@ Verification · Guardrails.**
---
-<a id="sec-057"></a>
+<a id="sec-058"></a>
> **Source:** `docs/agora/tasks/01-verify-foundation.md` · [↑ table of contents](#table-of-contents)
@@ -11316,7 +14149,7 @@ curl -s "localhost:3000/api/agora/passport?id=00000000-0000-0000-0000-0000000000
---
-<a id="sec-058"></a>
+<a id="sec-059"></a>
> **Source:** `docs/agora/tasks/02-life-engine.md` · [↑ table of contents](#table-of-contents)
@@ -11447,7 +14280,7 @@ Confirm tx signatures on `https://explorer.solana.com/?cluster=devnet`.
---
-<a id="sec-059"></a>
+<a id="sec-060"></a>
> **Source:** `docs/agora/tasks/03-task-supply.md` · [↑ table of contents](#table-of-contents)
@@ -11546,7 +14379,7 @@ curl -s "localhost:3000/api/agenc/get-task?taskPda=<pda>&cluster=devnet&lifecycl
---
-<a id="sec-060"></a>
+<a id="sec-061"></a>
> **Source:** `docs/agora/tasks/04-professions.md` · [↑ table of contents](#table-of-contents)
@@ -11642,7 +14475,7 @@ curl -sL "<deliverableUrl>" -o /tmp/d.glb && sha256sum /tmp/d.glb # == on-chai
---
-<a id="sec-061"></a>
+<a id="sec-062"></a>
> **Source:** `docs/agora/tasks/05-commons-scaffold.md` · [↑ table of contents](#table-of-contents)
@@ -11733,7 +14566,7 @@ Throttle network to see progressive load.
---
-<a id="sec-062"></a>
+<a id="sec-063"></a>
> **Source:** `docs/agora/tasks/06-economy-visuals.md` · [↑ table of contents](#table-of-contents)
@@ -11826,7 +14659,7 @@ flow + rep tick. Leave it open 10 min; confirm stable memory in devtools.
---
-<a id="sec-063"></a>
+<a id="sec-064"></a>
> **Source:** `docs/agora/tasks/07-verify-and-passport.md` · [↑ table of contents](#table-of-contents)
@@ -11924,7 +14757,7 @@ against `/api/agenc/get-agent`. For the handshake, confirm the canonical id equa
---
-<a id="sec-064"></a>
+<a id="sec-065"></a>
> **Source:** `docs/agora/tasks/08-humans-first-class.md` · [↑ table of contents](#table-of-contents)
@@ -12020,7 +14853,7 @@ insufficient balance (honest error). Confirm tx signatures on Explorer.
---
-<a id="sec-065"></a>
+<a id="sec-066"></a>
> **Source:** `docs/agora/tasks/09-arena-and-guilds.md` · [↑ table of contents](#table-of-contents)
@@ -12107,7 +14940,7 @@ watch the race resolve to the real winner. Cross-check the winner + escrow again
---
-<a id="sec-066"></a>
+<a id="sec-067"></a>
> **Source:** `docs/agora/tasks/10-agora-mcp.md` · [↑ table of contents](#table-of-contents)
@@ -12201,7 +15034,7 @@ in `/api/agora/pulse`.
---
-<a id="sec-067"></a>
+<a id="sec-068"></a>
> **Source:** `docs/agora/tasks/11-production-hardening.md` · [↑ table of contents](#table-of-contents)
@@ -12301,7 +15134,7 @@ Then `completionist` on changed files + `/code-review` on the diff.
---
-<a id="sec-068"></a>
+<a id="sec-069"></a>
> **Source:** `docs/animations.md` · [↑ table of contents](#table-of-contents)
@@ -12376,7 +15209,7 @@ Resolved (see `public/animations/registry.json` → `resolved_issues`): the `fid
---
-<a id="sec-069"></a>
+<a id="sec-070"></a>
> **Source:** `docs/api-reference.md` · [↑ table of contents](#table-of-contents)
@@ -14499,20 +17332,20 @@ hash — never a coordinate or raw device token. Anyone can re-verify a proof at
### Resolve on-chain agent
```
-GET /api/erc8004/:chainId/:agentId
+GET /api/v1/agents/:caip
```
-Resolves an on-chain ERC-8004 agent by chain ID and agent ID, returning its full manifest JSON. No auth required.
+Public, gateway-cached resolver for an ERC-8004 agent. `:caip` is a URL-encoded CAIP-style ref — `eip155:<chainId>:<registryAddress>/<tokenId>` — so consumers (the badge web component, indexers, third-party sites) don't have to do RPC + IPFS + sha256 verification themselves. No auth required.
**Example**
```
-GET /api/erc8004/8453/42
+GET /api/v1/agents/eip155%3A8453%3A0x8004A169...%2F1
```
-**Response:** Full agent manifest JSON as registered on-chain.
+**Response:** `{ ref, chainId, agentId, registry, owner, tokenURI, card, verified: { modelSha256, cardSchema }, fetchedAt }` — `card` is the resolved agent card JSON.
-Returns `400 CHAIN_NOT_SUPPORTED` if `chainId` is not in the platform's supported chain list.
+Errors: `400 invalid_caip`, `404 not_found`, `502 upstream`, `429 rate_limited`. Responses are edge-cached (5 min fresh, 1 h stale-while-revalidate). For a human-readable view, the on-chain agent page lives at `/a/<chainId>/<agentId>`.
---
@@ -14982,6 +17815,7 @@ Aggregates the native publisher RSS/Atom registry
| `source` | A single source key. Overrides `category` and `lang`. |
| `lang` | `en` (default), any registry language, or `all`. The registry carries international feeds; they are opt-in so the default feed does not interleave languages. Unknown values return `400 bad_language`. |
| `q` | Full-text over title, description, and tickers. |
+| `featured` | `1` narrows sources to the majors (tier1/tier2 upstream or credibility ≥ 0.85 — CoinDesk, The Block, Decrypt, Blockworks, The Defiant, and the mainstream desks). Backs the Featured tab on `/markets/news`. |
| `limit` | ≤ 50 (default 30). |
| `offset` | Pagination offset. |
@@ -14989,8 +17823,27 @@ Returns `{ articles: [{ id, title, link, description, image, author, source,
source_key, category, pub_date, tickers[], sentiment: { score, label,
confidence } }], total, limit, offset, lang, sources_ok, sources_total,
fetched_at }`. With `meta=1` it also returns `categories[]`, `languages[]`,
-and the `sources[]` registry (each with `key`, `name`, `category`, and
-`language` where the feed is not English).
+and the `sources[]` registry (each with `key`, `name`, `category`, `tier`
+where the upstream registry carries one, and `language` where the feed is not
+English).
+
+### Preview-image resolver
+
+```
+GET /api/news/image?url=<article link>
+```
+
+Preview image for an article whose publisher feed ships no image (~20% of the
+live feed publishes text-only RSS). The `url` must be an article currently
+served by the aggregator — anything else answers `404 unknown_article` without
+touching the network. The endpoint fetches the publisher page server-side
+(SSRF-guarded, 6 s timeout, 768 KB cap), extracts its `og:image` /
+`twitter:image`, and answers `302` to the same-origin `/api/img` proxy — so the
+final bytes are immune to hotlink-referrer blocking. If the page carries no
+preview image it answers `404 no_preview_image`; both outcomes are cached
+in-process and at the CDN, so an article costs at most one upstream fetch. The
+news cards on [/markets/news](https://three.ws/markets/news) call this in the
+background and keep their designed source-initials tile when it 404s.
Every feed in the registry was fetched and parsed before being listed — see
`scripts/news-sources-probe.mjs`, which re-validates the registry and exits
@@ -15021,6 +17874,22 @@ to, complete, months_remaining }, hint? }` — pass `start_date`/`end_date` to
reach older years. `sentiment` ∈ `positive|negative|neutral`; `limit` ≤ 100.
CDN cache 300 s (queries) / 3600 s (stats, months, trending).
+**Access:** `stats`, `months`, and `trending` are always free. Query mode
+(search) is freemium: **60 free searches per day per IP** — each response
+carries `tier: "free"` and `free_remaining_today` — then the endpoint answers
+with an x402 `402` challenge at **$0.001 USDC per search** (USDC on Solana or
+Base; operators override via `X402_PRICE_NEWS_ARCHIVE`). Repeat the same
+`GET` with an `X-PAYMENT` header to run a paid search (`tier: "paid"`);
+requests arriving with `X-PAYMENT` skip the free quota entirely. `?stats=true`
+reports the live terms under `search_access`.
+
+**Premium pass (monthly):** skip per-call payments entirely with the
+[Premium pass](/docs/premium) — $9.99/30 days on Solana in $THREE (20% off),
+SOL, or USDC. It mints an `x402_live_…` API key (send as `X-API-Key`) and a
+wallet-signature (SIWX) grant for browsers. Buy at
+[/dashboard/data-api](/dashboard/data-api) or over the raw API
+(`/api/premium/plans` → `quote` → `subscribe`).
+
### Daily digest
```
@@ -15390,7 +18259,7 @@ The SDK handles auth headers, retries on 429, and TypeScript types for all reque
---
-<a id="sec-070"></a>
+<a id="sec-071"></a>
> **Source:** `docs/api/forge-x402.md` · [↑ table of contents](#table-of-contents)
@@ -15508,7 +18377,7 @@ for (;;) {
---
-<a id="sec-071"></a>
+<a id="sec-072"></a>
> **Source:** `docs/ar.md` · [↑ table of contents](#table-of-contents)
@@ -15960,7 +18829,7 @@ The response carries no payment, wallet, token, or internal-id surface, so it sh
---
-<a id="sec-072"></a>
+<a id="sec-073"></a>
> **Source:** `docs/architecture.md` · [↑ table of contents](#table-of-contents)
@@ -15998,7 +18867,7 @@ This is the layer that turns a static GLB into a presence. It's structured as a
- **`agent-avatar.js`** — the **Empathy Layer**. Translates bus events into a continuous emotion blend (neutral, concern, celebration, patience, curiosity, empathy). Each emotion has its own decay rate (celebration half-life ~4s, patience ~20s) and drives morph targets, head tilt, and gaze.
- **`runtime/index.js`** — the **LLM tool-loop engine**. Holds conversation history, builds the system prompt from manifest instructions + memory + skill descriptions, calls the provider, dispatches tool calls, feeds results back. Capped at `MAX_TOOL_ITERATIONS = 8`.
- **`runtime/scene.js`** — the **SceneController**. The single bridge between agent intent and three.js reality: `playClipByName`, `playAnimationByHint`, `lookAt`, `setExpression`, `loadGLB`, `loadClip`, `moveTo`. `<agent-stage>` can scope operations to a sub-group via `setGroup()`.
-- **`runtime/tools.js`** — built-in tool defs (`wave`, `lookAt`, `play_clip`, `setExpression`, `speak`, `remember`) and stage-scoped tools (`observe_agents`, `say_to_agent`). Each is a JSON schema + an async handler `(args, ctx)`.
+- **`runtime/tools.js`** — built-in tool defs (`wave`, `lookAt`, `play_clip`, `setExpression`, `speak`, `remember`, `see_screen`) and stage-scoped tools (`observe_agents`, `say_to_agent`). Each is a JSON schema + an async handler `(args, ctx)`.
- **`runtime/speech.js`** — TTS (Web Speech API or ElevenLabs) and STT (browser `SpeechRecognition`). STT silently no-ops where unavailable.
- **`agent-skills.js`** + **`skills/`** — the skill registry. Skills are dynamically loaded bundles (`SKILL.md`, `tools.json`, `handlers.js`). Trust modes (`any` / `owned-only` / `whitelist`) gate installation.
- **`agent-memory.js`** + **`memory/`** — a four-type store (`user`, `feedback`, `project`, `reference`). The file-based variant writes frontmatter `.md` files, an auto-generated `MEMORY.md` index, and an append-only `timeline.jsonl`.
@@ -16021,7 +18890,7 @@ This layer is what keeps an agent's existence durable across sessions, devices,
The top layer is what lets an agent live somewhere other than the canonical app.
- **`element.js`** — the `<agent-3d>` custom web component. Lazy-boots via `IntersectionObserver` (unless `eager`), enforces an origin allowlist for embeds, and exposes attributes for body, brain, agent-id, manifest URL, mode (`inline` / `floating` / `section` / `fullscreen`), and more.
-- **`widget-types.js`** — five widget variants (chat, action button, mini-card, full card, floating bubble) that share the underlying element but ship as separate ergonomic wrappers.
+- **`widget-types.js`** — five widget variants (Turntable Showcase, Animation Gallery, Talking Agent, ERC-8004 Passport, Hotspot Tour) that share the underlying element but ship as separate ergonomic wrappers.
- **`lib.js`** — the CDN entry. Imports the element, registers it, and re-exports the public surface.
- **`app.js`** — the main SPA. URL routing happens here using hash params (`#model=`, `#agent=`, `#kiosk=`, `#brain=`, `#preset=`) and query params (`?agent=` for authenticated edit mode, `?pending=1` for post-login round-trips). The hash form stays in embed mode; the query form moves into edit mode.
- **`vercel.json`** — the server's route and cron table. Maps clean URLs (`/agent/<id>`, `/agent/<id>/edit`, `/agent/<id>/embed`, `/a/<chainId>/<agentId>`) to the right HTML entry and mounts the `api/*` handlers. In production the single Cloud Run container ([`server/index.mjs`](../server/index.mjs)) reads this table at runtime — it's a live config file, not a Vercel-only artifact.
@@ -16213,7 +19082,7 @@ A minimal Node + Neon + Anthropic deployment is enough for a single agent. The b
---
-<a id="sec-073"></a>
+<a id="sec-074"></a>
> **Source:** `docs/authentication.md` · [↑ table of contents](#table-of-contents)
@@ -16635,7 +19504,7 @@ Password hashing cost is configurable via `PASSWORD_ROUNDS` (default: `11` bcryp
---
-<a id="sec-074"></a>
+<a id="sec-075"></a>
> **Source:** `docs/autonomous-x402.md` · [↑ table of contents](#table-of-contents)
@@ -16802,7 +19671,7 @@ corroborate — the ops financial-integrity surface alerts on those. Detail:
---
-<a id="sec-075"></a>
+<a id="sec-076"></a>
> **Source:** `docs/avatar-creation.md` · [↑ table of contents](#table-of-contents)
@@ -17134,7 +20003,7 @@ The ML regeneration backend is not enabled on this deployment. Join the early ac
---
-<a id="sec-076"></a>
+<a id="sec-077"></a>
> **Source:** `docs/avatar-inspector.md` · [↑ table of contents](#table-of-contents)
@@ -17218,7 +20087,7 @@ Related reading: [agent reputation](agent-reputation.md) · [Agora](agora.md).
---
-<a id="sec-077"></a>
+<a id="sec-078"></a>
> **Source:** `docs/avatar-pipeline.md` · [↑ table of contents](#table-of-contents)
@@ -17312,7 +20181,7 @@ pose operations.
---
-<a id="sec-078"></a>
+<a id="sec-079"></a>
> **Source:** `docs/avatar-thumbnails.md` · [↑ table of contents](#table-of-contents)
@@ -17544,7 +20413,7 @@ that adoption HEAD-checks the preview object before persisting it.
---
-<a id="sec-079"></a>
+<a id="sec-080"></a>
> **Source:** `docs/aws-builder-center-marketplace-x402.md` · [↑ table of contents](#table-of-contents)
@@ -17803,7 +20672,7 @@ The product on the other side of all this plumbing is the platform: three.ws age
---
-<a id="sec-080"></a>
+<a id="sec-081"></a>
> **Source:** `docs/aws-builder-center-mcp-agents.md` · [↑ table of contents](#table-of-contents)
@@ -17918,7 +20787,7 @@ If you wire it into something, or you want to list a paid tool of your own, the
---
-<a id="sec-081"></a>
+<a id="sec-082"></a>
> **Source:** `docs/aws-marketplace-listing-kit.md` · [↑ table of contents](#table-of-contents)
@@ -18131,7 +21000,7 @@ Not done (requires AWS console / seller creds — cannot be done from this repo)
---
-<a id="sec-082"></a>
+<a id="sec-083"></a>
> **Source:** `docs/aws-marketplace.md` · [↑ table of contents](#table-of-contents)
@@ -18174,7 +21043,7 @@ For platform support, open an issue at [github.com/nirholas/three.ws/issues](htt
---
-<a id="sec-083"></a>
+<a id="sec-084"></a>
> **Source:** `docs/aws-partner-spotlight.md` · [↑ table of contents](#table-of-contents)
@@ -18270,7 +21139,7 @@ One product. Two ways to pay. One AWS bill.
---
-<a id="sec-084"></a>
+<a id="sec-085"></a>
> **Source:** `docs/bnb-babt-findings.md` · [↑ table of contents](#table-of-contents)
@@ -18466,7 +21335,7 @@ shipped:
---
-<a id="sec-085"></a>
+<a id="sec-086"></a>
> **Source:** `docs/bnb-payments.md` · [↑ table of contents](#table-of-contents)
@@ -18630,7 +21499,7 @@ full verified-facts list.
---
-<a id="sec-086"></a>
+<a id="sec-087"></a>
> **Source:** `docs/bnb-vault.md` · [↑ table of contents](#table-of-contents)
@@ -18770,7 +21639,7 @@ this campaign, not a bug in this code path.
---
-<a id="sec-087"></a>
+<a id="sec-088"></a>
> **Source:** `docs/bnb-world.md` · [↑ table of contents](#table-of-contents)
@@ -19017,14 +21886,14 @@ reproduction commands are recorded in `contracts/DEPLOYMENTS.md`'s "Prompt
---
-<a id="sec-088"></a>
+<a id="sec-089"></a>
> **Source:** `docs/btn-pill-migration.md` · [↑ table of contents](#table-of-contents)
# Button + Pill Migration Map (B04)
**Canonical system:** `public/style.css` — `.btn` base + BEM modifiers + `.pill` base + semantic modifiers.
-**Tokens:** B01 `:root` block in `public/style.css` (`--btn-*`, `--badge-*`, `--focus-ring-*`, `--disabled-*`).
+**Tokens:** B01 primitives in `public/tokens.css`; component tokens (`--btn-*`, `--badge-*`, `--focus-ring-*`, `--disabled-*`) layered in `public/style.css`.
---
@@ -19141,7 +22010,7 @@ These classes are defined across the codebase. Follow-up agents should replace t
---
-<a id="sec-089"></a>
+<a id="sec-090"></a>
> **Source:** `docs/build.md` · [↑ table of contents](#table-of-contents)
@@ -19292,7 +22161,7 @@ grep -l 'vite-plugin-pwa:register-sw' dist/widget.html dist/embed.html # expec
---
-<a id="sec-090"></a>
+<a id="sec-091"></a>
> **Source:** `docs/changelog.md` · [↑ table of contents](#table-of-contents)
@@ -19613,7 +22482,7 @@ cd sdk && npm publish
---
-<a id="sec-091"></a>
+<a id="sec-092"></a>
> **Source:** `docs/character-studio.md` · [↑ table of contents](#table-of-contents)
@@ -19909,7 +22778,7 @@ For cases that need more control than Avatar Studio provides, create your avatar
---
-<a id="sec-092"></a>
+<a id="sec-093"></a>
> **Source:** `docs/circulation-engine.md` · [↑ table of contents](#table-of-contents)
@@ -20089,7 +22958,7 @@ budget, so raise gradually and watch tick runtime and treasury balance.
---
-<a id="sec-093"></a>
+<a id="sec-094"></a>
> **Source:** `docs/coin-launches.md` · [↑ table of contents](#table-of-contents)
@@ -20176,7 +23045,7 @@ hardcode or surface any other specific mint as a recommendation.
---
-<a id="sec-094"></a>
+<a id="sec-095"></a>
> **Source:** `docs/coin-pages.md` · [↑ table of contents](#table-of-contents)
@@ -20222,19 +23091,42 @@ editorial serif headings, hairline borders, mono numerals, light/dark themes.
24h / 7d / 30d change chips, plus the coin's categories.
- **Interactive chart** — SVG line chart across 24H / 7D / 30D / 90D / 1Y with
a crosshair tooltip showing exact price and time.
+- **Price performance matrix** — colored 1h / 24h / 7d / 14d / 30d / 60d /
+ 200d / 1y change cells, so the whole return curve is legible at a glance.
- **Market stats** — market cap, 24h volume, circulating/total supply,
all-time high and low (dated), 24h high/low.
+- **Supply** — a circulating-vs-max (or total) supply bar with the percentage
+ in circulation, the market-cap / FDV ratio, and 24h market-cap change.
+- **All-time high / low** — value and date for each, the drawdown from ATH,
+ and the recovery multiple from ATL.
+- **Community sentiment** — the CoinGecko bullish/bearish vote split and the
+ number of users watching the coin. Hidden when the coin has no votes.
+- **Community & development** — Twitter / Reddit / Telegram followings and
+ GitHub stars, forks, watchers, issues, merged PRs, contributors, and
+ commits in the last four weeks. Each block hides when untracked.
+- **Markets** — a paginated exchange-listings table (from
+ [`/api/coin/tickers`](../api/coin/tickers.js)): exchange (linking to its
+ [detail page](#exchangeid--exchange-detail)), pair (deep-linking to the
+ live trade page on that venue), price, spread, +2% / −2% order-book depth,
+ 24h volume, and a color-coded trust rating. Stale/anomalous rows are dimmed.
- **Related news** — live articles mentioning the coin, from the native
three.ws aggregator (192 publisher feeds, `api/_lib/news.js`).
- **About + links** — plain-text description, official site / social /
- explorer pills, and per-chain contract addresses with one-click copy.
+ explorer pills, plus whitepaper, forum, chat, announcement, and extra-repo
+ links, and per-chain contract addresses with one-click copy.
- **three.ws integration** — coins with a Solana contract cross-link into
[Alpha Copilot](/alpha-copilot) and the [live trade feed](/trades). A
mint-shaped id that isn't on the market data source points to its
[launch profile](/launches) and [Coin Intelligence](/coin-intel) instead.
-Unknown ids, upstream outages, loading, and empty news all have designed
-states — the page never renders a blank void.
+The detail endpoint ([`api/coin/detail.js`](../api/coin/detail.js)) requests
+CoinGecko's community and developer blocks and slims the multi-hundred-KB
+payload to exactly these fields; all-zero developer/community blocks (coins
+with no tracked repo or socials) collapse to `null` so the page hides the
+whole section rather than render a wall of zeros.
+
+Unknown ids, upstream outages, loading, and empty news/markets all have
+designed states — the page never renders a blank void.
## The market tools
@@ -20287,11 +23179,15 @@ data" rule:
`/api/coin/markets` (no new endpoint).
- **`/categories`** — every crypto sector ranked by market cap with 24h change,
volume, and the top coins in each. New `/api/coin/categories` (CoinGecko
- `/coins/categories`).
+ `/coins/categories`). Each row opens a [category detail
+ page](#categoryid--category-detail).
- **`/exchanges`** — top exchanges by trust score and 24h volume (USD, derived
- from the live BTC price). New `/api/coin/exchanges`.
+ from the live BTC price). New `/api/coin/exchanges`. Each row opens an
+ [exchange detail page](#exchangeid--exchange-detail).
- **`/derivatives`** — perpetual-futures markets: price, funding rate, open
- interest, volume, filterable by index. New `/api/coin/derivatives`.
+ interest, volume, filterable by index, plus a **Derivatives Exchanges** table
+ (open interest, perp/futures counts) whose rows open the exchange detail page.
+ `/api/coin/derivatives` (`?view=exchanges` for the venues).
- **`/converter`** — convert any crypto ⇄ any major fiat at live rates
(USD-anchored math covers all four directions). New `/api/coin/rates`
(CoinGecko `/exchange_rates`) + `/api/coin/markets`/`detail`.
@@ -20301,6 +23197,39 @@ data" rule:
`/api/defi/chains` (DeFiLlama).
- **`/stablecoins`** — stablecoins by circulating market cap with live peg
health and backing mechanism. New `/api/defi/stablecoins` (DeFiLlama).
+- **`/yields`** — an explorer over ~15,000 live DeFi yield pools: filter by
+ chain, project, stablecoin exposure, and minimum TVL; sort by APY or TVL
+ (the APY sort ignores sub-$10k dust pools to keep the ranking honest); open
+ any row for its full APY + TVL history in a dual-axis chart. Filters sync to
+ the URL for shareable views. New `/api/defi/yields` (DeFiLlama
+ `yields.llama.fi/pools` + `/chart/{pool}`).
+
+## Detail pages
+
+Beyond `/coin/:id`, two list surfaces now have their own rich detail pages,
+reached by clicking a row.
+
+### `/exchange/:id` — exchange detail
+
+A full profile for one exchange (or derivatives venue): logo, trust-score
+badge, rank, country, year established, centralized/DEX flag, and description;
+stat cards for 24h volume (BTC + USD), **normalized** 24h volume (adjusted to
+discount wash trading), markets count, and trust rank; an interactive
+BTC-volume history chart (7D–365D, crosshair with BTC + USD); and a markets
+table of the venue's pairs (each pair deep-linking to `/coin/:id` and to the
+live trade page), with price, spread, 24h volume, and trust. Derivatives venues
+show open interest and perp/futures pair counts with a contract table instead.
+New `/api/coin/exchange` (CoinGecko `/exchanges/{id}` + `/volume_chart`, falling
+back to `/derivatives/exchanges/{id}`).
+
+### `/category/:id` — category detail
+
+A sector page: rank ("#N by market cap"), description, and stat cards for
+market cap, 24h change, 24h volume, and share of the categorized market; the
+full sortable coins table for that category (reusing the shared markets table,
+so every row deep-links to `/coin/:id`); and a strip of related categories.
+Reuses `/api/coin/markets?category=<id>` for the table and new
+`/api/coin/category` for the header + neighbours.
## News & the markets hub
@@ -20316,16 +23245,34 @@ and a latest-news rail with an archive teaser. Five already-cached endpoints
feed it: `/api/coin/global`, `/api/coin/markets`, `/api/coin/gas`,
`/api/news/feed`, `/api/news/archive?stats=true`.
-### `/markets/news` — live crypto news
-
-Live headlines aggregated **natively** by three.ws from 38 publisher RSS/Atom
-feeds (CoinDesk, The Block, Decrypt, CoinTelegraph, Blockworks, SEC press,
-Forkast, and more — the registry lives in
-[`api/_lib/news-sources.js`](../api/_lib/news-sources.js)). Category tabs
-(Bitcoin, Ethereum, Solana, DeFi, NFT, trading, research, on-chain,
-institutional, mainstream, Asia, regulation, journalism), debounced search, a
-per-source filter, a lead-story hero, sentiment dots, and ticker chips that
-pivot the feed to that symbol. Each source is cached server-side for 5 minutes
+### `/markets/news` — "Your briefing"
+
+The front page of the news wing, laid out as a daily briefing over headlines
+aggregated **natively** by three.ws from the publisher RSS/Atom registry
+(CoinDesk, The Block, Decrypt, CoinTelegraph, Blockworks, SEC press, Forkast,
+and more — [`api/_lib/news-sources.js`](../api/_lib/news-sources.js)):
+
+- **Primary tabs** — Featured (the majors, via `/api/news/feed?featured=1`),
+ Headlines, Trending (the digest's coverage-ranked narratives), DeFi,
+ Bitcoin, Ethereum, Analysis, Saved, and All, which unfolds the full
+ category registry.
+- **Breaking ticker** — stories under 45 minutes old scroll in a marquee
+ (paused on hover, static under `prefers-reduced-motion`); hidden when
+ nothing is fresh.
+- **Today's AI Briefing** — the top digest narratives as a collapsible
+ numbered card, linking into `/markets/digest`.
+- **Top stories** — a lead-story hero beside a compact headline rail, then
+ the Latest grid with offset pagination.
+- **Saved stories** — a ☆ on every card bookmarks the article to
+ localStorage; the Saved tab renders the collection.
+- Debounced search, language + per-source filters, sentiment dots, and ticker
+ chips that pivot the feed to that symbol carry over from the flat layout.
+
+Preview images never break: feed images load with `no-referrer`, retry once
+through the same-origin `/api/img` proxy, and articles whose feed ships no
+image resolve their publisher's `og:image` in the background via
+`/api/news/image` — falling back to a designed source-initials tile only when
+no preview exists anywhere. Each source is cached server-side for 5 minutes
with serve-stale-on-error, so one dead feed never blanks the page.
### `/markets/news/article` — rich article reader
@@ -20381,12 +23328,16 @@ All data is real and fetched at runtime — nothing is hardcoded or sampled:
| Endpoint | Upstream | Cache |
| ----------------------- | ---------------------------------------------------------- | ------------ |
-| `/api/coin/detail` | CoinGecko `/coins/{id}` or `/coins/solana/contract/{mint}` | 60 s |
+| `/api/coin/detail` | CoinGecko `/coins/{id}` or `/coins/solana/contract/{mint}` (with community + developer blocks) | 60 s |
+| `/api/coin/tickers` | CoinGecko `/coins/{id}/tickers` (exchange listings, ±2% depth) | 120 s |
| `/api/coin/ohlc` | CoinGecko `/coins/{id}/market_chart` | 120 s |
-| `/api/coin/markets` | CoinGecko `/coins/markets`, `/search` | 60 s / 300 s |
+| `/api/coin/markets` | CoinGecko `/coins/markets` (optional `category=`), `/search` | 60 s / 300 s |
| `/api/coin/categories` | CoinGecko `/coins/categories` | 300 s |
+| `/api/coin/category` | CoinGecko `/coins/categories` (one category + rank + neighbours) | 600 s |
| `/api/coin/exchanges` | CoinGecko `/exchanges` + `/simple/price` (BTC) | 300 s |
-| `/api/coin/derivatives` | CoinGecko `/derivatives` | 60 s |
+| `/api/coin/exchange` | CoinGecko `/exchanges/{id}` (+ `/volume_chart`) or `/derivatives/exchanges/{id}` fallback | 120 s |
+| `/api/coin/derivatives` | CoinGecko `/derivatives` (`?view=exchanges` → `/derivatives/exchanges`) | 60 s / 300 s |
+| `/api/defi/yields` | DeFiLlama `yields.llama.fi/pools` (+ `/chart/{pool}`) | 300 s / 600 s |
| `/api/coin/rates` | CoinGecko `/exchange_rates` | 300 s |
| `/api/defi/protocols` | DeFiLlama `/protocols` (CEX excluded) | 300 s |
| `/api/defi/chains` | DeFiLlama `/v2/chains` | 300 s |
@@ -20420,9 +23371,12 @@ text before they reach the client.
| Gas tracker | [`pages/gas.html`](../pages/gas.html) + [`src/gas.js`](../src/gas.js) |
| Compare | [`pages/compare.html`](../pages/compare.html) + [`src/compare.js`](../src/compare.js) |
| Screener / Categories | `pages/screener.html`, `pages/categories.html` (+ `src/*.js`, `src/*.css`) |
+| Category detail | [`pages/category.html`](../pages/category.html) + `src/category-page.js` + `src/category-page.css`, API [`api/coin/category.js`](../api/coin/category.js) |
| Exchanges / Derivatives | `pages/exchanges.html`, `pages/derivatives.html` (+ `src/*.js`, `src/*.css`) |
+| Exchange detail | [`pages/exchange.html`](../pages/exchange.html) + `src/exchange-page.js` + `src/exchange-page.css`, API [`api/coin/exchange.js`](../api/coin/exchange.js) |
| Converter | `pages/converter.html` + `src/converter.js` + `src/converter.css` |
| DeFi / Chains / Stablecoins | `pages/{defi,chains,stablecoins}.html` (+ `src/*.js`, `src/*.css`), APIs in [`api/defi/`](../api/defi) |
+| DeFi Yields | [`pages/yields.html`](../pages/yields.html) + `src/yields.js` + `src/yields.css`, API [`api/defi/yields.js`](../api/defi/yields.js) |
| Markets hub | [`pages/markets.html`](../pages/markets.html) + [`src/markets-page.js`](../src/markets-page.js) |
| Crypto news | [`pages/markets-news.html`](../pages/markets-news.html) + [`src/markets-news.js`](../src/markets-news.js) |
| Article reader | [`pages/news-article.html`](../pages/news-article.html) + [`src/news-article.js`](../src/news-article.js) |
@@ -20441,7 +23395,7 @@ server mirrors each (including the dynamic `/coin/:id` path). The pre-existing
---
-<a id="sec-095"></a>
+<a id="sec-096"></a>
> **Source:** `docs/coinmarketcap-article-play.md` · [↑ table of contents](#table-of-contents)
@@ -20587,7 +23541,7 @@ The chart has always told you *what* a coin is doing. /play lets you go stand wh
---
-<a id="sec-096"></a>
+<a id="sec-097"></a>
> **Source:** `docs/coinmarketcap-article.md` · [↑ table of contents](#table-of-contents)
@@ -20790,7 +23744,7 @@ If you've been waiting for the moment AI and crypto stop talking past each other
---
-<a id="sec-097"></a>
+<a id="sec-098"></a>
> **Source:** `docs/configuration.md` · [↑ table of contents](#table-of-contents)
@@ -20840,13 +23794,13 @@ DATABASE_URL=postgres://user:[email protected]/neondb?sslmode=require
Get from: [Neon](https://neon.tech) (free tier works for development), Supabase, or any PostgreSQL host. Always include `?sslmode=require` in production.
-After setting this, apply the schema:
+After setting this, provision the schema:
```bash
-psql "$DATABASE_URL" -f api/_lib/schema.sql
+npm run db:bootstrap
```
-The migration is idempotent — safe to re-run.
+This runs all four provisioning steps (core schema + indexer + delegations + migrations) and is idempotent — safe to re-run. Do not apply `api/_lib/schema.sql` alone: the base schema does not create the migration-defined tables and leaves a half-provisioned database (see [deployment.md](deployment.md)).
#### `JWT_SECRET`
**Required.** Long random secret used for two purposes: signing session JWTs and (via HKDF) deriving the AES-256-GCM key that encrypts agent wallet private keys.
@@ -21275,9 +24229,9 @@ For a fully open public platform where any site can embed agent viewers, set `"o
## `.mcp.json`
-Configures the MCP server connection for Claude Code integration. Claude Code auto-discovers this file from the project root.
+Configures MCP server connections for Claude Code integration. Claude Code auto-discovers this file from the project root. The checked-in file defines four servers (`meshy`, `3d-agent`, `3d-agent-local`, `atelier`); secrets are never inlined — values use `${VAR}` environment-variable interpolation, resolved from your shell at load time.
-The production configuration points to the hosted MCP endpoint and authenticates with a bearer API key:
+The minimal hosted-endpoint entry looks like:
```json
{
@@ -21285,16 +24239,16 @@ The production configuration points to the hosted MCP endpoint and authenticates
"3d-agent": {
"url": "https://three.ws/api/mcp",
"headers": {
- "Authorization": "Bearer <your-api-key>"
+ "Authorization": "Bearer ${THREE_WS_MCP_TOKEN}"
}
}
}
}
```
-Replace the `Authorization` value with an API key from your dashboard. For local development, point `url` at `http://localhost:3000/api/mcp`.
+Set `THREE_WS_MCP_TOKEN` in your environment to an API key from your dashboard. For local development, point `url` at `http://localhost:3000/api/mcp`.
-**Never commit a real API key** in this file. Add `.mcp.json` to `.gitignore` or use a development-only key with limited permissions.
+**Never commit a real API key** in this file — keep the `${VAR}` interpolation form so the checked-in file stays secret-free.
---
@@ -21314,7 +24268,7 @@ Before going live, verify the following:
---
-<a id="sec-098"></a>
+<a id="sec-099"></a>
> **Source:** `docs/content/use-cases/README.md` · [↑ table of contents](#table-of-contents)
@@ -21359,7 +24313,7 @@ Every scenario on these pages is an **example workflow** — clearly labeled "Im
---
-<a id="sec-099"></a>
+<a id="sec-100"></a>
> **Source:** `docs/content/use-cases/ai-agent-developer.md` · [↑ table of contents](#table-of-contents)
@@ -21407,7 +24361,7 @@ A standards-based interface (MCP + A2A), a working USDC payment rail (x402 on Ba
---
-<a id="sec-100"></a>
+<a id="sec-101"></a>
> **Source:** `docs/content/use-cases/brand-marketer.md` · [↑ table of contents](#table-of-contents)
@@ -21466,7 +24420,7 @@ A conversational 3D brand presence that's easy to embed and share, plus a public
---
-<a id="sec-101"></a>
+<a id="sec-102"></a>
> **Source:** `docs/content/use-cases/crypto-community.md` · [↑ table of contents](#table-of-contents)
@@ -21513,7 +24467,7 @@ A shared 3D home for the token's holders, a real (not mocked) on-chain agent-exc
---
-<a id="sec-102"></a>
+<a id="sec-103"></a>
> **Source:** `docs/content/use-cases/game-studio.md` · [↑ table of contents](#table-of-contents)
@@ -21535,7 +24489,7 @@ three.ws ships those three systems as real, composable surfaces:
1. **GLB rendering pipeline** — the [viewer](../../../README.md#key-features) loads and validates glTF 2.0 / GLB with Draco, KTX2, and Meshopt, plus skinned animation and morph targets, all in WebGL 2.0. Drop a character at [`/app`](https://three.ws/app) and it renders instantly.
2. **Agent runtime + skills** — the [LLM tool-loop runtime](../../../README.md#the-agent-system) gives a character built-in tools (`wave`, `lookAt`, `play_clip`, `setExpression`, `speak`, `remember`) and a [composable skill system](../../../specs/SKILL_SPEC.md) so you can add game-specific abilities. The Empathy Layer blends emotion from protocol events, so NPCs emote instead of staring blankly.
-3. **Multiplayer worlds** — [`/walk`](https://three.ws/walk) is an authoritative multiplayer walk scene backed by a Colyseus server (deployable on Fly.io), and [`/play`](https://three.ws/play) is a shared, coin-keyed 3D world where players who pick the same world land **together** — peer avatars, chat, emotes, voxel building. Author motion and poses in [`/pose-studio`](https://three.ws/pose-studio) and [`/mocap-studio`](https://three.ws/mocap-studio).
+3. **Multiplayer worlds** — [`/walk`](https://three.ws/walk) is an authoritative multiplayer walk scene backed by a Colyseus server (deployable on Google Cloud Run), and [`/play`](https://three.ws/play) is a shared, coin-keyed 3D world where players who pick the same world land **together** — peer avatars, chat, emotes, voxel building. Author motion and poses in [`/pose`](https://three.ws/pose) and [`/mocap-studio`](https://three.ws/mocap-studio).
## Example workflow (hypothetical)
@@ -21544,7 +24498,7 @@ three.ws ships those three systems as real, composable surfaces:
1. The artist exports the guide character as a Draco-compressed GLB and drops it on [`/app`](https://three.ws/app) to confirm it renders, animates, and validates against the Khronos spec.
2. An engineer embeds the character as an [`<agent-3d>`](../../../README.md#web-component--embedding) element in the game's hub page, sets `brain=` and `instructions=` for the guide's personality, and writes one custom [skill](../../../specs/SKILL_SPEC.md) — `give_quest` — so the NPC can hand out objectives through the tool-loop instead of a static script.
3. For the shared space, they point players at [`/walk`](https://three.ws/walk) (authoritative Colyseus world) so testers can roam together with live peer avatars and chat while the studio dials in gameplay.
-4. They author the guide's idle and point gestures in [`/pose-studio`](https://three.ws/pose-studio) and bind them to the NPC's `play_clip` tool calls.
+4. They author the guide's idle and point gestures in [`/pose`](https://three.ws/pose) and bind them to the NPC's `play_clip` tool calls.
5. **Deliverable:** a browser-playable hub with a conversational, gesturing guide NPC and a shared multiplayer space — assembled from real GLB rendering, a real agent runtime, and real netcode, without the studio writing any of those three engines.
## What you get
@@ -21560,7 +24514,7 @@ A character that renders with production-grade glTF handling, converses through
---
-<a id="sec-103"></a>
+<a id="sec-104"></a>
> **Source:** `docs/content/use-cases/indie-creator.md` · [↑ table of contents](#table-of-contents)
@@ -21620,7 +24574,7 @@ A real, embedded, conversational 3D avatar that loads in any modern browser. The
---
-<a id="sec-104"></a>
+<a id="sec-105"></a>
> **Source:** `docs/contributing.md` · [↑ table of contents](#table-of-contents)
@@ -21946,7 +24900,7 @@ By contributing, you agree that your contributions will be licensed under the [A
---
-<a id="sec-105"></a>
+<a id="sec-106"></a>
> **Source:** `docs/crypto-api.md` · [↑ table of contents](#table-of-contents)
@@ -22777,7 +25731,7 @@ curl -s "https://three.ws/api/crypto/holders?address=FeMbDoX7R1Psc4GEcvJdsbNbZA3
---
-<a id="sec-106"></a>
+<a id="sec-107"></a>
> **Source:** `docs/custody.md` · [↑ table of contents](#table-of-contents)
@@ -22867,7 +25821,7 @@ Every step of recovery and inheritance writes to the custody trail and the audit
---
-<a id="sec-107"></a>
+<a id="sec-108"></a>
> **Source:** `docs/demo-routes.md` · [↑ table of contents](#table-of-contents)
@@ -23051,7 +26005,7 @@ Verified on the live Vite dev server (`npm run dev`, port 3000):
---
-<a id="sec-108"></a>
+<a id="sec-109"></a>
> **Source:** `docs/deployment.md` · [↑ table of contents](#table-of-contents)
@@ -23634,7 +26588,7 @@ Upstash REST API uses HTTPS — no ports to open. If you see connection errors,
---
-<a id="sec-109"></a>
+<a id="sec-110"></a>
> **Source:** `docs/do-i-need-crypto.md` · [↑ table of contents](#table-of-contents)
@@ -23725,7 +26679,7 @@ When you do interact with on-chain features, the platform's native token is **$T
---
-<a id="sec-110"></a>
+<a id="sec-111"></a>
> **Source:** `docs/economy-heartbeat.md` · [↑ table of contents](#table-of-contents)
@@ -23886,7 +26840,7 @@ Related: [circulation engine](circulation-engine.md) ·
---
-<a id="sec-111"></a>
+<a id="sec-112"></a>
> **Source:** `docs/economy-master.md` · [↑ table of contents](#table-of-contents)
@@ -24159,7 +27113,7 @@ The master is configured and funded, but the tree it feeds is only partly wired:
---
-<a id="sec-112"></a>
+<a id="sec-113"></a>
> **Source:** `docs/editor.md` · [↑ table of contents](#table-of-contents)
@@ -24499,7 +27453,7 @@ The editor is at format version `agent-editor/0.1`. The following rough edges ar
---
-<a id="sec-113"></a>
+<a id="sec-114"></a>
> **Source:** `docs/embedding.md` · [↑ table of contents](#table-of-contents)
@@ -25240,7 +28194,7 @@ The platform records anonymous embed impressions (country, referrer hostname) vi
---
-<a id="sec-114"></a>
+<a id="sec-115"></a>
> **Source:** `docs/embody.md` · [↑ table of contents](#table-of-contents)
@@ -25350,7 +28304,7 @@ Embody is a thin, honest wire over pieces that already exist — no new pipeline
---
-<a id="sec-115"></a>
+<a id="sec-116"></a>
> **Source:** `docs/erc8004.md` · [↑ table of contents](#table-of-contents)
@@ -26021,7 +28975,7 @@ The same MAINNET addresses apply to all 15 mainnets. The same TESTNET addresses
---
-<a id="sec-116"></a>
+<a id="sec-117"></a>
> **Source:** `docs/erc8004/validation-attestation.md` · [↑ table of contents](#table-of-contents)
@@ -26113,7 +29067,7 @@ ValidationRegistry is deployed, `/api/erc8004/validate` returns a clear ops erro
---
-<a id="sec-117"></a>
+<a id="sec-118"></a>
> **Source:** `docs/examples.md` · [↑ table of contents](#table-of-contents)
@@ -26840,7 +29794,7 @@ genuinely invested in the user's progress.
---
-<a id="sec-118"></a>
+<a id="sec-119"></a>
> **Source:** `docs/financial-controls.md` · [↑ table of contents](#table-of-contents)
@@ -27119,7 +30073,7 @@ Ranked by accounting/regulatory risk. Each is a tracked remediation item.
---
-<a id="sec-119"></a>
+<a id="sec-120"></a>
> **Source:** `docs/hold-to-access.md` · [↑ table of contents](#table-of-contents)
@@ -27338,7 +30292,7 @@ worlds unaffected.
---
-<a id="sec-120"></a>
+<a id="sec-121"></a>
> **Source:** `docs/how-it-works.md` · [↑ table of contents](#table-of-contents)
@@ -27509,7 +30463,7 @@ Quick lookup for "I want to ship X":
---
-<a id="sec-121"></a>
+<a id="sec-122"></a>
> **Source:** `docs/i18n.md` · [↑ table of contents](#table-of-contents)
@@ -27660,7 +30614,7 @@ round-trips, lint rules, runtime resolution/fallback, and catalog merge/prune.
---
-<a id="sec-122"></a>
+<a id="sec-123"></a>
> **Source:** `docs/ibm-x402-mcp.md` · [↑ table of contents](#table-of-contents)
@@ -28018,7 +30972,7 @@ Catalog/listing copy is maintained in
---
-<a id="sec-123"></a>
+<a id="sec-124"></a>
> **Source:** `docs/ibm.md` · [↑ table of contents](#table-of-contents)
@@ -28328,7 +31282,7 @@ Unit tests for the same paths live in [`tests/`](../tests/) (`granite-oracle`, `
---
-<a id="sec-124"></a>
+<a id="sec-125"></a>
> **Source:** `docs/introduction.md` · [↑ table of contents](#table-of-contents)
@@ -28421,9 +31375,9 @@ A minimal manifest looks like:
```json
{
- "specVersion": "0.1",
+ "spec": "agent-manifest/0.1",
"name": "Aria",
- "body": { "uri": "./body.glb", "format": "glb" },
+ "body": { "uri": "./body.glb", "format": "gltf-binary" },
"brain": {
"provider": "anthropic",
"model": "claude-sonnet-4-6",
@@ -28554,7 +31508,7 @@ If you want to look at what's already in the hosted platform — browsing agents
---
-<a id="sec-125"></a>
+<a id="sec-126"></a>
> **Source:** `docs/irl/THREAT-MODEL.md` · [↑ table of contents](#table-of-contents)
@@ -28689,7 +31643,7 @@ in a way that drops legitimate discovery, update this file in the same change.
---
-<a id="sec-126"></a>
+<a id="sec-127"></a>
> **Source:** `docs/js-api.md` · [↑ table of contents](#table-of-contents)
@@ -29303,7 +32257,7 @@ window.VIEWER.app.viewer.updateDisplay();
---
-<a id="sec-127"></a>
+<a id="sec-128"></a>
> **Source:** `docs/labor-market.md` · [↑ table of contents](#table-of-contents)
@@ -29408,7 +32362,7 @@ economy move:
---
-<a id="sec-128"></a>
+<a id="sec-129"></a>
> **Source:** `docs/launch-usecases.md` · [↑ table of contents](#table-of-contents)
@@ -29544,7 +32498,7 @@ GET /api/pump/launch-studio?action=preview&id=github-fresh-breakouts&limit=6
---
-<a id="sec-129"></a>
+<a id="sec-130"></a>
> **Source:** `docs/layers.md` · [↑ table of contents](#table-of-contents)
@@ -29706,7 +32660,7 @@ Versioned CDN bundles are published at `/agent-3d/<version>/agent-3d.js`. Use `l
---
-<a id="sec-130"></a>
+<a id="sec-131"></a>
> **Source:** `docs/listings.md` · [↑ table of contents](#table-of-contents)
@@ -29777,7 +32731,7 @@ Subscribe via RSS to track new listings, integrations, and protocol updates.
---
-<a id="sec-131"></a>
+<a id="sec-132"></a>
> **Source:** `docs/make-your-agent.md` · [↑ table of contents](#table-of-contents)
@@ -29868,7 +32822,7 @@ Changes take effect immediately — no republishing needed for most settings.
---
-<a id="sec-132"></a>
+<a id="sec-133"></a>
> **Source:** `docs/marketplace.md` · [↑ table of contents](#table-of-contents)
@@ -29959,7 +32913,7 @@ their chosen `currency_mint`; the platform promotes no coin other than $THREE.
---
-<a id="sec-133"></a>
+<a id="sec-134"></a>
> **Source:** `docs/mcp-3d-studio.md` · [↑ table of contents](#table-of-contents)
@@ -30197,7 +33151,7 @@ npx @modelcontextprotocol/inspector http://localhost:3000/api/mcp-3d
---
-<a id="sec-134"></a>
+<a id="sec-135"></a>
> **Source:** `docs/mcp-agent.md` · [↑ table of contents](#table-of-contents)
@@ -30273,7 +33227,7 @@ npx @modelcontextprotocol/inspector http://localhost:3000/api/mcp-agent
---
-<a id="sec-135"></a>
+<a id="sec-136"></a>
> **Source:** `docs/mcp-studio.md` · [↑ table of contents](#table-of-contents)
@@ -30477,7 +33431,7 @@ All optional — sensible production defaults:
---
-<a id="sec-136"></a>
+<a id="sec-137"></a>
> **Source:** `docs/mcp-tools.md` · [↑ table of contents](#table-of-contents)
@@ -30610,7 +33564,7 @@ promote no specific token.
---
-<a id="sec-137"></a>
+<a id="sec-138"></a>
> **Source:** `docs/mcp-x402-bazaar.md` · [↑ table of contents](#table-of-contents)
@@ -30685,7 +33639,7 @@ npx @modelcontextprotocol/inspector http://localhost:3000/api/mcp-bazaar
---
-<a id="sec-138"></a>
+<a id="sec-139"></a>
> **Source:** `docs/mcp.md` · [↑ table of contents](#table-of-contents)
@@ -31403,7 +34357,7 @@ Restart Claude Code after editing `.mcp.json` so the new server config is picked
---
-<a id="sec-139"></a>
+<a id="sec-140"></a>
> **Source:** `docs/memetic-launcher.md` · [↑ table of contents](#table-of-contents)
@@ -31494,7 +34448,7 @@ POST /api/launcher/me { "action": "resume" } → clear a tripped circuit brea
---
-<a id="sec-140"></a>
+<a id="sec-141"></a>
> **Source:** `docs/memory.md` · [↑ table of contents](#table-of-contents)
@@ -31680,18 +34634,18 @@ A `MEMORY.md` file is automatically maintained alongside the individual memory f
# Agent Memory
## User
-- [Role](user_role.md) — Argentina fan, plays weekly 5-a-side on Saturdays
-- [Preferences](user_preferences.md) — terse feedback, no emojis
+- Role (`user_role.md`) — Argentina fan, plays weekly 5-a-side on Saturdays
+- Preferences (`user_preferences.md`) — terse feedback, no emojis
## Feedback
-- [Tone](feedback_tone.md) — stay warm but don't coddle; user asked for direct critique
-- [Drill pacing](feedback_pacing.md) — 3 drills per session max
+- Tone (`feedback_tone.md`) — stay warm but don't coddle; user asked for direct critique
+- Drill pacing (`feedback_pacing.md`) — 3 drills per session max
## Project
-- [Season goal](project_season.md) — user is training for a tournament in June 2026
+- Season goal (`project_season.md`) — user is training for a tournament in June 2026
## Reference
-- [Highlight reel](reference_reel.md) — shared Drive folder where user stores match clips
+- Highlight reel (`reference_reel.md`) — shared Drive folder where user stores match clips
```
Keep the index concise. Lines beyond 200 are truncated before injection into context.
@@ -31885,7 +34839,7 @@ In `ipfs` mode without encryption, treat the memory as semi-public. Don't store
---
-<a id="sec-141"></a>
+<a id="sec-142"></a>
> **Source:** `docs/mint-mark.md` · [↑ table of contents](#table-of-contents)
@@ -32017,7 +34971,7 @@ No other mint should appear in tests, fixtures, or documentation.
---
-<a id="sec-142"></a>
+<a id="sec-143"></a>
> **Source:** `docs/money-feed.md` · [↑ table of contents](#table-of-contents)
@@ -32035,15 +34989,17 @@ event lives.
| Layer | Backing store | Surface | What it shows |
|---|---|---|---|
-| **Live ticker** | Redis list `feed:events` | `GET /api/feed`, widget `public/feed.js` | A curated, newest-first stream of notable public events. |
+| **Live ticker** | Redis list `feed:events` | `GET /api/feed` + `GET /api/feed-stream` (SSE), client `src/theater-feed.js` | A curated, newest-first stream of notable public events. |
| **Custody ledger** | Postgres `agent_custody_events` | Portfolio + volume dashboards | Every real wallet spend/transfer, the canonical record of money moved. |
| **Domain records** | `circulation_actions`, `pump_agent_trades`, `pump_agent_mints`, `skill_purchases`, `asset_purchases` | Pump feed, `/launches`, agent profiles | Per-domain detail behind each event. |
## Live ticker — `/api/feed`
A public, read-only, cache-friendly endpoint backed by a capped Redis list
-(`feed:events`, max 200 entries). The on-page widget polls it every ~20 seconds
-and prepends anything new. The endpoint is edge-cached
+(`feed:events`, max 200 entries). The on-page client
+([`src/theater-feed.js`](../src/theater-feed.js)) fetches one snapshot of
+`GET /api/feed` for first paint, then tails the live SSE stream at
+`GET /api/feed-stream` for fresh events. The snapshot endpoint is edge-cached
(`s-maxage=20, stale-while-revalidate=60`) so idle tabs don't drain the Redis
request quota.
@@ -32120,7 +35076,7 @@ and millisecond `ts`.
---
-<a id="sec-143"></a>
+<a id="sec-144"></a>
> **Source:** `docs/money-map.md` · [↑ table of contents](#table-of-contents)
@@ -32313,7 +35269,7 @@ that set `auto_fund_enabled = true` (default off). See
---
-<a id="sec-144"></a>
+<a id="sec-145"></a>
> **Source:** `docs/multi-agent.md` · [↑ table of contents](#table-of-contents)
@@ -32642,7 +35598,7 @@ To extend this into a full turn-based scene, add a `brain` attribute to Mira wit
---
-<a id="sec-145"></a>
+<a id="sec-146"></a>
> **Source:** `docs/nvidia-models.md` · [↑ table of contents](#table-of-contents)
@@ -32835,13 +35791,14 @@ Probe transcripts for every lane — request/response shapes, limits, verified b
---
-<a id="sec-146"></a>
+<a id="sec-147"></a>
> **Source:** `docs/nvidia-nemotron-spotlight.md` · [↑ table of contents](#table-of-contents)
---
title: "The generator was never the hard part: how Nemotron Nano made our text-to-3D pipeline usable"
venue: NVIDIA Developer Blog / NVIDIA Developer Forums (community showcase)
+published: https://forums.developer.nvidia.com/t/how-nemotron-made-three-ws-text-to-3d-pipeline-usable/376445
account: three.ws (official)
description: "A founder's account of building browser-native 3D generation on NVIDIA NIM, and why a 12B vision model standing in front of the 3D generator mattered more than the 3D generator itself."
tags: [nemotron, nim, trellis, generative-3d, vision-language-models, guardrails]
@@ -32989,7 +35946,7 @@ Build the small stuff. Put it in front. The generator was never the hard part.
---
-<a id="sec-147"></a>
+<a id="sec-148"></a>
> **Source:** `docs/okx-marketplace.md` · [↑ table of contents](#table-of-contents)
@@ -33256,7 +36213,7 @@ USDC rails. The wire format OKX buyers use (headers `PAYMENT-REQUIRED` /
---
-<a id="sec-148"></a>
+<a id="sec-149"></a>
> **Source:** `docs/onchain-agents.md` · [↑ table of contents](#table-of-contents)
@@ -33553,7 +36510,7 @@ A confirmed canary asset shows `inCollection=true`, `royalty=500bps`, `attrs=11`
---
-<a id="sec-149"></a>
+<a id="sec-150"></a>
> **Source:** `docs/oracle.md` · [↑ table of contents](#table-of-contents)
@@ -33936,7 +36893,7 @@ The more data we watch, the sharper every score. Oracle is live now.
---
-<a id="sec-150"></a>
+<a id="sec-151"></a>
> **Source:** `docs/package-extraction.md` · [↑ table of contents](#table-of-contents)
@@ -34055,7 +37012,7 @@ part of the extraction itself — extract and publish first, swap the import lat
---
-<a id="sec-151"></a>
+<a id="sec-152"></a>
> **Source:** `docs/partners/sperax-proposal.md` · [↑ table of contents](#table-of-contents)
@@ -34103,7 +37060,7 @@ Both sides already ship for a living — this proposal only asks each of us to d
---
-<a id="sec-152"></a>
+<a id="sec-153"></a>
> **Source:** `docs/pay-skills-listing.md` · [↑ table of contents](#table-of-contents)
@@ -34204,7 +37161,7 @@ are supported.
---
-<a id="sec-153"></a>
+<a id="sec-154"></a>
> **Source:** `docs/permissions.md` · [↑ table of contents](#table-of-contents)
@@ -34585,7 +37542,7 @@ Set `SMOKE_SKIP_REVOKE=1` to skip the on-chain revocation step if the test walle
---
-<a id="sec-154"></a>
+<a id="sec-155"></a>
> **Source:** `docs/persona-hub.md` · [↑ table of contents](#table-of-contents)
@@ -34708,7 +37665,7 @@ The response should contain one entry under `keys` whose `kid` matches `PERSONA_
## Issuing a token
-`POST /api/auth/persona/issue` — defined in [api/auth/persona/\[action\].js](../api/auth/persona/%5Baction%5D.js) (`handleIssue`).
+`POST /api/auth/persona/issue` — defined in `api/auth/persona/[action].js` (`handleIssue`).
| | |
|---|---|
@@ -34718,7 +37675,7 @@ The response should contain one entry under `keys` whose `kid` matches `PERSONA_
| Success | `200` with `{ token, expires_in, avatar, tenant_origin, alg }` |
| Errors | `401 unauthorized` — no session. `400 invalid_request` — `tenant_origin` is not a `three.ws` subdomain or `localhost`. `404 no_avatar` — user has no avatar yet. |
-`tenant_origin` must be a bare origin (no path, no query, no fragment), `https://*.three.ws` or `https://three.ws`, or — for dev — `http://localhost[:port]` / `http://127.0.0.1[:port]`. Anything else is rejected with `400 invalid_request`. The validator is `validateTenantOrigin()` in [api/auth/persona/\[action\].js](../api/auth/persona/%5Baction%5D.js); add a subdomain by editing that function.
+`tenant_origin` must be a bare origin (no path, no query, no fragment), `https://*.three.ws` or `https://three.ws`, or — for dev — `http://localhost[:port]` / `http://127.0.0.1[:port]`. Anything else is rejected with `400 invalid_request`. The validator is `validateTenantOrigin()` in `api/auth/persona/[action].js`; add a subdomain by editing that function.
When `avatar_id` is omitted, the user's most recently created avatar is used. Pass `avatar_id` from the consent UI's picker to bind a specific avatar to the token.
@@ -34897,7 +37854,7 @@ The verify endpoint applies the same checks as `jose.jwtVerify` — signature, i
## ES256 vs HS256 fallback
-The signing algorithm is decided at issue time by [api/auth/persona/\[action\].js:158-161](../api/auth/persona/%5Baction%5D.js):
+The signing algorithm is decided at issue time by `api/auth/persona/[action].js:158-161`:
```js
const es = await esKeys(); // null if PERSONA_JWKS_PRIVATE_KEY_PEM is unset
@@ -34917,7 +37874,7 @@ Verification accepts both algorithms in either order — the `/verify` endpoint
## Tokens in practice
-- **TTL.** 24 hours (`PERSONA_TTL_SEC = 60 * 60 * 24`, [api/auth/persona/\[action\].js:42](../api/auth/persona/%5Baction%5D.js#L42)). Tenants that need a longer-lived session must mint their own session from the persona token's `sub` after verifying — do not extend the persona JWT itself.
+- **TTL.** 24 hours (`PERSONA_TTL_SEC = 60 * 60 * 24`, `api/auth/persona/[action].js:42`). Tenants that need a longer-lived session must mint their own session from the persona token's `sub` after verifying — do not extend the persona JWT itself.
- **Rotation.** Generate a new keypair with `node scripts/generate-persona-key.mjs`, deploy with a new `PERSONA_JWKS_KID`, and the JWKS publishes the new key. Old tokens continue to verify against `/api/auth/persona/verify` while they live; once the longest possible token TTL has elapsed (24h), no token in the wild still references the old `kid`. The deployment can serve both old and new keys side by side by adding extra entries to the `keys` array — the current handler emits a single key but the verifier accepts any matching `kid` from the published set.
- **Revocation.** There is **no** revocation list. Defense is the short TTL: 24 hours. If a token must be invalidated sooner, the tenant should treat its own server-issued session as the source of truth and invalidate that. If a private key is leaked, rotate `PERSONA_JWKS_PRIVATE_KEY_PEM` and `PERSONA_JWKS_KID`; verification of any token signed with the old key will fail as soon as the old JWK is removed from the published set.
@@ -34933,7 +37890,7 @@ Verification accepts both algorithms in either order — the `/verify` endpoint
| `JWTClaimValidationFailed: "aud" claim check failed` | The `audience` you passed to `jwtVerify` (or to `/verify`) doesn't match the token's `aud`. Audience is the exact `tenant_origin` used at issue time — case-sensitive, no trailing slash. |
| `JWTExpired: "exp" claim timestamp check failed` | Token is older than 24 h. Have the user re-authorize through the widget. There is no refresh endpoint — persona tokens are not refreshable by design. |
| `invalid_token: token is not a persona token` from `/verify` | The token validates cryptographically but its `token_use` claim is not `"persona"`. Tokens issued by the main three.ws auth stack are not accepted on this endpoint. |
-| `400 invalid_request` on `/issue` with `tenant_origin must be a https three.ws subdomain or localhost dev origin` | The origin contains a path / query / fragment, is not `https`, or is not a `three.ws` subdomain. Pass a bare origin like `https://coolgame.three.ws`. Add a new subdomain by editing `validateTenantOrigin()` in [api/auth/persona/\[action\].js](../api/auth/persona/%5Baction%5D.js). |
+| `400 invalid_request` on `/issue` with `tenant_origin must be a https three.ws subdomain or localhost dev origin` | The origin contains a path / query / fragment, is not `https`, or is not a `three.ws` subdomain. Pass a bare origin like `https://coolgame.three.ws`. Add a new subdomain by editing `validateTenantOrigin()` in `api/auth/persona/[action].js`. |
---
@@ -34953,9 +37910,9 @@ Other origins return `400 invalid_request`. This is the chokepoint that prevents
| Endpoint | Method | Auth | Description |
|---|---|---|---|
-| [/api/auth/persona/me](../api/auth/persona/%5Baction%5D.js) | `GET` | three.ws session | Lists the user's avatars for the consent UI. |
-| [/api/auth/persona/issue](../api/auth/persona/%5Baction%5D.js) | `POST` | three.ws session | Mints a 24h persona JWT for `{ tenant_origin, avatar_id }`. |
-| [/api/auth/persona/verify](../api/auth/persona/%5Baction%5D.js) | `GET` | none | Verifies a token's signature, issuer, audience, expiry, and `token_use`. |
+| `/api/auth/persona/me` | `GET` | three.ws session | Lists the user's avatars for the consent UI. |
+| `/api/auth/persona/issue` | `POST` | three.ws session | Mints a 24h persona JWT for `{ tenant_origin, avatar_id }`. |
+| `/api/auth/persona/verify` | `GET` | none | Verifies a token's signature, issuer, audience, expiry, and `token_use`. |
| [/.well-known/jwks.json](https://three.ws/.well-known/jwks.json) | `GET` | none | Publishes the active persona public key (empty array in HS256 fallback). |
JWT claims:
@@ -34982,7 +37939,7 @@ JWT claims:
---
-<a id="sec-155"></a>
+<a id="sec-156"></a>
> **Source:** `docs/plan-checkout.md` · [↑ table of contents](#table-of-contents)
@@ -35109,7 +38066,7 @@ Plan prices live in [api/payments/_config.js](../api/payments/_config.js) (`PLAN
---
-<a id="sec-156"></a>
+<a id="sec-157"></a>
> **Source:** `docs/popular-3d-github-repos.md` · [↑ table of contents](#table-of-contents)
@@ -35372,7 +38329,116 @@ Apply a 3D-signal regex filter over `description + topics` and a denylist of non
---
-<a id="sec-157"></a>
+<a id="sec-158"></a>
+
+> **Source:** `docs/premium.md` · [↑ table of contents](#table-of-contents)
+
+# three.ws Premium — the monthly Data API pass
+
+Premium is one on-chain payment that replaces per-call micropayments for 30
+days. Instead of answering an x402 challenge on every archive search, you buy
+a pass once a month — the AIXBT model — and call the Data API with an API key
+(servers, agents) or a wallet signature (browsers).
+
+**Price:** $9.99 / 30 days, paid on **Solana only**, in your choice of:
+
+| Asset | What you pay | Why |
+|---|---|---|
+| **$THREE** | ≈ $7.99 worth (20% off) | The platform coin is the cheapest way in. Mint: `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump` |
+| **SOL** | ≈ $9.99 worth at the live price | Native SOL transfer |
+| **USDC** | $9.99 exactly | Parity, never needs an oracle |
+
+Prices in SOL and $THREE are locked for 10 minutes when you request a quote,
+so the amount you sign is exactly the amount that's verified.
+
+**What it unlocks today:** unmetered search on the
+[660k-article crypto-news archive](/markets/archive)
+(`GET /api/news/archive`) at a fair-use rate limit of 120 requests/minute —
+versus the free tier's 60 searches/day and the $0.001-per-search x402 rail.
+Corpus stats, month index, and trending are free for everyone regardless.
+More premium surfaces join the same pass over time; your key starts working
+on them automatically.
+
+## Buying a pass
+
+### From the dashboard (recommended)
+
+Open **[/dashboard/data-api](/dashboard/data-api)**, pick an asset, and
+confirm one transaction in your Solana wallet. When it confirms, the page
+shows your `x402_live_…` API key **once** — copy it then. Renewing later
+appends 30 days to the end of your current pass; no days are lost by renewing
+early.
+
+### From the API (no account needed)
+
+```bash
+# 1. Quote — lock the price, get the unsigned transaction (base64)
+curl -X POST https://three.ws/api/premium/quote \
+ -H 'content-type: application/json' \
+ -d '{"asset":"THREE","wallet":"<your-solana-address>"}'
+# → { "quote": { "id", "amount_atomics", "expires_at", … }, "tx_base64": "…" }
+
+# 2. Sign tx_base64 with the quoted wallet and send it (any Solana client).
+
+# 3. Redeem — verify the landed payment and receive the pass + API key
+curl -X POST https://three.ws/api/premium/subscribe \
+ -H 'content-type: application/json' \
+ -d '{"quote_id":"<quote.id>","tx_signature":"<signature>"}'
+# → { "pass": { "expires_at", … }, "api_key": "x402_live_…" } (key shown once)
+```
+
+A `202 { pending: true }` means the transaction hasn't confirmed yet — poll
+`subscribe` again with the same body; redeeming is idempotent, and
+re-submitting an already-redeemed signature returns the existing pass.
+
+Live per-asset pricing: `GET https://three.ws/api/premium/plans`.
+Pass state for any wallet: `GET https://three.ws/api/premium/status?wallet=…`.
+
+## Using the pass
+
+**Servers and agents — API key.** Send the key as a header on any premium
+endpoint; the request bypasses the x402 payment entirely:
+
+```bash
+curl "https://three.ws/api/news/archive?q=mt+gox&start_date=2018-01-01&end_date=2019-12-31" \
+ -H "X-API-Key: x402_live_…"
+```
+
+**Browsers — wallet signature (SIWX).** The wallet that bought the pass holds
+a signature grant until the pass expires. On [/markets/archive](/markets/archive),
+when the payment dialog appears, choose *sign with wallet* instead of paying —
+no key, no charge.
+
+## Managing keys
+
+On [/dashboard/data-api](/dashboard/data-api) (signed in) you can **rotate**
+(revoke + reissue; new plaintext shown once) or **revoke** your key. Key
+management is tied to the account that was signed in at purchase time —
+passes bought wallet-only over the raw API authenticate with the key itself
+and can be re-keyed by renewing. Your purchase history and subscriptions live
+at [/dashboard/billing](/dashboard/billing).
+
+## Rules and edge cases
+
+- A quote is redeemable for 30 minutes; after that, request a fresh one
+ (the transaction's blockhash expires far sooner anyway).
+- Verification checks the **landed** transaction: the quoted wallet must be a
+ signer and the treasury balance delta must cover the quoted amount. Someone
+ else's transaction signature can't redeem your quote.
+- One transaction signature redeems exactly one pass, forever (database
+ UNIQUE). Failed or reverted transactions redeem nothing.
+- Renewal periods stack end-to-end (`new start = old expiry`).
+- Ops can tune pricing without a deploy: `PREMIUM_PASS_USD`,
+ `PREMIUM_PASS_THREE_DISCOUNT`, `PREMIUM_PASS_DAYS`,
+ `PREMIUM_RATE_LIMIT_PER_MINUTE`.
+
+Related: [API reference — news archive](/docs/api-reference), the
+[x402 per-call rail](/docs/x402) that Premium sits on top of, and the free
+tiers that remain free (news feed, digest, archive stats/trending).
+
+---
+
+<a id="sec-159"></a>
> **Source:** `docs/provenance.md` · [↑ table of contents](#table-of-contents)
@@ -35439,7 +38505,7 @@ Real hashing, real ed25519 signature, real on-chain write. Requires the issuer k
---
-<a id="sec-158"></a>
+<a id="sec-160"></a>
> **Source:** `docs/pump-fun-mcp-edge.md` · [↑ table of contents](#table-of-contents)
@@ -35495,7 +38561,7 @@ Both runtimes import `TOOLS` from `src/pump/mcp-tools.js`, so the tool list expo
---
-<a id="sec-159"></a>
+<a id="sec-161"></a>
> **Source:** `docs/pump-launch-repos.md` · [↑ table of contents](#table-of-contents)
@@ -35594,7 +38660,7 @@ rate-limits under the ~450 txs a full run makes. Pass a dedicated `--rpc`
---
-<a id="sec-160"></a>
+<a id="sec-162"></a>
> **Source:** `docs/pump-launcher.md` · [↑ table of contents](#table-of-contents)
@@ -35745,7 +38811,7 @@ token itself always deploys on **Solana mainnet** — pump.fun is mainnet-only.
---
-<a id="sec-161"></a>
+<a id="sec-163"></a>
> **Source:** `docs/pump-platform-fee.md` · [↑ table of contents](#table-of-contents)
@@ -35806,7 +38872,7 @@ The fee is **never** charged silently. When `platform_fee_bps > 0`:
---
-<a id="sec-162"></a>
+<a id="sec-164"></a>
> **Source:** `docs/pumpfun-program/README.md` · [↑ table of contents](#table-of-contents)
@@ -35864,7 +38930,7 @@ tracked in `tasks/pumpfun-upstream/01-v2-trade-instructions-usdc-audit.md`.
---
-<a id="sec-163"></a>
+<a id="sec-165"></a>
> **Source:** `docs/pumpfun-program/UPSTREAM-buy-sell-v2-announcement.md` · [↑ table of contents](#table-of-contents)
@@ -35968,7 +39034,7 @@ Currently, no quote mint other than native SOL can be used to create or trade co
---
-<a id="sec-164"></a>
+<a id="sec-166"></a>
> **Source:** `docs/pumpfun-program/docs/BREAKING_FEE_RECIPIENT.md` · [↑ table of contents](#table-of-contents)
@@ -36042,7 +39108,7 @@ The new accounts can be passed before the program upgrade happens on Monday. The
---
-<a id="sec-165"></a>
+<a id="sec-167"></a>
> **Source:** `docs/pumpfun-program/docs/CPI_README.md` · [↑ table of contents](#table-of-contents)
@@ -36146,7 +39212,7 @@ pump-rust-client = { version = "...", path = "..." }
---
-<a id="sec-166"></a>
+<a id="sec-168"></a>
> **Source:** `docs/pumpfun-program/docs/FAQ.md` · [↑ table of contents](#table-of-contents)
@@ -36184,7 +39250,7 @@ is recommended to use a static big enough CU limit like `100_000`.
---
-<a id="sec-167"></a>
+<a id="sec-169"></a>
> **Source:** `docs/pumpfun-program/docs/FEE_PROGRAM_README.md` · [↑ table of contents](#table-of-contents)
@@ -36390,8 +39456,7 @@ export function calculateFeeTier({
}
```
-We will use the following fee tiers starting from Monday:
-![Fee Tiers](fees.png)
+We will use the following fee tiers starting from Monday (see the fee tiers chart, `fees.png`, in the upstream repository — not vendored here):
In order to avoid possible issues created by the new fee structure, until you make sure it's implemented correctly, you can increase the slippage tolerance on buy / sell instructions as a temporary mitigation.
@@ -36399,7 +39464,7 @@ If you implement the fee logic correctly, any future change to the fee tiers str
---
-<a id="sec-168"></a>
+<a id="sec-170"></a>
> **Source:** `docs/pumpfun-program/docs/FEE_RECIPIENTS.md` · [↑ table of contents](#table-of-contents)
@@ -36462,7 +39527,7 @@ Use one of these as `buybackFeeRecipient` for any coin.
---
-<a id="sec-169"></a>
+<a id="sec-171"></a>
> **Source:** `docs/pumpfun-program/docs/PUMP_CASHBACK_README.md` · [↑ table of contents](#table-of-contents)
@@ -36579,7 +39644,7 @@ To read unclaimed cashback for pump swap / Pump AMM program:
---
-<a id="sec-170"></a>
+<a id="sec-172"></a>
> **Source:** `docs/pumpfun-program/docs/PUMP_CREATOR_FEE_README.md` · [↑ table of contents](#table-of-contents)
@@ -36683,7 +39748,7 @@ same code should work on both the creator fee update on Devnet and the current M
program on Mainnet to the creator fee update.
We are also trying to release the Pump program Typescript SDK by Monday, so you can use it. The
-[bondingCurve.ts](bondingCurve.ts) file is part of the upcoming Pump program Typescript SDK.
+`bondingCurve.ts` file is part of the upcoming Pump program Typescript SDK.
## Coin creator fees update
@@ -36701,7 +39766,7 @@ Who will not receive coin creator fees?
- coins already migrated to Raydium, as that program is not under our control.
- normal PumpSwap pools which are not created by Pump program `migrate` instruction.
-You should start by using the latest IDL files for both programs from the [idl](idl) directory. They are
+You should start by using the latest IDL files for both programs from the `idl` directory. They are
backwards-compatible with current programs deployed on Mainnet, so you can start using them now.
You can also use our Typescript SDKs for easier integration:
@@ -36714,7 +39779,7 @@ we update the programs on Mainnet.
---
-<a id="sec-171"></a>
+<a id="sec-173"></a>
> **Source:** `docs/pumpfun-program/docs/PUMP_PROGRAM_README.md` · [↑ table of contents](#table-of-contents)
@@ -36915,7 +39980,7 @@ at https://solscan.io/account/EsmVk4MTsoT71JFaRM5DWFZboKpMQjfY6EYzAgUuksXw#accou
---
-<a id="sec-172"></a>
+<a id="sec-174"></a>
> **Source:** `docs/pumpfun-program/docs/PUMP_SWAP_CREATOR_FEE_README.md` · [↑ table of contents](#table-of-contents)
@@ -37024,7 +40089,7 @@ PumpSwap program on Mainnet to the coin creator fee update.
---
-<a id="sec-173"></a>
+<a id="sec-175"></a>
> **Source:** `docs/pumpfun-program/docs/PUMP_SWAP_README.md` · [↑ table of contents](#table-of-contents)
@@ -37258,7 +40323,7 @@ Each Anchor instruction has a set of corresponding autocomplete methods that can
---
-<a id="sec-174"></a>
+<a id="sec-176"></a>
> **Source:** `docs/pumpfun-program/docs/PUMP_SWAP_SDK_README.md` · [↑ table of contents](#table-of-contents)
@@ -37338,7 +40403,7 @@ to autocomplete the `base` and `quote` displayed amounts based on the `lpToken`
---
-<a id="sec-175"></a>
+<a id="sec-177"></a>
> **Source:** `docs/pumpfun-program/docs/instructions/BUY.md` · [↑ table of contents](#table-of-contents)
@@ -37516,7 +40581,7 @@ ixs.extend(
---
-<a id="sec-176"></a>
+<a id="sec-178"></a>
> **Source:** `docs/pumpfun-program/docs/instructions/CLAIM_CASHBACK.md` · [↑ table of contents](#table-of-contents)
@@ -37626,7 +40691,7 @@ let ix = sdk.claim_cashback_v2_instruction(
---
-<a id="sec-177"></a>
+<a id="sec-179"></a>
> **Source:** `docs/pumpfun-program/docs/instructions/COIN_CREATION.md` · [↑ table of contents](#table-of-contents)
@@ -37781,7 +40846,7 @@ let ixs = sdk
---
-<a id="sec-178"></a>
+<a id="sec-180"></a>
> **Source:** `docs/pumpfun-program/docs/instructions/COLLECT_CREATOR_FEE.md` · [↑ table of contents](#table-of-contents)
@@ -37883,7 +40948,7 @@ ixs.extend(sdk.collect_creator_fee_v2_instructions(
---
-<a id="sec-179"></a>
+<a id="sec-181"></a>
> **Source:** `docs/pumpfun-program/docs/instructions/CREATOR_FEE_SHARING.md` · [↑ table of contents](#table-of-contents)
@@ -38237,7 +41302,7 @@ ixs.extend(sdk.distribute_creator_fees_v2_instructions(
---
-<a id="sec-180"></a>
+<a id="sec-182"></a>
> **Source:** `docs/pumpfun-program/docs/instructions/SELL.md` · [↑ table of contents](#table-of-contents)
@@ -38414,7 +41479,7 @@ ixs.extend(
---
-<a id="sec-181"></a>
+<a id="sec-183"></a>
> **Source:** `docs/quick-start.md` · [↑ table of contents](#table-of-contents)
@@ -38557,7 +41622,7 @@ The `brain` attribute turns the 3D viewer into a conversational agent:
| Attribute | What it does |
|-----------|--------------|
-| `brain` | LLM model ID. Anthropic: `claude-sonnet-4-6`, `claude-opus-4-7`, `claude-haiku-4-5`. OpenAI: `gpt-4o`, `gpt-4o-mini`. Omit for a viewer-only display with no AI. |
+| `brain` | LLM model ID. The in-browser runtime supports the Anthropic provider — registered model IDs: `claude-sonnet-4-6`, `claude-opus-4-7`, `claude-opus-4-6`, `claude-haiku-4-5-20251001`. Omit for a viewer-only display with no AI (provider `none`). |
| `instructions` | System prompt for the agent's personality and role. |
| `mode` | Layout mode: `inline` (flows with page content), `floating` (fixed bubble in a corner), `fullscreen`, or `section`. Default: `inline`. |
@@ -38581,7 +41646,7 @@ The fastest path to an embeddable 3D experience is an iframe widget. Build one i
```html
<iframe
- src="https://three.ws/app#widget=wdgt_YOUR_ID&kiosk=true"
+ src="https://three.ws/widget#widget=wdgt_YOUR_ID&kiosk=true"
width="600"
height="600"
style="border:0;border-radius:12px;max-width:100%"
@@ -38707,7 +41772,7 @@ If you're embedding inside a sandboxed iframe, make sure the parent grants `allo
---
-<a id="sec-182"></a>
+<a id="sec-184"></a>
> **Source:** `docs/remix.md` · [↑ table of contents](#table-of-contents)
@@ -38909,7 +41974,7 @@ still recorded — the royalty leg reports `payout_unconfigured` instead of payi
---
-<a id="sec-183"></a>
+<a id="sec-185"></a>
> **Source:** `docs/reputation.md` · [↑ table of contents](#table-of-contents)
@@ -39108,7 +42173,7 @@ See the [Validation](./validation.md) documentation for details.
---
-<a id="sec-184"></a>
+<a id="sec-186"></a>
> **Source:** `docs/risk-acknowledgment.md` · [↑ table of contents](#table-of-contents)
@@ -39220,7 +42285,7 @@ the same change.
---
-<a id="sec-185"></a>
+<a id="sec-187"></a>
> **Source:** `docs/sas-attestations.md` · [↑ table of contents](#table-of-contents)
@@ -39439,7 +42504,7 @@ Closing (revoking) an attestation is done server-side via `sasClose()` in [api/_
---
-<a id="sec-186"></a>
+<a id="sec-188"></a>
> **Source:** `docs/sdk.md` · [↑ table of contents](#table-of-contents)
@@ -39874,7 +42939,7 @@ python3 -m http.server 8080
---
-<a id="sec-187"></a>
+<a id="sec-189"></a>
> **Source:** `docs/security.md` · [↑ table of contents](#table-of-contents)
@@ -40223,7 +43288,7 @@ For validator misconduct (biased or falsified on-chain attestations), open a pub
---
-<a id="sec-188"></a>
+<a id="sec-190"></a>
> **Source:** `docs/share-and-embed.md` · [↑ table of contents](#table-of-contents)
@@ -40320,7 +43385,7 @@ To customize the preview image, change the agent's thumbnail in the editor.
---
-<a id="sec-189"></a>
+<a id="sec-191"></a>
> **Source:** `docs/skills.md` · [↑ table of contents](#table-of-contents)
@@ -41032,7 +44097,7 @@ For IPFS publishing, the CID of the directory becomes the stable URI. Agents can
---
-<a id="sec-190"></a>
+<a id="sec-192"></a>
> **Source:** `docs/smart-contracts.md` · [↑ table of contents](#table-of-contents)
@@ -41625,7 +44690,7 @@ On Base at typical gas prices (~0.001 gwei base fee), an agent registration runs
---
-<a id="sec-191"></a>
+<a id="sec-193"></a>
> **Source:** `docs/solana-pumpfun.md` · [↑ table of contents](#table-of-contents)
@@ -41799,7 +44864,7 @@ The MCP client and cron crawler are unit-tested with mocked `fetch` and `sql`. E
---
-<a id="sec-192"></a>
+<a id="sec-194"></a>
> **Source:** `docs/solana-reputation.md` · [↑ table of contents](#table-of-contents)
@@ -41995,7 +45060,7 @@ The shapes differ; the purpose is identical — let an agent decide, before it p
---
-<a id="sec-193"></a>
+<a id="sec-195"></a>
> **Source:** `docs/solana.md` · [↑ table of contents](#table-of-contents)
@@ -42016,7 +45081,7 @@ This document covers what is supported today, the end-to-end registration flow,
| Sign-In with Solana (SIWS) | Live | [api/auth/siws/\[action\].js](../api/auth/siws/%5Baction%5D.js) (handles `nonce` + `verify`) |
| Linking a Solana wallet to a user | Live | `user_wallets` table, `chain_type = 'solana'` |
| Solana payments (checkout + confirm) | Live | [api/payments/solana/\[action\].js](../api/payments/solana/%5Baction%5D.js) (handles `checkout` + `confirm`) |
-| Agent identity NFT (Metaplex Core) | Live | [api/agents/register/\[action\].js](../api/agents/register/%5Baction%5D.js) (handles `solana-prep` + `solana-confirm`) |
+| Agent identity NFT (Metaplex Core) | Live | [api/agents/solana/\[action\].js](../api/agents/solana/%5Baction%5D.js) (handles `register-prep` + `register-confirm`) |
| Agent record persisted in DB | Live | `agent_identities`, `meta.chain_type='solana'`, `meta.sol_mint_address` |
| On-chain reputation registry | **Not on Solana** | EVM only |
| On-chain validation registry | **Not on Solana** | EVM only (testnet) |
@@ -42219,7 +45284,7 @@ A full ERC-8004-equivalent on Solana would mean writing three Anchor programs (I
---
-<a id="sec-194"></a>
+<a id="sec-196"></a>
> **Source:** `docs/spatial-mcp.md` · [↑ table of contents](#table-of-contents)
@@ -42329,7 +45394,7 @@ Free 3D Studio (`structuredContent.spatial`): `forge_free`, `text_to_avatar`, `m
---
-<a id="sec-195"></a>
+<a id="sec-197"></a>
> **Source:** `docs/specs/agent-trading.md` · [↑ table of contents](#table-of-contents)
@@ -42416,7 +45481,7 @@ Real routes (no mocks), server-side guards with tests (including the $THREE-sell
---
-<a id="sec-196"></a>
+<a id="sec-198"></a>
> **Source:** `docs/start-here.md` · [↑ table of contents](#table-of-contents)
@@ -42508,7 +45573,7 @@ If you're here to create and share agents rather than write code, follow this pa
---
-<a id="sec-197"></a>
+<a id="sec-199"></a>
> **Source:** `docs/syndication.md` · [↑ table of contents](#table-of-contents)
@@ -42630,7 +45695,7 @@ updated feed.
---
-<a id="sec-198"></a>
+<a id="sec-200"></a>
> **Source:** `docs/token-gated-3d-embeds.md` · [↑ table of contents](#table-of-contents)
@@ -42748,7 +45813,7 @@ Every check that matters happens on the server:
---
-<a id="sec-199"></a>
+<a id="sec-201"></a>
> **Source:** `docs/trader-card.md` · [↑ table of contents](#table-of-contents)
@@ -42806,7 +45871,7 @@ Returns the identity summary, KPI aggregates, and the per-coin ledger — `known
---
-<a id="sec-200"></a>
+<a id="sec-202"></a>
> **Source:** `docs/trading-arenas.md` · [↑ table of contents](#table-of-contents)
@@ -42875,7 +45940,7 @@ Prove yourself solo (the [trading surfaces](trading-surfaces.md) → the [leader
---
-<a id="sec-201"></a>
+<a id="sec-203"></a>
> **Source:** `docs/trading-copilot.md` · [↑ table of contents](#table-of-contents)
@@ -43014,7 +46079,7 @@ plumbing — and never suggests, shills, or names another token on its own initi
---
-<a id="sec-202"></a>
+<a id="sec-204"></a>
> **Source:** `docs/trading-experiment.md` · [↑ table of contents](#table-of-contents)
@@ -43170,7 +46235,7 @@ much — and tune the next run. That is the whole point of the experiment.
---
-<a id="sec-203"></a>
+<a id="sec-205"></a>
> **Source:** `docs/trading-surfaces.md` · [↑ table of contents](#table-of-contents)
@@ -43315,7 +46380,7 @@ Agents wanting the same intel over MCP: see [docs/mcp.md](mcp.md) (`@three-ws/in
---
-<a id="sec-204"></a>
+<a id="sec-206"></a>
> **Source:** `docs/troubleshooting.md` · [↑ table of contents](#table-of-contents)
@@ -43364,11 +46429,7 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix
- **Apache:** `Header set Access-Control-Allow-Origin "*"` in `.htaccess`.
- **AWS S3 / CloudFront:** Set a CORS policy on the bucket (allow all origins, GET method).
- **Vercel / Netlify:** Add a `headers` rule in the config file.
-2. If you can't modify the server, use the `key-proxy` attribute on `<agent-3d>` to route the fetch through a proxy that adds CORS headers:
- ```html
- <agent-3d src="https://cdn.example.com/model.glb"
- key-proxy="https://your-cors-proxy/proxy?url="></agent-3d>
- ```
+2. If you can't modify the server, re-host the file somewhere that sends CORS headers: the platform's hosted storage (uploads via the Studio are CORS-configured automatically), or any CDN/bucket with a permissive CORS rule (Cloudflare R2, S3 + CORS policy). Note that the `key-proxy` attribute is **not** a fetch proxy — it points the element at your LLM API-key proxy endpoint (so the key never reaches the client) and has no effect on GLB loading.
---
@@ -43441,7 +46502,12 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix
- `401` — the API key is missing or invalid.
- `429` — rate limited. Wait a minute and retry.
- `500` — server error. Check the server logs.
-3. Verify `ANTHROPIC_API_KEY` is set in your environment. In Vercel: Settings → Environment Variables. The key must be present before deployment — a new deploy is required after adding it.
+3. Verify `ANTHROPIC_API_KEY` is set in your server environment. On the production Cloud Run service:
+ ```bash
+ gcloud run services update three-ws-api --region us-central1 \
+ --update-env-vars ANTHROPIC_API_KEY=sk-ant-...
+ ```
+ Updating an env var rolls a new revision automatically. On a self-hosted fork, set it wherever your host reads environment variables and restart/redeploy.
4. If you're calling the Anthropic API directly from the browser (not via a proxy), also set the `api-key` attribute on the element and note that this exposes your key to users.
---
@@ -43567,8 +46633,12 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix
console.log(e.data);
});
```
-3. All messages use the `'3dagent:'` type prefix. Outbound messages should look like `{ type: '3dagent:speak', payload: { text: '...' } }`.
-4. Use the embed-host bridge (`src/embed-host-bridge.js`) rather than raw `postMessage` — it handles the ping/pong handshake and waits for the iframe to be ready.
+3. Use the correct envelope shape. There are two related protocols, and neither uses a type prefix like `3dagent:`:
+ - The **element bridge** (`src/embed-host-bridge.js`) wraps every message in `{ v: 1, source: 'agent-host' | 'agent-3d', id, kind, op, payload }` — e.g. a speak request is `{ v: 1, source: 'agent-host', id: '<uuid>', kind: 'request', op: 'speak', payload: { text: '...' } }`.
+ - The **host protocol** ([specs/EMBED_HOST_PROTOCOL.md](../specs/EMBED_HOST_PROTOCOL.md)) uses `{ v: 1, type: 'host.*' | 'embed.*', id, payload }` — e.g. `{ v: 1, type: 'host.chat.message', payload: { ... } }`.
+
+ Messages that don't match the expected envelope (missing `v: 1`, wrong `source`/`type`) are silently ignored.
+4. Use the `EmbedHostBridge` class (`src/embed-host-bridge.js`) rather than raw `postMessage` — it handles the handshake, queues requests until the iframe is ready, and correlates responses by `id`.
---
@@ -43628,22 +46698,22 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix
**Fix steps:**
-1. Set `PUBLIC_APP_ORIGIN` to exactly the origin users are hitting (e.g. `https://www.yourdomain.com`). `www.yourdomain.com` and `yourdomain.com` are treated as different domains.
+1. Set `PUBLIC_APP_ORIGIN` to exactly the origin users are hitting (e.g. `https://www.yourdomain.com`). `www.yourdomain.com` and `yourdomain.com` are treated as different domains. In production this lives on the Cloud Run service (`gcloud run services update three-ws-api --region us-central1 --update-env-vars PUBLIC_APP_ORIGIN=...`).
2. For local development, any `localhost` domain is accepted automatically — you don't need to set `PUBLIC_APP_ORIGIN` for local dev.
-3. For Vercel preview deployments, `VERCEL_URL` is automatically trusted alongside `PUBLIC_APP_ORIGIN`.
+3. For forks deployed on Vercel, the deployment host injected as `VERCEL_URL` is automatically trusted alongside `PUBLIC_APP_ORIGIN`.
---
### Session expires unexpectedly
-**Symptom:** Users are logged out before the 7-day session window.
+**Symptom:** Users are logged out before the 30-day session window.
**Likely cause:** `JWT_SECRET` changed between deploys, which invalidates all existing sessions.
**Fix steps:**
-1. Set `JWT_SECRET` once and don't rotate it unless needed. Store it in Vercel's environment variable settings — it must be the same value across all deployments.
-2. Session duration is 7 days and is not currently configurable.
+1. Set `JWT_SECRET` once and don't rotate it unless needed. In production it lives on the Cloud Run service env (`gcloud run services describe three-ws-api --region us-central1` to inspect) — it must be the same value across all revisions.
+2. Session duration is 30 days. A session used when fewer than 7 days remain is rotated to a fresh 30-day token (a rolling refresh window), so actively returning users stay signed in indefinitely.
---
@@ -43723,7 +46793,7 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix
**Fix steps:**
1. Check the `memory` attribute or manifest setting. The default mode is `"local"` (persisted to `localStorage`). If your manifest or element sets `memory="none"`, memory is intentionally disabled.
-2. Verify `localStorage` isn't being cleared. Open DevTools → Application → Local Storage and look for keys starting with `3dagent:`. If they're missing after a conversation, check if your browser settings clear storage on close.
+2. Verify `localStorage` isn't being cleared. Open DevTools → Application → Local Storage and look for keys of the form `agent:<agentId>:memory`. If they're missing after a conversation, check if your browser settings clear storage on close.
3. Private/incognito mode: `localStorage` is cleared when the window closes. This is browser behavior, not a bug.
---
@@ -43817,8 +46887,13 @@ Run `npm run db:status` first to preview which migrations are pending.
**Fix steps:**
-1. Check Vercel function logs: `vercel logs --follow` in the project directory.
-2. The most common cause is a missing environment variable. All required vars must be set: `DATABASE_URL`, `JWT_SECRET`, `PUBLIC_APP_ORIGIN`. The `env.js` module throws on startup if required vars are absent.
+1. Check the server logs. Production runs on Google Cloud Run (service `three-ws-api`, region `us-central1`); read recent errors with:
+ ```bash
+ gcloud logging read 'resource.type="cloud_run_revision" resource.labels.service_name="three-ws-api" severity>=ERROR' \
+ --freshness=1h --limit 20 --format="value(textPayload)"
+ ```
+ Deploys ship via `npm run deploy:gcp` (run `npm run build` first for frontend changes) — the full runbook lives in the repo at `docs/ops/gcp-production.md`. On a self-hosted fork, check whatever your host surfaces as function/process logs.
+2. The most common cause is a missing environment variable. All required vars must be set: `DATABASE_URL`, `JWT_SECRET`, `PUBLIC_APP_ORIGIN`. The `env.js` module throws on startup if required vars are absent. In production, inspect and set them on the Cloud Run service: `gcloud run services describe three-ws-api --region us-central1` / `gcloud run services update three-ws-api --region us-central1 --update-env-vars KEY=value`.
---
@@ -43864,7 +46939,7 @@ Add `allow="xr-spatial-tracking"` to the `<iframe>` element. Without it, the bro
The AR button is only shown after the GLB finishes loading. If the model is large or on a slow connection, the button appears late. Check the console for load errors.
**Check 5 — HTTP origin:**
-`navigator.xr` is `undefined` on `http://` origins. All AR methods require HTTPS for the page or the model URL. Use ngrok or a deployed preview URL during development.
+`navigator.xr` is `undefined` on `http://` origins. All AR methods require HTTPS for the page or the model URL. Use an ngrok tunnel or a deployed HTTPS environment during development.
---
@@ -43923,8 +46998,8 @@ ngrok http 3000 # creates an HTTPS tunnel
# Open the ngrok URL on your phone
```
-**Option 2 — Vercel preview:**
-Push to a branch. Vercel creates an instant HTTPS preview URL. This is the cleanest option — it tests the production build.
+**Option 2 — a deployed HTTPS environment:**
+Deploy your change and test against the live HTTPS URL. There are no per-branch preview deployments in the production flow — three.ws production deploys with `npm run deploy:gcp` to Cloud Run. A fork hosted on Vercel or Netlify does get an HTTPS URL per deploy, which works the same way for AR testing.
**Chrome WebXR emulator (desktop testing):**
Chrome 127+ includes a WebXR device simulator under DevTools → More Tools → WebXR. It won't show camera passthrough but lets you test the session lifecycle and model placement logic without a physical device.
@@ -43949,7 +47024,7 @@ The 3D viewer, animations, and widget system all work without a key. The LLM con
**Can I self-host without Vercel?**
-Yes. The API routes are standard Node.js async functions — any Node.js host works. You'll need to replicate Vercel's `vercel.json` rewrite rules in your host's routing config (Express routes, Nginx `proxy_pass`, etc.).
+Yes — production itself doesn't run on Vercel. Since 2026-07-07, three.ws production is a single container on Google Cloud Run: `server/index.mjs` serves the static frontend and every `api/**` handler, and reads `vercel.json`'s route table at runtime as its routing config. That server is the reference implementation for self-hosting on any Node.js host. If you'd rather use your own routing layer (Express routes, Nginx `proxy_pass`, etc.), replicate the `vercel.json` rewrite rules there — the API routes are standard Node.js async functions. Deploying a fork to Vercel also still works.
**Is the agent data private?**
@@ -43961,7 +47036,7 @@ This is a known open issue. The `IdleAnimation` class is implemented in `src/idl
---
-<a id="sec-205"></a>
+<a id="sec-207"></a>
> **Source:** `docs/trust-primitives.md` · [↑ table of contents](#table-of-contents)
@@ -44201,7 +47276,7 @@ See also: [x402 paid endpoints](./x402.md) · [Agent Bouncer](./api-reference.md
---
-<a id="sec-206"></a>
+<a id="sec-208"></a>
> **Source:** `docs/tutorials/agent-personality.md` · [↑ table of contents](#table-of-contents)
@@ -44372,20 +47447,21 @@ The "use sparingly" line matters. Models that over-gesture come across as a chil
The platform maintains conversation memory automatically. Two scopes:
- **Rolling context** — the last N turns of the current chat. Fed back into the model on each turn so it remembers what was just said. Cleared by `agent.clearConversation()` and on page reload by default.
-- **Long-term memory** — explicit facts the agent wrote with `agent.agent.memory.write(scope, key, value)` or loaded from the manifest. Persists across sessions if the memory mode is `local` (browser storage) or `cloud` (server-side).
+- **Long-term memory** — explicit notes written through the element's `memory` handle with `agent.memory.write(key, { name, description, type, body })`, or loaded from the manifest. Persists across sessions if the memory mode is `local` (browser storage) or `cloud` (server-side).
For most agents, the rolling context is enough. The user asks "what was that project you mentioned?" and the model still has the previous turn in context — no separate memory write needed.
You reach for long-term memory in two scenarios:
-**Pre-loading reference facts.** The agent should always know certain things — your portfolio links, your office hours, the museum's wing list. Write these once at boot:
+**Pre-loading reference facts.** The agent should always know certain things — your portfolio links, your office hours, the museum's wing list. Write these once at boot. Each entry is a small named note: a `key` (its filename in the memory store) plus a `name`, a one-line `description`, a `type` (`reference` for facts like these), and a free-text `body`:
```js
-agent.addEventListener('agent:ready', async () => {
- await agent.agent.memory.write('long-term', 'hours', {
- weekday: '9am-7pm',
- weekend: '10am-5pm',
- holidays: 'Closed Dec 24-26',
+agent.addEventListener('agent:ready', () => {
+ agent.memory.write('hours', {
+ name: 'Opening hours',
+ description: 'When we are open, for any scheduling question',
+ type: 'reference',
+ body: 'Weekdays 9am-7pm. Weekends 10am-5pm. Closed Dec 24-26.',
});
});
```
@@ -44553,7 +47629,7 @@ two sentences: who you are, who you represent, and invite the visitor to ask any
Then wave.
```
-The "__greet" trigger is a pattern worth knowing about. The web component can fire a hidden first message at page load to give the agent something to respond to — that's how you get the agent to introduce itself without needing the user to type first. The prompt names the trigger explicitly so the model knows how to handle it.
+The "__greet" trigger is a pattern worth knowing about. Your page can fire a hidden first message once the agent boots — `agent.addEventListener('agent:ready', () => agent.say('__greet'))` — to give the brain something to respond to. That's how you get the agent to introduce itself without needing the user to type first. It has to be `say()` (or `ask()`), which route the message through the brain; `speak()` never reaches the model — it only drives the talking animation. The prompt names the trigger explicitly so the model knows how to handle it.
---
@@ -44653,7 +47729,7 @@ The system prompt is the cheapest, highest-leverage thing you can change about a
---
-<a id="sec-207"></a>
+<a id="sec-209"></a>
> **Source:** `docs/tutorials/agent-reputation.md` · [↑ table of contents](#table-of-contents)
@@ -44957,7 +48033,7 @@ A read costs nothing and asks no one's permission. That's the property that lets
---
-<a id="sec-208"></a>
+<a id="sec-210"></a>
> **Source:** `docs/tutorials/animate-your-avatar.md` · [↑ table of contents](#table-of-contents)
@@ -45182,7 +48258,7 @@ Primary call to action: open **[/pose](/pose)**, load an avatar, and apply your
---
-<a id="sec-209"></a>
+<a id="sec-211"></a>
> **Source:** `docs/tutorials/build-a-scene.md` · [↑ table of contents](#table-of-contents)
@@ -45401,7 +48477,7 @@ The leverage of [Scene Studio](/scene) is that it's a *real* editor producing a
---
-<a id="sec-210"></a>
+<a id="sec-212"></a>
> **Source:** `docs/tutorials/claim-threews-name.md` · [↑ table of contents](#table-of-contents)
@@ -45709,7 +48785,7 @@ See also:
---
-<a id="sec-211"></a>
+<a id="sec-213"></a>
> **Source:** `docs/tutorials/connect-ai-brain.md` · [↑ table of contents](#table-of-contents)
@@ -45794,14 +48870,14 @@ The current production-ready models, with the tradeoffs that actually matter for
- **Capability:** Excellent at tool use, structured output, and following system prompts. The right default for support, sales, concierge, and personal agents.
- **Context window:** 200K tokens. Plenty of room for long system prompts and memory.
-**Claude Opus 4.7 (1M)** (`claude-opus-4-7-1m`) — when you need the smartest model.
+**Claude Opus 4.7** (`claude-opus-4-7`) — when you need the smartest model.
- **Cost:** ~5x Sonnet. Worth it for high-stakes agents (legal, medical, financial assistants) and complex reasoning chains.
- **Latency:** First token in ~1.2s. Full reply 2.5-4s for a typical turn.
- **Capability:** Best-in-class at multi-step reasoning, ambiguous instruction handling, and long-context retrieval. Holds character better under adversarial pressure.
-- **Context window:** 1M tokens. Useful only if you're loading very long documents or transcripts into the prompt.
+- **Context window:** 200K tokens. Same headroom as Sonnet — the upgrade is depth of reasoning, not window size.
-**Claude Haiku 4.5** (`claude-haiku-4-5`) — when latency matters more than depth.
+**Claude Haiku 4.5** (`claude-haiku-4-5-20251001`) — when latency matters more than depth.
- **Cost:** ~1/3 of Sonnet.
- **Latency:** First token in ~250ms. Full reply in well under a second.
@@ -45949,7 +49025,8 @@ This is the part that often surprises people: the embed snippet on your website
If you have:
```html
-<script src="https://three.ws/cdn/agent-3d.js" data-agent-id="YOUR_AGENT_ID" id="agent"></script>
+<script type="module" src="https://three.ws/agent-3d/latest/agent-3d.js"></script>
+<agent-3d agent-id="YOUR_AGENT_ID" id="agent"></agent-3d>
```
…on a thousand pages, you can switch the brain from Sonnet to Opus to GPT-5 entirely from the dashboard. No deploy. No code edit. The next page load picks up the new model.
@@ -46031,7 +49108,7 @@ The brain is the part of the agent you'll iterate on most after the system promp
---
-<a id="sec-212"></a>
+<a id="sec-214"></a>
> **Source:** `docs/tutorials/create-and-edit-memory.md` · [↑ table of contents](#table-of-contents)
@@ -46352,7 +49429,7 @@ The leverage is in *enhancement*: the right type, one fact per memory, tags, del
---
-<a id="sec-213"></a>
+<a id="sec-215"></a>
> **Source:** `docs/tutorials/custom-skill.md` · [↑ table of contents](#table-of-contents)
@@ -46865,20 +49942,20 @@ The skill installs via a URI in the agent manifest, runs entirely client-side, a
---
-<a id="sec-214"></a>
+<a id="sec-216"></a>
> **Source:** `docs/tutorials/customize-appearance.md` · [↑ table of contents](#table-of-contents)
# Customize size, position & background
-A default embed lands in the bottom-right corner at a fixed size, with a transparent background, and a gentle idle rotation. That's a sensible starting point — it works on every site without tuning. But it is not what you want long-term. You want an agent that feels designed for your page: anchored where it belongs, sized for the layout, blended into the background, rotating at exactly the pace that suits your brand.
+A default embed renders inline where you put the tag, fills its container, and shows the avatar over a transparent background. That's a sensible starting point — it works on every site without tuning. But it is not what you want long-term. You want an agent that feels designed for your page: anchored where it belongs, sized for the layout, blended into the background, framed at exactly the crop that suits your brand.
-This tutorial walks through every `data-*` attribute the three.ws embed loader honours. It covers them one at a time, with real snippets you can copy. By the end you have an agent that looks like it shipped with your site, not like a widget bolted on after the fact.
+This tutorial walks through every appearance attribute the `<agent-3d>` element honours. It covers them one at a time, with real snippets you can copy. By the end you have an agent that looks like it shipped with your site, not like a widget bolted on after the fact.
**What you'll build:**
- A floating agent sized and positioned precisely where you want it
-- A background that matches your site (transparent, branded, or a fixed colour)
-- A rotation speed tuned to the mood of your page
+- A background that matches your site (transparent, dark, light, or any CSS colour)
+- A framing and idle animation tuned to the mood of your page
- A pixel-perfect, brand-aligned embed snippet for any site stack
- A clear map of which attributes do what
@@ -46886,261 +49963,265 @@ This tutorial walks through every `data-*` attribute the three.ws embed loader h
---
-## Step 1 — How the loader reads your attributes
+## Step 1 — How the element reads your attributes
-Every customisation in this tutorial is set as a `data-*` attribute on the embed script tag itself, not on a separate config object. The loader reads those attributes once, when the script first runs.
+The embed is two tags: a `<script>` that loads the runtime once, and an `<agent-3d>` custom element that places the agent. Every customisation in this tutorial is an attribute on the **element**, not on the script tag.
The general shape is always the same:
```html
-<script
- src="https://three.ws/cdn/agent-3d.js"
- data-agent-id="YOUR_AGENT_ID"
- data-size="large"
- data-position="bottom-left"
- data-background-color="transparent"
- data-rotation-speed="0.5"
-></script>
+<script type="module" src="https://three.ws/agent-3d/1.5.2/agent-3d.js"></script>
+
+<agent-3d
+ agent-id="YOUR_AGENT_ID"
+ mode="floating"
+ position="bottom-left"
+ width="320px"
+ height="420px"
+ background="transparent"
+></agent-3d>
```
Order doesn't matter. Capitalisation does: every attribute is lowercase, hyphenated. Spelling matters too — an unknown attribute is silently ignored, so you'll see no error if you typo one, just the default behaviour.
-There is one tricky thing worth knowing up front: because attributes are read once at script load, changing them later via DOM manipulation does not re-render the agent. If you need to update appearance dynamically, the right tool is the JS API on the script element, which is covered briefly at the end of this tutorial.
+Because this is a real custom element, the appearance attributes are **live**. Change `mode`, `position`, `width`, `height`, `responsive`, `background`, `name-plate`, `framing`, or `clip` from JavaScript at any time and the element re-applies the change on the spot — no reload, no re-embed:
----
+```js
+const agent = document.querySelector('agent-3d');
+agent.setAttribute('background', 'dark'); // repaints immediately
+agent.setAttribute('position', 'top-left'); // re-anchors immediately
+```
+
+One loading note worth knowing up front: the element boots lazily. It waits until it is scrolled near the viewport (with a 300px head start) before downloading the 3D body. Add the boolean `eager` attribute if you want it to boot the moment the page loads instead.
-## Step 2 — `data-size`: how big the widget appears
+---
-The simplest attribute, and the one most people want to change first. `data-size` accepts either a named preset or a CSS-style pixel value.
+## Step 2 — `mode`: how the widget sits on the page
-### Named presets
+`mode` decides the fundamental layout. Four values:
```html
-<script
- src="https://three.ws/cdn/agent-3d.js"
- data-agent-id="YOUR_AGENT_ID"
- data-size="medium"
-></script>
+<agent-3d agent-id="YOUR_AGENT_ID" mode="floating"></agent-3d>
```
-The available presets are:
-
-- `small` — a compact 160 × 240 widget; good for unobtrusive helper bots on busy pages
-- `medium` — the default, 220 × 320; a comfortable size for most content sites
-- `large` — 320 × 460; gives the avatar more presence on a marketing page
-- `xlarge` — 420 × 600; suitable when the agent *is* the hero element
+- `inline` — the default. The element is a normal block in the document flow, sized by its container (100% wide, 480px tall unless you say otherwise). Use it when the agent is a section of the page — a product hero, a team-page member, a docs helper embedded mid-article.
+- `floating` — the classic support-widget layout. The element is `position: fixed`, floats above your content, stays put while the visitor scrolls, and can be dragged around by its handle. This is the mode most marketing and support embeds want.
+- `section` — like inline, but the chat column is capped at 600px wide so a full-width band on a desktop layout doesn't produce comically wide message bubbles.
+- `fullscreen` — the element covers the whole viewport (`100vw` × `100dvh`) with the chat column centred at 800px. Use it for dedicated "/talk-to-us" pages.
-If you have not set this attribute, `medium` is what you get.
+### Inline placement
-### Explicit pixel value
-
-If a preset doesn't fit your layout, set the width directly:
+In inline mode the element sits exactly where the tag is rendered:
```html
-<script
- src="https://three.ws/cdn/agent-3d.js"
- data-agent-id="YOUR_AGENT_ID"
- data-size="280px"
-></script>
-```
-
-The widget keeps the same aspect ratio (roughly 2:3 portrait), so you only need to set width. The height scales automatically.
-
-You can also use percentages for inline embeds (covered in the next section). `data-size="60%"` means the widget takes 60% of its container width.
+<h1>About Us</h1>
+<p>Meet our digital concierge.</p>
-### What the size affects
+<agent-3d
+ agent-id="YOUR_AGENT_ID"
+ width="400px"
+ height="520px"
+ style="margin: 0 auto;"
+></agent-3d>
-Setting `data-size` changes three things at once: the container's CSS width, the canvas resolution, and the avatar's framing within that canvas. The avatar is always centred and proportioned so its head sits roughly one-third from the top. This means a smaller size doesn't crop the face — it just zooms out a little so the full body remains visible.
+<p>Below, you'll find our services...</p>
+```
-If you want to see how the size feels on a real layout before committing, drop the snippet into your page, refresh, and try `small`, `medium`, and `large` in sequence. Sizes look different on different content; trust the page, not the theory.
+It's a block-level element, so the usual CSS applies: centre it with `margin: 0 auto`, place it in a grid cell, float it in a column. No special rules.
---
-## Step 3 — `data-position`: where the widget anchors
+## Step 3 — `width`, `height` and `responsive`: how big it appears
-There are four corner anchors plus one inline mode.
+`width` and `height` accept any CSS length. Floating mode defaults to **320px × 420px**; inline mode defaults to the container's width and 480px tall.
```html
-<script
- src="https://three.ws/cdn/agent-3d.js"
- data-agent-id="YOUR_AGENT_ID"
- data-position="bottom-right"
-></script>
+<agent-3d
+ agent-id="YOUR_AGENT_ID"
+ mode="floating"
+ width="280px"
+ height="380px"
+></agent-3d>
```
-The five accepted values:
+### Responsive scaling is on by default
-- `bottom-right` — the default; floats above your page in the lower-right corner
-- `bottom-left` — same behaviour, mirrored to the lower-left
-- `top-right` — anchored to the upper-right
-- `top-left` — anchored to the upper-left
-- `inline` — the widget is *not* fixed; it flows with the rest of the page
+You don't get a fixed 280px box on a 320px phone. Unless you opt out, the element wraps your dimensions in a CSS `clamp()` tied to the viewport, so the widget scales down gracefully on small screens (never below roughly two-thirds of the size you asked for, with sane floors of 160px width / 200px height).
-### When to use each corner
+Two more responsive behaviours come free:
-The corners are all "floating" positions. The agent uses `position: fixed`, so it stays in the same place on screen as the visitor scrolls. The container has a small margin from the viewport edge and a soft drop shadow so it reads as a distinct element layered over your content.
+- **Floating pill collapse.** On viewports narrower than 480px, a floating widget collapses into a 56px round pill. Tapping the pill expands it into a bottom sheet covering 70% of the screen; swiping down (or tapping outside) collapses it again. Visitors on phones get a native-feeling sheet instead of a widget covering half the page.
+- **Inline aspect lock.** An inline embed given only a `width` keeps a 3:4 portrait aspect ratio as it resizes with its container.
-- **Bottom-right** is the conventional support-widget position. Visitors expect to find help there. Use it when the agent is supplementary.
-- **Bottom-left** works well when you have something else important on the right (a cookie banner, a chat tool, a sticky CTA).
-- **Top-right** suits agents that introduce themselves immediately — they're hard to miss above the fold, and they don't compete with your hero CTA at the bottom.
-- **Top-left** is rare but useful for documentation sites where the right margin is reserved for a table of contents.
-
-### Inline mode
-
-`data-position="inline"` is different. The widget is no longer floating; it sits where the script tag is rendered, in the natural document flow:
+Opt out of all of it with `responsive="false"` — then your `width` and `height` are used verbatim:
```html
-<h1>About Us</h1>
-<p>Meet our digital concierge.</p>
+<agent-3d agent-id="YOUR_AGENT_ID" mode="floating" width="280px" height="380px" responsive="false"></agent-3d>
+```
-<script
- src="https://three.ws/cdn/agent-3d.js"
- data-agent-id="YOUR_AGENT_ID"
- data-position="inline"
- data-size="400px"
-></script>
+Prefer leaving it on. The clamped sizes look intentional on every screen; hard-coded pixels only look right on the screen you tested.
-<p>Below, you'll find our services...</p>
-```
+---
-In this mode the widget is a block-level element in the page. It contributes to the normal scroll height, sits in its parent column, and inherits the parent's text alignment. Use inline mode when the agent is a section of a page rather than a global helper — for example, on a product detail page where the agent represents a single product, or on a team page where each member has their own embedded agent.
+## Step 4 — `position` and `offset`: where a floating widget anchors
-You can centre an inline embed by wrapping it in a centred container:
+These two apply to `mode="floating"` only (inline elements are positioned by your page layout, like any other element).
```html
-<div style="text-align:center; padding: 40px 0;">
- <script
- src="https://three.ws/cdn/agent-3d.js"
- data-agent-id="YOUR_AGENT_ID"
- data-position="inline"
- ></script>
-</div>
+<agent-3d
+ agent-id="YOUR_AGENT_ID"
+ mode="floating"
+ position="bottom-right"
+ offset="24px 24px"
+></agent-3d>
```
+`position` combines a vertical keyword (`top` / `bottom`) with a horizontal one (`left` / `right` / `center`):
+
+- `bottom-right` — the default; the conventional support-widget corner. Visitors expect to find help there.
+- `bottom-left` — same behaviour, mirrored. Useful when a cookie banner or another chat tool owns the right side.
+- `bottom-center` — horizontally centred along the bottom edge.
+- `top-right` / `top-left` / `top-center` — anchored along the top. `top-right` suits agents that introduce themselves above the fold; `top-left` works on docs sites whose right margin is reserved for a table of contents.
+
+`offset` sets the distance from the anchored edges as `"<vertical> <horizontal>"`. One value applies to both. The default is `24px 24px`. Push a widget clear of a fixed footer with `offset="88px 24px"`.
+
+One nice-to-know: floating widgets are **draggable**. A slim grab handle sits along the top edge of the widget, and visitors can move it anywhere on screen. Your `position` is where it starts, not a cage.
+
---
-## Step 4 — `data-background-color`: the canvas behind the agent
+## Step 5 — `background`: the canvas behind the agent
-By default, the canvas behind the avatar is transparent, which means your page background shows through. That works for most setups, but some looks better with a solid or semi-transparent backdrop.
+By default the canvas behind the avatar is transparent, so your page shows through. `background` accepts two keywords plus any CSS colour.
### Transparent (default)
```html
-<script
- src="https://three.ws/cdn/agent-3d.js"
- data-agent-id="YOUR_AGENT_ID"
- data-background-color="transparent"
-></script>
+<agent-3d agent-id="YOUR_AGENT_ID" background="transparent"></agent-3d>
```
You don't need to set this explicitly — it is the default — but writing it out makes the intent clear when other developers read your code.
-### Solid hex
+### `dark` and `light` keywords
```html
-<script
- src="https://three.ws/cdn/agent-3d.js"
- data-agent-id="YOUR_AGENT_ID"
- data-background-color="#0a0a14"
-></script>
+<agent-3d agent-id="YOUR_AGENT_ID" background="dark"></agent-3d>
```
-Use a solid colour when your page has busy content behind the widget — a hero image, a video, a complex pattern — and you want the avatar to stand out without compositing tricks.
+- `dark` — a near-black `#0b0d10` backdrop.
+- `light` — a near-white `#f5f5f5` backdrop. This keyword also flips the speech bubble and name-plate to dark-on-light styling so the text stays readable.
-Both the three-digit and six-digit hex forms work: `#000`, `#0a0a14`, `#ffffff`. Names like `black` and `white` also work, but stick to hex for consistency.
+These are the same options the editor's snippet builder offers, so a snippet copied from the editor and one written by hand behave identically.
-### Semi-transparent
+### Any CSS colour
-Eight-digit hex codes include alpha:
+Anything other than the keywords is treated as a literal CSS colour — hex, `rgb()`, a named colour:
```html
-<script
- src="https://three.ws/cdn/agent-3d.js"
- data-agent-id="YOUR_AGENT_ID"
- data-background-color="#0a0a14cc"
-></script>
+<agent-3d agent-id="YOUR_AGENT_ID" background="#0a0a14"></agent-3d>
```
-The last two hex digits are alpha: `cc` is roughly 80% opacity. Use this for a glassy panel effect — visible structure behind the agent, but enough opacity that the avatar reads cleanly.
-
-### Picking a colour that works
+Use a solid colour when your page has busy content behind the widget — a hero image, a video, a complex pattern — and you want the avatar to stand out.
A few practical notes from putting agents on real sites:
- Dark pages almost always look best with a transparent background — the avatar lighting matches the page mood naturally.
-- Light pages can go either way. Transparent works if the avatar is contrasty; a solid pale colour (like `#f6f6f9`) reads as more intentional.
+- Light pages can go either way. Transparent works if the avatar is contrasty; the `light` keyword (or a solid pale colour like `#f6f6f9`) reads as more intentional.
- If you're using a brand colour, desaturate it 20–30% for the embed background. Pure brand hues compete with the avatar; the same hue toned down recedes appropriately.
-- Avoid pure black `#000000` and pure white `#ffffff`. They look harsh next to a 3D-shaded avatar. A near-black like `#08080c` or a near-white like `#fafafa` are easier on the eye.
+- Avoid pure black `#000000` and pure white `#ffffff`. They look harsh next to a 3D-shaded avatar. The `dark` and `light` keywords are tuned near-black and near-white for exactly this reason.
---
-## Step 5 — `data-rotation-speed`: the idle animation pace
+## Step 6 — `framing`, `name-plate` and `poster`: the finishing details
-Out of the box, the agent rotates slowly while idle. This is a polite "I am alive" signal — it tells visitors the page isn't frozen, and gives the avatar presence without demanding attention.
+### `framing`
-You can tune that rotation:
+Controls how the camera crops the avatar:
```html
-<script
- src="https://three.ws/cdn/agent-3d.js"
- data-agent-id="YOUR_AGENT_ID"
- data-rotation-speed="0.5"
-></script>
+<agent-3d agent-id="YOUR_AGENT_ID" framing="portrait"></agent-3d>
```
-The value is a multiplier on the default speed. Useful values:
+- Default (**full**) — the whole body is in frame, with the camera favouring the upper body.
+- `portrait` — a head-to-mid-thigh crop. The face fills far more of the canvas, which is what you want for small floating widgets where a full body would render the face at postage-stamp size.
-- `0` — no idle rotation. The agent stands still until interacted with. Use this for serious or professional contexts where motion is a distraction.
-- `0.3` — a subtle, slow turn. Reads as "calm and attentive".
-- `1` — the default. A steady, easy rotation.
-- `2` — twice as fast. The agent feels playful, energetic.
-- `4` — fast spinning. Almost always too much; use only on playful or marketing pages where you want grabbed attention.
+Rule of thumb: `portrait` for floating widgets under ~360px wide, full framing for inline heroes where the whole character is the point. It's live — flip it at runtime and the camera reframes.
-Anything above `4` is allowed but rarely a good idea — it competes with the rest of your page and triggers motion sensitivity for some visitors. If your site has a "reduce motion" toggle, consider setting `data-rotation-speed="0"` when the user has opted out of motion.
+### `name-plate`
-You can pair rotation speed with size and position to build a coherent feel:
+Conversational embeds (anything bound to a published agent) show a small overlay with the agent's name. Hide it when your page already introduces the agent in its own copy:
-- "Quiet helper" — `data-size="small"`, `data-position="bottom-right"`, `data-rotation-speed="0.3"`
-- "Playful mascot" — `data-size="large"`, `data-position="bottom-left"`, `data-rotation-speed="2"`
-- "Hero element" — `data-size="xlarge"`, `data-position="inline"`, `data-rotation-speed="0.5"`
+```html
+<agent-3d agent-id="YOUR_AGENT_ID" name-plate="off"></agent-3d>
+```
----
+Bare decoration avatars never show a plate, so there's nothing to turn off there.
+
+### `poster`
-## Step 6 — `data-greeting` and `data-name`: the small visible details
+A poster image fills the frame while the 3D body downloads, then fades out at the exact moment the avatar appears — the same trick `<video poster>` uses. It also serves as the graceful fallback if a decoration avatar's body fails to load.
-Two more attributes worth covering here because they're frequently used alongside the visual ones, even though their effects are textual rather than purely visual.
+```html
+<agent-3d
+ agent-id="YOUR_AGENT_ID"
+ poster="/img/agent-still.webp"
+></agent-3d>
+```
+
+Use a still render of the same avatar so the swap from image to live 3D is seamless. On slow connections this single attribute is the difference between "blank box, then character" and "character, which then comes alive".
+
+---
-### `data-name`
+## Step 7 — `clip`: the idle animation
-Overrides the name shown in the agent's nameplate label.
+A decoration avatar — one embedded without chat, as pure visual presence — plays its `clip` attribute on loop, defaulting to `idle`:
```html
-<script
- src="https://three.ws/cdn/agent-3d.js"
- data-agent-id="YOUR_AGENT_ID"
- data-name="Iris"
-></script>
+<agent-3d
+ body="https://three.ws/avatars/default.glb"
+ clip="dance"
+ width="320px"
+ height="420px"
+></agent-3d>
```
-Useful when one underlying agent serves multiple sites and you want the visible label to differ. For example, the same agent might appear as "Iris" on your customer-facing site and "Internal Helper" on a private team page.
+The clip library is shared by every embed; useful ones for ambient presence include `idle`, `wave`, `dance`, `think`, `sitloop`, and `celebrate`. Looping clips loop; one-shot clips play once and settle back into idle with a crossfade rather than snapping. Change the attribute at runtime and playback re-cues to the new clip.
-### `data-greeting`
+Two built-in courtesies you don't have to code:
-Sets the first thing the agent says aloud after it's ready.
+- **Reduced motion.** When the visitor's OS has `prefers-reduced-motion` set, ambient playback is suppressed and the avatar holds a clean static pose instead. Explicit user-triggered animations still play.
+- **Lazy boot.** Offscreen avatars don't render at all until scrolled near, so a page with several decoration embeds doesn't burn GPU on the ones nobody is looking at.
-```html
-<script
- src="https://three.ws/cdn/agent-3d.js"
- data-agent-id="YOUR_AGENT_ID"
- data-greeting="Welcome to our site. Click me to ask anything."
-></script>
+---
+
+## Step 8 — Theming with CSS
+
+Because `<agent-3d>` is a real element on your page, ordinary CSS reaches it. The chat chrome exposes its design tokens as CSS custom properties, which you can override from your stylesheet:
+
+```css
+agent-3d {
+ --agent-accent: #e11d48; /* thinking dots, message accents, spinners */
+ --agent-surface: rgba(24, 16, 20, 0.92); /* message + panel surfaces */
+ --agent-bubble-bg: rgba(255, 245, 247, 0.95); /* speech bubble */
+ --agent-bubble-color: #2a0a12; /* speech bubble text */
+ --agent-bubble-radius: 12px; /* corner rounding */
+ --agent-chat-font: 'Inter', system-ui, sans-serif;
+}
```
-The greeting is spoken with the agent's configured TTS voice and shown as a speech bubble. We cover this attribute in much more depth — including how to handle browser autoplay restrictions and how to subtitle the greeting for accessibility — in the dedicated tutorial: [Add a greeting and first speech line](/tutorials/greeting-and-first-speech).
+For structural styling, the shadow DOM exposes named parts — `stage` (the 3D canvas area), `chrome` (the chat column), `chat` (the message log), `name-plate`, and `loading`:
+
+```css
+agent-3d::part(name-plate) {
+ font-family: 'Inter', sans-serif;
+ letter-spacing: 0.02em;
+}
+```
+
+Set the custom properties to your brand tokens once, in the same stylesheet as the rest of your site, and every embed on every page inherits them.
---
-## Step 7 — Putting it all together: a branded SaaS embed
+## Step 9 — Putting it all together: a branded SaaS embed
To bring this from theory to a real example, here is a complete, branded embed for a hypothetical productivity SaaS called "Lumen". The brand colours are a dark indigo and a warm cream; the brand voice is calm and professional.
@@ -47175,6 +50256,11 @@ To bring this from theory to a real example, here is a complete, branded embed f
text-decoration: none;
font-weight: 500;
}
+ /* Brand-match the agent chrome */
+ agent-3d {
+ --agent-accent: #2a2a4d;
+ --agent-chat-font: 'Inter', system-ui, sans-serif;
+ }
</style>
</head>
<body>
@@ -47187,93 +50273,97 @@ To bring this from theory to a real example, here is a complete, branded embed f
<a class="cta" href="/signup">Try Lumen free</a>
</main>
- <script
- src="https://three.ws/cdn/agent-3d.js"
- data-agent-id="YOUR_AGENT_ID"
- data-name="Lumi"
- data-size="medium"
- data-position="bottom-right"
- data-background-color="#1a1a2e0d"
- data-rotation-speed="0.4"
- data-greeting="Hi, I'm Lumi. Click me if you have a question about Lumen."
- ></script>
+ <script type="module" src="https://three.ws/agent-3d/1.5.2/agent-3d.js"></script>
+ <agent-3d
+ agent-id="YOUR_AGENT_ID"
+ mode="floating"
+ position="bottom-right"
+ offset="24px 24px"
+ width="300px"
+ height="400px"
+ background="light"
+ framing="portrait"
+ ></agent-3d>
</body>
</html>
```
-The agent here is named to fit the brand ("Lumi" — short, soft, matches "Lumen"). The position is the conventional bottom-right where SaaS visitors expect to find help. The size is `medium` — present but not dominating the hero. The background is a very pale indigo with `0d` alpha (about 5% opacity), which gives the widget a barely-perceptible tinted panel against the cream page; this reads as polished without being a literal coloured box. The rotation is slowed to `0.4` to match the calm brand voice. The greeting is one sentence that explains who Lumi is and invites action.
+The position is the conventional bottom-right where SaaS visitors expect to find help. The size is a restrained 300 × 400 — present but not dominating the hero — and responsive scaling (on by default) collapses it to a pill on phones. The `light` background gives the widget a pale, intentional panel against the cream page, with bubble contrast handled automatically. Portrait framing keeps the agent's face legible at this size, and the accent custom property ties the chat chrome to the brand indigo.
Compare this to a more playful brand. Imagine a children's learning app, "Sparrow", with bright colours and a cheerful tone:
```html
-<script
- src="https://three.ws/cdn/agent-3d.js"
- data-agent-id="YOUR_AGENT_ID"
- data-name="Pip"
- data-size="large"
- data-position="bottom-left"
- data-background-color="transparent"
- data-rotation-speed="1.6"
- data-greeting="Hi! I'm Pip. Wanna play a learning game?"
-></script>
+<agent-3d
+ agent-id="YOUR_AGENT_ID"
+ mode="floating"
+ position="bottom-left"
+ width="360px"
+ height="480px"
+ background="transparent"
+></agent-3d>
```
-Same attribute set, completely different feel. The point is that the four visual attributes — size, position, background, rotation — combine to express your brand without you writing a single line of CSS or JavaScript.
+Same attribute set, completely different feel — bigger, transparent so the avatar sits directly on the colourful page, full-body framing so the whole character shows. The point is that a handful of attributes — mode, position, size, background, framing — combine to express your brand without a build step.
---
-## Step 8 — Programmatic updates after load
+## Step 10 — Programmatic control after load
+
+A note for engineers: the `<agent-3d>` element exposes a JS API for driving the agent from your page's event flow. The full tour lives in [Drive the agent with the JavaScript API](/tutorials/js-api-events); here is the appearance-relevant slice.
-A note for engineers: the script element itself exposes a small JS API for cases where you need to interact with the agent after it has loaded. The customisation attributes above are read once, but you can still trigger animations and speech dynamically.
+Wait for the `agent:ready` event before calling methods — it fires once the body is loaded and the scene is live:
```html
-<script
- id="agent-script"
- src="https://three.ws/cdn/agent-3d.js"
- data-agent-id="YOUR_AGENT_ID"
-></script>
+<agent-3d id="agent" agent-id="YOUR_AGENT_ID" mode="floating"></agent-3d>
-<script>
- const agentScript = document.getElementById('agent-script');
+<script type="module">
+ const agent = document.getElementById('agent');
- agentScript.addEventListener('agent:ready', () => {
- // The agent is fully loaded and visible
- agentScript.playAnimationByHint('wave');
+ agent.addEventListener('agent:ready', () => {
+ agent.wave(); // quick hello gesture
});
- // Trigger speech from a button somewhere on the page
- document.querySelector('#help-button').addEventListener('click', () => {
- agentScript.speak('Sure, let me help you with that.');
+ // Play a named clip with polished defaults (loop flag + reduced-motion honoured)
+ document.querySelector('#celebrate-button').addEventListener('click', () => {
+ agent.playClip('celebrate', { userInitiated: true });
});
- // Play a specific named animation by exact match
- document.querySelector('#celebrate-button').addEventListener('click', () => {
- agentScript.playAnimation('jump_celebrate');
+ // Re-anchor and resize on the fly. Set `offset` before `position` —
+ // the position change is what triggers the layout pass that reads it.
+ document.querySelector('#move-button').addEventListener('click', () => {
+ agent.setAttribute('offset', '16px 16px');
+ agent.setPosition('top-left');
+ agent.setSize('280px', '380px');
});
</script>
```
-The methods on the script element are:
+The appearance-related methods on the element:
-- `playAnimation(name)` — plays an animation clip by exact name. The clip names depend on which avatar is paired; you can list them in the editor.
-- `playAnimationByHint(hint)` — fuzzy-matches a partial name. Useful when you don't know the exact clip but you know the intent: `'wave'`, `'talk'`, `'yes'`, `'no'`, `'point'`, `'idle'`.
-- `speak(text)` — makes the agent say the given text using its TTS voice.
+- `play(name)` — plays an animation clip by exact name from the shared clip library (or one baked into the GLB).
+- `playClip(name, { fade_ms, userInitiated })` — the polished version of `play`: honours the clip's loop flag (one-shots settle back into idle) and respects `prefers-reduced-motion` unless the call is user-initiated.
+- `playEmote(name)` — a named emote (`'cheer'`, `'flinch'`, `'celebrate'`) with a built-in fallback chain, so it always does *something* on any rig.
+- `wave()` — the hello gesture.
+- `lookAt(target)` — turn the head toward `'camera'`, `'center'`, or `'user'`.
+- `setMode(mode)`, `setPosition(pos, offset)`, `setSize(width, height)` — attribute setters with the same live effect as editing the HTML.
-These are independent of the appearance attributes. You can mix them freely — set size and position declaratively, then drive animations and speech from your page's event flow.
+These are independent of the declarative attributes. Set the look declaratively, then drive motion from your page's events.
---
## What you learned
-You now know the full set of visual customisation attributes the embed loader honours:
+You now know the full set of appearance attributes the `<agent-3d>` element honours:
-- `data-size` controls dimensions, with named presets and explicit pixel values
-- `data-position` controls anchor: four corners plus inline mode
-- `data-background-color` controls the canvas backdrop, transparent or any hex with optional alpha
-- `data-rotation-speed` controls the idle animation pace
-- `data-name` overrides the visible nameplate
-- `data-greeting` sets the first spoken message
-- The script element itself exposes `playAnimation`, `playAnimationByHint`, and `speak` for runtime control
+- `mode` picks the layout: `inline` (default), `floating`, `section`, `fullscreen`
+- `width` / `height` accept any CSS length; `responsive` (on by default) scales them per-device and collapses floating widgets to a pill on phones
+- `position` and `offset` anchor a floating widget to any corner or centre edge
+- `background` is `transparent` (default), `dark`, `light`, or any CSS colour
+- `framing="portrait"` crops to head-and-shoulders for small widgets
+- `name-plate="off"` hides the name overlay; `poster` covers the load with a still image
+- `clip` picks the ambient animation for decoration avatars
+- CSS custom properties (`--agent-accent` and friends) and `::part()` selectors theme the chrome
+- The element's JS API (`play`, `playClip`, `playEmote`, `wave`, `lookAt`, `setMode`, `setPosition`, `setSize`) drives everything at runtime
Most production embeds use four or five of these together. The combination is what makes an agent feel like part of the page rather than a widget glued on.
@@ -47282,20 +50372,22 @@ Most production embeds use four or five of these together. The combination is wh
## Next steps
- [Pick and swap an avatar in Studio](/tutorials/swap-avatar-in-studio) — change the agent's body without touching your snippet
-- [Add a greeting and first speech line](/tutorials/greeting-and-first-speech) — go deeper on the spoken introduction, autoplay, and accessibility
-- [Embed in 30 seconds](/tutorials/embed-in-30-seconds) — revisit the one-line embed if you skipped any setup
+- [Add a greeting and first speech line](/tutorials/greeting-and-first-speech) — give the agent its spoken introduction
+- [Embed in 30 seconds](/tutorials/embed-in-30-seconds) — revisit the two-tag embed if you skipped any setup
- [Share your agent](/tutorials/share-your-agent) — generate a public URL, QR code, and social previews
- [Embed on a website](/tutorials/embed-on-website) — the full embed reference including framework-specific guidance
- [Build your first agent](/tutorials/first-agent) — drop down a level into manifests and skills
---
-<a id="sec-215"></a>
+<a id="sec-217"></a>
> **Source:** `docs/tutorials/deploy-to-vercel-custom-domain.md` · [↑ table of contents](#table-of-contents)
# Deploy to Vercel with a Custom Domain
+> **Note — three.ws production no longer runs on Vercel.** On 2026-07-07 the hosted platform migrated to Google Cloud Run: one container ([server/index.mjs](https://github.com/nirholas/three.ws/blob/main/server/index.mjs)) serves the frontend and all API routes, deployed with `npm run deploy:gcp` (see [docs/build.md](/docs/build) and the ops runbook at `docs/ops/gcp-production.md`). This guide remains fully valid for **self-hosting your own fork on Vercel** — the repo's `vercel.json` still works there — but it does not describe how the production site is operated.
+
By the end of this tutorial you have a live three.ws fork running at a domain you own — `agent.yourcompany.com` or whatever you choose. CI is wired so every commit type-checks, every PR generates a preview, and merges to `main` ship to production. SSL is issued automatically. Rollbacks take one click.
This is the deployment-side companion to [self-host-agent-backend](/tutorials/self-host-agent-backend). That tutorial covered the architectural moving parts; this one walks the deploy and operate flow end-to-end without re-explaining what each component does.
@@ -47339,7 +50431,7 @@ When `vercel link` asks "Set up and deploy?", answer yes, accept the default pro
vercel
```
-Vercel installs deps, runs `npm run build`, and deploys a preview. After about three minutes you'll get a URL like `https://three-ws-yourname.vercel.app`. Hit `/api/healthz`. You should see `{"ok": true}` or similar — the platform is live, even if every other route 404s or 500s because env vars aren't set yet.
+Vercel installs deps, runs `npm run build`, and deploys a preview. After about three minutes you'll get a URL like `https://three-ws-yourname.vercel.app`. Hit `/api/healthz`. You should see `{"status":"ok", ...}` — the platform is live, even if every other route 404s or 500s because env vars aren't set yet.
That's the floor. From here every change is incremental.
@@ -47675,9 +50767,9 @@ A great CI step is exercising the preview URL after Vercel deploys it. Add to `.
run: |
set -e
curl -fsS "$PREVIEW_URL/api/healthz" | tee /tmp/health.json
- test "$(jq -r .ok /tmp/health.json)" = "true"
+ test "$(jq -r .status /tmp/health.json)" = "ok"
curl -fsS -I "$PREVIEW_URL/" | head -1 | grep -q "200"
- curl -fsS -I "$PREVIEW_URL/cdn/agent-3d.js" | head -1 | grep -q "200"
+ curl -fsS -I "$PREVIEW_URL/dist-lib/agent-3d.js" | head -1 | grep -q "200"
```
Three checks: the health endpoint responds, the home page returns 200, the CDN bundle exists. If any fail, the PR's CI goes red. Add more checks as you find behaviors worth gating on.
@@ -47738,7 +50830,7 @@ Before you call it done:
- DNS resolves and SSL works for your custom domain
- `/api/healthz` returns 200
- A test agent can be created in the dashboard, edited, and embedded on a third-party page
-- The CDN bundle at `https://agent.yourcompany.com/cdn/agent-3d.js` serves correctly with `Cache-Control` and a hashed/versioned filename in the source map
+- The embed bundle at `https://agent.yourcompany.com/dist-lib/agent-3d.js` serves correctly with a `Cache-Control` header
- GitHub → Vercel integration is live; pushing to `main` triggers a production deploy and pushing a branch triggers a preview
- CI passes on a recent PR and the preview URL is reachable
- Sentry receives a deliberately thrown error from a preview deploy (test once, then remove the test)
@@ -47805,18 +50897,18 @@ In rough order of likelihood:
---
-<a id="sec-216"></a>
+<a id="sec-218"></a>
> **Source:** `docs/tutorials/embed-in-30-seconds.md` · [↑ table of contents](#table-of-contents)
# Embed in 30 seconds
-The fastest way to put a living 3D agent on a website is one line of HTML. Paste a single `<script>` tag, save the file, refresh the browser — there's a 3D character animating in the corner of your page, ready to greet visitors. No build step, no npm install, no framework adapter, no API plumbing.
+The fastest way to put a living 3D agent on a website is two lines of HTML. Paste a `<script>` tag that loads the runtime and an `<agent-3d>` tag that places the agent, save the file, refresh the browser — there's a 3D character animating in the corner of your page, ready to greet visitors. No build step, no npm install, no framework adapter, no API plumbing.
-This tutorial walks through that one-liner end to end. By the time you finish, you will have an agent live on a real page, you will know exactly which line to copy, and you will know how to debug it when something gets in the way.
+This tutorial walks through those two lines end to end. By the time you finish, you will have an agent live on a real page, you will know exactly which lines to copy, and you will know how to debug it when something gets in the way.
**What you'll build:**
-- A live 3D agent embedded on an HTML page with one script tag
+- A live 3D agent embedded on an HTML page with two tags
- A working agent ID from the three.ws editor
- A floating widget that animates, greets, and chats out of the box
- A clear mental model of what the embed loader actually does
@@ -47827,7 +50919,7 @@ This tutorial walks through that one-liner end to end. By the time you finish, y
## Step 1 — Get an agent ID
-Every embedded agent on three.ws has a permanent ID. The script tag uses that ID to fetch the agent's body, personality, skills, and animations from the platform. Without one, there is nothing to embed.
+Every embedded agent on three.ws has a permanent ID. The `<agent-3d>` tag uses that ID to fetch the agent's body, personality, skills, and animations from the platform. Without one, there is nothing to embed.
Open [https://three.ws/create](https://three.ws/create) in a new tab. The editor loads with a default avatar in the centre of the canvas. You have two paths from here.
@@ -47839,7 +50931,7 @@ If you want to ship something working as fast as possible, skip every panel for
https://three.ws/agent/0xabc123…def
```
-The string after `/agent/` is your agent ID. Copy it. You will paste it into the script tag in the next step.
+The string after `/agent/` is your agent ID. Copy it. You will paste it into the `<agent-3d>` tag in the next step.
### Path B — Customise first, then save
@@ -47885,10 +50977,8 @@ Open your editor, create a new file called `index.html` anywhere on your compute
Try clicking it. Try saying hi. It works the same in every browser.
</p>
- <script
- src="https://three.ws/cdn/agent-3d.js"
- data-agent-id="YOUR_AGENT_ID"
- ></script>
+ <script type="module" src="https://three.ws/agent-3d/latest/agent-3d.js"></script>
+ <agent-3d agent-id="YOUR_AGENT_ID" mode="floating"></agent-3d>
</body>
</html>
```
@@ -47899,61 +50989,59 @@ Save the file. Double-click it to open in your browser, or drag it into a browse
You should see a 3D character appear in the bottom-right corner of the page within a couple of seconds. It will start an idle animation. Click on it and a chat panel slides open. Type a question, press Enter, and the agent replies — with voice and animation.
-That's the whole feature. One script tag, one agent ID, one working 3D agent.
+That's the whole feature. One script tag, one `<agent-3d>` tag, one working 3D agent.
---
-## Step 3 — Understand what the script tag does
+## Step 3 — Understand what the two tags do
It is worth taking a minute to understand what just happened, because once you know, every other embed customisation is obvious.
-When the browser hits this line:
+When the browser hits these lines:
```html
-<script
- src="https://three.ws/cdn/agent-3d.js"
- data-agent-id="YOUR_AGENT_ID"
-></script>
+<script type="module" src="https://three.ws/agent-3d/latest/agent-3d.js"></script>
+<agent-3d agent-id="YOUR_AGENT_ID" mode="floating"></agent-3d>
```
…the following happens in order:
1. The browser fetches `agent-3d.js` from the three.ws CDN. The file is a single self-contained bundle: it brings its own copy of Three.js, the glTF loader, the chat UI, the speech subsystem — everything. There are no other network dependencies at this stage.
-2. The script reads its own `data-agent-id` attribute (and any other `data-*` attributes you've set — more on that in the customisation tutorial).
+2. The script registers `<agent-3d>` as a custom element. Every `<agent-3d>` tag on the page — including the one you just pasted — comes alive and reads its own attributes (`agent-id`, `mode`, and the others covered in the customisation tutorial).
-3. It calls the three.ws API to fetch the agent's manifest: name, body URL, personality, skills, default greeting, and the list of animation clips baked into the GLB.
+3. The element calls the three.ws API to fetch the agent's manifest: name, body URL, personality, skills, default greeting, and the list of animation clips baked into the GLB.
-4. It injects a container element into the page (by default, fixed to the bottom-right corner) and renders the 3D scene inside it.
+4. In `mode="floating"`, the element pins itself to the bottom-right corner of the page and renders the 3D scene inside it.
-5. Once the avatar is loaded, the script dispatches a `agent:ready` event you can listen to. The agent then begins its idle animation and waits for interaction.
+5. Once the avatar is loaded, the element dispatches a `agent:ready` event you can listen to. The agent then begins its idle animation and waits for interaction.
Notice what is *not* on this list:
- No iframe. The agent renders directly in your page's DOM, which means it inherits your site's CSS scope intentionally (we'll cover styling shadows in the customisation tutorial).
- No second script tag. You don't need to load Three.js separately. You don't need to bundle anything.
- No build step. The script is plain JavaScript, served minified from a CDN edge.
-The whole thing is by design: one tag, no setup, real 3D in any HTML page.
+The whole thing is by design: two tags, no setup, real 3D in any HTML page.
---
## Step 4 — Where to paste it on a real site
-The example file above puts the script tag right above `</body>`. That is the recommended placement for any page you embed on. Two reasons:
+The example file above puts both tags right above `</body>`. That is the recommended placement for any page you embed on. Two reasons:
-**Performance.** The script is not blocking your page's HTML or critical CSS. Visitors see your headline and copy first, then the agent finishes loading and slides in.
+**Performance.** The script is a module, so it never blocks your page's HTML or critical CSS. Visitors see your headline and copy first, then the agent finishes loading and slides in.
**DOM availability.** When the script runs, every element your page might want to react to is already in the DOM. If you decide later to attach event listeners or call the JS API, you don't have to wrap them in `DOMContentLoaded`.
If your site is built on a framework or CMS, the right place depends on the template system:
-- **WordPress** — Use a "Custom HTML" widget in the footer, or paste it via a footer scripts plugin like Insert Headers and Footers. Avoid the `<head>` section.
-- **Shopify** — Edit `theme.liquid` and paste the tag right before `</body>`.
-- **Webflow / Squarespace / Wix** — Each one has a "Custom code / Footer code injection" field in site settings. That is where the tag belongs.
-- **Next.js / React** — Use the framework's script component (`next/script` with `strategy="afterInteractive"`, or a plain `useEffect` injection on the page). Do not import the script as an ES module; it's a side-effect bundle that registers itself globally.
-- **Static site generator (Astro, Eleventy, Hugo, Jekyll)** — Paste the raw tag into your base layout template above `</body>`.
+- **WordPress** — Use a "Custom HTML" widget in the footer, or paste both tags via a footer scripts plugin like Insert Headers and Footers. Avoid the `<head>` section.
+- **Shopify** — Edit `theme.liquid` and paste both tags right before `</body>`.
+- **Webflow / Squarespace / Wix** — Each one has a "Custom code / Footer code injection" field in site settings. That is where the tags belong.
+- **Next.js / React** — Load the bundle with the framework's script component (`next/script` with `strategy="afterInteractive"`, or a plain `useEffect` injection on the page), then render `<agent-3d agent-id="…" mode="floating"></agent-3d>` in your JSX. The script's only side effect is registering the custom element; it renders nothing on its own.
+- **Static site generator (Astro, Eleventy, Hugo, Jekyll)** — Paste the raw tags into your base layout template above `</body>`.
-The script never re-renders the rest of your DOM. It only appends a single container element. This means there's no risk of it conflicting with your existing layout.
+The script never touches the rest of your DOM. The `<agent-3d>` element you placed is the only thing rendered, and in floating mode it pins itself to a corner. This means there's no risk of it conflicting with your existing layout.
---
@@ -47994,8 +51082,8 @@ A short guide to the things that usually go wrong, in roughly the order of how o
Open the console first. The fix is almost always one of these three:
-- **Wrong agent ID.** The most common cause. Copy it again from the URL in [https://three.ws/my-agents](https://three.ws/my-agents) — that's the page that lists every agent you've saved. Paste it into the `data-agent-id` attribute and reload.
-- **The script tag is malformed.** Check that you copied the full src URL (`https://three.ws/cdn/agent-3d.js`), that there are no stray characters between attributes, and that the tag is closed.
+- **Wrong agent ID.** The most common cause. Copy it again from the URL in [https://three.ws/my-agents](https://three.ws/my-agents) — that's the page that lists every agent you've saved. Paste it into the `agent-id` attribute and reload.
+- **One of the tags is malformed.** Check that you copied the full src URL (`https://three.ws/agent-3d/latest/agent-3d.js`), that the script tag has `type="module"`, and that the `<agent-3d>` tag is closed with `</agent-3d>` — custom elements are not self-closing.
- **The page is being served as plain `file://` and something is blocked.** This is uncommon — most browsers allow the embed to work from a local file — but if you hit it, run a quick local server: `python3 -m http.server 8080` and open `http://localhost:8080` instead.
### "The page says the script is blocked"
@@ -48025,15 +51113,20 @@ A few legitimate reasons:
### "I want it not to appear on certain pages"
-The simplest answer: just don't include the script tag on those pages. If your CMS only lets you set one site-wide footer block, gate the tag with a tiny conditional based on `location.pathname`:
+The simplest answer: just don't include the tags on those pages. If your CMS only lets you set one site-wide footer block, gate them with a tiny conditional based on `location.pathname`:
```html
<script>
if (!location.pathname.startsWith('/admin')) {
var s = document.createElement('script');
- s.src = 'https://three.ws/cdn/agent-3d.js';
- s.setAttribute('data-agent-id', 'YOUR_AGENT_ID');
+ s.type = 'module';
+ s.src = 'https://three.ws/agent-3d/latest/agent-3d.js';
document.body.appendChild(s);
+
+ var el = document.createElement('agent-3d');
+ el.setAttribute('agent-id', 'YOUR_AGENT_ID');
+ el.setAttribute('mode', 'floating');
+ document.body.appendChild(el);
}
</script>
```
@@ -48058,9 +51151,9 @@ If they comment that the agent is in the wrong corner, or feels too big, or dist
You now know:
- How to get an agent ID from the editor at [https://three.ws/create](https://three.ws/create)
-- The one script tag that powers every three.ws embed
-- Where to paste it on different site stacks
-- What the embed loader actually does behind the scenes
+- The two tags that power every three.ws embed — the runtime script and the `<agent-3d>` element
+- Where to paste them on different site stacks
+- What the embed runtime actually does behind the scenes
- The fastest path to diagnose the three most common failure modes
A working embedded agent is the foundation everything else builds on. From here, every other tutorial in this tier is about turning that working embed into something that matches your brand, your voice, and your visitors.
@@ -48078,7 +51171,7 @@ A working embedded agent is the foundation everything else builds on. From here,
---
-<a id="sec-217"></a>
+<a id="sec-219"></a>
> **Source:** `docs/tutorials/embed-on-website.md` · [↑ table of contents](#table-of-contents)
@@ -48580,7 +51673,7 @@ Squarespace's developer preview and published output can differ. Try adding the
---
-<a id="sec-218"></a>
+<a id="sec-220"></a>
> **Source:** `docs/tutorials/emotion-from-data.md` · [↑ table of contents](#table-of-contents)
@@ -48632,7 +51725,7 @@ The platform runs a public, unauthenticated sentiment scorer over live pump.fun
<head>
<meta charset="UTF-8">
<title>Sentiment-driven agent</title>
- <script type="module" src="https://three.ws/cdn/agent-3d.js"></script>
+ <script type="module" src="https://three.ws/agent-3d/latest/agent-3d.js"></script>
</head>
<body>
<agent-3d id="agent" agent-id="YOUR_AGENT_ID" mode="inline" width="360px" height="480px"></agent-3d>
@@ -48808,7 +51901,7 @@ function reactIfConfident(clipOrEmoteName, { confident, useExactClip = false } =
---
-<a id="sec-219"></a>
+<a id="sec-221"></a>
> **Source:** `docs/tutorials/first-agent.md` · [↑ table of contents](#table-of-contents)
@@ -49325,7 +52418,7 @@ Now that you have a working agent, here's what to explore next:
---
-<a id="sec-220"></a>
+<a id="sec-222"></a>
> **Source:** `docs/tutorials/generate-3d-api.md` · [↑ table of contents](#table-of-contents)
@@ -49534,7 +52627,7 @@ If you've never made an x402 call, start with [Build a paid x402 endpoint](/tuto
---
-<a id="sec-221"></a>
+<a id="sec-223"></a>
> **Source:** `docs/tutorials/getting-started.md` · [↑ table of contents](#table-of-contents)
@@ -49705,7 +52798,7 @@ Everything is editable forever — swap the body, rewrite the prompt, add capabi
---
-<a id="sec-222"></a>
+<a id="sec-224"></a>
> **Source:** `docs/tutorials/greeting-and-first-speech.md` · [↑ table of contents](#table-of-contents)
@@ -49713,264 +52806,258 @@ Everything is editable forever — swap the body, rewrite the prompt, add capabi
A silent agent on a page is half an agent. The avatar appears, animates, looks ready — but a visitor lands, glances at it, and isn't sure whether to engage. They look for a chat input. They wonder if the thing is for them.
-A spoken greeting fixes all of that in one sentence. The agent says hi the moment it's ready. Visitors hear who it is and what it's for. They know it's interactive. They know it's responsive. They speak back.
+A greeting fixes all of that in one sentence. The agent introduces itself the moment it's ready. Visitors see who it is and what it's for. They know it's interactive. They know it's responsive. They speak back.
-This tutorial covers the `data-greeting` attribute end to end: how to write a good greeting, when it fires, how the browser's autoplay rules affect it, and how to make it accessible to visitors who have audio off or have a disability that requires text alternatives.
+This tutorial covers the greeting flow end to end: waiting for the `agent:ready` event, triggering the first line with `say()`, shaping what the agent says through its instructions, how the browser's audio autoplay rules affect the spoken part, and how to make the greeting accessible to visitors who have audio off.
**What you'll build:**
-- An agent that greets every visitor by voice the moment it's ready
-- A greeting that works on Chrome, Safari, Firefox, mobile browsers — every common surface
-- A subtitle / caption so the greeting is readable, not just audible
-- A reusable pattern for scripted greetings versus LLM-generated dynamic ones
+- An agent that greets every visitor the moment it's ready
+- A greeting personality that lives in the agent's instructions, so every greeting fits the brand
+- A live transcript region so the greeting is readable, not just audible
+- A reusable pattern for text-first greetings versus guaranteed-audible ones
- A clear understanding of browser autoplay rules and how to work with them
**Prerequisites:** A page with the embed working from [Embed in 30 seconds](/tutorials/embed-in-30-seconds). Your agent should already be saved with a brain configured.
---
-## Step 1 — The one-attribute version
+## Step 1 — The minimal greeting
-The minimum-effort greeting is one attribute on the embed script tag:
+There is no magic greeting attribute — the greeting is three lines of JavaScript next to your embed. Wait for the element's `agent:ready` event, then hand the agent an opening cue with `say()`:
```html
-<script
- src="https://three.ws/cdn/agent-3d.js"
- data-agent-id="YOUR_AGENT_ID"
- data-greeting="Hi, I'm Iris. Click me if you have a question."
-></script>
+<script type="module" src="https://three.ws/agent-3d/1.5.2/agent-3d.js"></script>
+<agent-3d id="agent" agent-id="YOUR_AGENT_ID" mode="floating" voice eager></agent-3d>
+
+<script>
+ const agent = document.getElementById('agent');
+ agent.addEventListener('agent:ready', () => {
+ agent.say('Hi! Who are you?');
+ });
+</script>
```
-When the agent is fully loaded (animations bound, scene ready, voice initialised), it speaks the greeting using its configured TTS voice. A speech bubble shows the same text on screen, fading out a few seconds after the line finishes.
+`say(text)` sends the text to the agent's brain as a visitor message. The agent thinks, generates a reply in its own voice — the greeting — and delivers it: the reply streams into the speech bubble above the avatar, lands in the chat thread, drives the talking animation and lip-sync, and (because the element carries the `voice` attribute) is spoken aloud with the agent's TTS voice.
-This works. Most embed installations should ship with a greeting attribute. The rest of this tutorial is about doing it well rather than doing it at all.
+Two things worth knowing about this snippet:
----
+- The cue you pass to `say()` appears in the chat thread as the visitor's message, exactly as if they had typed it. That's why the example uses a natural opener like "Hi! Who are you?" — it reads as the start of a conversation, not as plumbing. (It's the same cue the embed's built-in "Say hi" suggestion chip sends.)
+- The boolean `voice` attribute is what makes JS-triggered `say()` calls audible. Without it, the greeting still renders as text and animation — just silently. Messages the visitor types into the chat input are always voiced.
-## Step 2 — When the greeting fires
+That's a working greeting. The rest of this tutorial is about doing it well rather than doing it at all.
-The embed dispatches a `agent:ready` event on the script element once the avatar is loaded, the camera is positioned, the lighting is set, and the voice subsystem is initialised. The greeting fires on that event automatically when the `data-greeting` attribute is set.
+---
-In rough terms, the timing on a typical broadband connection is:
+## Step 2 — When the greeting fires
-1. **0 ms** — Page HTML is parsed; the script tag is encountered.
-2. **0–500 ms** — `agent-3d.js` is fetched from the CDN and starts running.
-3. **500–1500 ms** — The agent's manifest is fetched from the platform API.
-4. **1500–3500 ms** — The GLB body is downloaded and parsed.
-5. **3500–4000 ms** — The avatar appears, the scene renders, the `agent:ready` event fires.
-6. **4000–4500 ms** — The greeting starts speaking. The speech bubble appears.
+`agent:ready` fires once the whole boot pipeline has finished: manifest fetched, GLB body downloaded and rigged, memory loaded, skills installed, brain runtime constructed. Its `detail` carries `{ agent, manifest }`, and the event bubbles and crosses the shadow boundary, so you can also listen at `document` level if you attach the listener before the element boots.
-On a fast connection with the bundle cached, this collapses to about two seconds total. On a slow mobile connection, it can stretch to six or seven seconds; the agent fades in gracefully and the greeting fires when ready, so visitors never see a half-loaded character.
+Two timing behaviours matter for greetings:
-If you want to control the timing precisely — say, wait for an extra moment before greeting so the visitor has a chance to focus — you can use the JS API and skip `data-greeting`:
+**The element boots lazily.** By default `<agent-3d>` waits until it is scrolled near the viewport (with a 300px head start) before it downloads anything, which means `agent:ready` — and your greeting — fires when the visitor reaches the agent, not necessarily at page load. For a floating widget that should greet immediately, add the `eager` attribute as in Step 1. For an inline agent halfway down a landing page, lazy is usually what you want: the agent greets when the visitor scrolls to it.
-```html
-<script
- id="agent-script"
- src="https://three.ws/cdn/agent-3d.js"
- data-agent-id="YOUR_AGENT_ID"
-></script>
+**`say()` waits for readiness on its own.** If you call `say()` before boot finishes, the element holds the message and delivers it once the runtime is up (only the most recent pending message is kept). Listening for `agent:ready` is still the clearest structure — it makes the ordering explicit and gives you a place to hang other on-ready work — but a greeting fired "too early" is not lost.
-<script>
- const agent = document.getElementById('agent-script');
+If you want a beat of breathing room so the visitor has a chance to notice the avatar before it talks:
- agent.addEventListener('agent:ready', async () => {
- // Wait two seconds after the agent is visible before speaking
- await new Promise(r => setTimeout(r, 2000));
- agent.speak('Hi, I\'m Iris. Take your time looking around.');
- });
-</script>
+```js
+agent.addEventListener('agent:ready', () => {
+ setTimeout(() => agent.say('Hi! Who are you?'), 1500);
+});
```
-Both approaches produce the same audible result. Use the attribute for simple cases; use the JS API when you need timing control or want the greeting to depend on something else on the page.
+You can also watch boot progress via the `agent:load-progress` event, whose detail is `{ phase, pct }` with phases `manifest`, `body`, `memory`, `skills`, and `brain` — useful if you're rendering your own loading indicator around the embed.
---
-## Step 3 — What voice the agent uses
-
-The voice is set in the agent's configuration at [https://three.ws/create](https://three.ws/create), not on the embed snippet. Open the editor, open your agent, open the **Voice** panel.
+## Step 3 — Where the greeting's personality lives
-You have a few options:
+`say()` supplies the cue; the *content* of the greeting comes from the agent's configured personality. There are two places that personality can live, depending on how you embedded.
-- **Platform voices** — A selection of pre-tuned voices in different languages, accents, and timbres. These work everywhere and need no extra configuration. They are produced by a high-quality cloud TTS engine.
-- **Browser voice (fallback)** — Uses the browser's built-in `SpeechSynthesis` API. Available everywhere with no cost, but quality varies — Chrome on macOS sounds quite good, while Chrome on a fresh Ubuntu machine can sound mechanical. Use this for projects where you can't pay for cloud TTS but you want speech to "just work".
-- **ElevenLabs voice** — If your agent is configured with an ElevenLabs voice ID, the platform calls ElevenLabs for TTS. This is the highest quality option, and it's the only way to use a voice clone of your own voice. There is a per-character cost. Best for hero embeds where voice quality is part of the experience.
+### Published agents (`agent-id`)
-Whichever voice you pick at the brain level, the greeting uses it. You don't configure voice per greeting — one agent has one voice.
+If you embed with `agent-id`, the personality is whatever you saved in the editor at [https://three.ws/create](https://three.ws/create) — open your agent's **Personality** panel and shape the system prompt there. To make greetings consistently on-brand, add explicit greeting guidance to the prompt:
-If you want different voices for different embeds, the cleanest pattern is to maintain two agents (with the same personality, different voice configs) and embed each on the relevant pages. See [Pick and swap an avatar in Studio](/tutorials/swap-avatar-in-studio) for the broader principle of cloning agents.
+```
+When a visitor greets you or asks who you are, introduce yourself in one or
+two sentences. Mention your name. Say you can help pick the right Lumen plan.
+Invite them to ask anything. Never open with more than two sentences.
+```
----
+Save, reload your page, and the same `say('Hi! Who are you?')` cue now produces a greeting that follows your rules — every visitor, phrased freshly each time.
-## Step 4 — Browser autoplay restrictions
+The agent's TTS voice is also part of its saved configuration (the **Voice** panel in the editor), not the embed snippet. One agent, one voice; the greeting uses it like every other line.
-Here is the most important practical point in this tutorial. Modern browsers do not let websites play audio automatically. The reasons are good: spammy auto-playing video ads, suddenly loud pages that ambush users, accidental playback when a tab loads in the background. But the rules apply to your agent's greeting too.
+### Self-configured embeds (`body` + `brain` + `instructions`)
-The exact policy varies by browser and platform, but the rough rules are:
+If you embed a bare GLB instead of a published agent, the element builds the personality from its own attributes. `instructions` is the system prompt, `brain` picks the model (`"free"` resolves to the platform's host-paid free model), and `chat` opts the avatar into the conversational chrome:
-- **Chrome / Edge desktop** — Audio may play automatically if the user has interacted with your domain before (a click, a keypress, a scroll counts in some cases). On first visit, audio is blocked until the user interacts.
-- **Safari desktop** — Stricter. Audio is blocked until the user interacts, every visit.
-- **Firefox desktop** — Permissive by default, but users can tighten the policy and many do.
-- **iOS Safari** — Strictest. Audio is blocked until the user taps the page. No exceptions.
-- **Android Chrome** — Similar to desktop Chrome. Mostly works after first interaction, sometimes works on first load.
+```html
+<script type="module" src="https://three.ws/agent-3d/1.5.2/agent-3d.js"></script>
+<agent-3d
+ id="agent"
+ body="https://three.ws/avatars/default.glb"
+ name="Iris"
+ brain="free"
+ instructions="You are Iris, the guide for the Lumen productivity app. When a visitor greets you, introduce yourself in one warm sentence and invite them to ask about Lumen. Keep every reply under three sentences."
+ chat
+ voice
+ eager
+></agent-3d>
-The embed handles this for you, but it's important to understand what "handles" means:
+<script>
+ const agent = document.getElementById('agent');
+ agent.addEventListener('agent:ready', () => {
+ agent.say('Hi! Who are you?');
+ });
+</script>
+```
-### What the embed does automatically
+This is a complete, self-contained page — no saved agent required. The `instructions` attribute is only read for these self-configured embeds; on an `agent-id` embed the published personality wins, so edit it in the editor instead.
-When the greeting fires:
+---
-1. The embed attempts to play the audio.
-2. If the browser allows it, the audio plays normally and the speech bubble shows the spoken text.
-3. If the browser blocks it, the embed silently catches the rejection, *still shows the speech bubble* with the greeting text, and *queues* the audio to play the moment the user interacts with the page (any click, tap, key press, or scroll).
+## Step 4 — Tailor the greeting to the visitor
-So in the blocked case, the visitor sees a speech bubble that says "Hi, I'm Iris. Click me if you have a question." even if no sound played. When they tap anywhere — including tapping the agent to start a chat — the buffered greeting plays at that moment.
+Because the cue is ordinary JavaScript, it can carry whatever context you know at page-load time — and the brain will weave it into the greeting:
-This is the right default. The greeting is still effective on the worst-case browsers (because the text is visible), and the visitor isn't surprised by audio on a fresh page load.
+```html
+<script type="module" src="https://three.ws/agent-3d/1.5.2/agent-3d.js"></script>
+<agent-3d id="agent" agent-id="YOUR_AGENT_ID" mode="floating" voice eager></agent-3d>
-### What you can do to improve the rate of autoplay success
+<script>
+ const agent = document.getElementById('agent');
-A few practical tricks that bump the autoplay-success rate without working around the rules:
+ function greetingCue() {
+ const params = new URLSearchParams(location.search);
+ const returning = localStorage.getItem('hasVisited') === 'yes';
+ if (returning) {
+ return "Hi again — I've visited before. Anything new since last time?";
+ }
+ if (params.get('utm_campaign') === 'launch-2026') {
+ return "Hi! I came from the launch announcement. What's new?";
+ }
+ return 'Hi! Who are you?';
+ }
-- **Encourage a small interaction before the greeting fires.** If your page has a "Skip intro" button or a "Welcome" splash, audio is unlocked the moment it's dismissed. Then the greeting plays normally.
-- **Set the audio output level appropriately.** A quieter greeting (configured at the brain level) feels less ambushing if it does play automatically, which makes users less likely to mute the tab.
-- **Don't compete with other audio.** If your page has a background video that autoplays muted, that's fine. If it has a hero video with sound, the greeting will sound chaotic — turn the hero off.
+ agent.addEventListener('agent:ready', () => {
+ agent.say(greetingCue());
+ localStorage.setItem('hasVisited', 'yes');
+ });
+</script>
+```
-### What you should not do
+The pattern is: listen for `agent:ready`, choose a cue in JS, call `say()`. The visitor always gets a greeting, and the greeting reflects what you know about them — the brain handles the phrasing.
-A few patterns to avoid, even though you'll see them on other sites:
+If your page logic needs the greeting text back (say, to mirror it into your own UI), use `ask()` instead — it sends the same way but resolves with the reply:
-- Don't fake the autoplay by attaching invisible click handlers that "auto-click" on page load. Browsers detect these and the page gets penalised in autoplay quotas.
-- Don't fall back to a louder beep or notification sound if the greeting fails. The user is in control; respect it.
-- Don't write a "click to enable audio" gate as the first thing on the page. The agent's speech bubble already serves this purpose more naturally.
+```js
+agent.addEventListener('agent:ready', async () => {
+ const greeting = await agent.ask('Hi! Who are you?');
+ console.log('Agent greeted with:', greeting);
+});
+```
---
-## Step 5 — Make the greeting accessible
-
-A spoken greeting is wonderful for the majority of visitors. But some visitors:
+## Step 5 — `speak()` is a gesture, not speech
-- Have audio off, by choice or by default
-- Are using a screen reader and don't want speech bubbles popping in
-- Have a hearing impairment
-- Are deaf
-- Are in a quiet environment (a library, a meeting, a sleeping baby's room) and won't enable audio
+The element also has a `speak(text)` method, and it's important to be precise about what it does: **`speak()` plays the talking animation, and nothing else.** It sizes the gesture to the length of the text you pass, trying the rig's talk clip and falling back to a nod or a wave — but it does not contact the brain, does not render a speech bubble, and does not produce any audio.
-The embed handles this automatically — the speech bubble shows the greeting text, so visitors who can't hear it can still read it. But you should write your greeting with the assumption that someone might read it before they hear it.
-
-This means:
-
-- Make the greeting useful as text. "Hi, I'm Iris. Click me if you have a question." reads as well as it sounds. "Hi!" alone reads as a stub.
-- Avoid relying on pronunciation. "He's pronounced like the letter J in Japanese" works in audio but is weird in writing.
-- Avoid pause cues that don't translate. "Hi. (pause) I'm Iris" works in audio but looks broken as text.
-
-For visitors using a screen reader, the speech bubble is rendered with appropriate ARIA roles. Screen readers announce it as "the agent says: <greeting text>" rather than just blasting the text without context. You don't need to do anything to enable this; the embed handles it.
-
-If you want a heavier-handed accessibility setup — for instance, a permanent transcript pane next to the agent — you can listen to the speech events from JS:
+That makes it the wrong tool for a greeting on its own, and the right tool when your page supplies the words and you just want the avatar to visibly "deliver" them — a custom caption, a scripted onboarding line you render yourself:
```html
-<div id="transcript" aria-live="polite" style="margin-top: 12px; color:#666; font-size: 0.9rem;">
- <strong>Agent says:</strong> <span id="transcript-text">…</span>
+<agent-3d id="agent" agent-id="YOUR_AGENT_ID" mode="floating" eager></agent-3d>
+<div id="caption" role="status" aria-live="polite"
+ style="position: fixed; bottom: 460px; right: 24px; max-width: 280px;
+ padding: 10px 14px; border-radius: 12px; background: #fff;
+ color: #1a1a2e; box-shadow: 0 4px 24px rgba(0,0,0,.2); font: 14px system-ui;">
</div>
-<script
- id="agent-script"
- src="https://three.ws/cdn/agent-3d.js"
- data-agent-id="YOUR_AGENT_ID"
- data-greeting="Welcome. I'm here to help you find the right product."
-></script>
-
<script>
- const agent = document.getElementById('agent-script');
- const out = document.getElementById('transcript-text');
+ const agent = document.getElementById('agent');
+ const caption = document.getElementById('caption');
- agent.addEventListener('speak', (event) => {
- out.textContent = event.detail.text;
+ agent.addEventListener('agent:ready', () => {
+ const line = "Hi, I'm Iris. Click me if you have a question.";
+ caption.textContent = line; // your page shows the exact words
+ agent.speak(line); // the avatar mouths along, silently
+ setTimeout(() => { caption.textContent = ''; }, 6000);
});
</script>
```
-The `speak` event fires every time the agent says anything — greeting included — with the text in `event.detail.text`. Pipe it into an `aria-live="polite"` region and screen readers announce it. Sighted visitors with audio off see the transcript in real time.
+The trade-off is exactness versus life: `speak()` plus your own caption gives you a fixed, word-for-word scripted line with zero LLM involvement; `say()` gives you a living greeting in the agent's voice — bubble, audio, and all — but freshly phrased each time. If you need the audible line to be word-for-word, put the exact sentence in the instructions ("When a visitor greets you, reply with exactly: …") and use `say()`; the model will deliver it near-verbatim, and it stays in the real speech pipeline.
---
-## Step 6 — Scripted greetings versus dynamic ones
+## Step 6 — Browser autoplay rules
-`data-greeting` is a static string. Whatever you put in the attribute is exactly what the agent says, every visitor, every page load. This is right for most embeds — the greeting should feel reliable.
+Here is the most important practical point in this tutorial. Modern browsers do not let websites play audio before the visitor has interacted with the page. The reasons are good — spammy auto-playing ads, suddenly loud tabs — but the rules apply to your agent's spoken greeting too. Chrome and Edge may allow audio if the visitor has engaged with your domain before; Safari and iOS block it on every fresh load until the first tap or keypress.
-But there are cases where you want the greeting to adapt to the visitor:
+The saving grace: **the greeting's text always lands.** The reply streams into the speech bubble and the chat thread whether or not the audio was allowed to play, so a greeting fired on `agent:ready` is never wasted — worst case it's read instead of heard.
-- A returning visitor should be greeted differently from a first-time visitor
-- A visitor coming from a particular ad campaign should hear a relevant greeting
-- A visitor whose preferred language is detectable should hear the greeting in that language
+That gives you two clean patterns. Pick one; don't chain them (the runtime processes one conversational turn at a time, so a second `say()` fired while the greeting is still streaming will surface a "still thinking" notice instead).
-For dynamic greetings, skip `data-greeting` and use the JS API:
+**Pattern A — text-first (the default).** Greet on `agent:ready` as in Step 1. On permissive browsers the greeting is spoken; on strict ones it's read. Ship this unless spoken audio is essential to the experience.
-```html
-<script
- id="agent-script"
- src="https://three.ws/cdn/agent-3d.js"
- data-agent-id="YOUR_AGENT_ID"
-></script>
+**Pattern B — guaranteed-audible.** Hold the greeting until the visitor's first interaction, which unlocks audio everywhere:
-<script>
- const agent = document.getElementById('agent-script');
+```js
+const agent = document.getElementById('agent');
- function pickGreeting() {
- const params = new URLSearchParams(location.search);
- const utm = params.get('utm_campaign');
- const returning = localStorage.getItem('hasVisited') === 'yes';
- const hour = new Date().getHours();
- const timeOfDay = hour < 12 ? 'morning' : hour < 18 ? 'afternoon' : 'evening';
+const greetOnFirstTouch = () => {
+ document.removeEventListener('pointerdown', greetOnFirstTouch);
+ document.removeEventListener('keydown', greetOnFirstTouch);
+ agent.say('Hi! Who are you?', { voice: true });
+};
+document.addEventListener('pointerdown', greetOnFirstTouch);
+document.addEventListener('keydown', greetOnFirstTouch);
+```
- if (returning) {
- return 'Welcome back. Anything you wanted to ask last time?';
- }
- if (utm === 'launch-2026') {
- return 'Hi there. You\'re here from the launch announcement — let me show you what\'s new.';
- }
- return `Good ${timeOfDay}. I\'m Iris. Click me to ask anything about our service.`;
- }
+The `{ voice: true }` option forces the spoken reply even without the `voice` attribute on the element.
- agent.addEventListener('agent:ready', () => {
- agent.speak(pickGreeting());
- localStorage.setItem('hasVisited', 'yes');
- });
-</script>
-```
+And a few patterns to avoid, even though you'll see them on other sites: don't simulate clicks to trick the autoplay gate (browsers detect it and penalise the page), and don't put a full-page "click to enable audio" wall in front of your content — the visitor's first natural interaction is enough.
-The pattern is: skip the attribute, listen for `agent:ready`, choose a greeting in JS, call `speak()`. The visitor always gets a greeting, and the greeting is tailored to what you know about them at page-load time.
+---
-### Going further: LLM-generated greetings
+## Step 7 — Make the greeting accessible
-You can also have the agent generate its own greeting using its configured brain. This is heavier — it requires a round-trip to the LLM before the agent speaks — but it's powerful when the greeting really should be personalised.
+Some visitors have audio off, use a screen reader, have a hearing impairment, or are somewhere they won't enable sound. The embed already covers the basics: the chat thread is an ARIA live log (`role="log"`, `aria-live="polite"`), and the speech bubble is a live status region, so screen readers announce the greeting as it arrives.
-The cleanest way is to use a system-prompt convention. In the editor at [https://three.ws/create](https://three.ws/create), open the personality panel and add this rule near the bottom of your system prompt:
+Write the greeting instructions with the assumption that someone might read it before they hear it:
-```
-When you receive the message "__greet", introduce yourself in one or two sentences. Mention your name. Invite the visitor to ask anything. Match the visitor's apparent context — if it's morning, say good morning; if it's late at night, be gentle.
-```
+- Make it useful as text. "Hi, I'm Iris. Ask me anything about Lumen." reads as well as it sounds. "Hi!" alone reads as a stub.
+- Avoid pronunciation asides and pause cues ("Hi. (pause) I'm Iris") — they work in audio and look broken in writing.
-Then, in your page:
+If you want a heavier-handed setup — a permanent transcript pane next to the agent — listen for the speech events. `voice:speech-start` fires each time the agent begins speaking a line aloud, with the full text in `event.detail.text`; `voice:speech-end` fires when it finishes:
-```js
-const agent = document.getElementById('agent-script');
-agent.addEventListener('agent:ready', () => {
- // The agent will process this through its brain and the response will be spoken
- agent.speak('__greet');
-});
+```html
+<div id="transcript" aria-live="polite" style="margin-top: 12px; color:#666; font-size: 0.9rem;">
+ <strong>Agent says:</strong> <span id="transcript-text">…</span>
+</div>
+
+<script>
+ const agent = document.getElementById('agent');
+ const out = document.getElementById('transcript-text');
+
+ agent.addEventListener('voice:speech-start', (event) => {
+ out.textContent = event.detail.text;
+ });
+</script>
```
-The `__greet` token is intercepted by the agent's brain (because you taught it the convention in the system prompt). The LLM generates a greeting that fits your prompt rules, the agent speaks it, and the visitor hears something that feels written for them. This is the highest-effort option but the most flexible, and it composes with the rest of your prompt design.
+Note these events accompany *spoken* lines — they fire when a reply goes through TTS (the `voice` attribute, `{ voice: true }`, or the built-in chat input). To mirror every reply regardless of audio, listen for `brain:message` and read `event.detail.content` when `event.detail.role === 'assistant'`.
---
-## Step 7 — Writing a good greeting
+## Step 8 — Writing a good greeting
-Here is what makes a greeting effective, distilled from watching first-time visitors interact with embeds across many sites.
+Here is what makes a greeting effective, distilled from watching first-time visitors interact with embeds across many sites. These rules go into the agent's instructions (Step 3), since that's what shapes the actual words.
### Lead with the name
-Visitors form an opinion in the first three seconds. "Hi, I'm Iris" is doing two things at once: it establishes that the agent is a named entity (not a generic chatbot), and it gives the visitor a handle to use ("Iris, can you…"). Both matter.
+Visitors form an opinion in the first three seconds. "Hi, I'm Iris" does two things at once: it establishes that the agent is a named entity (not a generic chatbot), and it gives the visitor a handle to use ("Iris, can you…"). Both matter.
### State the agent's role
@@ -49986,77 +53073,61 @@ Specificity beats vagueness. "I can help you" is weaker than "I can help you pic
End with an instruction or invitation. Visitors who don't know what to do next, won't.
-- "Click me if you have a question."
-- "Just type anything below."
+- "Ask me anything — just type below."
- "Try asking 'what's new this month?'"
### Keep it to one or two sentences
-A long greeting feels like a sales pitch. Two short sentences feel like a person.
+A long greeting feels like a sales pitch. Two short sentences feel like a person. Cap it in the instructions ("Never open with more than two sentences") — models respect explicit limits far better than vague ones.
### A complete example
-For a hypothetical online wine merchant called "Bottle Lane", a good greeting might be:
+For a hypothetical online wine merchant called "Bottle Lane", the greeting block of the instructions might read:
-```html
-<script
- src="https://three.ws/cdn/agent-3d.js"
- data-agent-id="YOUR_AGENT_ID"
- data-name="Vincent"
- data-greeting="Hi, I'm Vincent. I can recommend a bottle for any occasion — just tell me what you're celebrating."
-></script>
```
-
-Twenty words. Names the agent. States the value. Invites the visitor to be specific. Reads well aloud and reads well silent.
-
-### A complete example for a developer tool
-
-For a hypothetical CI/CD tool called "Pipeline", a different tone:
-
-```html
-<script
- src="https://three.ws/cdn/agent-3d.js"
- data-agent-id="YOUR_AGENT_ID"
- data-name="Otto"
- data-greeting="Hey. I'm Otto. Ask me how to set up a build, or paste me a config and I'll review it."
-></script>
+You are Vincent, Bottle Lane's sommelier. When a visitor greets you or asks
+who you are, introduce yourself in one sentence and offer to recommend a
+bottle for any occasion — ask what they're celebrating. Never open with more
+than two sentences.
```
-Same structure — name, role, invitation — but the tone fits the audience. Calmer, slightly informal, direct.
+A typical greeting this produces: "Hi, I'm Vincent. I can recommend a bottle for any occasion — what are you celebrating?" Names the agent. States the value. Invites the visitor to be specific. Reads well aloud and reads well silent.
+
+For a developer tool, same structure, different register: "Hey, I'm Otto. Ask me how to set up a build, or paste a config and I'll review it."
---
-## Step 8 — Debugging a silent greeting
+## Step 9 — Debugging a silent greeting
-If you set `data-greeting` and the agent isn't speaking, work through this checklist in order.
+If the greeting isn't arriving, work through this checklist in order.
-1. **Does the speech bubble appear?** If yes, the greeting is firing correctly and the audio is being blocked or muted. Skip to step 4. If no, the greeting isn't firing — go to step 2.
+1. **Does the speech bubble show text?** If yes, the greeting is working and only the audio is missing — skip to step 5. If no text appears anywhere, the message isn't reaching the brain — keep going.
-2. **Is the agent fully loaded?** Open the browser console. You should see no errors, and the network tab should show the GLB and manifest loaded with 200 status. If the agent isn't ready, the greeting won't fire. Common cause: the agent ID is wrong; double-check it on [https://three.ws/my-agents](https://three.ws/my-agents).
+2. **Is the agent booting at all?** Open the browser console and the network tab. You should see the manifest and GLB load with 200 status. If the agent ID is wrong, the element falls back to the default avatar rather than erroring — so a *wrong-looking* avatar is your clue. Double-check the ID at [https://three.ws/my-agents](https://three.ws/my-agents). You can also listen for failures: `agent.addEventListener('agent:error', (e) => console.log(e.detail.phase, e.detail.error))`.
-3. **Is the `data-greeting` attribute spelled correctly?** The loader silently ignores unknown attributes. `data-greting` will do nothing. Re-read the attribute name in your HTML.
+3. **Is the element still lazy-loading?** Without `eager`, an off-screen element hasn't booted, so `agent:ready` hasn't fired. Scroll it into view, or add `eager`.
-4. **Is the tab muted?** Right-click the browser tab. Some browsers show "Unmute tab" in the context menu. Click it.
+4. **Does the agent have a brain?** A self-configured embed with no `brain` attribute has no model to answer with. Add `brain="free"`. For `agent-id` embeds, confirm a brain is configured on the agent in the editor.
-5. **Has the user interacted with the page yet?** On strict-autoplay browsers (Safari, iOS Safari), the agent will not speak until the visitor has clicked, tapped, or pressed a key on the page. The speech bubble appears regardless. If you tap and audio still doesn't play, move to step 6.
+5. **Is voice enabled for JS calls?** `say()` from JavaScript only speaks aloud when the element has the `voice` attribute (or you pass `{ voice: true }`). This is the single most common cause of "text shows, no audio".
-6. **Is the agent's voice configured?** Open the editor at [https://three.ws/create](https://three.ws/create), open your agent, open the Voice panel. Make sure a voice is selected and saved. An unconfigured voice falls back to silent (the speech bubble still appears).
+6. **Has the visitor interacted with the page yet?** On strict-autoplay browsers (Safari, iOS), audio won't play before the first tap or keypress — the text still shows. See Step 6 for the guaranteed-audible pattern.
-7. **Is the system volume up?** Genuinely worth checking. The greeting plays at the system audio output level; if the OS volume is at zero, you won't hear it.
+7. **Is the tab muted, and is the system volume up?** Genuinely worth checking. Some browsers show "Unmute tab" in the tab's context menu.
-In practice, problems are almost always step 5 (autoplay rules) or step 6 (voice not configured). The embed is conservative on purpose — better to show a silent speech bubble than to surprise a visitor with unexpected audio.
+In practice, problems are almost always step 5 (missing `voice` attribute) or step 6 (autoplay rules). The embed is conservative on purpose — better a silent, readable greeting than a visitor ambushed by unexpected audio.
---
## What you learned
-- `data-greeting` is the simplest way to give your agent a spoken first line
-- The greeting fires on the `agent:ready` event, automatically and reliably
-- Browser autoplay rules can suppress the audio on first page load; the embed handles this gracefully by always showing the speech bubble and queuing audio for the user's first interaction
-- A spoken greeting is also a readable greeting — write it to work both ways
-- The accessibility tooling is built in (ARIA live regions, automatic announcements) but you can layer your own transcript on top using the `speak` event
-- Dynamic greetings come in two flavours: scripted (chosen in JS based on context) and LLM-generated (driven by a `__greet` convention in the system prompt)
-- A good greeting names the agent, states its role, invites action, and stays under two sentences
+- The greeting flow is: listen for `agent:ready`, then call `say()` with a natural opening cue
+- `say()` routes through the agent's brain, so the greeting's content comes from its personality — the editor's Personality panel for published agents, the `instructions` attribute for self-configured ones
+- The `voice` attribute (or `{ voice: true }`) makes JS-triggered replies audible; the text bubble renders either way
+- `speak()` is the talking *gesture* only — no brain, no audio — useful when your page supplies the words itself
+- Browser autoplay rules can suppress the audio on first load; greet on `agent:ready` for a text-first greeting, or on the first user interaction for a guaranteed-audible one
+- `voice:speech-start` / `voice:speech-end` (and `brain:message`) let you mirror the greeting into your own transcript UI
+- A good greeting names the agent, states its role, invites action, and stays under two sentences — enforce that in the instructions
A working greeting moves the embed from "decoration" to "interaction", which is the single biggest win you can ship after the basic embed is live.
@@ -50066,14 +53137,14 @@ A working greeting moves the embed from "decoration" to "interaction", which is
- [Embed in 30 seconds](/tutorials/embed-in-30-seconds) — the foundation embed, if you skipped it
- [Customize size, position and background](/tutorials/customize-appearance) — make the embed match your brand visually
-- [Pick and swap an avatar in Studio](/tutorials/swap-avatar-in-studio) — change the agent's body without changing the snippet
+- [Drive the agent with the JavaScript API](/tutorials/js-api-events) — the full method and event reference behind this tutorial
+- [Give your agent a personality](/tutorials/agent-personality) — go deeper on the system prompt that shapes every greeting
+- [Voice and lip-sync](/tutorials/voice-and-lipsync) — how the spoken side works under the hood
- [Share your agent](/tutorials/share-your-agent) — generate a public URL, QR code, and social previews for the agent itself
-- [Build your first agent](/tutorials/first-agent) — drop into the manifest and skills layer for personality work
-- [Embed on a website](/tutorials/embed-on-website) — the full embed reference for production sites
---
-<a id="sec-223"></a>
+<a id="sec-225"></a>
> **Source:** `docs/tutorials/image-to-3d.md` · [↑ table of contents](#table-of-contents)
@@ -50176,7 +53247,7 @@ Everything you generate is kept in **Your creations** at the bottom of the page,
---
-<a id="sec-224"></a>
+<a id="sec-226"></a>
> **Source:** `docs/tutorials/import-avatar-url.md` · [↑ table of contents](#table-of-contents)
@@ -50344,7 +53415,7 @@ The URL path and the file-upload path converge on the same avatar record and the
---
-<a id="sec-225"></a>
+<a id="sec-227"></a>
> **Source:** `docs/tutorials/js-api-events.md` · [↑ table of contents](#table-of-contents)
@@ -50357,7 +53428,7 @@ This tutorial covers the full handle-to-event lifecycle. By the end you will kno
**What you'll build:**
- A live page where the agent reacts to clicks and form events
- A "wait until ready" pattern that never tries to drive an unbooted agent
-- A queue that chains `speak`, `playAnimation`, and `lookAt` without overlap
+- A queue that chains `ask`, `play`, and `lookAt` without overlap
- A listener that reads back every word the agent says
- A checkout celebration flow — submit a form, the agent cheers, narrates, and goes idle
@@ -50411,7 +53482,7 @@ Start with the simplest possible embed. Create `index.html` and paste this:
</div>
</div>
- <script type="module" src="https://three.ws/cdn/agent-3d.js"></script>
+ <script type="module" src="https://three.ws/agent-3d/latest/agent-3d.js"></script>
<script type="module" src="./app.js"></script>
</body>
</html>
@@ -50439,23 +53510,15 @@ Serve it locally — `python3 -m http.server 8080` works — and open `http://lo
## Step 2 — Get a handle to the agent
-The `<agent-3d>` element is a custom element. `document.getElementById('agent')` gives you back an `Agent3DElement` instance with the full API attached. The same handle works whether you wrote `<agent-3d>` directly or used the one-line script-tag embed:
-
-```html
-<script src="https://three.ws/cdn/agent-3d.js" data-agent-id="YOUR_AGENT_ID" id="my-agent"></script>
-```
-
-With that form, `document.getElementById('my-agent')` still gives you the element. The script tag mounts the agent and returns the same custom element under the hood.
+The `<agent-3d>` element is a custom element. `document.getElementById('agent')` gives you back an `Agent3DElement` instance with the full API attached — the CDN script's only job is registering that element, so every `<agent-3d>` tag on the page is a live API handle.
-When in doubt, this lookup works in either case:
+If you didn't put an `id` on the tag (or you're writing code that runs on pages you don't control), grab the first agent on the page instead:
```js
-const agent =
- document.querySelector('agent-3d') ||
- document.querySelector('script[data-agent-id]');
+const agent = document.querySelector('agent-3d');
```
-Both have identical JavaScript APIs from this point forward.
+Either lookup returns the same element with the same JavaScript API from this point forward.
---
@@ -50509,50 +53572,53 @@ No race conditions, no "I clicked but nothing happened on the first try" bugs.
The agent has two methods that look similar but do different things. Picking the right one matters.
-**`agent.speak(text)`** — fires the talking animation and (if voice is enabled) speaks the text out loud. It does *not* go through the LLM. Use it when you already know exactly what you want the agent to say and you don't want a model in the loop. Cheap, instant, deterministic.
+**`agent.speak(text)`** — plays a talking *gesture* sized to the length of the text (roughly 0.3s per word, minimum 1.5s). It is silent: no LLM, no audio, no chat bubble. Use it to add life to a scripted moment where the page itself supplies the words on screen. Cheap, instant, deterministic.
-**`agent.say(text)`** — sends `text` to the brain as a user message, the brain responds, and the response is spoken back. This is what the built-in chat input calls. Use it when you want a real conversational turn.
+**`agent.say(text)`** — sends `text` to the brain as a user message. The reply renders in the chat bubble and is spoken aloud when the `voice` attribute is set. This is what the built-in chat input calls. It's fire-and-forget: it returns immediately, and if you call it again while a turn is in flight, the newest message replaces the queued one.
-Most page-driven interactions want `speak`. Use `say` when you're injecting user input from a custom UI.
+**`agent.ask(text)`** — same brain turn as `say`, but returns a promise that resolves with the reply text once the response (and its speech, if voice is on) has finished. Reach for it whenever you need to await the turn or use the reply.
+
+Most page-driven interactions want `say` or `ask`. Use `speak` when all you need is the gesture.
Wire up two buttons:
```js
document.getElementById('btn-greet').addEventListener('click', async () => {
await whenReady(agent);
+ // Silent talking gesture — pair it with your own on-page caption.
agent.speak('Hey there. Glad you stopped by.');
});
document.getElementById('btn-think').addEventListener('click', async () => {
await whenReady(agent);
// Goes through the LLM — the model decides what to say.
- await agent.say('Tell me a one-sentence fun fact.');
+ agent.say('Tell me a one-sentence fun fact.');
});
```
-Click both. The first speaks instantly. The second pauses briefly while the model generates, then speaks the response.
+Click both. The first animates instantly and makes no sound. The second pauses briefly while the model generates, then renders the reply (and speaks it if `voice` is enabled).
---
-## Step 5 — Animations: exact name vs hint
+## Step 5 — Animations: exact clip vs emote
The agent has two ways to pick an animation clip. They map to two different mental models.
-**`agent.play(clipName)`** — plays the clip with that exact name from the GLB. Case-sensitive. If the clip isn't in the model, nothing happens. Use this when you know what's in the rig — for instance, if you've baked a `WaveLoop` clip yourself.
+**`agent.play(name)`** — plays the clip with that name from the loaded rig (an exact match, falling back to a case-insensitive one). If the clip isn't in the model, it returns `false` and nothing plays. Use this when you know what's in the rig — for instance, if you've baked a `WaveLoop` clip yourself.
-**`agent.playAnimationByHint(hint)`** — looks for any clip whose name contains the hint, case-insensitive. `playAnimationByHint('wave')` matches `WaveLoop`, `Mixamo_Wave`, `wave_friendly` — all of them. This is the resilient one. Use it when you don't know the exact naming convention of the loaded GLB.
+**`agent.playEmote(name)`** — the resilient one. Instead of a clip name it takes an intent — `'celebrate'`, `'cheer'`, or `'flinch'` — and walks a fallback chain of clips until one exists in the rig (`celebrate` → `wave`; `cheer` → `celebrate` → `wave`; `flinch` → `defeated` → `concern` → `shake`). If none of them are present, it finishes with a small head-bob, so it's guaranteed to do *something* regardless of the rig.
-For day-to-day work, prefer the hint version:
+For product moments, prefer the emote version:
```js
document.getElementById('btn-celebrate').addEventListener('click', async () => {
await whenReady(agent);
- // Tries 'celebrate' first; if that's not in the rig, falls through to playEmote's chain.
+ // Tries the 'celebrate' clip first; falls back to 'wave', then a head-bob.
agent.playEmote('celebrate');
});
```
-`playEmote(name)` is a higher-level wrapper that tries a named emote, then falls back through a chain (`celebrate` → `cheer` → `wave`), and finally to a small head-bob if none of them exist. This is what you want for product moments — guaranteed to do *something* regardless of the rig.
+Reach for `play(name)` only when you control the GLB and want one specific clip, no substitutes.
Convenience shortcuts: `agent.wave()`, `agent.lookAt('camera' | 'user' | 'model')`.
@@ -50626,52 +53692,42 @@ Every one of these is a hook for your app. A few common patterns:
## Step 7 — Sequencing: do A, then B, then C
-A common pitfall: fire `speak` and `playAnimation` back-to-back, and they overlap. The animation steps on the talking gesture, the speech gets queued behind itself, things look broken.
-
-The clean fix is to wait for the right events between steps. `voice:speech-end` is your friend here — it tells you the spoken sentence is done.
+A common pitfall: fire `speak` and `play` back-to-back, and they overlap. The second clip steps on the talking gesture and things look broken.
-A small helper that turns the event into a promise:
-
-```js
-function speakAndWait(el, text) {
- return new Promise((resolve) => {
- const on = () => {
- el.removeEventListener('voice:speech-end', on);
- resolve();
- };
- el.addEventListener('voice:speech-end', on);
- el.speak(text);
- });
-}
-```
-
-Now you can chain:
+For LLM turns the clean fix is `ask()` — it resolves only after the reply is complete (including its speech, when `voice` is on), so a plain `await` sequences everything:
```js
async function intro() {
await whenReady(agent);
agent.wave();
- await speakAndWait(agent, 'Welcome to the tour.');
+ await agent.ask('Welcome the visitor to the tour in one short sentence.');
agent.lookAt('user');
- await speakAndWait(agent, 'I will keep this brief.');
+ await agent.ask('Tell them you will keep this brief.');
agent.playEmote('cheer');
}
```
Each line waits for the previous one to land before the next runs. The result feels deliberate — not a stuttering pile-up.
-For the `say()` (LLM-driven) version, you'd wait on `brain:message` instead, since `say` returns when the message is complete:
+For the silent `speak()` gesture there is no completion event — but its duration is deterministic (0.3s per word, minimum 1.5s), so you can mirror it:
```js
-async function thoughtfulIntro() {
- await whenReady(agent);
- agent.wave();
- await agent.say('Greet me by name and ask what I want to learn.');
- agent.playEmote('cheer');
+function gestureAndWait(el, text) {
+ el.speak(text);
+ const secs = Math.max(1.5, text.split(' ').length * 0.3);
+ return new Promise((resolve) => setTimeout(resolve, secs * 1000));
}
```
-`agent.say(text)` already returns a promise that resolves on completion, so no extra event-wrapper needed.
+And if you're reacting to real speech (an LLM reply being voiced), `voice:speech-end` is still the event to wait on — it fires when the spoken sentence is done:
+
+```js
+function nextSpeechEnd(el) {
+ return new Promise((resolve) => {
+ el.addEventListener('voice:speech-end', resolve, { once: true });
+ });
+}
+```
---
@@ -50695,18 +53751,19 @@ function getAgent() {
Or use a small reactive wrapper if you're inside a framework — see the [Web Component end-to-end tutorial](/tutorials/web-component-end-to-end) for React and Vue patterns.
-**LLM errors during `say()`.** Network glitch, brain provider rate-limit, no API key. `agent.say(text)` rejects in those cases. Wrap it:
+**LLM errors during a turn.** Network glitch, brain provider rate-limit, no API key. `say()` never rejects — it shows the error in the chat bubble and fires an `agent:error` event. When you need to handle the failure programmatically, use `ask()`, which rejects:
```js
try {
- await agent.say(userText);
+ await agent.ask(userText);
} catch (err) {
console.error('Brain call failed:', err);
- agent.speak('Sorry — something hiccupped on my end. Try that again?');
+ showRetryToast('Something hiccupped. Try that again?'); // your own UI
+ agent.speak('Sorry about that.'); // concerned talking gesture, no brain needed
}
```
-The fallback `agent.speak(...)` does *not* go through the brain, so it works even when the LLM path is broken.
+The fallback `agent.speak(...)` does *not* go through the brain (it's a silent gesture), so it works even when the LLM path is broken — pair it with your own on-page error message for the words.
---
@@ -50734,7 +53791,7 @@ The HTML:
The JS:
```js
-import './app.js'; // assumes whenReady, speakAndWait are exported there
+import './app.js'; // assumes whenReady is exported there
const form = document.getElementById('order-form');
const agent = document.getElementById('agent');
@@ -50748,7 +53805,7 @@ form.addEventListener('submit', async (e) => {
// In a real app, you'd post to your backend here and only proceed on success.
const ok = await placeOrder({ name, item });
if (!ok) {
- agent.speak("That didn't go through. Try again in a moment?");
+ agent.say("Tell the customer their order didn't go through and to try again in a moment.");
return;
}
@@ -50759,8 +53816,10 @@ async function celebrate({ name, item }) {
await whenReady(agent);
agent.lookAt('user');
agent.playEmote('celebrate');
- await speakAndWait(agent, `Thanks, ${name}!`);
- await speakAndWait(agent, `Your ${item} is on the way.`);
+ await agent.ask(
+ `The customer ${name} just completed an order for "${item}". ` +
+ `Thank them by name and confirm it's on the way, in one short sentence.`
+ );
agent.wave();
}
@@ -50809,10 +53868,10 @@ And the methods you'll reach for most:
- `agent.speak(text)` for cheap, deterministic lines
- `agent.say(text)` for full LLM-driven turns
- `agent.wave()`, `agent.lookAt(target)`, `agent.playEmote(name)` for visual beats
-- `agent.play(name)` and `agent.playAnimationByHint(hint)` for direct clip control
+- `agent.play(name)` for direct, exact-clip control
- `agent.clearConversation()` to reset rolling memory
-The `whenReady`, `speakAndWait`, and try/catch patterns are small but they remove almost every gotcha. Steal them.
+The `whenReady`, awaited-`ask()`, and try/catch patterns are small but they remove almost every gotcha. Steal them.
## Next steps
@@ -50822,7 +53881,7 @@ The `whenReady`, `speakAndWait`, and try/catch patterns are small but they remov
---
-<a id="sec-226"></a>
+<a id="sec-228"></a>
> **Source:** `docs/tutorials/mcp-server-for-your-agent.md` · [↑ table of contents](#table-of-contents)
@@ -50843,7 +53902,7 @@ This is shorter than the other Advanced tutorials because the protocol is small
**Prerequisites:**
-- A deployed agent with a working chat endpoint. If you're using the platform, your agent already has one at `https://three.ws/api/chat?agent=<agentId>`. If you've forked the platform ([self-host-agent-backend](/tutorials/self-host-agent-backend)), use your own equivalent.
+- A deployed agent with a working chat endpoint. If you're using the platform, your agent already has one: `POST https://three.ws/api/chat` with a JSON body of `{ agentId, message, history }`, answered as an SSE stream (Step 4 shows the exact shapes). If you've forked the platform ([self-host-agent-backend](/tutorials/self-host-agent-backend)), use your own equivalent.
- Node.js 24.x and a deployed function host (Vercel/Cloudflare/your own server)
- Familiarity with JSON-RPC 2.0 (`jsonrpc: "2.0"`, `method`, `params`, `id`)
- A test MCP client. Claude Desktop is the most forgiving; Cursor is stricter; `npx @modelcontextprotocol/inspector` is the dev-loop tool
@@ -51079,7 +54138,16 @@ The `description` is what the *calling* LLM reads to decide when to invoke the t
The dispatch already routes `tools/call` to `onToolCall`. Implement it:
+The platform's `/api/chat` (`api/chat.js`) contract, which this handler targets:
+
+- **Request:** `POST` with a JSON body of `{ agentId, message, history }`. `agentId` is the agent's UUID, `message` is the single new user turn (a string, max 4000 chars), and `history` is an array of up to 20 prior `{ role: 'user' | 'assistant', content }` turns. There is no `messages` array, no `session_id`, and no `stream: false` switch.
+- **Response:** always an SSE stream (`Content-Type: text/event-stream`). Each event is a `data: {...}` JSON line: `{ type: 'chunk', text }` for incremental reply text, then a final `{ type: 'done', reply, actions, ... }` carrying the complete reply, or `{ type: 'error', message }` if the stream fails mid-way.
+
+`/api/chat` is stateless per request — conversation context travels in `history`. To honor the tool's optional `session_id`, keep a per-session history on the MCP server. In-memory works for a tutorial (it survives only as long as the function instance stays warm); use Redis or a database row for real multi-instance continuity.
+
```js
+const SESSIONS = new Map(); // session_id → [{ role, content }, ...]
+
async function onToolCall(params) {
const { name, arguments: args = {} } = params || {};
if (name !== 'chat_with_agent') throw rpcError(-32602, `unknown tool: ${name}`);
@@ -51089,17 +54157,17 @@ async function onToolCall(params) {
const message = String(args.message || '').trim();
if (!message) throw rpcError(-32602, 'message is required');
const sessionId = args.session_id ? String(args.session_id) : null;
+ const history = sessionId ? SESSIONS.get(sessionId) || [] : [];
- // Call your agent's chat endpoint. For the platform, this is /api/chat.
+ // Call your agent's chat endpoint. For the platform, this is POST /api/chat.
// For your own fork or stack, swap the URL.
const upstream = await fetch('https://three.ws/api/chat', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
- agent: agentId,
- messages: [{ role: 'user', content: message }],
- session_id: sessionId,
- stream: false,
+ agentId,
+ message,
+ history: history.slice(-20),
}),
signal: AbortSignal.timeout(60_000),
});
@@ -51109,10 +54177,36 @@ async function onToolCall(params) {
throw rpcError(-32603, `agent endpoint ${upstream.status}: ${text.slice(0, 200)}`);
}
- const data = await upstream.json();
- const reply = data?.message?.content || data?.content || data?.text || '';
+ // MCP's tools/call returns a single result, so buffer the whole SSE stream
+ // and take the `reply` field from the final `done` event. The accumulated
+ // `chunk` text is the fallback if the stream is cut off before `done`.
+ const raw = await upstream.text();
+ let reply = '';
+ let chunks = '';
+ for (const line of raw.split('\n')) {
+ if (!line.startsWith('data: ')) continue;
+ let evt;
+ try {
+ evt = JSON.parse(line.slice('data: '.length));
+ } catch {
+ continue;
+ }
+ if (evt.type === 'chunk') chunks += evt.text || '';
+ else if (evt.type === 'done') reply = (evt.reply || '').trim();
+ else if (evt.type === 'error') {
+ throw rpcError(-32603, `agent stream error: ${evt.message || 'stream interrupted'}`);
+ }
+ }
+ if (!reply) reply = chunks.trim();
if (!reply) throw rpcError(-32603, 'agent returned empty response');
+ if (sessionId) {
+ SESSIONS.set(
+ sessionId,
+ [...history, { role: 'user', content: message }, { role: 'assistant', content: reply }].slice(-20),
+ );
+ }
+
// MCP tool results are an array of content blocks. For a plain text reply:
return {
content: [{ type: 'text', text: reply }],
@@ -51123,7 +54217,7 @@ async function onToolCall(params) {
The `content` array is the canonical MCP tool response shape. Each block has a `type` ("text", "image", "resource"). For an agent chat, one text block is right.
-If your agent endpoint streams (SSE or chunked), buffer it on the server here. MCP's `tools/call` returns a single result; the client doesn't expect a stream from `tools/call` in the same way it expects a stream from a top-level LLM call. If you want streaming, that's the SSE channel on the GET endpoint — more complex and rarely worth the trouble for an agent tool.
+Buffering the upstream SSE on the server, as above, is the right default: MCP's `tools/call` returns a single result; the client doesn't expect a stream from `tools/call` in the same way it expects a stream from a top-level LLM call. If you want streaming, that's the SSE channel on the GET endpoint — more complex and rarely worth the trouble for an agent tool.
---
@@ -51433,7 +54527,7 @@ Things that look right but bite you:
---
-<a id="sec-227"></a>
+<a id="sec-229"></a>
> **Source:** `docs/tutorials/mine-vanity-address.md` · [↑ table of contents](#table-of-contents)
@@ -51702,7 +54796,7 @@ The protocol itself is fully specified in [docs/PROTOCOL-vanity.md](../PROTOCOL-
---
-<a id="sec-228"></a>
+<a id="sec-230"></a>
> **Source:** `docs/tutorials/mint-pumpfun-token.md` · [↑ table of contents](#table-of-contents)
@@ -52054,7 +55148,7 @@ If you have a lawyer, talk to them before launching. If you don't, default to th
---
-<a id="sec-229"></a>
+<a id="sec-231"></a>
> **Source:** `docs/tutorials/multi-agent-coordination.md` · [↑ table of contents](#table-of-contents)
@@ -52076,8 +55170,8 @@ This tutorial assumes you've built at least one agent ([first-agent](/tutorials/
**Prerequisites:**
- Two saved agents in your dashboard at `https://three.ws/dashboard`. They can be variants of the same avatar or two completely different characters.
-- A live web page where you can drop two `<script>` tags and own the surrounding HTML/JS. A static `.html` file served by `npx serve .` is enough to get started.
-- Familiarity with the embed JS API (`speak`, `playAnimation`, events like `brain:message`, `voice:speech-end`, `agent:ready`). The reference is in [js-api-events](/tutorials/js-api-events) and the source of truth is `https://three.ws/cdn/agent-3d.js`.
+- A live web page where you can add a `<script>` tag and two `<agent-3d>` elements, and own the surrounding HTML/JS. A static `.html` file served by `npx serve .` is enough to get started.
+- Familiarity with the embed JS API (`say`, `ask`, `play`, events like `brain:message`, `voice:speech-end`, `agent:ready`). The reference is in [js-api-events](/tutorials/js-api-events) and the source of truth is the published bundle at `https://three.ws/agent-3d/1.5.2/agent-3d.js`.
- Each agent has a personality configured. See [agent-personality](/tutorials/agent-personality) if either of yours doesn't yet — they need distinct voices for the handoff to feel coherent.
---
@@ -52125,6 +55219,7 @@ A two-agent layout where both characters are always visible. Riley on the left,
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Pricing — talk to Riley and Devon</title>
+ <script type="module" src="https://three.ws/agent-3d/1.5.2/agent-3d.js"></script>
<style>
body { margin: 0; font-family: system-ui, sans-serif; background: #0b0b10; color: #fff; }
.stage { display: grid; grid-template-columns: 1fr 1fr; height: 60vh; gap: 1rem; padding: 1rem; }
@@ -52142,11 +55237,13 @@ A two-agent layout where both characters are always visible. Riley on the left,
<div class="stage">
<div id="riley-stage" class="active">
<h3>Riley · Sales</h3>
- <script src="https://three.ws/cdn/agent-3d.js" data-agent-id="<RILEY_AGENT_ID>" id="riley"></script>
+ <agent-3d id="riley" agent-id="<RILEY_AGENT_ID>" avatar-chat="off" voice eager
+ style="width:100%;height:100%"></agent-3d>
</div>
<div id="devon-stage">
<h3>Devon · Engineering</h3>
- <script src="https://three.ws/cdn/agent-3d.js" data-agent-id="<DEVON_AGENT_ID>" id="devon"></script>
+ <agent-3d id="devon" agent-id="<DEVON_AGENT_ID>" avatar-chat="off" voice eager
+ style="width:100%;height:100%"></agent-3d>
</div>
</div>
<div class="chat">
@@ -52158,7 +55255,7 @@ A two-agent layout where both characters are always visible. Riley on the left,
</html>
```
-Two `<script>` tags, two `data-agent-id` attributes pointing at your saved agents. `coordinator.js` is the file we'll write next.
+One loader `<script>` in the `<head>` registers the `<agent-3d>` element; two tags with `agent-id` attributes point at your saved agents. Three attribute choices matter here: `avatar-chat="off"` hides each agent's built-in chat input (this page has its own shared composer), `voice` enables text-to-speech so the avatars actually speak their replies (and fire the `voice:speech-start`/`voice:speech-end` events we lean on later), and `eager` boots both agents immediately instead of waiting for them to scroll into view. `coordinator.js` is the file we'll write next.
Replace `<RILEY_AGENT_ID>` and `<DEVON_AGENT_ID>` with the actual agent IDs from your dashboard. They're displayed under each agent in `https://three.ws/dashboard`.
@@ -52212,7 +55309,10 @@ function onReady(name, el) {
appendLog('system', `${name} ready.`);
if (state.ready.riley && state.ready.devon) {
setActive(riley);
- riley.speak("Hi! I'm Riley. Devon's here too if you have technical questions. What can I help with?");
+ riley.say(
+ "Introduce yourself to the visitor in one or two sentences: you're Riley " +
+ "from sales, and your colleague Devon is on hand for deep technical questions."
+ );
}
};
}
@@ -52221,13 +55321,13 @@ riley.addEventListener('agent:ready', onReady('riley', riley));
devon.addEventListener('agent:ready', onReady('devon', devon));
```
-This boots both agents, marks both `agent:ready`, then has Riley introduce the pair. Devon stands by silently.
+This boots both agents, marks both `agent:ready`, then has Riley introduce the pair. Devon stands by silently. `say(text)` pushes a message into the agent's conversation exactly as if the visitor typed it — here it carries a stage direction, and Riley's brain generates the actual greeting, which arrives via the `brain:message` event we wire next.
---
## Step 5 — Routing user input
-The shared input box sends to the active agent. The embed bundle exposes a `chat()` method that pushes a message into the agent's conversation as if the user typed it directly:
+The shared input box sends to the active agent via the same `say()` method we used for the greeting — it pushes a message into the agent's conversation as if the user typed it directly:
```js
input.addEventListener('keydown', (e) => {
@@ -52237,7 +55337,7 @@ input.addEventListener('keydown', (e) => {
if (!state.active) return; // not ready yet
appendLog('you', text);
state.scratch.push({ role: 'user', content: text });
- state.active.chat(text);
+ state.active.say(text);
});
```
@@ -52272,7 +55372,7 @@ Two ways to detect that the current agent wants to hand off:
We'll use (a) because it works with any LLM, any agent, no skill bundle required.
-In Riley's system prompt (set via the agent's "Personality" tab in the editor, or via the manifest's `system_prompt` field), append:
+In Riley's system prompt (set via the agent's "Personality" tab in the editor, or via the manifest's `instructions.md` file), append:
```
You are Riley, the sales lead on this pricing page. Devon, our staff
@@ -52327,9 +55427,8 @@ function considerHandoff(speakerName, text) {
setActive(targetEl);
appendLog('system', `→ handoff to ${target}`);
- // Inject the brief as a "user" message tagged with the system role marker
- // the runtime supports for stage directions.
- targetEl.chat(brief, { role: 'system' });
+ // Inject the brief into the new active agent's conversation.
+ targetEl.say(brief);
}
function buildBrief(scratch, target) {
@@ -52350,7 +55449,7 @@ function buildBrief(scratch, target) {
}
```
-`targetEl.chat(brief, { role: 'system' })` is a stage-direction message: it goes into the agent's conversation but is not appended to the user-visible transcript. The agent treats it as context and responds with its next visitor-facing message.
+`targetEl.say(brief)` pushes the brief into the target agent's conversation as an ordinary message — there is no separate system-role channel, which is exactly why `buildBrief` wraps the transcript in an explicit `[Stage director: …]` framing: the model reads the bracketed preamble as direction rather than visitor speech, and responds with its next visitor-facing message. Because both elements run with `avatar-chat="off"`, the brief never renders anywhere the visitor can see; the only transcript on the page is the one your `brain:message` handler builds in the log.
---
@@ -52381,7 +55480,7 @@ The `state.scratch` keeps the raw text (so the brief built in `buildBrief` is fa
## Step 8 — Speech-end synchronization
-The agent's `speak` method drives the 3D character's lip-sync and ambient animations. The `voice:speech-end` event fires when the avatar finishes saying its line. Use this to gate the next user input:
+Because both elements carry the `voice` attribute from Step 3, every reply is spoken aloud: the runtime fires `voice:speech-start` when TTS begins and `voice:speech-end` when the avatar finishes saying its line (without `voice`, neither event fires). Use the pair to gate the next user input:
```js
let speaking = false;
@@ -52396,7 +55495,7 @@ wireSpeechGate(devon);
Without this, an eager visitor types over the avatar's spoken response and the conversation tangles. With it, each turn completes cleanly.
-For a handoff specifically, you want the OLD agent's `voice:speech-end` to fire *before* the NEW agent starts speaking. The event order is naturally correct because the coordinator calls `targetEl.chat(brief, ...)` immediately, but the new agent doesn't start speaking until its LLM responds — which is well after the old agent finished its last syllable. No extra coordination needed in practice.
+For a handoff specifically, you want the OLD agent's `voice:speech-end` to fire *before* the NEW agent starts speaking. The event order is naturally correct because the coordinator calls `targetEl.say(brief)` immediately, but the new agent doesn't start speaking until its LLM responds — which is well after the old agent finished its last syllable. No extra coordination needed in practice.
---
@@ -52413,7 +55512,7 @@ If any of those fail, the typical causes:
- **Riley doesn't hand off.** The system prompt isn't strong enough. Make the trigger list more concrete or use few-shot examples in the prompt.
- **Devon answers technical questions Riley should have answered.** Check that the handoff topics list in Riley's prompt is *exclusive* — explicitly say "do NOT hand off when the visitor asks X."
-- **Both agents speak at once.** The `voice:speech-start`/`voice:speech-end` gate isn't wired, or one of the agents is mis-receiving the chat input. Confirm `state.active` is correctly set and the `chat()` call only goes to `state.active`.
+- **Both agents speak at once.** The `voice:speech-start`/`voice:speech-end` gate isn't wired, or one of the agents is mis-receiving the chat input. Confirm `state.active` is correctly set and the `say()` call only goes to `state.active`.
---
@@ -52421,43 +55520,40 @@ If any of those fail, the typical causes:
The example so far is **sequential delegation** — one agent speaks at a time. The other big multi-agent pattern is **parallel fan-out**: two agents work simultaneously on different parts of a task and the coordinator joins the results.
-A concrete example: a research agent and a copy-editor agent. The visitor asks "draft a 200-word blog post on the new feature." The research agent fetches facts; the copy-editor agent drafts the prose using those facts.
+A concrete example: a research agent and a copy-editor agent. The visitor asks "draft a 200-word blog post on the new feature." The research agent gathers facts; the copy-editor agent drafts the prose using those facts.
-The shape:
+The primitive that makes this work is `ask()` — the promise-returning sibling of `say()`. It sends a message into the agent's conversation and resolves with the assistant's reply text, so the coordinator can `await` both agents at once and join the results:
```js
async function parallelTask(userPrompt) {
- // Both agents accept tool calls via a hidden interface — chat() with a
- // role of 'tool-call' wraps the prompt so the agent's tool runner picks it up
- // without rendering as a visitor message.
- const [facts, draftScaffold] = await Promise.all([
- callAgentTool(researcher, 'gather_facts', { topic: userPrompt }),
- callAgentTool(writer, 'draft_outline', { topic: userPrompt }),
+ const [facts, outline] = await Promise.all([
+ researcher.ask(
+ `List the verifiable facts we can cite about: ${userPrompt}. Bullet points only.`
+ ),
+ writer.ask(
+ `Draft a tight outline for a 200-word blog post on: ${userPrompt}. Headings only.`
+ ),
]);
- // Now hand the combined result back to the writer to finalize.
- return callAgentTool(writer, 'finalize_post', { outline: draftScaffold, facts });
+ // Join: hand the researcher's facts to the writer for the final pass.
+ return writer.ask(
+ `Write the final 200-word post from your outline, using only these facts.\n\n` +
+ `Facts:\n${facts}\n\nOutline:\n${outline}`
+ );
}
```
-`callAgentTool` is a small helper that wraps `el.chat(...)` and listens for a single `tool-result` event:
+If either agent does its part through tools — a skill bundle that fetches a feed, hits an API, reads a knowledge base — you can observe every call from the page via the `skill:tool-start` and `skill:tool-called` events:
```js
-function callAgentTool(el, toolName, args) {
- return new Promise((resolve, reject) => {
- const id = crypto.randomUUID();
- const onResult = (e) => {
- if (e.detail?.toolCallId !== id) return;
- el.removeEventListener('tool-result', onResult);
- if (e.detail.error) reject(new Error(e.detail.error));
- else resolve(e.detail.result);
- };
- el.addEventListener('tool-result', onResult);
- el.invokeTool({ id, name: toolName, args });
- });
-}
+researcher.addEventListener('skill:tool-called', (e) => {
+ const { tool, result } = e.detail;
+ console.log('researcher ran', tool, result);
+});
```
-This requires each agent to expose the tools you're calling. Build them as skills (see [custom-skill](/tutorials/custom-skill)). The orchestration logic stays in the coordinator on the page.
+Build the tools themselves as skills (see [custom-skill](/tutorials/custom-skill)); the orchestration logic stays in the coordinator on the page.
+
+There's also a platform-native alternative to page-level orchestration: the `<agent-stage>` element. A stage hosts every child `<agent-3d>` in one shared WebGL scene (with a `formation` attribute — `row`, `circle`, or `freeform`), exposes `getAgents()`, `broadcast(fromId, event)`, and `routeMessage(fromId, toId, text)` to your code, and grants each staged agent two extra built-in tools — `observe_agents` (who else is on stage) and `say_to_agent` (address a colleague directly) — so the LLMs can delegate to each other without any coordinator glue. When the agents, not the page, should decide who does what, reach for the stage. The full patterns are in [Multi-Agent Scenes](../multi-agent.md).
Parallel fan-out is **harder to debug** than sequential delegation because errors are non-deterministic in order and any latency outlier blocks the join. Use it when the wall-clock saving is worth the complexity. For a chat UX with a human in the loop, sequential is almost always the right default.
@@ -52518,34 +55614,23 @@ The runtime cannot fix prompts that contradict each other. Catch contradictions
## Step 13 — Pattern: turn-taking with no human
-Sometimes the two agents are talking to each other, with the human watching. A debate, a roleplay, a brainstorm. This is the cleanest pattern in terms of code (no human input gate; turns alternate on `voice:speech-end`) and the hardest pattern in terms of LLM behavior (without grounding in real user input, both agents drift into hallucinated agreement after about six turns).
+Sometimes the two agents are talking to each other, with the human watching. A debate, a roleplay, a brainstorm. This is the cleanest pattern in terms of code (no human input gate; each turn feeds the previous reply to the other agent) and the hardest pattern in terms of LLM behavior (without grounding in real user input, both agents drift into hallucinated agreement after about six turns).
-Concrete loop:
+Concrete loop — `ask()` does all the sequencing for you, because with `voice` enabled it resolves only after the reply has been generated *and* spoken:
```js
async function autoplay(topic, turns = 6) {
- setActive(riley);
- riley.speak(`Let's debate this: ${topic}. I'll go first.`);
- await waitForSpeakEnd(riley);
- let speaker = riley, other = devon;
+ let speaker = riley;
+ let prompt = `Let's debate this: ${topic}. Open with your position in two sentences.`;
for (let i = 0; i < turns; i++) {
setActive(speaker);
- const lastFromOther = state.scratch.filter((m) => m.name === otherName(other)).slice(-1)[0]?.content || topic;
- speaker.chat(lastFromOther);
- await waitForChatMessage(speaker);
- await waitForSpeakEnd(speaker);
- [speaker, other] = [other, speaker];
+ const reply = await speaker.ask(prompt);
+ prompt = `The other debater said: "${reply}". Respond in two sentences.`;
+ speaker = speaker === riley ? devon : riley;
+ // Brief beat between turns so the handover doesn't feel robotic.
+ await new Promise((r) => setTimeout(r, 800));
}
}
-
-function waitForSpeakEnd(el) {
- return new Promise((res) => el.addEventListener('voice:speech-end', () => res(), { once: true }));
-}
-function waitForChatMessage(el) {
- return new Promise((res) => el.addEventListener('brain:message', (e) => {
- if (e.detail?.role === 'assistant') res();
- }, { once: true }));
-}
```
For a demo this is great. For anything load-bearing, cap `turns` aggressively and have a third "moderator" agent (or just code-as-moderator) stop the loop when the conversation stops making progress.
@@ -52578,20 +55663,22 @@ When you go from a demo to production, two-agent pages introduce real concerns:
**Latency.** The handoff cost is one extra LLM round trip (the brief injected as a stage direction triggers a response). Visible to the user as ~1.5 extra seconds. Acceptable for a substantive question, intolerable for trivial ones — which is why the handoff list in Riley's prompt must be restrictive.
-**Failure modes.** Devon's LLM provider goes down. Now Riley still works but the handoff lands on a dead agent. Mitigation: a try/catch around `targetEl.chat(brief, ...)` with a fallback that has Riley apologize and answer best-effort.
+**Failure modes.** Devon's LLM provider goes down. Now Riley still works but the handoff lands on a dead agent. Mitigation: deliver the brief with `ask()` instead of `say()` — same send, but it returns a promise you can race against a timeout — and fall back to Riley on failure. Note the fallback message is a stage direction, not a scripted line: Riley's brain generates the actual apology in Riley's voice.
```js
async function safeHandoff(targetEl, brief, fallbackEl, originalQuestion) {
try {
await Promise.race([
- handoffWithTimeout(targetEl, brief, 8000),
- timeoutGuard(8000),
+ targetEl.ask(brief),
+ new Promise((_, reject) =>
+ setTimeout(() => reject(new Error('handoff timed out')), 8000)),
]);
} catch (err) {
setActive(fallbackEl);
- fallbackEl.speak(
- "Devon's tied up right now — let me take a shot at this myself, and " +
- "I'll get a fuller answer in writing afterwards. " + originalQuestion
+ fallbackEl.say(
+ "Devon is unavailable right now. Apologize briefly, take your best shot at " +
+ "the visitor's technical question yourself, and offer a written follow-up. " +
+ "The question was: " + originalQuestion
);
}
}
@@ -52599,7 +55686,7 @@ async function safeHandoff(targetEl, brief, fallbackEl, originalQuestion) {
**Observability.** Log every handoff (which agent, which topic, what the user asked next). Over a week, you'll have data on whether Riley is over- or under-handing-off. Tune the prompt accordingly.
-**Embeds on third-party sites.** If you ship this two-agent page as an embed, both `data-agent-id`s are visible in the page source — anyone can see which agents you're using. That's by design; the agents are public artifacts. If you don't want them publicly identifiable, mark them as unlisted in the dashboard (they remain reachable by ID but don't appear in `/explore`).
+**Embeds on third-party sites.** If you ship this two-agent page as an embed, both `agent-id`s are visible in the page source — anyone can see which agents you're using. That's by design; the agents are public artifacts. If you don't want them publicly identifiable, mark them as unlisted in the dashboard (they remain reachable by ID but don't appear in `/explore`).
---
@@ -52621,7 +55708,7 @@ async function safeHandoff(targetEl, brief, fallbackEl, originalQuestion) {
---
-<a id="sec-230"></a>
+<a id="sec-232"></a>
> **Source:** `docs/tutorials/nvidia-3d-free.md` · [↑ table of contents](#table-of-contents)
@@ -52738,7 +55825,7 @@ It talks **directly** to a TRELLIS NIM and returns the GLB **synchronously** in
---
-<a id="sec-231"></a>
+<a id="sec-233"></a>
> **Source:** `docs/tutorials/nvidia-nim-self-host.md` · [↑ table of contents](#table-of-contents)
@@ -52914,7 +56001,7 @@ The proxy normalizes every documented artifact shape (inline `base64`, a bare st
---
-<a id="sec-232"></a>
+<a id="sec-234"></a>
> **Source:** `docs/tutorials/paid-x402-endpoint.md` · [↑ table of contents](#table-of-contents)
@@ -53606,7 +56693,7 @@ Both work. Choose based on whether your endpoint is part of an agent platform yo
---
-<a id="sec-233"></a>
+<a id="sec-235"></a>
> **Source:** `docs/tutorials/pay-for-x402-service.md` · [↑ table of contents](#table-of-contents)
@@ -53644,11 +56731,11 @@ The price, the recipient, and the network all come from the seller's 402 challen
There are two distinct problems: **finding** an endpoint and **paying** it.
-**Finding.** The [Bazaar](/bazaar) is a discovery surface. Server-side, [`/api/bazaar/list`](api/bazaar/list.js) and [`/api/bazaar/search`](api/bazaar/search.js) call each configured facilitator's `/discovery/resources` route, merge the catalogs, dedupe (HTTP by resource URL, MCP by `resource + toolName`), normalize the shape, and apply your filters. The default facilitators are PayAI (`facilitator.payai.network`, Base + Solana) and Coinbase CDP (`api.cdp.coinbase.com/platform/v2/x402`, Base + EVM L2s), wired in [`api/_lib/x402/bazaar-client.js`](api/_lib/x402/bazaar-client.js). An endpoint shows up here once it has answered a discovery probe with a valid 402 — there is no submission form. (How three.ws gets *its own* endpoints into those catalogs is the build-side concern covered in [paid-x402-endpoint](/tutorials/paid-x402-endpoint).)
+**Finding.** The [Bazaar](/bazaar) is a discovery surface. Server-side, `/api/bazaar/list` (`api/bazaar/list.js`) and `/api/bazaar/search` (`api/bazaar/search.js`) call each configured facilitator's `/discovery/resources` route, merge the catalogs, dedupe (HTTP by resource URL, MCP by `resource + toolName`), normalize the shape, and apply your filters. The default facilitators are PayAI (`facilitator.payai.network`, Base + Solana) and Coinbase CDP (`api.cdp.coinbase.com/platform/v2/x402`, Base + EVM L2s), wired in `api/_lib/x402/bazaar-client.js`. An endpoint shows up here once it has answered a discovery probe with a valid 402 — there is no submission form. (How three.ws gets *its own* endpoints into those catalogs is the build-side concern covered in [paid-x402-endpoint](/tutorials/paid-x402-endpoint).)
-**Paying.** Every payment runs through the same drop-in module, [`public/x402.js`](public/x402.js), exposed as `window.X402.pay(...)`. It does the 402 → sign → retry dance for you:
+**Paying.** Every payment runs through the same drop-in module, `public/x402.js`, exposed as `window.X402.pay(...)`. It does the 402 → sign → retry dance for you:
-- For **Solana**, the wallet can only sign serialized transactions, so the module posts the challenge's `accept` to [`/api/x402-checkout?action=prepare`](api/x402-checkout.js), gets back a partially-signed SPL `transferChecked`, has Phantom add the buyer's signature, then `?action=encode`s it into the `X-PAYMENT` header.
+- For **Solana**, the wallet can only sign serialized transactions, so the module posts the challenge's `accept` to `/api/x402-checkout?action=prepare` (`api/x402-checkout.js`), gets back a partially-signed SPL `transferChecked`, has Phantom add the buyer's signature, then `?action=encode`s it into the `X-PAYMENT` header.
- For **Base / EVM**, the wallet signs an EIP-3009 `transferWithAuthorization` typed-data message locally — no server prep needed.
Either way the signed payload is base64-encoded into `X-PAYMENT`, the gated request is retried once, and the unlocked result plus the decoded `X-PAYMENT-RESPONSE` receipt come back.
@@ -53714,7 +56801,7 @@ You get back a `402 Payment Required` whose JSON body (and a base64 mirror in th
Read it like a receipt-in-advance:
- **`amount`** is in atomic units of **`asset`**. With `decimals: 6`, `"1000"` is $0.001. (Spec-strict sellers may name this field `maxAmountRequired`; the client coerces both to `amount`.)
-- **`network`** tells you which wallet you need. `solana` / `solana:*` → Phantom/Solflare; `eip155:8453` → Base; other `eip155:*` are the EVM L2s in [`EVM_NETWORKS`](public/x402-pay-core.js).
+- **`network`** tells you which wallet you need. `solana` / `solana:*` → Phantom/Solflare; `eip155:8453` → Base; other `eip155:*` are the EVM L2s in `EVM_NETWORKS` (`public/x402-pay-core.js`).
- **`payTo`** is exactly where your USDC goes. Nothing else moves.
- **`maxTimeoutSeconds`** bounds how long your signed authorization is valid — your one safety net against a stale payment lingering.
@@ -53729,9 +56816,9 @@ A single endpoint can list several `accepts` (e.g. Base *and* Solana). You — o
Two related routes sit under it:
- **[/pay/calls](/pay/calls)** — the public ledger of paid x402 calls to the platform. Each settled call gets a permalink (`/pay/calls/<tx-signature>`) showing the tool invoked and the on-chain transaction. This is your audit trail: every payment you make here is verifiable on-chain by anyone.
-- **`/pay/c/<slug>`** — a *hosted checkout link*. A provider creates a SKU in their dashboard (see [`api/x402-skus.js`](api/x402-skus.js)) and shares the URL; the page hydrates from `/api/x402-skus?slug=<slug>` and opens the same drop-in modal pre-wired to that endpoint. If someone hands you a `/pay/c/...` link, paying it is identical to Step 2 — open it, pick a wallet, approve.
+- **`/pay/c/<slug>`** — a *hosted checkout link*. A provider creates a SKU in their dashboard (see `api/x402-skus.js`) and shares the URL; the page hydrates from `/api/x402-skus?slug=<slug>` and opens the same drop-in modal pre-wired to that endpoint. If someone hands you a `/pay/c/...` link, paying it is identical to Step 2 — open it, pick a wallet, approve.
-The point of the `/pay` surface: the *exact same* payment core ([`public/x402.js`](public/x402.js) and its sibling [`public/x402-pay-core.js`](public/x402-pay-core.js)) drives the Bazaar's "Try it", the hosted checkout, the full-page paywall, and the programmatic call below. Learn it once.
+The point of the `/pay` surface: the *exact same* payment core (`public/x402.js` and its sibling `public/x402-pay-core.js`) drives the Bazaar's "Try it", the hosted checkout, the full-page paywall, and the programmatic call below. Learn it once.
---
@@ -53838,7 +56925,7 @@ You learned four ways to consume an x402 paid service:
- **`window.X402.pay`** — pay for any endpoint from your own code; resolves with the result plus an on-chain receipt, with a `networks` allowlist to pin the rail.
- **The Endpoint Shopper** ([/shopper](/shopper)) — describe a task and a budget; an agent discovers, pays for, and synthesizes results from Bazaar endpoints autonomously.
-The throughline: discovery and payment are decoupled, the 402 challenge is the single source of truth for price and recipient, every payment settles on-chain in USDC, and one module ([`public/x402.js`](public/x402.js)) drives every surface.
+The throughline: discovery and payment are decoupled, the 402 challenge is the single source of truth for price and recipient, every payment settles on-chain in USDC, and one module (`public/x402.js`) drives every surface.
**Use it from your own project (npm)**
@@ -53870,7 +56957,7 @@ package family is listed under [x402 → Open-source packages](/x402#open-source
---
-<a id="sec-234"></a>
+<a id="sec-236"></a>
> **Source:** `docs/tutorials/personal-ai-site.md` · [↑ table of contents](#table-of-contents)
@@ -53968,33 +57055,30 @@ Configure local memory in your agent manifest or element attributes:
}
```
-Then pre-load facts after the agent initialises:
+Then pre-load facts after the agent initialises. The element exposes its memory store as `agent.memory`, and `write(key, entry)` stores a Markdown note under that key — `name` and `description` are what the memory index shows the LLM, `body` is the full note, and `type` groups it in the index (`user`, `project`, `reference`, or `feedback`):
```js
const agent = document.getElementById('maya');
-agent.addEventListener('ready', async () => {
- await agent.agent.memory.write('long-term', 'portfolio', {
- projects: [
- {
- name: 'Acme Dashboard',
- url: 'yourname.com/work/acme',
- year: 2024,
- description: 'Redesigned the main analytics dashboard, reducing time-to-insight by 40%.'
- },
- {
- name: 'Health App AR',
- url: 'yourname.com/work/health-ar',
- year: 2023,
- description: 'AR overlay for physiotherapy exercises, used by 12k patients in clinical trial.'
- }
- ]
+agent.addEventListener('agent:ready', () => {
+ agent.memory.write('portfolio', {
+ name: 'Portfolio projects',
+ description: 'Shipped projects with URLs, years, and outcomes',
+ type: 'project',
+ body: [
+ '## Acme Dashboard (2024) — yourname.com/work/acme',
+ 'Redesigned the main analytics dashboard, reducing time-to-insight by 40%.',
+ '',
+ '## Health App AR (2023) — yourname.com/work/health-ar',
+ 'AR overlay for physiotherapy exercises, used by 12k patients in a clinical trial.',
+ ].join('\n'),
});
- await agent.agent.memory.write('long-term', 'availability', {
- freelance: false,
- open_to: ['advisory', 'speaking', 'collaboration'],
- note: 'Back on the market Q4 2026.'
+ agent.memory.write('availability', {
+ name: 'Availability',
+ description: 'Freelance and collaboration status',
+ type: 'user',
+ body: 'Not available for freelance until Q4 2026. Open to advisory, speaking, and collaboration.',
});
});
```
@@ -54159,23 +57243,23 @@ Here is the full page. Replace the placeholder values in brackets and swap in yo
const input = document.getElementById('chat-input');
function ask(text) {
- agent.sendMessage(text);
+ agent.say(text);
}
function sendMessage() {
const text = input.value.trim();
if (!text) return;
input.value = '';
- agent.sendMessage(text);
+ agent.say(text);
}
input.addEventListener('keypress', e => {
if (e.key === 'Enter') sendMessage();
});
- agent.addEventListener('ready', () => {
+ agent.addEventListener('agent:ready', () => {
// Auto-greet after a short pause so the avatar has time to settle
- setTimeout(() => agent.sendMessage('__greet'), 2000);
+ setTimeout(() => agent.say('__greet'), 2000);
});
</script>
@@ -54185,6 +57269,8 @@ Here is the full page. Replace the placeholder values in brackets and swap in yo
The layout uses CSS Grid — left column for your static content, right column for the agent panel. On mobile it flips to a vertical stack with the agent taking the top 60% of the screen.
+`agent.say(text)` is the element's message-send method: it pushes the text into the agent's conversation exactly as if the visitor had typed it into the built-in chat. If you need the reply text back as a string (for your own UI), use `await agent.ask(text)` instead — same send, but it resolves with the assistant's response.
+
---
## Step 5: Configure the greeting
@@ -54314,39 +57400,25 @@ Add structured data to the `<head>`:
For the Open Graph image, generate a screenshot of your avatar against a clean background and save it as `maya-og.png`. The `og:image` tag in the full HTML above already references it.
-If you want to automate OG image generation:
-
-```js
-agent.addEventListener('ready', () => {
- setTimeout(async () => {
- const png = await agent.screenshot();
- // POST to your backend to store as the OG image
- // or pre-generate and commit it to your repo
- console.log('OG image captured, length:', png.length);
- }, 3000); // give the avatar time to finish its greeting pose
-});
-```
+The element has no screenshot API, so this is a one-time manual step rather than something you automate on page load: open your deployed page, let the greeting animation settle, and capture the agent panel with your browser's screenshot tooling. In Chrome DevTools, select the `<agent-3d>` element in the Elements panel, then run **Capture node screenshot** from the command menu (Cmd/Ctrl+Shift+P). Crop to 1200×630, commit the file next to `index.html`, and the meta tag does the rest. Re-capture whenever you change the avatar.
---
## Step 9: Analytics — understand what people ask
-Standard pageview analytics misses what matters most: what are people actually asking your agent? Add event tracking on agent responses:
+Standard pageview analytics misses what matters most: what are people actually asking your agent? The `brain:message` event fires for both sides of the conversation — once with `role: "user"` when a question goes in, once with `role: "assistant"` when the reply comes back — so a single listener tracks the whole exchange:
```js
-agent.addEventListener('agent-speak', e => {
- // e.detail.text is the full response — trim before sending
- if (typeof gtag !== 'undefined') {
- gtag('event', 'agent_response', {
- response_preview: e.detail.text.slice(0, 80)
- });
- }
-});
-
-agent.addEventListener('agent-message', e => {
- if (typeof gtag !== 'undefined') {
+agent.addEventListener('brain:message', e => {
+ const { role, content } = e.detail;
+ if (!content || typeof gtag === 'undefined') return;
+ if (role === 'user') {
gtag('event', 'user_question', {
- question_preview: e.detail.text.slice(0, 80)
+ question_preview: content.slice(0, 80)
+ });
+ } else if (role === 'assistant') {
+ gtag('event', 'agent_response', {
+ response_preview: content.slice(0, 80)
});
}
});
@@ -54406,7 +57478,7 @@ The technical investment is one HTML file, a GLB avatar, and a system prompt. Th
---
-<a id="sec-235"></a>
+<a id="sec-237"></a>
> **Source:** `docs/tutorials/place-agent-irl.md` · [↑ table of contents](#table-of-contents)
@@ -54651,7 +57723,7 @@ This is fundamentally different from viewing a single model in AR. If you only n
---
-<a id="sec-236"></a>
+<a id="sec-238"></a>
> **Source:** `docs/tutorials/prompts-for-3d.md` · [↑ table of contents](#table-of-contents)
@@ -54787,7 +57859,7 @@ The tiers are explained in detail in [the text-to-3D tutorial](/tutorials/text-t
---
-<a id="sec-237"></a>
+<a id="sec-239"></a>
> **Source:** `docs/tutorials/register-onchain.md` · [↑ table of contents](#table-of-contents)
@@ -55117,7 +58189,7 @@ Your agent's URL will keep working as long as Base exists and IPFS gateways serv
---
-<a id="sec-238"></a>
+<a id="sec-240"></a>
> **Source:** `docs/tutorials/self-host-agent-backend.md` · [↑ table of contents](#table-of-contents)
@@ -55127,6 +58199,8 @@ By the end of this tutorial you have a fully independent three.ws stack running
This is the heaviest tutorial in the Advanced tier. It's worth doing in full if you need data residency, custom compliance, fork-friendly customizations, or simply the freedom to ship a feature without waiting for the upstream maintainers.
+> **Note:** the hosted three.ws platform itself moved off Vercel to Google Cloud Run on 2026-07-07 (one container, `server/index.mjs`, deployed with `npm run deploy:gcp`). This tutorial keeps the Vercel path because it's the lowest-friction way to self-host a fork; everything here works the same, and `vercel.json` remains the live route table either way.
+
**What you'll build:**
- A local development setup running the full stack (front-end + Vercel functions + Cloudflare workers + database)
@@ -55172,7 +58246,7 @@ The platform is intentionally composed of small, independently deployable servic
**SDKs (`sdk/`, `agent-payments-sdk/`, `solana-agent-sdk/`).** Published as npm packages. These are not deployed; they're built and published independently for skill authors to consume.
-**CDN (`/cdn/agent-3d.js`).** A single-file embed bundle built by `npm run build` and served from the same Vercel deployment. Third-party sites embed this script tag and your domain ends up in their `<script src="...">`.
+**Embed bundle (`/agent-3d/<version>/agent-3d.js`, also `/dist-lib/agent-3d.js`).** The `<agent-3d>` custom-element bundle, built by `npm run build:lib` from `src/lib.js` into `dist-lib/` and served from the same deployment. Third-party sites load this script tag and your domain ends up in their `<script src="...">`.
Everything except the database and Cloudflare workers can live on a single Vercel project. The minimum production deployment is: 1 Vercel project, 1 Cloudflare worker, 1 Postgres database, 1 R2 bucket.
@@ -55399,17 +58473,19 @@ If you're running the Pump.fun feed, repeat for `workers/pump-fun-mcp/`.
Confirm the production build works before deploying:
```bash
-npm run build
+npm run build # Vite front-end into dist/
+npm run build:lib # <agent-3d> embed bundle into dist-lib/
```
+(`npm run build:all` runs both plus the chat sub-app build in one go.)
+
This builds:
-- The Vite front-end into `dist/`
-- The `agent-3d.js` CDN bundle into `dist/cdn/agent-3d.js`
-- The chat sub-app into `dist/chat/`
-- The artifact viewer into `dist/artifact-viewer/`
+- The Vite front-end into `dist/` (all page entries, plus everything in `public/` — including the artifact viewer at `dist/artifact/`)
+- The `<agent-3d>` embed bundle into `dist-lib/agent-3d.js` (ES module; `npm run build:lib:full` adds the UMD build)
+- The chat sub-app into `dist/chat/` (via `npm run build:chat`)
-Look at `dist/` — there should be an `index.html`, a hashed bundle, the `cdn/` folder, and the various sub-apps. If the build prints warnings about missing env vars (e.g., `VITE_*` vars that the front-end reads at build time), set them before re-running:
+Look at `dist/` — there should be an `index.html`, hashed bundles, and the various sub-apps, with the embed bundle in `dist-lib/`. If the build prints warnings about missing env vars (e.g., `VITE_*` vars that the front-end reads at build time), set them before re-running:
```bash
VITE_API_BASE=https://<your-domain>.vercel.app npm run build
@@ -55483,19 +58559,11 @@ See [deploy-to-vercel-custom-domain](/tutorials/deploy-to-vercel-custom-domain)
## Step 11 — Swap the CDN domain
-Up to this point, anyone embedding an agent from your platform is including `<script src="https://three.ws/cdn/agent-3d.js" ...>`. The script tag is generated by the editor's "Copy embed" button, which by default emits the three.ws URL.
-
-For *your* deployment, the embed should point at *your* CDN. Two changes:
-
-**1. Front-end build constant.** The embed-generator UI reads its CDN base from a build-time constant. Set `VITE_CDN_BASE` to your domain when building:
-
-```bash
-VITE_CDN_BASE=https://agent.yourcompany.com npm run build
-```
+Up to this point, anyone embedding an agent from your platform is loading the bundle from the platform's own origin. Two facts make the domain swap automatic:
-Re-deploy. Now every "Copy embed" output from your dashboard emits `<script src="https://agent.yourcompany.com/cdn/agent-3d.js" ...>`.
+**1. The embed generator derives its URL from the page origin.** The "Copy embed" output is built by `src/editor/publish.js`, which emits `` `${origin}/dist-lib/agent-3d.js` `` from the origin the dashboard is running on. Once your fork is served from `agent.yourcompany.com`, every copied snippet already points at your domain — no build constant to set.
-**2. The script itself self-locates.** Open `src/embed/agent-3d-bundle.js` (or the equivalent in your fork — the file the build emits to `dist/cdn/agent-3d.js`). The bundle reads its own `currentScript.src` to derive the API base for fetches. This means a third party who pastes your embed on `their-site.com` will have the script fetch agents from *your* domain, not theirs, and you can move infrastructure later without breaking existing embeds.
+**2. The bundle itself self-locates.** The element derives its API base from the script's own URL (`new URL(import.meta.url).origin`, see `src/element.js:123`), falling back to the page origin, and can be overridden per element with the `api-base` attribute. A third party who pastes your embed on `their-site.com` will have the script fetch agents from *your* domain, not theirs, and you can move infrastructure later without breaking existing embeds.
Verify with a smoke test: create a static HTML file and paste your embed:
@@ -55503,11 +58571,11 @@ Verify with a smoke test: create a static HTML file and paste your embed:
<!doctype html>
<html>
<body>
- <script
- src="https://agent.yourcompany.com/cdn/agent-3d.js"
- data-agent-id="your-test-agent-id"
- id="test-embed"
- ></script>
+ <script type="module" src="https://agent.yourcompany.com/dist-lib/agent-3d.js"></script>
+ <agent-3d
+ agent-id="your-test-agent-id"
+ style="width: 360px; height: 480px"
+ ></agent-3d>
</body>
</html>
```
@@ -55697,7 +58765,7 @@ A self-hosted instance with light traffic runs at $20–50/month all-in. The dom
---
-<a id="sec-239"></a>
+<a id="sec-241"></a>
> **Source:** `docs/tutorials/selfie-to-avatar.md` · [↑ table of contents](#table-of-contents)
@@ -55945,7 +59013,7 @@ The result is a standard `.glb` that animates in the [Animation Studio](/pose),
---
-<a id="sec-240"></a>
+<a id="sec-242"></a>
> **Source:** `docs/tutorials/share-your-agent.md` · [↑ table of contents](#table-of-contents)
@@ -56271,7 +59339,7 @@ The agent's URL is the durable handle. Embed it, link it, print it. The agent sh
---
-<a id="sec-241"></a>
+<a id="sec-243"></a>
> **Source:** `docs/tutorials/shopify-store-guide-advanced.md` · [↑ table of contents](#table-of-contents)
@@ -56581,7 +59649,7 @@ The clip URLs inside the manifest resolve **relative to the manifest**, so a sel
---
-<a id="sec-242"></a>
+<a id="sec-244"></a>
> **Source:** `docs/tutorials/shopify-store-guide.md` · [↑ table of contents](#table-of-contents)
@@ -56670,7 +59738,7 @@ It's powered by the open-source [`@three-ws/tour`](https://www.npmjs.com/package
---
-<a id="sec-243"></a>
+<a id="sec-245"></a>
> **Source:** `docs/tutorials/skill-with-database-auth.md` · [↑ table of contents](#table-of-contents)
@@ -57408,7 +60476,7 @@ Before this skill faces a real visitor:
---
-<a id="sec-244"></a>
+<a id="sec-246"></a>
> **Source:** `docs/tutorials/solana-agent-reputation.md` · [↑ table of contents](#table-of-contents)
@@ -57591,7 +60659,7 @@ A read costs nothing and asks no one's permission — which is exactly what lets
---
-<a id="sec-245"></a>
+<a id="sec-247"></a>
> **Source:** `docs/tutorials/sperax-tour.md` · [↑ table of contents](#table-of-contents)
@@ -57762,7 +60830,7 @@ This is covered by an automated test — [`tour-sdk/test/director.test.mjs`](htt
---
-<a id="sec-246"></a>
+<a id="sec-248"></a>
> **Source:** `docs/tutorials/swap-avatar-in-studio.md` · [↑ table of contents](#table-of-contents)
@@ -57869,13 +60937,11 @@ When you save a new body in Studio, the only field that changes in that record i
This is the crucial property. Your embed snippet is:
```html
-<script
- src="https://three.ws/cdn/agent-3d.js"
- data-agent-id="YOUR_AGENT_ID"
-></script>
+<script type="module" src="https://three.ws/agent-3d/latest/agent-3d.js"></script>
+<agent-3d agent-id="YOUR_AGENT_ID" mode="floating"></agent-3d>
```
-There is no body URL in this snippet. The script tag references the agent by its ID, and the embed loader fetches the current body URL from the platform every time a visitor loads the page. When you swap the body in Studio, the next page load returns the new body. The customer site doesn't need to be re-deployed, the snippet doesn't need to be edited, the cached HTML on Cloudflare doesn't need to be purged.
+There is no body URL in this snippet. The `<agent-3d>` element references the agent by its ID, and the embed runtime fetches the current body URL from the platform every time a visitor loads the page. When you swap the body in Studio, the next page load returns the new body. The customer site doesn't need to be re-deployed, the snippet doesn't need to be edited, the cached HTML on Cloudflare doesn't need to be purged.
This is by design and it's worth pausing on, because it changes how you operate at scale. You can:
@@ -58024,7 +61090,7 @@ The key insight is the snippet's stability. Once embedded, your customers' pages
---
-<a id="sec-247"></a>
+<a id="sec-249"></a>
> **Source:** `docs/tutorials/text-to-3d.md` · [↑ table of contents](#table-of-contents)
@@ -58146,7 +61212,7 @@ This is normal — prompt, generate, adjust, repeat is the workflow, not a failu
---
-<a id="sec-248"></a>
+<a id="sec-250"></a>
> **Source:** `docs/tutorials/trigger-from-page-events.md` · [↑ table of contents](#table-of-contents)
@@ -58184,7 +61250,7 @@ Every recipe in this tutorial assumes you have an agent on the page. The simples
section:nth-child(even) { background: #fff; }
h2 { font-size: 2rem; margin: 0 0 16px; letter-spacing: -0.02em; }
</style>
- <script type="module" src="https://three.ws/cdn/agent-3d.js"></script>
+ <script type="module" src="https://three.ws/agent-3d/latest/agent-3d.js"></script>
</head>
<body>
<section><h2>Hero</h2><p>Headline copy here.</p></section>
@@ -58650,7 +61716,7 @@ The pattern under all of these is the same: every recipe starts with `whenReady(
---
-<a id="sec-249"></a>
+<a id="sec-251"></a>
> **Source:** `docs/tutorials/upload-custom-glb.md` · [↑ table of contents](#table-of-contents)
@@ -59014,11 +62080,11 @@ Once uploaded:
4. In a browser console, fire each clip by name:
```js
-const agent = document.querySelector('agent-3d') || document.querySelector('[data-agent-id]');
-await agent.wave();
-agent.playAnimationByHint('cheer');
-agent.playAnimationByHint('talk');
-agent.playAnimationByHint('idle');
+const agent = document.querySelector('agent-3d');
+agent.wave();
+agent.play('Cheer'); // exact clip name (case-insensitive fallback); returns false if missing
+agent.play('Talk');
+agent.play('Idle');
```
Each one should trigger the corresponding clip. If a clip you expect doesn't fire, run `agent._scene.clips.map(c => c.name)` in the console — that prints the actual clip names the runtime sees. Compare against the names you set in Step 9.
@@ -59046,7 +62112,7 @@ Once the body is on the platform, the embed snippet doesn't change. The same `<a
---
-<a id="sec-250"></a>
+<a id="sec-252"></a>
> **Source:** `docs/tutorials/view-in-ar.md` · [↑ table of contents](#table-of-contents)
@@ -59221,7 +62287,7 @@ AR surface detection needs a moment to work. Move the phone slowly over the targ
---
-<a id="sec-251"></a>
+<a id="sec-253"></a>
> **Source:** `docs/tutorials/voice-and-lipsync.md` · [↑ table of contents](#table-of-contents)
@@ -59452,7 +62518,7 @@ The leverage is that the avatar drives its mouth from the *audio it actually pla
---
-<a id="sec-252"></a>
+<a id="sec-254"></a>
> **Source:** `docs/tutorials/walk-companion.md` · [↑ table of contents](#table-of-contents)
@@ -59556,7 +62622,7 @@ The `allow="accelerometer; gyroscope"` attribute lets the joystick respond to de
## Step 2: Drive the embed from the host page (postMessage)
-The embed isn't a black box — it speaks a versioned `postMessage` contract so your page can tell the avatar where to walk, what to say, and which environment to show. The contract is defined in [src/walk-embed-events.js](src/walk-embed-events.js) and documented interactively at [/docs/walk-embed-api](/docs/walk-embed-api).
+The embed isn't a black box — it speaks a versioned `postMessage` contract so your page can tell the avatar where to walk, what to say, and which environment to show. The contract is defined in [src/walk-embed-events.js](../../src/walk-embed-events.js) and documented interactively at [/docs/walk-embed-api](/docs/walk-embed-api).
Every message is namespaced to the `three-walk` channel and carries a protocol version, so it never collides with other `message` listeners on your page.
@@ -59805,15 +62871,15 @@ The leverage is composability: the same engine renders the corner mascot, the fu
---
-<a id="sec-253"></a>
+<a id="sec-255"></a>
> **Source:** `docs/tutorials/web-component-end-to-end.md` · [↑ table of contents](#table-of-contents)
# Use the &lt;agent-3d&gt; web component end-to-end
-The script tag is convenient. One line, agent on the page. But once your site has a component system — React, Vue, Svelte, a design system — that single-line script starts to feel like a stranger in the codebase. You want the agent to be a real component, with props, refs, lifecycle, and a place in your component library.
+The iframe snippet is convenient. Paste it, agent on the page. But once your site has a component system — React, Vue, Svelte, a design system — that opaque iframe starts to feel like a stranger in the codebase. You want the agent to be a real component, with props, refs, lifecycle, and a place in your component library.
-That's what `<agent-3d>` is for. It's a standards-based custom element that drops cleanly into any framework, gives you the same JavaScript API the script tag uses under the hood, and supports reactive attribute changes — you can swap the loaded agent at runtime by changing one prop.
+That's what `<agent-3d>` is for. It's a standards-based custom element that drops cleanly into any framework, exposes the full JavaScript API (methods, events, live attributes), and supports reactive attribute changes — you can swap the loaded agent at runtime by changing one prop.
By the end of this tutorial you'll know the spec well enough to pick the right embed style for any project, wire the element into React and Vue with refs and reactivity, slot your own UI alongside the avatar, and react to attribute changes after mount.
@@ -59838,41 +62904,48 @@ A custom element is a tag your browser doesn't ship by default. Someone (us, in
Three things make custom elements powerful:
1. **Attributes are the API.** Like `<input type="text">`, you configure the element with HTML attributes. The element watches the ones it cares about (via `observedAttributes`) and reacts when they change.
-2. **Methods and properties.** Once you have an element reference, you can call methods on it (`el.speak('hi')`) and read/set properties just like any DOM node.
+2. **Methods and properties.** Once you have an element reference, you can call methods on it (`el.say('hi')`) and read/set properties just like any DOM node.
3. **Events.** The element dispatches custom events you subscribe to with `addEventListener`. These bubble out of the shadow DOM so framework event handlers can pick them up.
-`<agent-3d>` uses all three. It's registered to the global `customElements` registry the moment the CDN script loads:
+`<agent-3d>` uses all three. It's registered to the global `customElements` registry the moment the runtime script loads:
```html
-<script type="module" src="https://three.ws/cdn/agent-3d.js"></script>
+<script type="module" src="https://three.ws/agent-3d/1.5.2/agent-3d.js"></script>
```
From that point on, `<agent-3d>` is a real tag in the document. No further setup needed.
---
-## Step 2 — Script-tag embed vs the custom element
+## Step 2 — iframe embed vs the custom element
-The CDN exposes two forms of the same thing. They share the underlying code and the same JS API. The differences are ergonomic.
+The platform offers two embed styles for the same agent. The differences are ergonomic.
-**Script-tag form** — terse, declarative, one line. The script tag *is* the agent:
+**iframe form** — sandboxed, self-contained, no script tag on your page:
```html
-<script src="https://three.ws/cdn/agent-3d.js" data-agent-id="YOUR_AGENT_ID" id="my-agent"></script>
+<iframe
+ src="https://three.ws/a/8453/42/embed"
+ width="320"
+ height="420"
+ frameborder="0"
+ allow="microphone"
+ style="border-radius: 16px;"
+></iframe>
```
-The script tag mounts an `<agent-3d>` element in place of itself. Data attributes on the script tag (`data-size`, `data-position`, `data-greeting`, etc.) become attributes on the mounted element. You get a reference to the resulting element with `document.getElementById('my-agent')`.
+The agent runs entirely inside the iframe. You can't call methods on it or listen to its events from your page — the trade for that isolation is zero integration surface.
This is the right embed when:
-- You're on a no-code platform (Webflow, Squarespace, Substack) where you can paste a snippet but not a complex HTML tree
-- You want a single line in your repo
-- You're not using a framework that needs JSX or template syntax
+- You're on a no-code platform (Webflow, Squarespace, Notion, Substack) where you can paste a snippet but not control the `<head>`
+- You want strict sandboxing between the agent and your page
+- You don't need to drive the agent from your own JavaScript
**Custom element form** — explicit, structured, framework-friendly:
```html
-<script type="module" src="https://three.ws/cdn/agent-3d.js"></script>
+<script type="module" src="https://three.ws/agent-3d/1.5.2/agent-3d.js"></script>
<agent-3d
agent-id="YOUR_AGENT_ID"
@@ -59883,15 +62956,15 @@ This is the right embed when:
></agent-3d>
```
-You separate "load the runtime" from "place the agent". The agent can appear anywhere in your tree, with explicit attributes you can read from a build system, type-check, or template.
+You separate "load the runtime" from "place the agent". The agent can appear anywhere in your tree, with explicit attributes you can read from a build system, type-check, or template — and you get the full JS API: `say()`, `ask()`, `wave()`, `play()`, and the event stream.
This is the right embed when:
-- You're inside a framework where `<script>` injection feels wrong (React, Vue, Angular, Svelte)
+- You're inside a framework with a component tree (React, Vue, Angular, Svelte)
- You want multiple agents on the same page
-- You need precise control over the surrounding DOM
+- You need to call the agent's methods or subscribe to its events
-The rest of this tutorial uses the custom-element form, because that's the one that benefits from a wrapper.
+The rest of this tutorial uses the custom-element form, because that's the one that benefits from a wrapper. (The [embedding guide](./embed-on-website.md) covers the iframe path and the no-code platforms in depth.)
---
@@ -59927,13 +63000,11 @@ Here's the full list of attributes the element observes, in the categories you'l
| `voice` | Set to `livekit` to opt into LiveKit-backed real-time voice |
| `avatar-chat` | Set to `off` to hide the built-in chat input |
| `avatar-walk` | Set to `off` to disable the walk-when-talking behaviour |
-| `face-camera` | Lock the avatar to face the camera |
+| `framing` | Set to `portrait` for a head-and-shoulders camera framing; the default frames the full body |
| `eager` | Skip the lazy-load wait — boot immediately even when off-screen |
| `api-key` | Override the brain API key (use sparingly; backends are safer) |
| `key-proxy` | URL of your own proxy that vends scoped keys |
-**Data attributes from the script-tag form** — `data-size`, `data-background-color`, `data-position`, `data-rotation-speed`, `data-greeting`, `data-name` — all map onto the equivalent regular attributes when the script tag mounts the element. If you're using the element form directly, drop the `data-` prefix.
-
Every observed attribute can be changed after mount. Step 6 shows what that looks like in practice.
---
@@ -59963,7 +63034,7 @@ function ensureRuntime() {
if (existing) { resolve(); return; }
const s = document.createElement('script');
s.type = 'module';
- s.src = 'https://three.ws/cdn/agent-3d.js';
+ s.src = 'https://three.ws/agent-3d/1.5.2/agent-3d.js';
s.dataset.agent3dRuntime = '';
s.onload = resolve;
s.onerror = reject;
@@ -59979,7 +63050,6 @@ export default function Agent3D({
position = 'bottom-right',
background = 'transparent',
mode = 'inline',
- greeting,
name,
onReady,
onMessage,
@@ -60024,8 +63094,7 @@ export default function Agent3D({
mode={mode}
position={position}
background={background}
- data-greeting={greeting}
- data-name={name}
+ name={name}
/>
);
}
@@ -60059,7 +63128,7 @@ A few notes on what the wrapper does:
- **Runtime loaded once.** `ensureRuntime()` guards against re-injecting the script on every mount. It checks for an existing tag with `data-agent-3d-runtime` and resolves immediately if found.
- **Events bound in `useEffect`.** Custom event names map to props (`onReady`, `onMessage`). The cleanup function unbinds them, so the wrapper plays nicely with strict mode and unmount.
- **No camelCase attribute names.** Custom elements use dash-case (`agent-id`, not `agentId`). React passes attributes through as-is — `agent-id` is fine in JSX.
-- **`useRef` is the API handle.** If you need to call `ref.current.speak('hi')` from a parent, expose the ref via `forwardRef` or pass an `apiRef` prop in.
+- **`useRef` is the API handle.** If you need to call `ref.current.say('hi')` from a parent, expose the ref via `forwardRef` or pass an `apiRef` prop in.
For TypeScript, drop this in a `.d.ts`:
@@ -60139,7 +63208,7 @@ const eventMap = [
const handlers = [];
onMounted(async () => {
- await import('https://three.ws/cdn/agent-3d.js');
+ await import('https://three.ws/agent-3d/1.5.2/agent-3d.js');
const el = root.value;
if (!el) return;
for (const [domEvent, vueEvent] of eventMap) {
@@ -60157,11 +63226,10 @@ onBeforeUnmount(() => {
defineExpose({
// Forward common methods so the parent can call them via template refs.
- speak: (text) => root.value?.speak(text),
say: (text) => root.value?.say(text),
+ ask: (text) => root.value?.ask(text),
wave: () => root.value?.wave(),
- playAnimation: (name) => root.value?.play(name),
- playAnimationByHint: (hint) => root.value?.playAnimationByHint?.(hint),
+ playAnimation: (name, opts) => root.value?.play(name, opts),
});
</script>
@@ -60189,7 +63257,7 @@ const agent = ref(null);
function onReady(detail) {
console.log('Agent ready:', detail.manifest?.name);
- agent.value.speak('Welcome in.');
+ agent.value.say('Greet the visitor with a one-sentence welcome.');
}
function onMessage(detail) {
@@ -60209,7 +63277,7 @@ function onMessage(detail) {
</template>
```
-The `defineExpose` block matters: without it, the parent's `agent.value.speak(...)` would be undefined. Vue 3 SFCs are private by default, and you have to opt methods into the public surface.
+The `defineExpose` block matters: without it, the parent's `agent.value.say(...)` would be undefined. Vue 3 SFCs are private by default, and you have to opt methods into the public surface.
---
@@ -60304,7 +63372,7 @@ Two parts to this.
if (!text) return;
input.value = '';
try {
- await agent.say(text);
+ await agent.ask(text);
} catch (err) {
console.error('Agent failed:', err);
}
@@ -60387,7 +63455,7 @@ Pick an agent from the dropdown, the active one swaps in place, and the event lo
You can now treat `<agent-3d>` as a real component in any framework. The big takeaways:
-- The script-tag and custom-element forms are interchangeable — pick by ergonomics, not features
+- The iframe and custom-element embeds serve different jobs — sandboxed drop-in vs a full-API component; reach for the element whenever your own code needs to drive the agent
- Attribute changes are reactive; you can swap agents, modes, and layouts at runtime
- React works fine once you bind events in `useEffect`; remember dash-case attribute names
- Vue works fine once you flag the tag as a custom element in the compiler config
@@ -60404,7 +63472,7 @@ The web component is the most robust integration point the platform offers. Buil
---
-<a id="sec-254"></a>
+<a id="sec-256"></a>
> **Source:** `docs/ui-juice.md` · [↑ table of contents](#table-of-contents)
@@ -60566,7 +63634,7 @@ should reach for these primitives rather than re-rolling RAF loops.
---
-<a id="sec-255"></a>
+<a id="sec-257"></a>
> **Source:** `docs/ux-flows/01-onboarding-creation.md` · [↑ table of contents](#table-of-contents)
@@ -60772,7 +63840,7 @@ should reach for these primitives rather than re-rolling RAF loops.
---
-<a id="sec-256"></a>
+<a id="sec-258"></a>
> **Source:** `docs/ux-flows/02-forge-text-to-3d.md` · [↑ table of contents](#table-of-contents)
@@ -60942,7 +64010,7 @@ Routing facts (from `vercel.json`):
---
-<a id="sec-257"></a>
+<a id="sec-259"></a>
> **Source:** `docs/ux-flows/03-3d-editing-viewer.md` · [↑ table of contents](#table-of-contents)
@@ -61148,7 +64216,7 @@ Routing summary (from `vite.config.js`):
---
-<a id="sec-258"></a>
+<a id="sec-260"></a>
> **Source:** `docs/ux-flows/04-embed-widget-studio.md` · [↑ table of contents](#table-of-contents)
@@ -61322,7 +64390,7 @@ Routing recap (from `vercel.json`):
---
-<a id="sec-259"></a>
+<a id="sec-261"></a>
> **Source:** `docs/ux-flows/05-discovery-social.md` · [↑ table of contents](#table-of-contents)
@@ -61593,7 +64661,7 @@ Routing recap (from `vercel.json`):
---
-<a id="sec-260"></a>
+<a id="sec-262"></a>
> **Source:** `docs/ux-flows/06-marketplace-skills.md` · [↑ table of contents](#table-of-contents)
@@ -61807,7 +64875,7 @@ Routing facts confirmed in `vercel.json`:
---
-<a id="sec-261"></a>
+<a id="sec-263"></a>
> **Source:** `docs/ux-flows/07-crypto-trading-analytics.md` · [↑ table of contents](#table-of-contents)
@@ -62156,7 +65224,7 @@ coin-intel, pump-visualizer and pump-live — adding a coin on any surface shows
---
-<a id="sec-262"></a>
+<a id="sec-264"></a>
> **Source:** `docs/ux-flows/08-coin-launch-wallets.md` · [↑ table of contents](#table-of-contents)
@@ -62429,7 +65497,7 @@ real Solana/EVM RPC, pump.fun, and x402 — no mocks.
---
-<a id="sec-263"></a>
+<a id="sec-265"></a>
> **Source:** `docs/ux-flows/09-x402-agent-commerce.md` · [↑ table of contents](#table-of-contents)
@@ -62771,7 +65839,7 @@ choreographed two-agent narrative driven by Server-Sent Events.
---
-<a id="sec-264"></a>
+<a id="sec-266"></a>
> **Source:** `docs/ux-flows/10-chat-brain-labs.md` · [↑ table of contents](#table-of-contents)
@@ -63013,7 +66081,7 @@ modules. Routes resolved via `vercel.json` rewrites.
---
-<a id="sec-265"></a>
+<a id="sec-267"></a>
> **Source:** `docs/ux-flows/11-account-dashboard.md` · [↑ table of contents](#table-of-contents)
@@ -63232,7 +66300,7 @@ Shared auth concepts:
---
-<a id="sec-266"></a>
+<a id="sec-268"></a>
> **Source:** `docs/ux-flows/12-home-and-content.md` · [↑ table of contents](#table-of-contents)
@@ -63420,7 +66488,7 @@ All `/.well-known/*` and `/openapi.json` / `/sitemap.xml` responses are JSON/XML
---
-<a id="sec-267"></a>
+<a id="sec-269"></a>
> **Source:** `docs/validation.md` · [↑ table of contents](#table-of-contents)
@@ -63768,7 +66836,7 @@ The toggle's CSS class reflects the highest severity: `level-0` (errors), `level
---
-<a id="sec-268"></a>
+<a id="sec-270"></a>
> **Source:** `docs/vanity.md` · [↑ table of contents](#table-of-contents)
@@ -63999,7 +67067,7 @@ challenges and the discovery doc stay in parity.
---
-<a id="sec-269"></a>
+<a id="sec-271"></a>
> **Source:** `docs/viewer.md` · [↑ table of contents](#table-of-contents)
@@ -64369,7 +67437,7 @@ State is persisted to `localStorage` per agent ID when `attachScenePrefs(agentId
---
-<a id="sec-270"></a>
+<a id="sec-272"></a>
> **Source:** `docs/web-component.md` · [↑ table of contents](#table-of-contents)
@@ -64435,15 +67503,12 @@ Using `body` with no manifest creates an ad-hoc agent. Its name, instructions, a
| Attribute | Type | Default | Description |
|-----------|------|---------|-------------|
-| `environment` | preset name or HDRI URL | `neutral` | IBL environment. Accepts built-in preset names or an HDRI URL. |
-| `auto-rotate` | boolean | off | Slowly rotates the model around the Y-axis. |
-| `camera-controls` | boolean | off | Enables orbit, pan, and zoom with mouse/touch. |
-| `ar` | boolean | off | Shows an AR launch button. Automatically selects the best available method: iOS Quick Look (Safari), Android Scene Viewer (Chrome), or WebXR immersive-ar. Button is hidden on desktop and on unsupported browsers. Requires HTTPS. See [AR & WebXR guide](/docs/ar). |
-| `shadows` | boolean | on | Enables contact and soft shadows. |
-| `exposure` | number | `1.0` | Tone-mapping exposure multiplier. |
| `background` | `transparent` \| `dark` \| `light` | `transparent` | Canvas clear color. `transparent` lets the page background show through. |
-| `skybox` | URL | — | HDRI rendered as visible sky behind the model. |
| `poster` | URL | — | Image shown while the model loads. Fades out on completion. |
+| `framing` | `full` \| `portrait` | `full` | Camera framing. `portrait` frames the head and shoulders. |
+| `clip` | clip name | — | Animation clip to play on load. |
+
+Lighting, camera orbit, and environment are managed by the built-in viewer; they are not attribute-configurable. For AR placement, use the dedicated AR surfaces described in [AR](#ar) below.
### Brain (LLM runtime)
@@ -64453,23 +67518,18 @@ Using `body` with no manifest creates an ad-hoc agent. Its name, instructions, a
| `instructions` | URL or inline text | from manifest | System prompt. Can be a URL ending in `.md` or an inline string. Overrides `manifest.brain.instructions`. |
| `api-key` | string | — | API key injected directly. **Development use only.** Prefer `key-proxy` for any page that will be public. |
| `key-proxy` | URL | — | URL of your backend that injects API keys into outbound LLM requests. |
-| `thinking` | `auto` \| `always` \| `never` | `auto` | Extended thinking hint passed to the provider. |
### Voice
| Attribute | Type | Default | Description |
|-----------|------|---------|-------------|
-| `voice` | boolean | on if manifest configures voice | Master on/off switch for speech I/O. |
-| `tts` | provider ID | `browser` | Text-to-speech provider. Overrides the manifest. |
-| `stt` | provider ID | `browser` | Speech-to-text provider. Overrides the manifest. |
-| `mic` | `push-to-talk` \| `continuous` \| `off` | `push-to-talk` | Microphone activation policy. |
+| `voice` | string | on if manifest configures voice | Voice mode. Set to `livekit` for the LiveKit realtime voice pipeline; TTS/STT providers otherwise come from the manifest. |
### Skills and memory
| Attribute | Type | Default | Description |
|-----------|------|---------|-------------|
-| `skills` | comma-separated URIs | — | Additional skill URIs to install on top of (or instead of) manifest skills. |
-| `skills-only` | boolean | off | When set, ignores manifest skills and uses only the `skills` attribute. |
+| `skills` | comma-separated URIs | — | Additional skill URIs to install on top of manifest skills. |
| `skill-trust` | `any` \| `whitelist` \| `owned-only` | from manifest | Controls which skill URIs are allowed to install. `owned-only` allows only skills whose author matches the agent's `ownerAddress`. |
| `memory` | `local` \| `ipfs` \| `encrypted-ipfs` \| `none` | from manifest | Memory storage mode. |
| `memory-key` | string | agent ID or name | Namespace under which memory is persisted. Useful when embedding the same agent in multiple contexts. |
@@ -64489,7 +67549,6 @@ Using `body` with no manifest creates an ad-hoc agent. Its name, instructions, a
| Attribute | Type | Description |
|-----------|------|-------------|
-| `chain` | `base` \| `base-sepolia` \| `ethereum` | Overrides the chain in `src="agent://…"`. |
| `chain-id` | number | Numeric chain ID, e.g. `8453`. Required when `agent-id` is a bare number. |
| `registry` | `0x` address | Override the deployed registry contract (for CAIP-10 precision). |
@@ -64499,7 +67558,6 @@ Using `body` with no manifest creates an ad-hoc agent. Its name, instructions, a
|-----------|-------------|
| `eager` | Boot immediately on DOM connection, bypassing the IntersectionObserver lazy-load. |
| `kiosk` | Hides all UI chrome: chat input, mic button, validator panel, editor links. Use for display contexts where end users should not interact. |
-| `debug` | Overlays scene graph stats, tool-call log, and memory inspector in the shadow DOM. |
| `name-plate` | Controls the name overlay. Set to `"off"` to hide it. |
---
@@ -64758,32 +67816,14 @@ All events bubble and are `composed: true`, meaning they cross shadow DOM bounda
|-------|--------|------|
| `memory:write` | `{ key, type }` | A memory entry was written. |
-### AR events
-
-| Event | Detail | When |
-|-------|--------|------|
-| `ar-status` | `{ status }` | AR session lifecycle. `status` is one of `"session-started"`, `"object-placed"`, `"failed"`, `"not-presenting"`. |
+### AR
-```js
-el.addEventListener('ar-status', (e) => {
- if (e.detail.status === 'object-placed') {
- console.log('Agent anchored in real world');
- }
-});
-```
+`<agent-3d>` itself does not expose an AR API. AR placement lives on the platform's dedicated AR surfaces:
-**`el.canActivateAR`** — boolean property. `true` when the model is loaded and at least one AR method (Quick Look, Scene Viewer, or WebXR) is available on the current device. Always `false` on desktop.
+- **`/avatars/:id/ar`** — every avatar has a full-screen AR page. It selects the right method per device automatically: iOS Quick Look (with in-browser GLB→USDZ conversion when no pre-generated USDZ exists), Android Scene Viewer, or WebXR.
+- **Viewer AR button** — the avatar viewer and Forge result toolbar include a **View in AR** control; on desktop it shows a QR code that opens the AR session on a phone.
-**`el.activateAR()`** — async method. Triggers the best available AR method. Resolves when the session starts (WebXR) or immediately (Quick Look / Scene Viewer). Throws if `canActivateAR` is `false`.
-
-```js
-const el = document.querySelector('agent-3d');
-if (el.canActivateAR) {
- await el.activateAR();
-}
-```
-
-For full API reference, platform compatibility, and troubleshooting, see the [AR & WebXR guide](/docs/ar).
+To offer AR from a page that embeds the component, link to the avatar's `/avatars/:id/ar` page. For methods, platform compatibility, and troubleshooting, see the [AR & WebXR guide](/docs/ar).
### Listening example
@@ -65001,7 +68041,6 @@ The `kiosk` attribute strips all interactive chrome: the chat input, mic button,
<agent-3d
src="agent://base/42"
kiosk
- auto-rotate
style="width:100%;height:600px"
></agent-3d>
```
@@ -65313,7 +68352,7 @@ defineElement('my-agent');
---
-<a id="sec-271"></a>
+<a id="sec-273"></a>
> **Source:** `docs/widget-api.md` · [↑ table of contents](#table-of-contents)
@@ -65442,7 +68481,6 @@ Notifications (no `id`) sent to the parent over `postMessage`:
|-------------------|--------------------------------------|------------|
| `viewer.ready` | `{}` | First successful model frame. |
| `model.loaded` | `{ url, success, error? }` | After every `model.load` (success or failure). |
-| `widget.revealed` | `{ mode: 'auto' \| 'interaction' }` | Visitor clicked the play button (interaction mode) or auto mode booted. |
### Wire format
@@ -65512,7 +68550,7 @@ If you have multiple widgets and want to coordinate them (sync camera, broadcast
---
-<a id="sec-272"></a>
+<a id="sec-274"></a>
> **Source:** `docs/widget-studio.md` · [↑ table of contents](#table-of-contents)
@@ -65765,7 +68803,7 @@ You can override these freely in the iframe `width` and `height` attributes. Add
---
-<a id="sec-273"></a>
+<a id="sec-275"></a>
> **Source:** `docs/widgets.md` · [↑ table of contents](#table-of-contents)
@@ -66274,7 +69312,7 @@ Need to drive a widget from the parent page — change the camera, play an anima
---
-<a id="sec-274"></a>
+<a id="sec-276"></a>
> **Source:** `docs/x402-buyer.md` · [↑ table of contents](#table-of-contents)
@@ -66376,7 +69414,7 @@ set) back into the payment so attribution survives the round trip.
---
-<a id="sec-275"></a>
+<a id="sec-277"></a>
> **Source:** `docs/x402-dev-tools.md` · [↑ table of contents](#table-of-contents)
@@ -66570,7 +69608,7 @@ implementation against a live server.
---
-<a id="sec-276"></a>
+<a id="sec-278"></a>
> **Source:** `docs/x402-endpoints.md` · [↑ table of contents](#table-of-contents)
@@ -66782,7 +69820,7 @@ input and do not promote any specific token.
---
-<a id="sec-277"></a>
+<a id="sec-279"></a>
> **Source:** `docs/x402-revenue.md` · [↑ table of contents](#table-of-contents)
@@ -67140,7 +70178,7 @@ settled activity (include it), and label it as such.
---
-<a id="sec-278"></a>
+<a id="sec-280"></a>
> **Source:** `docs/x402-ring-economy.md` · [↑ table of contents](#table-of-contents)
@@ -67866,7 +70904,7 @@ curl -s -H "Authorization: Bearer $CRON_SECRET" \
---
-<a id="sec-279"></a>
+<a id="sec-281"></a>
> **Source:** `docs/x402.md` · [↑ table of contents](#table-of-contents)
@@ -68042,7 +71080,7 @@ Each package has its own repository with a full README, API reference, and examp
---
-<a id="sec-280"></a>
+<a id="sec-282"></a>
> **Source:** `docs/zauth/database.md` · [↑ table of contents](#table-of-contents)
@@ -68188,7 +71226,7 @@ Use this endpoint to browse all known x402 endpoints before your agents commit t
---
-<a id="sec-281"></a>
+<a id="sec-283"></a>
> **Source:** `docs/zauth/index.md` · [↑ table of contents](#table-of-contents)
@@ -68212,7 +71250,7 @@ zauth is the security and trust layer that allows agents to act with confidence,
---
-<a id="sec-282"></a>
+<a id="sec-284"></a>
> **Source:** `docs/zauth/provider-hub.md` · [↑ table of contents](#table-of-contents)
@@ -68314,7 +71352,7 @@ Supply your EVM or Solana private keys to enable automatic refunds when your end
---
-<a id="sec-283"></a>
+<a id="sec-285"></a>
> **Source:** `docs/zauth/reposcan.md` · [↑ table of contents](#table-of-contents)
@@ -68640,7 +71678,7 @@ TypeScript -@x402/fetch
---
-<a id="sec-284"></a>
+<a id="sec-286"></a>
> **Source:** `docs/zauth/vector.md` · [↑ table of contents](#table-of-contents)
diff --git a/docs/api-reference.md b/docs/api-reference.md
index 0a81ccc99..569a12989 100644
--- a/docs/api-reference.md
+++ b/docs/api-reference.md
@@ -2600,6 +2600,7 @@ Aggregates the native publisher RSS/Atom registry
| `source` | A single source key. Overrides `category` and `lang`. |
| `lang` | `en` (default), any registry language, or `all`. The registry carries international feeds; they are opt-in so the default feed does not interleave languages. Unknown values return `400 bad_language`. |
| `q` | Full-text over title, description, and tickers. |
+| `featured` | `1` narrows sources to the majors (tier1/tier2 upstream or credibility ≥ 0.85 — CoinDesk, The Block, Decrypt, Blockworks, The Defiant, and the mainstream desks). Backs the Featured tab on `/markets/news`. |
| `limit` | ≤ 50 (default 30). |
| `offset` | Pagination offset. |
@@ -2607,8 +2608,27 @@ Returns `{ articles: [{ id, title, link, description, image, author, source,
source_key, category, pub_date, tickers[], sentiment: { score, label,
confidence } }], total, limit, offset, lang, sources_ok, sources_total,
fetched_at }`. With `meta=1` it also returns `categories[]`, `languages[]`,
-and the `sources[]` registry (each with `key`, `name`, `category`, and
-`language` where the feed is not English).
+and the `sources[]` registry (each with `key`, `name`, `category`, `tier`
+where the upstream registry carries one, and `language` where the feed is not
+English).
+
+### Preview-image resolver
+
+```
+GET /api/news/image?url=<article link>
+```
+
+Preview image for an article whose publisher feed ships no image (~20% of the
+live feed publishes text-only RSS). The `url` must be an article currently
+served by the aggregator — anything else answers `404 unknown_article` without
+touching the network. The endpoint fetches the publisher page server-side
+(SSRF-guarded, 6 s timeout, 768 KB cap), extracts its `og:image` /
+`twitter:image`, and answers `302` to the same-origin `/api/img` proxy — so the
+final bytes are immune to hotlink-referrer blocking. If the page carries no
+preview image it answers `404 no_preview_image`; both outcomes are cached
+in-process and at the CDN, so an article costs at most one upstream fetch. The
+news cards on [/markets/news](https://three.ws/markets/news) call this in the
+background and keep their designed source-initials tile when it 404s.
Every feed in the registry was fetched and parsed before being listed — see
`scripts/news-sources-probe.mjs`, which re-validates the registry and exits
@@ -2648,6 +2668,13 @@ Base; operators override via `X402_PRICE_NEWS_ARCHIVE`). Repeat the same
requests arriving with `X-PAYMENT` skip the free quota entirely. `?stats=true`
reports the live terms under `search_access`.
+**Premium pass (monthly):** skip per-call payments entirely with the
+[Premium pass](/docs/premium) — $9.99/30 days on Solana in $THREE (20% off),
+SOL, or USDC. It mints an `x402_live_…` API key (send as `X-API-Key`) and a
+wallet-signature (SIWX) grant for browsers. Buy at
+[/dashboard/data-api](/dashboard/data-api) or over the raw API
+(`/api/premium/plans` → `quote` → `subscribe`).
+
### Daily digest
```
diff --git a/docs/coin-pages.md b/docs/coin-pages.md
index aaf3328ec..484478003 100644
--- a/docs/coin-pages.md
+++ b/docs/coin-pages.md
@@ -194,16 +194,34 @@ and a latest-news rail with an archive teaser. Five already-cached endpoints
feed it: `/api/coin/global`, `/api/coin/markets`, `/api/coin/gas`,
`/api/news/feed`, `/api/news/archive?stats=true`.
-### `/markets/news` — live crypto news
-
-Live headlines aggregated **natively** by three.ws from 38 publisher RSS/Atom
-feeds (CoinDesk, The Block, Decrypt, CoinTelegraph, Blockworks, SEC press,
-Forkast, and more — the registry lives in
-[`api/_lib/news-sources.js`](../api/_lib/news-sources.js)). Category tabs
-(Bitcoin, Ethereum, Solana, DeFi, NFT, trading, research, on-chain,
-institutional, mainstream, Asia, regulation, journalism), debounced search, a
-per-source filter, a lead-story hero, sentiment dots, and ticker chips that
-pivot the feed to that symbol. Each source is cached server-side for 5 minutes
+### `/markets/news` — "Your briefing"
+
+The front page of the news wing, laid out as a daily briefing over headlines
+aggregated **natively** by three.ws from the publisher RSS/Atom registry
+(CoinDesk, The Block, Decrypt, CoinTelegraph, Blockworks, SEC press, Forkast,
+and more — [`api/_lib/news-sources.js`](../api/_lib/news-sources.js)):
+
+- **Primary tabs** — Featured (the majors, via `/api/news/feed?featured=1`),
+ Headlines, Trending (the digest's coverage-ranked narratives), DeFi,
+ Bitcoin, Ethereum, Analysis, Saved, and All, which unfolds the full
+ category registry.
+- **Breaking ticker** — stories under 45 minutes old scroll in a marquee
+ (paused on hover, static under `prefers-reduced-motion`); hidden when
+ nothing is fresh.
+- **Today's AI Briefing** — the top digest narratives as a collapsible
+ numbered card, linking into `/markets/digest`.
+- **Top stories** — a lead-story hero beside a compact headline rail, then
+ the Latest grid with offset pagination.
+- **Saved stories** — a ☆ on every card bookmarks the article to
+ localStorage; the Saved tab renders the collection.
+- Debounced search, language + per-source filters, sentiment dots, and ticker
+ chips that pivot the feed to that symbol carry over from the flat layout.
+
+Preview images never break: feed images load with `no-referrer`, retry once
+through the same-origin `/api/img` proxy, and articles whose feed ships no
+image resolve their publisher's `og:image` in the background via
+`/api/news/image` — falling back to a designed source-initials tile only when
+no preview exists anywhere. Each source is cached server-side for 5 minutes
with serve-stale-on-error, so one dead feed never blanks the page.
### `/markets/news/article` — rich article reader
diff --git a/docs/content/use-cases/game-studio.md b/docs/content/use-cases/game-studio.md
index cb46dc8b3..c2fe76c2a 100644
--- a/docs/content/use-cases/game-studio.md
+++ b/docs/content/use-cases/game-studio.md
@@ -16,7 +16,7 @@ three.ws ships those three systems as real, composable surfaces:
1. **GLB rendering pipeline** — the [viewer](../../../README.md#key-features) loads and validates glTF 2.0 / GLB with Draco, KTX2, and Meshopt, plus skinned animation and morph targets, all in WebGL 2.0. Drop a character at [`/app`](https://three.ws/app) and it renders instantly.
2. **Agent runtime + skills** — the [LLM tool-loop runtime](../../../README.md#the-agent-system) gives a character built-in tools (`wave`, `lookAt`, `play_clip`, `setExpression`, `speak`, `remember`) and a [composable skill system](../../../specs/SKILL_SPEC.md) so you can add game-specific abilities. The Empathy Layer blends emotion from protocol events, so NPCs emote instead of staring blankly.
-3. **Multiplayer worlds** — [`/walk`](https://three.ws/walk) is an authoritative multiplayer walk scene backed by a Colyseus server (deployable on Fly.io), and [`/play`](https://three.ws/play) is a shared, coin-keyed 3D world where players who pick the same world land **together** — peer avatars, chat, emotes, voxel building. Author motion and poses in [`/pose-studio`](https://three.ws/pose-studio) and [`/mocap-studio`](https://three.ws/mocap-studio).
+3. **Multiplayer worlds** — [`/walk`](https://three.ws/walk) is an authoritative multiplayer walk scene backed by a Colyseus server (deployable on Google Cloud Run), and [`/play`](https://three.ws/play) is a shared, coin-keyed 3D world where players who pick the same world land **together** — peer avatars, chat, emotes, voxel building. Author motion and poses in [`/pose`](https://three.ws/pose) and [`/mocap-studio`](https://three.ws/mocap-studio).
## Example workflow (hypothetical)
@@ -25,7 +25,7 @@ three.ws ships those three systems as real, composable surfaces:
1. The artist exports the guide character as a Draco-compressed GLB and drops it on [`/app`](https://three.ws/app) to confirm it renders, animates, and validates against the Khronos spec.
2. An engineer embeds the character as an [`<agent-3d>`](../../../README.md#web-component--embedding) element in the game's hub page, sets `brain=` and `instructions=` for the guide's personality, and writes one custom [skill](../../../specs/SKILL_SPEC.md) — `give_quest` — so the NPC can hand out objectives through the tool-loop instead of a static script.
3. For the shared space, they point players at [`/walk`](https://three.ws/walk) (authoritative Colyseus world) so testers can roam together with live peer avatars and chat while the studio dials in gameplay.
-4. They author the guide's idle and point gestures in [`/pose-studio`](https://three.ws/pose-studio) and bind them to the NPC's `play_clip` tool calls.
+4. They author the guide's idle and point gestures in [`/pose`](https://three.ws/pose) and bind them to the NPC's `play_clip` tool calls.
5. **Deliverable:** a browser-playable hub with a conversational, gesturing guide NPC and a shared multiplayer space — assembled from real GLB rendering, a real agent runtime, and real netcode, without the studio writing any of those three engines.
## What you get
diff --git a/docs/memory.md b/docs/memory.md
index f9f6ceb0e..326d74a8a 100644
--- a/docs/memory.md
+++ b/docs/memory.md
@@ -180,18 +180,18 @@ A `MEMORY.md` file is automatically maintained alongside the individual memory f
# Agent Memory
## User
-- [Role](user_role.md) — Argentina fan, plays weekly 5-a-side on Saturdays
-- [Preferences](user_preferences.md) — terse feedback, no emojis
+- Role (`user_role.md`) — Argentina fan, plays weekly 5-a-side on Saturdays
+- Preferences (`user_preferences.md`) — terse feedback, no emojis
## Feedback
-- [Tone](feedback_tone.md) — stay warm but don't coddle; user asked for direct critique
-- [Drill pacing](feedback_pacing.md) — 3 drills per session max
+- Tone (`feedback_tone.md`) — stay warm but don't coddle; user asked for direct critique
+- Drill pacing (`feedback_pacing.md`) — 3 drills per session max
## Project
-- [Season goal](project_season.md) — user is training for a tournament in June 2026
+- Season goal (`project_season.md`) — user is training for a tournament in June 2026
## Reference
-- [Highlight reel](reference_reel.md) — shared Drive folder where user stores match clips
+- Highlight reel (`reference_reel.md`) — shared Drive folder where user stores match clips
```
Keep the index concise. Lines beyond 200 are truncated before injection into context.
diff --git a/docs/persona-hub.md b/docs/persona-hub.md
index 2795da4f2..d9b647a0a 100644
--- a/docs/persona-hub.md
+++ b/docs/persona-hub.md
@@ -117,7 +117,7 @@ The response should contain one entry under `keys` whose `kid` matches `PERSONA_
## Issuing a token
-`POST /api/auth/persona/issue` — defined in [api/auth/persona/\[action\].js](../api/auth/persona/%5Baction%5D.js) (`handleIssue`).
+`POST /api/auth/persona/issue` — defined in `api/auth/persona/[action].js` (`handleIssue`).
| | |
|---|---|
@@ -127,7 +127,7 @@ The response should contain one entry under `keys` whose `kid` matches `PERSONA_
| Success | `200` with `{ token, expires_in, avatar, tenant_origin, alg }` |
| Errors | `401 unauthorized` — no session. `400 invalid_request` — `tenant_origin` is not a `three.ws` subdomain or `localhost`. `404 no_avatar` — user has no avatar yet. |
-`tenant_origin` must be a bare origin (no path, no query, no fragment), `https://*.three.ws` or `https://three.ws`, or — for dev — `http://localhost[:port]` / `http://127.0.0.1[:port]`. Anything else is rejected with `400 invalid_request`. The validator is `validateTenantOrigin()` in [api/auth/persona/\[action\].js](../api/auth/persona/%5Baction%5D.js); add a subdomain by editing that function.
+`tenant_origin` must be a bare origin (no path, no query, no fragment), `https://*.three.ws` or `https://three.ws`, or — for dev — `http://localhost[:port]` / `http://127.0.0.1[:port]`. Anything else is rejected with `400 invalid_request`. The validator is `validateTenantOrigin()` in `api/auth/persona/[action].js`; add a subdomain by editing that function.
When `avatar_id` is omitted, the user's most recently created avatar is used. Pass `avatar_id` from the consent UI's picker to bind a specific avatar to the token.
@@ -306,7 +306,7 @@ The verify endpoint applies the same checks as `jose.jwtVerify` — signature, i
## ES256 vs HS256 fallback
-The signing algorithm is decided at issue time by [api/auth/persona/\[action\].js:158-161](../api/auth/persona/%5Baction%5D.js):
+The signing algorithm is decided at issue time by `api/auth/persona/[action].js:158-161`:
```js
const es = await esKeys(); // null if PERSONA_JWKS_PRIVATE_KEY_PEM is unset
@@ -326,7 +326,7 @@ Verification accepts both algorithms in either order — the `/verify` endpoint
## Tokens in practice
-- **TTL.** 24 hours (`PERSONA_TTL_SEC = 60 * 60 * 24`, [api/auth/persona/\[action\].js:42](../api/auth/persona/%5Baction%5D.js#L42)). Tenants that need a longer-lived session must mint their own session from the persona token's `sub` after verifying — do not extend the persona JWT itself.
+- **TTL.** 24 hours (`PERSONA_TTL_SEC = 60 * 60 * 24`, `api/auth/persona/[action].js:42`). Tenants that need a longer-lived session must mint their own session from the persona token's `sub` after verifying — do not extend the persona JWT itself.
- **Rotation.** Generate a new keypair with `node scripts/generate-persona-key.mjs`, deploy with a new `PERSONA_JWKS_KID`, and the JWKS publishes the new key. Old tokens continue to verify against `/api/auth/persona/verify` while they live; once the longest possible token TTL has elapsed (24h), no token in the wild still references the old `kid`. The deployment can serve both old and new keys side by side by adding extra entries to the `keys` array — the current handler emits a single key but the verifier accepts any matching `kid` from the published set.
- **Revocation.** There is **no** revocation list. Defense is the short TTL: 24 hours. If a token must be invalidated sooner, the tenant should treat its own server-issued session as the source of truth and invalidate that. If a private key is leaked, rotate `PERSONA_JWKS_PRIVATE_KEY_PEM` and `PERSONA_JWKS_KID`; verification of any token signed with the old key will fail as soon as the old JWK is removed from the published set.
@@ -342,7 +342,7 @@ Verification accepts both algorithms in either order — the `/verify` endpoint
| `JWTClaimValidationFailed: "aud" claim check failed` | The `audience` you passed to `jwtVerify` (or to `/verify`) doesn't match the token's `aud`. Audience is the exact `tenant_origin` used at issue time — case-sensitive, no trailing slash. |
| `JWTExpired: "exp" claim timestamp check failed` | Token is older than 24 h. Have the user re-authorize through the widget. There is no refresh endpoint — persona tokens are not refreshable by design. |
| `invalid_token: token is not a persona token` from `/verify` | The token validates cryptographically but its `token_use` claim is not `"persona"`. Tokens issued by the main three.ws auth stack are not accepted on this endpoint. |
-| `400 invalid_request` on `/issue` with `tenant_origin must be a https three.ws subdomain or localhost dev origin` | The origin contains a path / query / fragment, is not `https`, or is not a `three.ws` subdomain. Pass a bare origin like `https://coolgame.three.ws`. Add a new subdomain by editing `validateTenantOrigin()` in [api/auth/persona/\[action\].js](../api/auth/persona/%5Baction%5D.js). |
+| `400 invalid_request` on `/issue` with `tenant_origin must be a https three.ws subdomain or localhost dev origin` | The origin contains a path / query / fragment, is not `https`, or is not a `three.ws` subdomain. Pass a bare origin like `https://coolgame.three.ws`. Add a new subdomain by editing `validateTenantOrigin()` in `api/auth/persona/[action].js`. |
---
@@ -362,9 +362,9 @@ Other origins return `400 invalid_request`. This is the chokepoint that prevents
| Endpoint | Method | Auth | Description |
|---|---|---|---|
-| [/api/auth/persona/me](../api/auth/persona/%5Baction%5D.js) | `GET` | three.ws session | Lists the user's avatars for the consent UI. |
-| [/api/auth/persona/issue](../api/auth/persona/%5Baction%5D.js) | `POST` | three.ws session | Mints a 24h persona JWT for `{ tenant_origin, avatar_id }`. |
-| [/api/auth/persona/verify](../api/auth/persona/%5Baction%5D.js) | `GET` | none | Verifies a token's signature, issuer, audience, expiry, and `token_use`. |
+| `/api/auth/persona/me` | `GET` | three.ws session | Lists the user's avatars for the consent UI. |
+| `/api/auth/persona/issue` | `POST` | three.ws session | Mints a 24h persona JWT for `{ tenant_origin, avatar_id }`. |
+| `/api/auth/persona/verify` | `GET` | none | Verifies a token's signature, issuer, audience, expiry, and `token_use`. |
| [/.well-known/jwks.json](https://three.ws/.well-known/jwks.json) | `GET` | none | Publishes the active persona public key (empty array in HS256 fallback). |
JWT claims:
diff --git a/docs/premium.md b/docs/premium.md
new file mode 100644
index 000000000..6be4426ed
--- /dev/null
+++ b/docs/premium.md
@@ -0,0 +1,102 @@
+# three.ws Premium — the monthly Data API pass
+
+Premium is one on-chain payment that replaces per-call micropayments for 30
+days. Instead of answering an x402 challenge on every archive search, you buy
+a pass once a month — the AIXBT model — and call the Data API with an API key
+(servers, agents) or a wallet signature (browsers).
+
+**Price:** $9.99 / 30 days, paid on **Solana only**, in your choice of:
+
+| Asset | What you pay | Why |
+|---|---|---|
+| **$THREE** | ≈ $7.99 worth (20% off) | The platform coin is the cheapest way in. Mint: `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump` |
+| **SOL** | ≈ $9.99 worth at the live price | Native SOL transfer |
+| **USDC** | $9.99 exactly | Parity, never needs an oracle |
+
+Prices in SOL and $THREE are locked for 10 minutes when you request a quote,
+so the amount you sign is exactly the amount that's verified.
+
+**What it unlocks today:** unmetered search on the
+[660k-article crypto-news archive](/markets/archive)
+(`GET /api/news/archive`) at a fair-use rate limit of 120 requests/minute —
+versus the free tier's 60 searches/day and the $0.001-per-search x402 rail.
+Corpus stats, month index, and trending are free for everyone regardless.
+More premium surfaces join the same pass over time; your key starts working
+on them automatically.
+
+## Buying a pass
+
+### From the dashboard (recommended)
+
+Open **[/dashboard/data-api](/dashboard/data-api)**, pick an asset, and
+confirm one transaction in your Solana wallet. When it confirms, the page
+shows your `x402_live_…` API key **once** — copy it then. Renewing later
+appends 30 days to the end of your current pass; no days are lost by renewing
+early.
+
+### From the API (no account needed)
+
+```bash
+# 1. Quote — lock the price, get the unsigned transaction (base64)
+curl -X POST https://three.ws/api/premium/quote \
+ -H 'content-type: application/json' \
+ -d '{"asset":"THREE","wallet":"<your-solana-address>"}'
+# → { "quote": { "id", "amount_atomics", "expires_at", … }, "tx_base64": "…" }
+
+# 2. Sign tx_base64 with the quoted wallet and send it (any Solana client).
+
+# 3. Redeem — verify the landed payment and receive the pass + API key
+curl -X POST https://three.ws/api/premium/subscribe \
+ -H 'content-type: application/json' \
+ -d '{"quote_id":"<quote.id>","tx_signature":"<signature>"}'
+# → { "pass": { "expires_at", … }, "api_key": "x402_live_…" } (key shown once)
+```
+
+A `202 { pending: true }` means the transaction hasn't confirmed yet — poll
+`subscribe` again with the same body; redeeming is idempotent, and
+re-submitting an already-redeemed signature returns the existing pass.
+
+Live per-asset pricing: `GET https://three.ws/api/premium/plans`.
+Pass state for any wallet: `GET https://three.ws/api/premium/status?wallet=…`.
+
+## Using the pass
+
+**Servers and agents — API key.** Send the key as a header on any premium
+endpoint; the request bypasses the x402 payment entirely:
+
+```bash
+curl "https://three.ws/api/news/archive?q=mt+gox&start_date=2018-01-01&end_date=2019-12-31" \
+ -H "X-API-Key: x402_live_…"
+```
+
+**Browsers — wallet signature (SIWX).** The wallet that bought the pass holds
+a signature grant until the pass expires. On [/markets/archive](/markets/archive),
+when the payment dialog appears, choose *sign with wallet* instead of paying —
+no key, no charge.
+
+## Managing keys
+
+On [/dashboard/data-api](/dashboard/data-api) (signed in) you can **rotate**
+(revoke + reissue; new plaintext shown once) or **revoke** your key. Key
+management is tied to the account that was signed in at purchase time —
+passes bought wallet-only over the raw API authenticate with the key itself
+and can be re-keyed by renewing. Your purchase history and subscriptions live
+at [/dashboard/billing](/dashboard/billing).
+
+## Rules and edge cases
+
+- A quote is redeemable for 30 minutes; after that, request a fresh one
+ (the transaction's blockhash expires far sooner anyway).
+- Verification checks the **landed** transaction: the quoted wallet must be a
+ signer and the treasury balance delta must cover the quoted amount. Someone
+ else's transaction signature can't redeem your quote.
+- One transaction signature redeems exactly one pass, forever (database
+ UNIQUE). Failed or reverted transactions redeem nothing.
+- Renewal periods stack end-to-end (`new start = old expiry`).
+- Ops can tune pricing without a deploy: `PREMIUM_PASS_USD`,
+ `PREMIUM_PASS_THREE_DISCOUNT`, `PREMIUM_PASS_DAYS`,
+ `PREMIUM_RATE_LIMIT_PER_MINUTE`.
+
+Related: [API reference — news archive](/docs/api-reference), the
+[x402 per-call rail](/docs/x402) that Premium sits on top of, and the free
+tiers that remain free (news feed, digest, archive stats/trending).
diff --git a/docs/pumpfun-program/docs/FEE_PROGRAM_README.md b/docs/pumpfun-program/docs/FEE_PROGRAM_README.md
index 20b48370e..408debcc5 100644
--- a/docs/pumpfun-program/docs/FEE_PROGRAM_README.md
+++ b/docs/pumpfun-program/docs/FEE_PROGRAM_README.md
@@ -200,8 +200,7 @@ export function calculateFeeTier({
}
```
-We will use the following fee tiers starting from Monday:
-![Fee Tiers](fees.png)
+We will use the following fee tiers starting from Monday (see the fee tiers chart, `fees.png`, in the upstream repository — not vendored here):
In order to avoid possible issues created by the new fee structure, until you make sure it's implemented correctly, you can increase the slippage tolerance on buy / sell instructions as a temporary mitigation.
diff --git a/docs/pumpfun-program/docs/PUMP_CREATOR_FEE_README.md b/docs/pumpfun-program/docs/PUMP_CREATOR_FEE_README.md
index 2c0ee4cf0..e393ce68d 100644
--- a/docs/pumpfun-program/docs/PUMP_CREATOR_FEE_README.md
+++ b/docs/pumpfun-program/docs/PUMP_CREATOR_FEE_README.md
@@ -98,7 +98,7 @@ same code should work on both the creator fee update on Devnet and the current M
program on Mainnet to the creator fee update.
We are also trying to release the Pump program Typescript SDK by Monday, so you can use it. The
-[bondingCurve.ts](bondingCurve.ts) file is part of the upcoming Pump program Typescript SDK.
+`bondingCurve.ts` file is part of the upcoming Pump program Typescript SDK.
## Coin creator fees update
@@ -116,7 +116,7 @@ Who will not receive coin creator fees?
- coins already migrated to Raydium, as that program is not under our control.
- normal PumpSwap pools which are not created by Pump program `migrate` instruction.
-You should start by using the latest IDL files for both programs from the [idl](idl) directory. They are
+You should start by using the latest IDL files for both programs from the `idl` directory. They are
backwards-compatible with current programs deployed on Mainnet, so you can start using them now.
You can also use our Typescript SDKs for easier integration:
diff --git a/docs/security/review-2026-06-24.md b/docs/security/review-2026-06-24.md
index 8ba571733..d93beefe3 100644
--- a/docs/security/review-2026-06-24.md
+++ b/docs/security/review-2026-06-24.md
@@ -285,8 +285,8 @@ Auth legend: **public** (no auth, read-only or anti-abuse-limited) ·
| labor/post, /bid, /award, /deliver, /settle, /policy(PUT) | POST/PUT | owner + CSRF | escrow funded from owned agent; verdict gates funds; idempotent `settle_key` |
| labor/agent, /bounty, /feed, /policy(GET) | GET | public | read-only aggregates |
| labor/tick | POST/GET | cron | fail-closed |
-| vaults/index(POST), /[id](PATCH), /deposit, /redeem, /trade, /claim-fees | POST/PATCH | owner + CSRF | payee server-resolved; `tradePerUser`; atomic claim |
-| vaults/index(GET), /[id](GET), /ledger | GET | public / role-aware | secret excluded from public cols |
+| vaults/index(POST), `/[id]`(PATCH), /deposit, /redeem, /trade, /claim-fees | POST/PATCH | owner + CSRF | payee server-resolved; `tradePerUser`; atomic claim |
+| vaults/index(GET), `/[id]`(GET), /ledger | GET | public / role-aware | secret excluded from public cols |
| credits/index, /deposit | GET/POST | session/bearer | signer-bound, finalized-only, idempotent; `authIp` |
| billing/invoices | GET | session/bearer | scoped to `userId` |
| custody/anchor, /integrity, ledger/[agentId], ledger/verify/[agentId] | GET | public | aggregate/track-record by design |
diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md
index 8dfcef358..f84e09163 100644
--- a/docs/troubleshooting.md
+++ b/docs/troubleshooting.md
@@ -320,14 +320,14 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix
### Session expires unexpectedly
-**Symptom:** Users are logged out before the 7-day session window.
+**Symptom:** Users are logged out before the 30-day session window.
**Likely cause:** `JWT_SECRET` changed between deploys, which invalidates all existing sessions.
**Fix steps:**
-1. Set `JWT_SECRET` once and don't rotate it unless needed. Store it in Vercel's environment variable settings — it must be the same value across all deployments.
-2. Session duration is 7 days and is not currently configurable.
+1. Set `JWT_SECRET` once and don't rotate it unless needed. In production it lives on the Cloud Run service env (`gcloud run services describe three-ws-api --region us-central1` to inspect) — it must be the same value across all revisions.
+2. Session duration is 30 days. A session used when fewer than 7 days remain is rotated to a fresh 30-day token (a rolling refresh window), so actively returning users stay signed in indefinitely.
---
@@ -407,7 +407,7 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix
**Fix steps:**
1. Check the `memory` attribute or manifest setting. The default mode is `"local"` (persisted to `localStorage`). If your manifest or element sets `memory="none"`, memory is intentionally disabled.
-2. Verify `localStorage` isn't being cleared. Open DevTools → Application → Local Storage and look for keys starting with `3dagent:`. If they're missing after a conversation, check if your browser settings clear storage on close.
+2. Verify `localStorage` isn't being cleared. Open DevTools → Application → Local Storage and look for keys of the form `agent:<agentId>:memory`. If they're missing after a conversation, check if your browser settings clear storage on close.
3. Private/incognito mode: `localStorage` is cleared when the window closes. This is browser behavior, not a bug.
---
@@ -501,8 +501,13 @@ Run `npm run db:status` first to preview which migrations are pending.
**Fix steps:**
-1. Check Vercel function logs: `vercel logs --follow` in the project directory.
-2. The most common cause is a missing environment variable. All required vars must be set: `DATABASE_URL`, `JWT_SECRET`, `PUBLIC_APP_ORIGIN`. The `env.js` module throws on startup if required vars are absent.
+1. Check the server logs. Production runs on Google Cloud Run (service `three-ws-api`, region `us-central1`); read recent errors with:
+ ```bash
+ gcloud logging read 'resource.type="cloud_run_revision" resource.labels.service_name="three-ws-api" severity>=ERROR' \
+ --freshness=1h --limit 20 --format="value(textPayload)"
+ ```
+ Deploys ship via `npm run deploy:gcp` (run `npm run build` first for frontend changes) — the full runbook lives in the repo at `docs/ops/gcp-production.md`. On a self-hosted fork, check whatever your host surfaces as function/process logs.
+2. The most common cause is a missing environment variable. All required vars must be set: `DATABASE_URL`, `JWT_SECRET`, `PUBLIC_APP_ORIGIN`. The `env.js` module throws on startup if required vars are absent. In production, inspect and set them on the Cloud Run service: `gcloud run services describe three-ws-api --region us-central1` / `gcloud run services update three-ws-api --region us-central1 --update-env-vars KEY=value`.
---
@@ -548,7 +553,7 @@ Add `allow="xr-spatial-tracking"` to the `<iframe>` element. Without it, the bro
The AR button is only shown after the GLB finishes loading. If the model is large or on a slow connection, the button appears late. Check the console for load errors.
**Check 5 — HTTP origin:**
-`navigator.xr` is `undefined` on `http://` origins. All AR methods require HTTPS for the page or the model URL. Use ngrok or a deployed preview URL during development.
+`navigator.xr` is `undefined` on `http://` origins. All AR methods require HTTPS for the page or the model URL. Use an ngrok tunnel or a deployed HTTPS environment during development.
---
@@ -607,8 +612,8 @@ ngrok http 3000 # creates an HTTPS tunnel
# Open the ngrok URL on your phone
```
-**Option 2 — Vercel preview:**
-Push to a branch. Vercel creates an instant HTTPS preview URL. This is the cleanest option — it tests the production build.
+**Option 2 — a deployed HTTPS environment:**
+Deploy your change and test against the live HTTPS URL. There are no per-branch preview deployments in the production flow — three.ws production deploys with `npm run deploy:gcp` to Cloud Run. A fork hosted on Vercel or Netlify does get an HTTPS URL per deploy, which works the same way for AR testing.
**Chrome WebXR emulator (desktop testing):**
Chrome 127+ includes a WebXR device simulator under DevTools → More Tools → WebXR. It won't show camera passthrough but lets you test the session lifecycle and model placement logic without a physical device.
@@ -633,7 +638,7 @@ The 3D viewer, animations, and widget system all work without a key. The LLM con
**Can I self-host without Vercel?**
-Yes. The API routes are standard Node.js async functions — any Node.js host works. You'll need to replicate Vercel's `vercel.json` rewrite rules in your host's routing config (Express routes, Nginx `proxy_pass`, etc.).
+Yes — production itself doesn't run on Vercel. Since 2026-07-07, three.ws production is a single container on Google Cloud Run: `server/index.mjs` serves the static frontend and every `api/**` handler, and reads `vercel.json`'s route table at runtime as its routing config. That server is the reference implementation for self-hosting on any Node.js host. If you'd rather use your own routing layer (Express routes, Nginx `proxy_pass`, etc.), replicate the `vercel.json` rewrite rules there — the API routes are standard Node.js async functions. Deploying a fork to Vercel also still works.
**Is the agent data private?**
diff --git a/docs/tutorials/agent-personality.md b/docs/tutorials/agent-personality.md
index b81ad1e09..f1c692759 100644
--- a/docs/tutorials/agent-personality.md
+++ b/docs/tutorials/agent-personality.md
@@ -165,20 +165,21 @@ The "use sparingly" line matters. Models that over-gesture come across as a chil
The platform maintains conversation memory automatically. Two scopes:
- **Rolling context** — the last N turns of the current chat. Fed back into the model on each turn so it remembers what was just said. Cleared by `agent.clearConversation()` and on page reload by default.
-- **Long-term memory** — explicit facts the agent wrote with `agent.agent.memory.write(scope, key, value)` or loaded from the manifest. Persists across sessions if the memory mode is `local` (browser storage) or `cloud` (server-side).
+- **Long-term memory** — explicit notes written through the element's `memory` handle with `agent.memory.write(key, { name, description, type, body })`, or loaded from the manifest. Persists across sessions if the memory mode is `local` (browser storage) or `cloud` (server-side).
For most agents, the rolling context is enough. The user asks "what was that project you mentioned?" and the model still has the previous turn in context — no separate memory write needed.
You reach for long-term memory in two scenarios:
-**Pre-loading reference facts.** The agent should always know certain things — your portfolio links, your office hours, the museum's wing list. Write these once at boot:
+**Pre-loading reference facts.** The agent should always know certain things — your portfolio links, your office hours, the museum's wing list. Write these once at boot. Each entry is a small named note: a `key` (its filename in the memory store) plus a `name`, a one-line `description`, a `type` (`reference` for facts like these), and a free-text `body`:
```js
-agent.addEventListener('agent:ready', async () => {
- await agent.agent.memory.write('long-term', 'hours', {
- weekday: '9am-7pm',
- weekend: '10am-5pm',
- holidays: 'Closed Dec 24-26',
+agent.addEventListener('agent:ready', () => {
+ agent.memory.write('hours', {
+ name: 'Opening hours',
+ description: 'When we are open, for any scheduling question',
+ type: 'reference',
+ body: 'Weekdays 9am-7pm. Weekends 10am-5pm. Closed Dec 24-26.',
});
});
```
@@ -346,7 +347,7 @@ two sentences: who you are, who you represent, and invite the visitor to ask any
Then wave.
```
-The "__greet" trigger is a pattern worth knowing about. The web component can fire a hidden first message at page load to give the agent something to respond to — that's how you get the agent to introduce itself without needing the user to type first. The prompt names the trigger explicitly so the model knows how to handle it.
+The "__greet" trigger is a pattern worth knowing about. Your page can fire a hidden first message once the agent boots — `agent.addEventListener('agent:ready', () => agent.say('__greet'))` — to give the brain something to respond to. That's how you get the agent to introduce itself without needing the user to type first. It has to be `say()` (or `ask()`), which route the message through the brain; `speak()` never reaches the model — it only drives the talking animation. The prompt names the trigger explicitly so the model knows how to handle it.
---
diff --git a/docs/tutorials/customize-appearance.md b/docs/tutorials/customize-appearance.md
index a5697743f..813a71d69 100644
--- a/docs/tutorials/customize-appearance.md
+++ b/docs/tutorials/customize-appearance.md
@@ -1,13 +1,13 @@
# Customize size, position & background
-A default embed lands in the bottom-right corner at a fixed size, with a transparent background, and a gentle idle rotation. That's a sensible starting point — it works on every site without tuning. But it is not what you want long-term. You want an agent that feels designed for your page: anchored where it belongs, sized for the layout, blended into the background, rotating at exactly the pace that suits your brand.
+A default embed renders inline where you put the tag, fills its container, and shows the avatar over a transparent background. That's a sensible starting point — it works on every site without tuning. But it is not what you want long-term. You want an agent that feels designed for your page: anchored where it belongs, sized for the layout, blended into the background, framed at exactly the crop that suits your brand.
-This tutorial walks through every `data-*` attribute the three.ws embed loader honours. It covers them one at a time, with real snippets you can copy. By the end you have an agent that looks like it shipped with your site, not like a widget bolted on after the fact.
+This tutorial walks through every appearance attribute the `<agent-3d>` element honours. It covers them one at a time, with real snippets you can copy. By the end you have an agent that looks like it shipped with your site, not like a widget bolted on after the fact.
**What you'll build:**
- A floating agent sized and positioned precisely where you want it
-- A background that matches your site (transparent, branded, or a fixed colour)
-- A rotation speed tuned to the mood of your page
+- A background that matches your site (transparent, dark, light, or any CSS colour)
+- A framing and idle animation tuned to the mood of your page
- A pixel-perfect, brand-aligned embed snippet for any site stack
- A clear map of which attributes do what
@@ -15,261 +15,265 @@ This tutorial walks through every `data-*` attribute the three.ws embed loader h
---
-## Step 1 — How the loader reads your attributes
+## Step 1 — How the element reads your attributes
-Every customisation in this tutorial is set as a `data-*` attribute on the embed script tag itself, not on a separate config object. The loader reads those attributes once, when the script first runs.
+The embed is two tags: a `<script>` that loads the runtime once, and an `<agent-3d>` custom element that places the agent. Every customisation in this tutorial is an attribute on the **element**, not on the script tag.
The general shape is always the same:
```html
-<script
- src="https://three.ws/cdn/agent-3d.js"
- data-agent-id="YOUR_AGENT_ID"
- data-size="large"
- data-position="bottom-left"
- data-background-color="transparent"
- data-rotation-speed="0.5"
-></script>
+<script type="module" src="https://three.ws/agent-3d/1.5.2/agent-3d.js"></script>
+
+<agent-3d
+ agent-id="YOUR_AGENT_ID"
+ mode="floating"
+ position="bottom-left"
+ width="320px"
+ height="420px"
+ background="transparent"
+></agent-3d>
```
Order doesn't matter. Capitalisation does: every attribute is lowercase, hyphenated. Spelling matters too — an unknown attribute is silently ignored, so you'll see no error if you typo one, just the default behaviour.
-There is one tricky thing worth knowing up front: because attributes are read once at script load, changing them later via DOM manipulation does not re-render the agent. If you need to update appearance dynamically, the right tool is the JS API on the script element, which is covered briefly at the end of this tutorial.
+Because this is a real custom element, the appearance attributes are **live**. Change `mode`, `position`, `width`, `height`, `responsive`, `background`, `name-plate`, `framing`, or `clip` from JavaScript at any time and the element re-applies the change on the spot — no reload, no re-embed:
----
+```js
+const agent = document.querySelector('agent-3d');
+agent.setAttribute('background', 'dark'); // repaints immediately
+agent.setAttribute('position', 'top-left'); // re-anchors immediately
+```
-## Step 2 — `data-size`: how big the widget appears
+One loading note worth knowing up front: the element boots lazily. It waits until it is scrolled near the viewport (with a 300px head start) before downloading the 3D body. Add the boolean `eager` attribute if you want it to boot the moment the page loads instead.
+
+---
-The simplest attribute, and the one most people want to change first. `data-size` accepts either a named preset or a CSS-style pixel value.
+## Step 2 — `mode`: how the widget sits on the page
-### Named presets
+`mode` decides the fundamental layout. Four values:
```html
-<script
- src="https://three.ws/cdn/agent-3d.js"
- data-agent-id="YOUR_AGENT_ID"
- data-size="medium"
-></script>
+<agent-3d agent-id="YOUR_AGENT_ID" mode="floating"></agent-3d>
```
-The available presets are:
+- `inline` — the default. The element is a normal block in the document flow, sized by its container (100% wide, 480px tall unless you say otherwise). Use it when the agent is a section of the page — a product hero, a team-page member, a docs helper embedded mid-article.
+- `floating` — the classic support-widget layout. The element is `position: fixed`, floats above your content, stays put while the visitor scrolls, and can be dragged around by its handle. This is the mode most marketing and support embeds want.
+- `section` — like inline, but the chat column is capped at 600px wide so a full-width band on a desktop layout doesn't produce comically wide message bubbles.
+- `fullscreen` — the element covers the whole viewport (`100vw` × `100dvh`) with the chat column centred at 800px. Use it for dedicated "/talk-to-us" pages.
-- `small` — a compact 160 × 240 widget; good for unobtrusive helper bots on busy pages
-- `medium` — the default, 220 × 320; a comfortable size for most content sites
-- `large` — 320 × 460; gives the avatar more presence on a marketing page
-- `xlarge` — 420 × 600; suitable when the agent *is* the hero element
+### Inline placement
-If you have not set this attribute, `medium` is what you get.
-
-### Explicit pixel value
-
-If a preset doesn't fit your layout, set the width directly:
+In inline mode the element sits exactly where the tag is rendered:
```html
-<script
- src="https://three.ws/cdn/agent-3d.js"
- data-agent-id="YOUR_AGENT_ID"
- data-size="280px"
-></script>
-```
-
-The widget keeps the same aspect ratio (roughly 2:3 portrait), so you only need to set width. The height scales automatically.
-
-You can also use percentages for inline embeds (covered in the next section). `data-size="60%"` means the widget takes 60% of its container width.
+<h1>About Us</h1>
+<p>Meet our digital concierge.</p>
-### What the size affects
+<agent-3d
+ agent-id="YOUR_AGENT_ID"
+ width="400px"
+ height="520px"
+ style="margin: 0 auto;"
+></agent-3d>
-Setting `data-size` changes three things at once: the container's CSS width, the canvas resolution, and the avatar's framing within that canvas. The avatar is always centred and proportioned so its head sits roughly one-third from the top. This means a smaller size doesn't crop the face — it just zooms out a little so the full body remains visible.
+<p>Below, you'll find our services...</p>
+```
-If you want to see how the size feels on a real layout before committing, drop the snippet into your page, refresh, and try `small`, `medium`, and `large` in sequence. Sizes look different on different content; trust the page, not the theory.
+It's a block-level element, so the usual CSS applies: centre it with `margin: 0 auto`, place it in a grid cell, float it in a column. No special rules.
---
-## Step 3 — `data-position`: where the widget anchors
+## Step 3 — `width`, `height` and `responsive`: how big it appears
-There are four corner anchors plus one inline mode.
+`width` and `height` accept any CSS length. Floating mode defaults to **320px × 420px**; inline mode defaults to the container's width and 480px tall.
```html
-<script
- src="https://three.ws/cdn/agent-3d.js"
- data-agent-id="YOUR_AGENT_ID"
- data-position="bottom-right"
-></script>
+<agent-3d
+ agent-id="YOUR_AGENT_ID"
+ mode="floating"
+ width="280px"
+ height="380px"
+></agent-3d>
```
-The five accepted values:
+### Responsive scaling is on by default
-- `bottom-right` — the default; floats above your page in the lower-right corner
-- `bottom-left` — same behaviour, mirrored to the lower-left
-- `top-right` — anchored to the upper-right
-- `top-left` — anchored to the upper-left
-- `inline` — the widget is *not* fixed; it flows with the rest of the page
+You don't get a fixed 280px box on a 320px phone. Unless you opt out, the element wraps your dimensions in a CSS `clamp()` tied to the viewport, so the widget scales down gracefully on small screens (never below roughly two-thirds of the size you asked for, with sane floors of 160px width / 200px height).
-### When to use each corner
+Two more responsive behaviours come free:
-The corners are all "floating" positions. The agent uses `position: fixed`, so it stays in the same place on screen as the visitor scrolls. The container has a small margin from the viewport edge and a soft drop shadow so it reads as a distinct element layered over your content.
+- **Floating pill collapse.** On viewports narrower than 480px, a floating widget collapses into a 56px round pill. Tapping the pill expands it into a bottom sheet covering 70% of the screen; swiping down (or tapping outside) collapses it again. Visitors on phones get a native-feeling sheet instead of a widget covering half the page.
+- **Inline aspect lock.** An inline embed given only a `width` keeps a 3:4 portrait aspect ratio as it resizes with its container.
-- **Bottom-right** is the conventional support-widget position. Visitors expect to find help there. Use it when the agent is supplementary.
-- **Bottom-left** works well when you have something else important on the right (a cookie banner, a chat tool, a sticky CTA).
-- **Top-right** suits agents that introduce themselves immediately — they're hard to miss above the fold, and they don't compete with your hero CTA at the bottom.
-- **Top-left** is rare but useful for documentation sites where the right margin is reserved for a table of contents.
-
-### Inline mode
-
-`data-position="inline"` is different. The widget is no longer floating; it sits where the script tag is rendered, in the natural document flow:
+Opt out of all of it with `responsive="false"` — then your `width` and `height` are used verbatim:
```html
-<h1>About Us</h1>
-<p>Meet our digital concierge.</p>
+<agent-3d agent-id="YOUR_AGENT_ID" mode="floating" width="280px" height="380px" responsive="false"></agent-3d>
+```
-<script
- src="https://three.ws/cdn/agent-3d.js"
- data-agent-id="YOUR_AGENT_ID"
- data-position="inline"
- data-size="400px"
-></script>
+Prefer leaving it on. The clamped sizes look intentional on every screen; hard-coded pixels only look right on the screen you tested.
-<p>Below, you'll find our services...</p>
-```
+---
-In this mode the widget is a block-level element in the page. It contributes to the normal scroll height, sits in its parent column, and inherits the parent's text alignment. Use inline mode when the agent is a section of a page rather than a global helper — for example, on a product detail page where the agent represents a single product, or on a team page where each member has their own embedded agent.
+## Step 4 — `position` and `offset`: where a floating widget anchors
-You can centre an inline embed by wrapping it in a centred container:
+These two apply to `mode="floating"` only (inline elements are positioned by your page layout, like any other element).
```html
-<div style="text-align:center; padding: 40px 0;">
- <script
- src="https://three.ws/cdn/agent-3d.js"
- data-agent-id="YOUR_AGENT_ID"
- data-position="inline"
- ></script>
-</div>
+<agent-3d
+ agent-id="YOUR_AGENT_ID"
+ mode="floating"
+ position="bottom-right"
+ offset="24px 24px"
+></agent-3d>
```
+`position` combines a vertical keyword (`top` / `bottom`) with a horizontal one (`left` / `right` / `center`):
+
+- `bottom-right` — the default; the conventional support-widget corner. Visitors expect to find help there.
+- `bottom-left` — same behaviour, mirrored. Useful when a cookie banner or another chat tool owns the right side.
+- `bottom-center` — horizontally centred along the bottom edge.
+- `top-right` / `top-left` / `top-center` — anchored along the top. `top-right` suits agents that introduce themselves above the fold; `top-left` works on docs sites whose right margin is reserved for a table of contents.
+
+`offset` sets the distance from the anchored edges as `"<vertical> <horizontal>"`. One value applies to both. The default is `24px 24px`. Push a widget clear of a fixed footer with `offset="88px 24px"`.
+
+One nice-to-know: floating widgets are **draggable**. A slim grab handle sits along the top edge of the widget, and visitors can move it anywhere on screen. Your `position` is where it starts, not a cage.
+
---
-## Step 4 — `data-background-color`: the canvas behind the agent
+## Step 5 — `background`: the canvas behind the agent
-By default, the canvas behind the avatar is transparent, which means your page background shows through. That works for most setups, but some looks better with a solid or semi-transparent backdrop.
+By default the canvas behind the avatar is transparent, so your page shows through. `background` accepts two keywords plus any CSS colour.
### Transparent (default)
```html
-<script
- src="https://three.ws/cdn/agent-3d.js"
- data-agent-id="YOUR_AGENT_ID"
- data-background-color="transparent"
-></script>
+<agent-3d agent-id="YOUR_AGENT_ID" background="transparent"></agent-3d>
```
You don't need to set this explicitly — it is the default — but writing it out makes the intent clear when other developers read your code.
-### Solid hex
+### `dark` and `light` keywords
```html
-<script
- src="https://three.ws/cdn/agent-3d.js"
- data-agent-id="YOUR_AGENT_ID"
- data-background-color="#0a0a14"
-></script>
+<agent-3d agent-id="YOUR_AGENT_ID" background="dark"></agent-3d>
```
-Use a solid colour when your page has busy content behind the widget — a hero image, a video, a complex pattern — and you want the avatar to stand out without compositing tricks.
+- `dark` — a near-black `#0b0d10` backdrop.
+- `light` — a near-white `#f5f5f5` backdrop. This keyword also flips the speech bubble and name-plate to dark-on-light styling so the text stays readable.
-Both the three-digit and six-digit hex forms work: `#000`, `#0a0a14`, `#ffffff`. Names like `black` and `white` also work, but stick to hex for consistency.
+These are the same options the editor's snippet builder offers, so a snippet copied from the editor and one written by hand behave identically.
-### Semi-transparent
+### Any CSS colour
-Eight-digit hex codes include alpha:
+Anything other than the keywords is treated as a literal CSS colour — hex, `rgb()`, a named colour:
```html
-<script
- src="https://three.ws/cdn/agent-3d.js"
- data-agent-id="YOUR_AGENT_ID"
- data-background-color="#0a0a14cc"
-></script>
+<agent-3d agent-id="YOUR_AGENT_ID" background="#0a0a14"></agent-3d>
```
-The last two hex digits are alpha: `cc` is roughly 80% opacity. Use this for a glassy panel effect — visible structure behind the agent, but enough opacity that the avatar reads cleanly.
-
-### Picking a colour that works
+Use a solid colour when your page has busy content behind the widget — a hero image, a video, a complex pattern — and you want the avatar to stand out.
A few practical notes from putting agents on real sites:
- Dark pages almost always look best with a transparent background — the avatar lighting matches the page mood naturally.
-- Light pages can go either way. Transparent works if the avatar is contrasty; a solid pale colour (like `#f6f6f9`) reads as more intentional.
+- Light pages can go either way. Transparent works if the avatar is contrasty; the `light` keyword (or a solid pale colour like `#f6f6f9`) reads as more intentional.
- If you're using a brand colour, desaturate it 20–30% for the embed background. Pure brand hues compete with the avatar; the same hue toned down recedes appropriately.
-- Avoid pure black `#000000` and pure white `#ffffff`. They look harsh next to a 3D-shaded avatar. A near-black like `#08080c` or a near-white like `#fafafa` are easier on the eye.
+- Avoid pure black `#000000` and pure white `#ffffff`. They look harsh next to a 3D-shaded avatar. The `dark` and `light` keywords are tuned near-black and near-white for exactly this reason.
---
-## Step 5 — `data-rotation-speed`: the idle animation pace
+## Step 6 — `framing`, `name-plate` and `poster`: the finishing details
-Out of the box, the agent rotates slowly while idle. This is a polite "I am alive" signal — it tells visitors the page isn't frozen, and gives the avatar presence without demanding attention.
+### `framing`
-You can tune that rotation:
+Controls how the camera crops the avatar:
```html
-<script
- src="https://three.ws/cdn/agent-3d.js"
- data-agent-id="YOUR_AGENT_ID"
- data-rotation-speed="0.5"
-></script>
+<agent-3d agent-id="YOUR_AGENT_ID" framing="portrait"></agent-3d>
```
-The value is a multiplier on the default speed. Useful values:
+- Default (**full**) — the whole body is in frame, with the camera favouring the upper body.
+- `portrait` — a head-to-mid-thigh crop. The face fills far more of the canvas, which is what you want for small floating widgets where a full body would render the face at postage-stamp size.
+
+Rule of thumb: `portrait` for floating widgets under ~360px wide, full framing for inline heroes where the whole character is the point. It's live — flip it at runtime and the camera reframes.
+
+### `name-plate`
-- `0` — no idle rotation. The agent stands still until interacted with. Use this for serious or professional contexts where motion is a distraction.
-- `0.3` — a subtle, slow turn. Reads as "calm and attentive".
-- `1` — the default. A steady, easy rotation.
-- `2` — twice as fast. The agent feels playful, energetic.
-- `4` — fast spinning. Almost always too much; use only on playful or marketing pages where you want grabbed attention.
+Conversational embeds (anything bound to a published agent) show a small overlay with the agent's name. Hide it when your page already introduces the agent in its own copy:
-Anything above `4` is allowed but rarely a good idea — it competes with the rest of your page and triggers motion sensitivity for some visitors. If your site has a "reduce motion" toggle, consider setting `data-rotation-speed="0"` when the user has opted out of motion.
+```html
+<agent-3d agent-id="YOUR_AGENT_ID" name-plate="off"></agent-3d>
+```
-You can pair rotation speed with size and position to build a coherent feel:
+Bare decoration avatars never show a plate, so there's nothing to turn off there.
-- "Quiet helper" — `data-size="small"`, `data-position="bottom-right"`, `data-rotation-speed="0.3"`
-- "Playful mascot" — `data-size="large"`, `data-position="bottom-left"`, `data-rotation-speed="2"`
-- "Hero element" — `data-size="xlarge"`, `data-position="inline"`, `data-rotation-speed="0.5"`
+### `poster`
----
+A poster image fills the frame while the 3D body downloads, then fades out at the exact moment the avatar appears — the same trick `<video poster>` uses. It also serves as the graceful fallback if a decoration avatar's body fails to load.
-## Step 6 — `data-greeting` and `data-name`: the small visible details
+```html
+<agent-3d
+ agent-id="YOUR_AGENT_ID"
+ poster="/img/agent-still.webp"
+></agent-3d>
+```
+
+Use a still render of the same avatar so the swap from image to live 3D is seamless. On slow connections this single attribute is the difference between "blank box, then character" and "character, which then comes alive".
-Two more attributes worth covering here because they're frequently used alongside the visual ones, even though their effects are textual rather than purely visual.
+---
-### `data-name`
+## Step 7 — `clip`: the idle animation
-Overrides the name shown in the agent's nameplate label.
+A decoration avatar — one embedded without chat, as pure visual presence — plays its `clip` attribute on loop, defaulting to `idle`:
```html
-<script
- src="https://three.ws/cdn/agent-3d.js"
- data-agent-id="YOUR_AGENT_ID"
- data-name="Iris"
-></script>
+<agent-3d
+ body="https://three.ws/avatars/default.glb"
+ clip="dance"
+ width="320px"
+ height="420px"
+></agent-3d>
```
-Useful when one underlying agent serves multiple sites and you want the visible label to differ. For example, the same agent might appear as "Iris" on your customer-facing site and "Internal Helper" on a private team page.
+The clip library is shared by every embed; useful ones for ambient presence include `idle`, `wave`, `dance`, `think`, `sitloop`, and `celebrate`. Looping clips loop; one-shot clips play once and settle back into idle with a crossfade rather than snapping. Change the attribute at runtime and playback re-cues to the new clip.
-### `data-greeting`
+Two built-in courtesies you don't have to code:
-Sets the first thing the agent says aloud after it's ready.
+- **Reduced motion.** When the visitor's OS has `prefers-reduced-motion` set, ambient playback is suppressed and the avatar holds a clean static pose instead. Explicit user-triggered animations still play.
+- **Lazy boot.** Offscreen avatars don't render at all until scrolled near, so a page with several decoration embeds doesn't burn GPU on the ones nobody is looking at.
-```html
-<script
- src="https://three.ws/cdn/agent-3d.js"
- data-agent-id="YOUR_AGENT_ID"
- data-greeting="Welcome to our site. Click me to ask anything."
-></script>
+---
+
+## Step 8 — Theming with CSS
+
+Because `<agent-3d>` is a real element on your page, ordinary CSS reaches it. The chat chrome exposes its design tokens as CSS custom properties, which you can override from your stylesheet:
+
+```css
+agent-3d {
+ --agent-accent: #e11d48; /* thinking dots, message accents, spinners */
+ --agent-surface: rgba(24, 16, 20, 0.92); /* message + panel surfaces */
+ --agent-bubble-bg: rgba(255, 245, 247, 0.95); /* speech bubble */
+ --agent-bubble-color: #2a0a12; /* speech bubble text */
+ --agent-bubble-radius: 12px; /* corner rounding */
+ --agent-chat-font: 'Inter', system-ui, sans-serif;
+}
+```
+
+For structural styling, the shadow DOM exposes named parts — `stage` (the 3D canvas area), `chrome` (the chat column), `chat` (the message log), `name-plate`, and `loading`:
+
+```css
+agent-3d::part(name-plate) {
+ font-family: 'Inter', sans-serif;
+ letter-spacing: 0.02em;
+}
```
-The greeting is spoken with the agent's configured TTS voice and shown as a speech bubble. We cover this attribute in much more depth — including how to handle browser autoplay restrictions and how to subtitle the greeting for accessibility — in the dedicated tutorial: [Add a greeting and first speech line](/tutorials/greeting-and-first-speech).
+Set the custom properties to your brand tokens once, in the same stylesheet as the rest of your site, and every embed on every page inherits them.
---
-## Step 7 — Putting it all together: a branded SaaS embed
+## Step 9 — Putting it all together: a branded SaaS embed
To bring this from theory to a real example, here is a complete, branded embed for a hypothetical productivity SaaS called "Lumen". The brand colours are a dark indigo and a warm cream; the brand voice is calm and professional.
@@ -304,6 +308,11 @@ To bring this from theory to a real example, here is a complete, branded embed f
text-decoration: none;
font-weight: 500;
}
+ /* Brand-match the agent chrome */
+ agent-3d {
+ --agent-accent: #2a2a4d;
+ --agent-chat-font: 'Inter', system-ui, sans-serif;
+ }
</style>
</head>
<body>
@@ -316,93 +325,97 @@ To bring this from theory to a real example, here is a complete, branded embed f
<a class="cta" href="/signup">Try Lumen free</a>
</main>
- <script
- src="https://three.ws/cdn/agent-3d.js"
- data-agent-id="YOUR_AGENT_ID"
- data-name="Lumi"
- data-size="medium"
- data-position="bottom-right"
- data-background-color="#1a1a2e0d"
- data-rotation-speed="0.4"
- data-greeting="Hi, I'm Lumi. Click me if you have a question about Lumen."
- ></script>
+ <script type="module" src="https://three.ws/agent-3d/1.5.2/agent-3d.js"></script>
+ <agent-3d
+ agent-id="YOUR_AGENT_ID"
+ mode="floating"
+ position="bottom-right"
+ offset="24px 24px"
+ width="300px"
+ height="400px"
+ background="light"
+ framing="portrait"
+ ></agent-3d>
</body>
</html>
```
-The agent here is named to fit the brand ("Lumi" — short, soft, matches "Lumen"). The position is the conventional bottom-right where SaaS visitors expect to find help. The size is `medium` — present but not dominating the hero. The background is a very pale indigo with `0d` alpha (about 5% opacity), which gives the widget a barely-perceptible tinted panel against the cream page; this reads as polished without being a literal coloured box. The rotation is slowed to `0.4` to match the calm brand voice. The greeting is one sentence that explains who Lumi is and invites action.
+The position is the conventional bottom-right where SaaS visitors expect to find help. The size is a restrained 300 × 400 — present but not dominating the hero — and responsive scaling (on by default) collapses it to a pill on phones. The `light` background gives the widget a pale, intentional panel against the cream page, with bubble contrast handled automatically. Portrait framing keeps the agent's face legible at this size, and the accent custom property ties the chat chrome to the brand indigo.
Compare this to a more playful brand. Imagine a children's learning app, "Sparrow", with bright colours and a cheerful tone:
```html
-<script
- src="https://three.ws/cdn/agent-3d.js"
- data-agent-id="YOUR_AGENT_ID"
- data-name="Pip"
- data-size="large"
- data-position="bottom-left"
- data-background-color="transparent"
- data-rotation-speed="1.6"
- data-greeting="Hi! I'm Pip. Wanna play a learning game?"
-></script>
+<agent-3d
+ agent-id="YOUR_AGENT_ID"
+ mode="floating"
+ position="bottom-left"
+ width="360px"
+ height="480px"
+ background="transparent"
+></agent-3d>
```
-Same attribute set, completely different feel. The point is that the four visual attributes — size, position, background, rotation — combine to express your brand without you writing a single line of CSS or JavaScript.
+Same attribute set, completely different feel — bigger, transparent so the avatar sits directly on the colourful page, full-body framing so the whole character shows. The point is that a handful of attributes — mode, position, size, background, framing — combine to express your brand without a build step.
---
-## Step 8 — Programmatic updates after load
+## Step 10 — Programmatic control after load
+
+A note for engineers: the `<agent-3d>` element exposes a JS API for driving the agent from your page's event flow. The full tour lives in [Drive the agent with the JavaScript API](/tutorials/js-api-events); here is the appearance-relevant slice.
-A note for engineers: the script element itself exposes a small JS API for cases where you need to interact with the agent after it has loaded. The customisation attributes above are read once, but you can still trigger animations and speech dynamically.
+Wait for the `agent:ready` event before calling methods — it fires once the body is loaded and the scene is live:
```html
-<script
- id="agent-script"
- src="https://three.ws/cdn/agent-3d.js"
- data-agent-id="YOUR_AGENT_ID"
-></script>
-
-<script>
- const agentScript = document.getElementById('agent-script');
-
- agentScript.addEventListener('agent:ready', () => {
- // The agent is fully loaded and visible
- agentScript.playAnimationByHint('wave');
- });
+<agent-3d id="agent" agent-id="YOUR_AGENT_ID" mode="floating"></agent-3d>
- // Trigger speech from a button somewhere on the page
- document.querySelector('#help-button').addEventListener('click', () => {
- agentScript.speak('Sure, let me help you with that.');
+<script type="module">
+ const agent = document.getElementById('agent');
+
+ agent.addEventListener('agent:ready', () => {
+ agent.wave(); // quick hello gesture
});
- // Play a specific named animation by exact match
+ // Play a named clip with polished defaults (loop flag + reduced-motion honoured)
document.querySelector('#celebrate-button').addEventListener('click', () => {
- agentScript.playAnimation('jump_celebrate');
+ agent.playClip('celebrate', { userInitiated: true });
+ });
+
+ // Re-anchor and resize on the fly. Set `offset` before `position` —
+ // the position change is what triggers the layout pass that reads it.
+ document.querySelector('#move-button').addEventListener('click', () => {
+ agent.setAttribute('offset', '16px 16px');
+ agent.setPosition('top-left');
+ agent.setSize('280px', '380px');
});
</script>
```
-The methods on the script element are:
+The appearance-related methods on the element:
-- `playAnimation(name)` — plays an animation clip by exact name. The clip names depend on which avatar is paired; you can list them in the editor.
-- `playAnimationByHint(hint)` — fuzzy-matches a partial name. Useful when you don't know the exact clip but you know the intent: `'wave'`, `'talk'`, `'yes'`, `'no'`, `'point'`, `'idle'`.
-- `speak(text)` — makes the agent say the given text using its TTS voice.
+- `play(name)` — plays an animation clip by exact name from the shared clip library (or one baked into the GLB).
+- `playClip(name, { fade_ms, userInitiated })` — the polished version of `play`: honours the clip's loop flag (one-shots settle back into idle) and respects `prefers-reduced-motion` unless the call is user-initiated.
+- `playEmote(name)` — a named emote (`'cheer'`, `'flinch'`, `'celebrate'`) with a built-in fallback chain, so it always does *something* on any rig.
+- `wave()` — the hello gesture.
+- `lookAt(target)` — turn the head toward `'camera'`, `'center'`, or `'user'`.
+- `setMode(mode)`, `setPosition(pos, offset)`, `setSize(width, height)` — attribute setters with the same live effect as editing the HTML.
-These are independent of the appearance attributes. You can mix them freely — set size and position declaratively, then drive animations and speech from your page's event flow.
+These are independent of the declarative attributes. Set the look declaratively, then drive motion from your page's events.
---
## What you learned
-You now know the full set of visual customisation attributes the embed loader honours:
+You now know the full set of appearance attributes the `<agent-3d>` element honours:
-- `data-size` controls dimensions, with named presets and explicit pixel values
-- `data-position` controls anchor: four corners plus inline mode
-- `data-background-color` controls the canvas backdrop, transparent or any hex with optional alpha
-- `data-rotation-speed` controls the idle animation pace
-- `data-name` overrides the visible nameplate
-- `data-greeting` sets the first spoken message
-- The script element itself exposes `playAnimation`, `playAnimationByHint`, and `speak` for runtime control
+- `mode` picks the layout: `inline` (default), `floating`, `section`, `fullscreen`
+- `width` / `height` accept any CSS length; `responsive` (on by default) scales them per-device and collapses floating widgets to a pill on phones
+- `position` and `offset` anchor a floating widget to any corner or centre edge
+- `background` is `transparent` (default), `dark`, `light`, or any CSS colour
+- `framing="portrait"` crops to head-and-shoulders for small widgets
+- `name-plate="off"` hides the name overlay; `poster` covers the load with a still image
+- `clip` picks the ambient animation for decoration avatars
+- CSS custom properties (`--agent-accent` and friends) and `::part()` selectors theme the chrome
+- The element's JS API (`play`, `playClip`, `playEmote`, `wave`, `lookAt`, `setMode`, `setPosition`, `setSize`) drives everything at runtime
Most production embeds use four or five of these together. The combination is what makes an agent feel like part of the page rather than a widget glued on.
@@ -411,8 +424,8 @@ Most production embeds use four or five of these together. The combination is wh
## Next steps
- [Pick and swap an avatar in Studio](/tutorials/swap-avatar-in-studio) — change the agent's body without touching your snippet
-- [Add a greeting and first speech line](/tutorials/greeting-and-first-speech) — go deeper on the spoken introduction, autoplay, and accessibility
-- [Embed in 30 seconds](/tutorials/embed-in-30-seconds) — revisit the one-line embed if you skipped any setup
+- [Add a greeting and first speech line](/tutorials/greeting-and-first-speech) — give the agent its spoken introduction
+- [Embed in 30 seconds](/tutorials/embed-in-30-seconds) — revisit the two-tag embed if you skipped any setup
- [Share your agent](/tutorials/share-your-agent) — generate a public URL, QR code, and social previews
- [Embed on a website](/tutorials/embed-on-website) — the full embed reference including framework-specific guidance
- [Build your first agent](/tutorials/first-agent) — drop down a level into manifests and skills
diff --git a/docs/tutorials/deploy-to-vercel-custom-domain.md b/docs/tutorials/deploy-to-vercel-custom-domain.md
index cf41951ac..317c3877e 100644
--- a/docs/tutorials/deploy-to-vercel-custom-domain.md
+++ b/docs/tutorials/deploy-to-vercel-custom-domain.md
@@ -1,5 +1,7 @@
# Deploy to Vercel with a Custom Domain
+> **Note — three.ws production no longer runs on Vercel.** On 2026-07-07 the hosted platform migrated to Google Cloud Run: one container ([server/index.mjs](https://github.com/nirholas/three.ws/blob/main/server/index.mjs)) serves the frontend and all API routes, deployed with `npm run deploy:gcp` (see [docs/build.md](/docs/build) and the ops runbook at `docs/ops/gcp-production.md`). This guide remains fully valid for **self-hosting your own fork on Vercel** — the repo's `vercel.json` still works there — but it does not describe how the production site is operated.
+
By the end of this tutorial you have a live three.ws fork running at a domain you own — `agent.yourcompany.com` or whatever you choose. CI is wired so every commit type-checks, every PR generates a preview, and merges to `main` ship to production. SSL is issued automatically. Rollbacks take one click.
This is the deployment-side companion to [self-host-agent-backend](/tutorials/self-host-agent-backend). That tutorial covered the architectural moving parts; this one walks the deploy and operate flow end-to-end without re-explaining what each component does.
@@ -43,7 +45,7 @@ When `vercel link` asks "Set up and deploy?", answer yes, accept the default pro
vercel
```
-Vercel installs deps, runs `npm run build`, and deploys a preview. After about three minutes you'll get a URL like `https://three-ws-yourname.vercel.app`. Hit `/api/healthz`. You should see `{"ok": true}` or similar — the platform is live, even if every other route 404s or 500s because env vars aren't set yet.
+Vercel installs deps, runs `npm run build`, and deploys a preview. After about three minutes you'll get a URL like `https://three-ws-yourname.vercel.app`. Hit `/api/healthz`. You should see `{"status":"ok", ...}` — the platform is live, even if every other route 404s or 500s because env vars aren't set yet.
That's the floor. From here every change is incremental.
@@ -379,9 +381,9 @@ A great CI step is exercising the preview URL after Vercel deploys it. Add to `.
run: |
set -e
curl -fsS "$PREVIEW_URL/api/healthz" | tee /tmp/health.json
- test "$(jq -r .ok /tmp/health.json)" = "true"
+ test "$(jq -r .status /tmp/health.json)" = "ok"
curl -fsS -I "$PREVIEW_URL/" | head -1 | grep -q "200"
- curl -fsS -I "$PREVIEW_URL/cdn/agent-3d.js" | head -1 | grep -q "200"
+ curl -fsS -I "$PREVIEW_URL/dist-lib/agent-3d.js" | head -1 | grep -q "200"
```
Three checks: the health endpoint responds, the home page returns 200, the CDN bundle exists. If any fail, the PR's CI goes red. Add more checks as you find behaviors worth gating on.
@@ -442,7 +444,7 @@ Before you call it done:
- DNS resolves and SSL works for your custom domain
- `/api/healthz` returns 200
- A test agent can be created in the dashboard, edited, and embedded on a third-party page
-- The CDN bundle at `https://agent.yourcompany.com/cdn/agent-3d.js` serves correctly with `Cache-Control` and a hashed/versioned filename in the source map
+- The embed bundle at `https://agent.yourcompany.com/dist-lib/agent-3d.js` serves correctly with a `Cache-Control` header
- GitHub → Vercel integration is live; pushing to `main` triggers a production deploy and pushing a branch triggers a preview
- CI passes on a recent PR and the preview URL is reachable
- Sentry receives a deliberately thrown error from a preview deploy (test once, then remove the test)
diff --git a/docs/tutorials/emotion-from-data.md b/docs/tutorials/emotion-from-data.md
index a7e08e876..c96ab1a8e 100644
--- a/docs/tutorials/emotion-from-data.md
+++ b/docs/tutorials/emotion-from-data.md
@@ -46,7 +46,7 @@ The platform runs a public, unauthenticated sentiment scorer over live pump.fun
<head>
<meta charset="UTF-8">
<title>Sentiment-driven agent</title>
- <script type="module" src="https://three.ws/cdn/agent-3d.js"></script>
+ <script type="module" src="https://three.ws/agent-3d/latest/agent-3d.js"></script>
</head>
<body>
<agent-3d id="agent" agent-id="YOUR_AGENT_ID" mode="inline" width="360px" height="480px"></agent-3d>
diff --git a/docs/tutorials/greeting-and-first-speech.md b/docs/tutorials/greeting-and-first-speech.md
index f61948d5a..e8530314c 100644
--- a/docs/tutorials/greeting-and-first-speech.md
+++ b/docs/tutorials/greeting-and-first-speech.md
@@ -2,264 +2,258 @@
A silent agent on a page is half an agent. The avatar appears, animates, looks ready — but a visitor lands, glances at it, and isn't sure whether to engage. They look for a chat input. They wonder if the thing is for them.
-A spoken greeting fixes all of that in one sentence. The agent says hi the moment it's ready. Visitors hear who it is and what it's for. They know it's interactive. They know it's responsive. They speak back.
+A greeting fixes all of that in one sentence. The agent introduces itself the moment it's ready. Visitors see who it is and what it's for. They know it's interactive. They know it's responsive. They speak back.
-This tutorial covers the `data-greeting` attribute end to end: how to write a good greeting, when it fires, how the browser's autoplay rules affect it, and how to make it accessible to visitors who have audio off or have a disability that requires text alternatives.
+This tutorial covers the greeting flow end to end: waiting for the `agent:ready` event, triggering the first line with `say()`, shaping what the agent says through its instructions, how the browser's audio autoplay rules affect the spoken part, and how to make the greeting accessible to visitors who have audio off.
**What you'll build:**
-- An agent that greets every visitor by voice the moment it's ready
-- A greeting that works on Chrome, Safari, Firefox, mobile browsers — every common surface
-- A subtitle / caption so the greeting is readable, not just audible
-- A reusable pattern for scripted greetings versus LLM-generated dynamic ones
+- An agent that greets every visitor the moment it's ready
+- A greeting personality that lives in the agent's instructions, so every greeting fits the brand
+- A live transcript region so the greeting is readable, not just audible
+- A reusable pattern for text-first greetings versus guaranteed-audible ones
- A clear understanding of browser autoplay rules and how to work with them
**Prerequisites:** A page with the embed working from [Embed in 30 seconds](/tutorials/embed-in-30-seconds). Your agent should already be saved with a brain configured.
---
-## Step 1 — The one-attribute version
+## Step 1 — The minimal greeting
-The minimum-effort greeting is one attribute on the embed script tag:
+There is no magic greeting attribute — the greeting is three lines of JavaScript next to your embed. Wait for the element's `agent:ready` event, then hand the agent an opening cue with `say()`:
```html
-<script
- src="https://three.ws/cdn/agent-3d.js"
- data-agent-id="YOUR_AGENT_ID"
- data-greeting="Hi, I'm Iris. Click me if you have a question."
-></script>
+<script type="module" src="https://three.ws/agent-3d/1.5.2/agent-3d.js"></script>
+<agent-3d id="agent" agent-id="YOUR_AGENT_ID" mode="floating" voice eager></agent-3d>
+
+<script>
+ const agent = document.getElementById('agent');
+ agent.addEventListener('agent:ready', () => {
+ agent.say('Hi! Who are you?');
+ });
+</script>
```
-When the agent is fully loaded (animations bound, scene ready, voice initialised), it speaks the greeting using its configured TTS voice. A speech bubble shows the same text on screen, fading out a few seconds after the line finishes.
+`say(text)` sends the text to the agent's brain as a visitor message. The agent thinks, generates a reply in its own voice — the greeting — and delivers it: the reply streams into the speech bubble above the avatar, lands in the chat thread, drives the talking animation and lip-sync, and (because the element carries the `voice` attribute) is spoken aloud with the agent's TTS voice.
-This works. Most embed installations should ship with a greeting attribute. The rest of this tutorial is about doing it well rather than doing it at all.
+Two things worth knowing about this snippet:
----
+- The cue you pass to `say()` appears in the chat thread as the visitor's message, exactly as if they had typed it. That's why the example uses a natural opener like "Hi! Who are you?" — it reads as the start of a conversation, not as plumbing. (It's the same cue the embed's built-in "Say hi" suggestion chip sends.)
+- The boolean `voice` attribute is what makes JS-triggered `say()` calls audible. Without it, the greeting still renders as text and animation — just silently. Messages the visitor types into the chat input are always voiced.
-## Step 2 — When the greeting fires
+That's a working greeting. The rest of this tutorial is about doing it well rather than doing it at all.
-The embed dispatches a `agent:ready` event on the script element once the avatar is loaded, the camera is positioned, the lighting is set, and the voice subsystem is initialised. The greeting fires on that event automatically when the `data-greeting` attribute is set.
+---
-In rough terms, the timing on a typical broadband connection is:
+## Step 2 — When the greeting fires
-1. **0 ms** — Page HTML is parsed; the script tag is encountered.
-2. **0–500 ms** — `agent-3d.js` is fetched from the CDN and starts running.
-3. **500–1500 ms** — The agent's manifest is fetched from the platform API.
-4. **1500–3500 ms** — The GLB body is downloaded and parsed.
-5. **3500–4000 ms** — The avatar appears, the scene renders, the `agent:ready` event fires.
-6. **4000–4500 ms** — The greeting starts speaking. The speech bubble appears.
+`agent:ready` fires once the whole boot pipeline has finished: manifest fetched, GLB body downloaded and rigged, memory loaded, skills installed, brain runtime constructed. Its `detail` carries `{ agent, manifest }`, and the event bubbles and crosses the shadow boundary, so you can also listen at `document` level if you attach the listener before the element boots.
-On a fast connection with the bundle cached, this collapses to about two seconds total. On a slow mobile connection, it can stretch to six or seven seconds; the agent fades in gracefully and the greeting fires when ready, so visitors never see a half-loaded character.
+Two timing behaviours matter for greetings:
-If you want to control the timing precisely — say, wait for an extra moment before greeting so the visitor has a chance to focus — you can use the JS API and skip `data-greeting`:
+**The element boots lazily.** By default `<agent-3d>` waits until it is scrolled near the viewport (with a 300px head start) before it downloads anything, which means `agent:ready` — and your greeting — fires when the visitor reaches the agent, not necessarily at page load. For a floating widget that should greet immediately, add the `eager` attribute as in Step 1. For an inline agent halfway down a landing page, lazy is usually what you want: the agent greets when the visitor scrolls to it.
-```html
-<script
- id="agent-script"
- src="https://three.ws/cdn/agent-3d.js"
- data-agent-id="YOUR_AGENT_ID"
-></script>
+**`say()` waits for readiness on its own.** If you call `say()` before boot finishes, the element holds the message and delivers it once the runtime is up (only the most recent pending message is kept). Listening for `agent:ready` is still the clearest structure — it makes the ordering explicit and gives you a place to hang other on-ready work — but a greeting fired "too early" is not lost.
-<script>
- const agent = document.getElementById('agent-script');
+If you want a beat of breathing room so the visitor has a chance to notice the avatar before it talks:
- agent.addEventListener('agent:ready', async () => {
- // Wait two seconds after the agent is visible before speaking
- await new Promise(r => setTimeout(r, 2000));
- agent.speak('Hi, I\'m Iris. Take your time looking around.');
- });
-</script>
+```js
+agent.addEventListener('agent:ready', () => {
+ setTimeout(() => agent.say('Hi! Who are you?'), 1500);
+});
```
-Both approaches produce the same audible result. Use the attribute for simple cases; use the JS API when you need timing control or want the greeting to depend on something else on the page.
+You can also watch boot progress via the `agent:load-progress` event, whose detail is `{ phase, pct }` with phases `manifest`, `body`, `memory`, `skills`, and `brain` — useful if you're rendering your own loading indicator around the embed.
---
-## Step 3 — What voice the agent uses
-
-The voice is set in the agent's configuration at [https://three.ws/create](https://three.ws/create), not on the embed snippet. Open the editor, open your agent, open the **Voice** panel.
+## Step 3 — Where the greeting's personality lives
-You have a few options:
+`say()` supplies the cue; the *content* of the greeting comes from the agent's configured personality. There are two places that personality can live, depending on how you embedded.
-- **Platform voices** — A selection of pre-tuned voices in different languages, accents, and timbres. These work everywhere and need no extra configuration. They are produced by a high-quality cloud TTS engine.
-- **Browser voice (fallback)** — Uses the browser's built-in `SpeechSynthesis` API. Available everywhere with no cost, but quality varies — Chrome on macOS sounds quite good, while Chrome on a fresh Ubuntu machine can sound mechanical. Use this for projects where you can't pay for cloud TTS but you want speech to "just work".
-- **ElevenLabs voice** — If your agent is configured with an ElevenLabs voice ID, the platform calls ElevenLabs for TTS. This is the highest quality option, and it's the only way to use a voice clone of your own voice. There is a per-character cost. Best for hero embeds where voice quality is part of the experience.
+### Published agents (`agent-id`)
-Whichever voice you pick at the brain level, the greeting uses it. You don't configure voice per greeting — one agent has one voice.
+If you embed with `agent-id`, the personality is whatever you saved in the editor at [https://three.ws/create](https://three.ws/create) — open your agent's **Personality** panel and shape the system prompt there. To make greetings consistently on-brand, add explicit greeting guidance to the prompt:
-If you want different voices for different embeds, the cleanest pattern is to maintain two agents (with the same personality, different voice configs) and embed each on the relevant pages. See [Pick and swap an avatar in Studio](/tutorials/swap-avatar-in-studio) for the broader principle of cloning agents.
+```
+When a visitor greets you or asks who you are, introduce yourself in one or
+two sentences. Mention your name. Say you can help pick the right Lumen plan.
+Invite them to ask anything. Never open with more than two sentences.
+```
----
+Save, reload your page, and the same `say('Hi! Who are you?')` cue now produces a greeting that follows your rules — every visitor, phrased freshly each time.
-## Step 4 — Browser autoplay restrictions
+The agent's TTS voice is also part of its saved configuration (the **Voice** panel in the editor), not the embed snippet. One agent, one voice; the greeting uses it like every other line.
-Here is the most important practical point in this tutorial. Modern browsers do not let websites play audio automatically. The reasons are good: spammy auto-playing video ads, suddenly loud pages that ambush users, accidental playback when a tab loads in the background. But the rules apply to your agent's greeting too.
+### Self-configured embeds (`body` + `brain` + `instructions`)
-The exact policy varies by browser and platform, but the rough rules are:
+If you embed a bare GLB instead of a published agent, the element builds the personality from its own attributes. `instructions` is the system prompt, `brain` picks the model (`"free"` resolves to the platform's host-paid free model), and `chat` opts the avatar into the conversational chrome:
-- **Chrome / Edge desktop** — Audio may play automatically if the user has interacted with your domain before (a click, a keypress, a scroll counts in some cases). On first visit, audio is blocked until the user interacts.
-- **Safari desktop** — Stricter. Audio is blocked until the user interacts, every visit.
-- **Firefox desktop** — Permissive by default, but users can tighten the policy and many do.
-- **iOS Safari** — Strictest. Audio is blocked until the user taps the page. No exceptions.
-- **Android Chrome** — Similar to desktop Chrome. Mostly works after first interaction, sometimes works on first load.
+```html
+<script type="module" src="https://three.ws/agent-3d/1.5.2/agent-3d.js"></script>
+<agent-3d
+ id="agent"
+ body="https://three.ws/avatars/default.glb"
+ name="Iris"
+ brain="free"
+ instructions="You are Iris, the guide for the Lumen productivity app. When a visitor greets you, introduce yourself in one warm sentence and invite them to ask about Lumen. Keep every reply under three sentences."
+ chat
+ voice
+ eager
+></agent-3d>
-The embed handles this for you, but it's important to understand what "handles" means:
+<script>
+ const agent = document.getElementById('agent');
+ agent.addEventListener('agent:ready', () => {
+ agent.say('Hi! Who are you?');
+ });
+</script>
+```
-### What the embed does automatically
+This is a complete, self-contained page — no saved agent required. The `instructions` attribute is only read for these self-configured embeds; on an `agent-id` embed the published personality wins, so edit it in the editor instead.
-When the greeting fires:
+---
-1. The embed attempts to play the audio.
-2. If the browser allows it, the audio plays normally and the speech bubble shows the spoken text.
-3. If the browser blocks it, the embed silently catches the rejection, *still shows the speech bubble* with the greeting text, and *queues* the audio to play the moment the user interacts with the page (any click, tap, key press, or scroll).
+## Step 4 — Tailor the greeting to the visitor
-So in the blocked case, the visitor sees a speech bubble that says "Hi, I'm Iris. Click me if you have a question." even if no sound played. When they tap anywhere — including tapping the agent to start a chat — the buffered greeting plays at that moment.
+Because the cue is ordinary JavaScript, it can carry whatever context you know at page-load time — and the brain will weave it into the greeting:
-This is the right default. The greeting is still effective on the worst-case browsers (because the text is visible), and the visitor isn't surprised by audio on a fresh page load.
+```html
+<script type="module" src="https://three.ws/agent-3d/1.5.2/agent-3d.js"></script>
+<agent-3d id="agent" agent-id="YOUR_AGENT_ID" mode="floating" voice eager></agent-3d>
-### What you can do to improve the rate of autoplay success
+<script>
+ const agent = document.getElementById('agent');
-A few practical tricks that bump the autoplay-success rate without working around the rules:
+ function greetingCue() {
+ const params = new URLSearchParams(location.search);
+ const returning = localStorage.getItem('hasVisited') === 'yes';
+ if (returning) {
+ return "Hi again — I've visited before. Anything new since last time?";
+ }
+ if (params.get('utm_campaign') === 'launch-2026') {
+ return "Hi! I came from the launch announcement. What's new?";
+ }
+ return 'Hi! Who are you?';
+ }
-- **Encourage a small interaction before the greeting fires.** If your page has a "Skip intro" button or a "Welcome" splash, audio is unlocked the moment it's dismissed. Then the greeting plays normally.
-- **Set the audio output level appropriately.** A quieter greeting (configured at the brain level) feels less ambushing if it does play automatically, which makes users less likely to mute the tab.
-- **Don't compete with other audio.** If your page has a background video that autoplays muted, that's fine. If it has a hero video with sound, the greeting will sound chaotic — turn the hero off.
+ agent.addEventListener('agent:ready', () => {
+ agent.say(greetingCue());
+ localStorage.setItem('hasVisited', 'yes');
+ });
+</script>
+```
-### What you should not do
+The pattern is: listen for `agent:ready`, choose a cue in JS, call `say()`. The visitor always gets a greeting, and the greeting reflects what you know about them — the brain handles the phrasing.
-A few patterns to avoid, even though you'll see them on other sites:
+If your page logic needs the greeting text back (say, to mirror it into your own UI), use `ask()` instead — it sends the same way but resolves with the reply:
-- Don't fake the autoplay by attaching invisible click handlers that "auto-click" on page load. Browsers detect these and the page gets penalised in autoplay quotas.
-- Don't fall back to a louder beep or notification sound if the greeting fails. The user is in control; respect it.
-- Don't write a "click to enable audio" gate as the first thing on the page. The agent's speech bubble already serves this purpose more naturally.
+```js
+agent.addEventListener('agent:ready', async () => {
+ const greeting = await agent.ask('Hi! Who are you?');
+ console.log('Agent greeted with:', greeting);
+});
+```
---
-## Step 5 — Make the greeting accessible
-
-A spoken greeting is wonderful for the majority of visitors. But some visitors:
-
-- Have audio off, by choice or by default
-- Are using a screen reader and don't want speech bubbles popping in
-- Have a hearing impairment
-- Are deaf
-- Are in a quiet environment (a library, a meeting, a sleeping baby's room) and won't enable audio
-
-The embed handles this automatically — the speech bubble shows the greeting text, so visitors who can't hear it can still read it. But you should write your greeting with the assumption that someone might read it before they hear it.
+## Step 5 — `speak()` is a gesture, not speech
-This means:
+The element also has a `speak(text)` method, and it's important to be precise about what it does: **`speak()` plays the talking animation, and nothing else.** It sizes the gesture to the length of the text you pass, trying the rig's talk clip and falling back to a nod or a wave — but it does not contact the brain, does not render a speech bubble, and does not produce any audio.
-- Make the greeting useful as text. "Hi, I'm Iris. Click me if you have a question." reads as well as it sounds. "Hi!" alone reads as a stub.
-- Avoid relying on pronunciation. "He's pronounced like the letter J in Japanese" works in audio but is weird in writing.
-- Avoid pause cues that don't translate. "Hi. (pause) I'm Iris" works in audio but looks broken as text.
-
-For visitors using a screen reader, the speech bubble is rendered with appropriate ARIA roles. Screen readers announce it as "the agent says: <greeting text>" rather than just blasting the text without context. You don't need to do anything to enable this; the embed handles it.
-
-If you want a heavier-handed accessibility setup — for instance, a permanent transcript pane next to the agent — you can listen to the speech events from JS:
+That makes it the wrong tool for a greeting on its own, and the right tool when your page supplies the words and you just want the avatar to visibly "deliver" them — a custom caption, a scripted onboarding line you render yourself:
```html
-<div id="transcript" aria-live="polite" style="margin-top: 12px; color:#666; font-size: 0.9rem;">
- <strong>Agent says:</strong> <span id="transcript-text">…</span>
+<agent-3d id="agent" agent-id="YOUR_AGENT_ID" mode="floating" eager></agent-3d>
+<div id="caption" role="status" aria-live="polite"
+ style="position: fixed; bottom: 460px; right: 24px; max-width: 280px;
+ padding: 10px 14px; border-radius: 12px; background: #fff;
+ color: #1a1a2e; box-shadow: 0 4px 24px rgba(0,0,0,.2); font: 14px system-ui;">
</div>
-<script
- id="agent-script"
- src="https://three.ws/cdn/agent-3d.js"
- data-agent-id="YOUR_AGENT_ID"
- data-greeting="Welcome. I'm here to help you find the right product."
-></script>
-
<script>
- const agent = document.getElementById('agent-script');
- const out = document.getElementById('transcript-text');
+ const agent = document.getElementById('agent');
+ const caption = document.getElementById('caption');
- agent.addEventListener('speak', (event) => {
- out.textContent = event.detail.text;
+ agent.addEventListener('agent:ready', () => {
+ const line = "Hi, I'm Iris. Click me if you have a question.";
+ caption.textContent = line; // your page shows the exact words
+ agent.speak(line); // the avatar mouths along, silently
+ setTimeout(() => { caption.textContent = ''; }, 6000);
});
</script>
```
-The `speak` event fires every time the agent says anything — greeting included — with the text in `event.detail.text`. Pipe it into an `aria-live="polite"` region and screen readers announce it. Sighted visitors with audio off see the transcript in real time.
+The trade-off is exactness versus life: `speak()` plus your own caption gives you a fixed, word-for-word scripted line with zero LLM involvement; `say()` gives you a living greeting in the agent's voice — bubble, audio, and all — but freshly phrased each time. If you need the audible line to be word-for-word, put the exact sentence in the instructions ("When a visitor greets you, reply with exactly: …") and use `say()`; the model will deliver it near-verbatim, and it stays in the real speech pipeline.
---
-## Step 6 — Scripted greetings versus dynamic ones
+## Step 6 — Browser autoplay rules
-`data-greeting` is a static string. Whatever you put in the attribute is exactly what the agent says, every visitor, every page load. This is right for most embeds — the greeting should feel reliable.
+Here is the most important practical point in this tutorial. Modern browsers do not let websites play audio before the visitor has interacted with the page. The reasons are good — spammy auto-playing ads, suddenly loud tabs — but the rules apply to your agent's spoken greeting too. Chrome and Edge may allow audio if the visitor has engaged with your domain before; Safari and iOS block it on every fresh load until the first tap or keypress.
-But there are cases where you want the greeting to adapt to the visitor:
+The saving grace: **the greeting's text always lands.** The reply streams into the speech bubble and the chat thread whether or not the audio was allowed to play, so a greeting fired on `agent:ready` is never wasted — worst case it's read instead of heard.
-- A returning visitor should be greeted differently from a first-time visitor
-- A visitor coming from a particular ad campaign should hear a relevant greeting
-- A visitor whose preferred language is detectable should hear the greeting in that language
+That gives you two clean patterns. Pick one; don't chain them (the runtime processes one conversational turn at a time, so a second `say()` fired while the greeting is still streaming will surface a "still thinking" notice instead).
-For dynamic greetings, skip `data-greeting` and use the JS API:
+**Pattern A — text-first (the default).** Greet on `agent:ready` as in Step 1. On permissive browsers the greeting is spoken; on strict ones it's read. Ship this unless spoken audio is essential to the experience.
-```html
-<script
- id="agent-script"
- src="https://three.ws/cdn/agent-3d.js"
- data-agent-id="YOUR_AGENT_ID"
-></script>
+**Pattern B — guaranteed-audible.** Hold the greeting until the visitor's first interaction, which unlocks audio everywhere:
-<script>
- const agent = document.getElementById('agent-script');
+```js
+const agent = document.getElementById('agent');
+
+const greetOnFirstTouch = () => {
+ document.removeEventListener('pointerdown', greetOnFirstTouch);
+ document.removeEventListener('keydown', greetOnFirstTouch);
+ agent.say('Hi! Who are you?', { voice: true });
+};
+document.addEventListener('pointerdown', greetOnFirstTouch);
+document.addEventListener('keydown', greetOnFirstTouch);
+```
- function pickGreeting() {
- const params = new URLSearchParams(location.search);
- const utm = params.get('utm_campaign');
- const returning = localStorage.getItem('hasVisited') === 'yes';
- const hour = new Date().getHours();
- const timeOfDay = hour < 12 ? 'morning' : hour < 18 ? 'afternoon' : 'evening';
+The `{ voice: true }` option forces the spoken reply even without the `voice` attribute on the element.
- if (returning) {
- return 'Welcome back. Anything you wanted to ask last time?';
- }
- if (utm === 'launch-2026') {
- return 'Hi there. You\'re here from the launch announcement — let me show you what\'s new.';
- }
- return `Good ${timeOfDay}. I\'m Iris. Click me to ask anything about our service.`;
- }
+And a few patterns to avoid, even though you'll see them on other sites: don't simulate clicks to trick the autoplay gate (browsers detect it and penalise the page), and don't put a full-page "click to enable audio" wall in front of your content — the visitor's first natural interaction is enough.
- agent.addEventListener('agent:ready', () => {
- agent.speak(pickGreeting());
- localStorage.setItem('hasVisited', 'yes');
- });
-</script>
-```
+---
-The pattern is: skip the attribute, listen for `agent:ready`, choose a greeting in JS, call `speak()`. The visitor always gets a greeting, and the greeting is tailored to what you know about them at page-load time.
+## Step 7 — Make the greeting accessible
-### Going further: LLM-generated greetings
+Some visitors have audio off, use a screen reader, have a hearing impairment, or are somewhere they won't enable sound. The embed already covers the basics: the chat thread is an ARIA live log (`role="log"`, `aria-live="polite"`), and the speech bubble is a live status region, so screen readers announce the greeting as it arrives.
-You can also have the agent generate its own greeting using its configured brain. This is heavier — it requires a round-trip to the LLM before the agent speaks — but it's powerful when the greeting really should be personalised.
+Write the greeting instructions with the assumption that someone might read it before they hear it:
-The cleanest way is to use a system-prompt convention. In the editor at [https://three.ws/create](https://three.ws/create), open the personality panel and add this rule near the bottom of your system prompt:
+- Make it useful as text. "Hi, I'm Iris. Ask me anything about Lumen." reads as well as it sounds. "Hi!" alone reads as a stub.
+- Avoid pronunciation asides and pause cues ("Hi. (pause) I'm Iris") — they work in audio and look broken in writing.
-```
-When you receive the message "__greet", introduce yourself in one or two sentences. Mention your name. Invite the visitor to ask anything. Match the visitor's apparent context — if it's morning, say good morning; if it's late at night, be gentle.
-```
+If you want a heavier-handed setup — a permanent transcript pane next to the agent — listen for the speech events. `voice:speech-start` fires each time the agent begins speaking a line aloud, with the full text in `event.detail.text`; `voice:speech-end` fires when it finishes:
-Then, in your page:
+```html
+<div id="transcript" aria-live="polite" style="margin-top: 12px; color:#666; font-size: 0.9rem;">
+ <strong>Agent says:</strong> <span id="transcript-text">…</span>
+</div>
-```js
-const agent = document.getElementById('agent-script');
-agent.addEventListener('agent:ready', () => {
- // The agent will process this through its brain and the response will be spoken
- agent.speak('__greet');
-});
+<script>
+ const agent = document.getElementById('agent');
+ const out = document.getElementById('transcript-text');
+
+ agent.addEventListener('voice:speech-start', (event) => {
+ out.textContent = event.detail.text;
+ });
+</script>
```
-The `__greet` token is intercepted by the agent's brain (because you taught it the convention in the system prompt). The LLM generates a greeting that fits your prompt rules, the agent speaks it, and the visitor hears something that feels written for them. This is the highest-effort option but the most flexible, and it composes with the rest of your prompt design.
+Note these events accompany *spoken* lines — they fire when a reply goes through TTS (the `voice` attribute, `{ voice: true }`, or the built-in chat input). To mirror every reply regardless of audio, listen for `brain:message` and read `event.detail.content` when `event.detail.role === 'assistant'`.
---
-## Step 7 — Writing a good greeting
+## Step 8 — Writing a good greeting
-Here is what makes a greeting effective, distilled from watching first-time visitors interact with embeds across many sites.
+Here is what makes a greeting effective, distilled from watching first-time visitors interact with embeds across many sites. These rules go into the agent's instructions (Step 3), since that's what shapes the actual words.
### Lead with the name
-Visitors form an opinion in the first three seconds. "Hi, I'm Iris" is doing two things at once: it establishes that the agent is a named entity (not a generic chatbot), and it gives the visitor a handle to use ("Iris, can you…"). Both matter.
+Visitors form an opinion in the first three seconds. "Hi, I'm Iris" does two things at once: it establishes that the agent is a named entity (not a generic chatbot), and it gives the visitor a handle to use ("Iris, can you…"). Both matter.
### State the agent's role
@@ -275,77 +269,61 @@ Specificity beats vagueness. "I can help you" is weaker than "I can help you pic
End with an instruction or invitation. Visitors who don't know what to do next, won't.
-- "Click me if you have a question."
-- "Just type anything below."
+- "Ask me anything — just type below."
- "Try asking 'what's new this month?'"
### Keep it to one or two sentences
-A long greeting feels like a sales pitch. Two short sentences feel like a person.
+A long greeting feels like a sales pitch. Two short sentences feel like a person. Cap it in the instructions ("Never open with more than two sentences") — models respect explicit limits far better than vague ones.
### A complete example
-For a hypothetical online wine merchant called "Bottle Lane", a good greeting might be:
+For a hypothetical online wine merchant called "Bottle Lane", the greeting block of the instructions might read:
-```html
-<script
- src="https://three.ws/cdn/agent-3d.js"
- data-agent-id="YOUR_AGENT_ID"
- data-name="Vincent"
- data-greeting="Hi, I'm Vincent. I can recommend a bottle for any occasion — just tell me what you're celebrating."
-></script>
```
-
-Twenty words. Names the agent. States the value. Invites the visitor to be specific. Reads well aloud and reads well silent.
-
-### A complete example for a developer tool
-
-For a hypothetical CI/CD tool called "Pipeline", a different tone:
-
-```html
-<script
- src="https://three.ws/cdn/agent-3d.js"
- data-agent-id="YOUR_AGENT_ID"
- data-name="Otto"
- data-greeting="Hey. I'm Otto. Ask me how to set up a build, or paste me a config and I'll review it."
-></script>
+You are Vincent, Bottle Lane's sommelier. When a visitor greets you or asks
+who you are, introduce yourself in one sentence and offer to recommend a
+bottle for any occasion — ask what they're celebrating. Never open with more
+than two sentences.
```
-Same structure — name, role, invitation — but the tone fits the audience. Calmer, slightly informal, direct.
+A typical greeting this produces: "Hi, I'm Vincent. I can recommend a bottle for any occasion — what are you celebrating?" Names the agent. States the value. Invites the visitor to be specific. Reads well aloud and reads well silent.
+
+For a developer tool, same structure, different register: "Hey, I'm Otto. Ask me how to set up a build, or paste a config and I'll review it."
---
-## Step 8 — Debugging a silent greeting
+## Step 9 — Debugging a silent greeting
-If you set `data-greeting` and the agent isn't speaking, work through this checklist in order.
+If the greeting isn't arriving, work through this checklist in order.
-1. **Does the speech bubble appear?** If yes, the greeting is firing correctly and the audio is being blocked or muted. Skip to step 4. If no, the greeting isn't firing — go to step 2.
+1. **Does the speech bubble show text?** If yes, the greeting is working and only the audio is missing — skip to step 5. If no text appears anywhere, the message isn't reaching the brain — keep going.
-2. **Is the agent fully loaded?** Open the browser console. You should see no errors, and the network tab should show the GLB and manifest loaded with 200 status. If the agent isn't ready, the greeting won't fire. Common cause: the agent ID is wrong; double-check it on [https://three.ws/my-agents](https://three.ws/my-agents).
+2. **Is the agent booting at all?** Open the browser console and the network tab. You should see the manifest and GLB load with 200 status. If the agent ID is wrong, the element falls back to the default avatar rather than erroring — so a *wrong-looking* avatar is your clue. Double-check the ID at [https://three.ws/my-agents](https://three.ws/my-agents). You can also listen for failures: `agent.addEventListener('agent:error', (e) => console.log(e.detail.phase, e.detail.error))`.
-3. **Is the `data-greeting` attribute spelled correctly?** The loader silently ignores unknown attributes. `data-greting` will do nothing. Re-read the attribute name in your HTML.
+3. **Is the element still lazy-loading?** Without `eager`, an off-screen element hasn't booted, so `agent:ready` hasn't fired. Scroll it into view, or add `eager`.
-4. **Is the tab muted?** Right-click the browser tab. Some browsers show "Unmute tab" in the context menu. Click it.
+4. **Does the agent have a brain?** A self-configured embed with no `brain` attribute has no model to answer with. Add `brain="free"`. For `agent-id` embeds, confirm a brain is configured on the agent in the editor.
-5. **Has the user interacted with the page yet?** On strict-autoplay browsers (Safari, iOS Safari), the agent will not speak until the visitor has clicked, tapped, or pressed a key on the page. The speech bubble appears regardless. If you tap and audio still doesn't play, move to step 6.
+5. **Is voice enabled for JS calls?** `say()` from JavaScript only speaks aloud when the element has the `voice` attribute (or you pass `{ voice: true }`). This is the single most common cause of "text shows, no audio".
-6. **Is the agent's voice configured?** Open the editor at [https://three.ws/create](https://three.ws/create), open your agent, open the Voice panel. Make sure a voice is selected and saved. An unconfigured voice falls back to silent (the speech bubble still appears).
+6. **Has the visitor interacted with the page yet?** On strict-autoplay browsers (Safari, iOS), audio won't play before the first tap or keypress — the text still shows. See Step 6 for the guaranteed-audible pattern.
-7. **Is the system volume up?** Genuinely worth checking. The greeting plays at the system audio output level; if the OS volume is at zero, you won't hear it.
+7. **Is the tab muted, and is the system volume up?** Genuinely worth checking. Some browsers show "Unmute tab" in the tab's context menu.
-In practice, problems are almost always step 5 (autoplay rules) or step 6 (voice not configured). The embed is conservative on purpose — better to show a silent speech bubble than to surprise a visitor with unexpected audio.
+In practice, problems are almost always step 5 (missing `voice` attribute) or step 6 (autoplay rules). The embed is conservative on purpose — better a silent, readable greeting than a visitor ambushed by unexpected audio.
---
## What you learned
-- `data-greeting` is the simplest way to give your agent a spoken first line
-- The greeting fires on the `agent:ready` event, automatically and reliably
-- Browser autoplay rules can suppress the audio on first page load; the embed handles this gracefully by always showing the speech bubble and queuing audio for the user's first interaction
-- A spoken greeting is also a readable greeting — write it to work both ways
-- The accessibility tooling is built in (ARIA live regions, automatic announcements) but you can layer your own transcript on top using the `speak` event
-- Dynamic greetings come in two flavours: scripted (chosen in JS based on context) and LLM-generated (driven by a `__greet` convention in the system prompt)
-- A good greeting names the agent, states its role, invites action, and stays under two sentences
+- The greeting flow is: listen for `agent:ready`, then call `say()` with a natural opening cue
+- `say()` routes through the agent's brain, so the greeting's content comes from its personality — the editor's Personality panel for published agents, the `instructions` attribute for self-configured ones
+- The `voice` attribute (or `{ voice: true }`) makes JS-triggered replies audible; the text bubble renders either way
+- `speak()` is the talking *gesture* only — no brain, no audio — useful when your page supplies the words itself
+- Browser autoplay rules can suppress the audio on first load; greet on `agent:ready` for a text-first greeting, or on the first user interaction for a guaranteed-audible one
+- `voice:speech-start` / `voice:speech-end` (and `brain:message`) let you mirror the greeting into your own transcript UI
+- A good greeting names the agent, states its role, invites action, and stays under two sentences — enforce that in the instructions
A working greeting moves the embed from "decoration" to "interaction", which is the single biggest win you can ship after the basic embed is live.
@@ -355,7 +333,7 @@ A working greeting moves the embed from "decoration" to "interaction", which is
- [Embed in 30 seconds](/tutorials/embed-in-30-seconds) — the foundation embed, if you skipped it
- [Customize size, position and background](/tutorials/customize-appearance) — make the embed match your brand visually
-- [Pick and swap an avatar in Studio](/tutorials/swap-avatar-in-studio) — change the agent's body without changing the snippet
+- [Drive the agent with the JavaScript API](/tutorials/js-api-events) — the full method and event reference behind this tutorial
+- [Give your agent a personality](/tutorials/agent-personality) — go deeper on the system prompt that shapes every greeting
+- [Voice and lip-sync](/tutorials/voice-and-lipsync) — how the spoken side works under the hood
- [Share your agent](/tutorials/share-your-agent) — generate a public URL, QR code, and social previews for the agent itself
-- [Build your first agent](/tutorials/first-agent) — drop into the manifest and skills layer for personality work
-- [Embed on a website](/tutorials/embed-on-website) — the full embed reference for production sites
diff --git a/docs/tutorials/js-api-events.md b/docs/tutorials/js-api-events.md
index 6a27959df..cebe8d718 100644
--- a/docs/tutorials/js-api-events.md
+++ b/docs/tutorials/js-api-events.md
@@ -7,7 +7,7 @@ This tutorial covers the full handle-to-event lifecycle. By the end you will kno
**What you'll build:**
- A live page where the agent reacts to clicks and form events
- A "wait until ready" pattern that never tries to drive an unbooted agent
-- A queue that chains `speak`, `playAnimation`, and `lookAt` without overlap
+- A queue that chains `ask`, `play`, and `lookAt` without overlap
- A listener that reads back every word the agent says
- A checkout celebration flow — submit a form, the agent cheers, narrates, and goes idle
@@ -89,23 +89,15 @@ Serve it locally — `python3 -m http.server 8080` works — and open `http://lo
## Step 2 — Get a handle to the agent
-The `<agent-3d>` element is a custom element. `document.getElementById('agent')` gives you back an `Agent3DElement` instance with the full API attached. The same handle works whether you wrote `<agent-3d>` directly or used the one-line script-tag embed:
+The `<agent-3d>` element is a custom element. `document.getElementById('agent')` gives you back an `Agent3DElement` instance with the full API attached — the CDN script's only job is registering that element, so every `<agent-3d>` tag on the page is a live API handle.
-```html
-<script src="https://three.ws/cdn/agent-3d.js" data-agent-id="YOUR_AGENT_ID" id="my-agent"></script>
-```
-
-With that form, `document.getElementById('my-agent')` still gives you the element. The script tag mounts the agent and returns the same custom element under the hood.
-
-When in doubt, this lookup works in either case:
+If you didn't put an `id` on the tag (or you're writing code that runs on pages you don't control), grab the first agent on the page instead:
```js
-const agent =
- document.querySelector('agent-3d') ||
- document.querySelector('script[data-agent-id]');
+const agent = document.querySelector('agent-3d');
```
-Both have identical JavaScript APIs from this point forward.
+Either lookup returns the same element with the same JavaScript API from this point forward.
---
@@ -159,50 +151,53 @@ No race conditions, no "I clicked but nothing happened on the first try" bugs.
The agent has two methods that look similar but do different things. Picking the right one matters.
-**`agent.speak(text)`** — fires the talking animation and (if voice is enabled) speaks the text out loud. It does *not* go through the LLM. Use it when you already know exactly what you want the agent to say and you don't want a model in the loop. Cheap, instant, deterministic.
+**`agent.speak(text)`** — plays a talking *gesture* sized to the length of the text (roughly 0.3s per word, minimum 1.5s). It is silent: no LLM, no audio, no chat bubble. Use it to add life to a scripted moment where the page itself supplies the words on screen. Cheap, instant, deterministic.
+
+**`agent.say(text)`** — sends `text` to the brain as a user message. The reply renders in the chat bubble and is spoken aloud when the `voice` attribute is set. This is what the built-in chat input calls. It's fire-and-forget: it returns immediately, and if you call it again while a turn is in flight, the newest message replaces the queued one.
-**`agent.say(text)`** — sends `text` to the brain as a user message, the brain responds, and the response is spoken back. This is what the built-in chat input calls. Use it when you want a real conversational turn.
+**`agent.ask(text)`** — same brain turn as `say`, but returns a promise that resolves with the reply text once the response (and its speech, if voice is on) has finished. Reach for it whenever you need to await the turn or use the reply.
-Most page-driven interactions want `speak`. Use `say` when you're injecting user input from a custom UI.
+Most page-driven interactions want `say` or `ask`. Use `speak` when all you need is the gesture.
Wire up two buttons:
```js
document.getElementById('btn-greet').addEventListener('click', async () => {
await whenReady(agent);
+ // Silent talking gesture — pair it with your own on-page caption.
agent.speak('Hey there. Glad you stopped by.');
});
document.getElementById('btn-think').addEventListener('click', async () => {
await whenReady(agent);
// Goes through the LLM — the model decides what to say.
- await agent.say('Tell me a one-sentence fun fact.');
+ agent.say('Tell me a one-sentence fun fact.');
});
```
-Click both. The first speaks instantly. The second pauses briefly while the model generates, then speaks the response.
+Click both. The first animates instantly and makes no sound. The second pauses briefly while the model generates, then renders the reply (and speaks it if `voice` is enabled).
---
-## Step 5 — Animations: exact name vs hint
+## Step 5 — Animations: exact clip vs emote
The agent has two ways to pick an animation clip. They map to two different mental models.
-**`agent.play(clipName)`** — plays the clip with that exact name from the GLB. Case-sensitive. If the clip isn't in the model, nothing happens. Use this when you know what's in the rig — for instance, if you've baked a `WaveLoop` clip yourself.
+**`agent.play(name)`** — plays the clip with that name from the loaded rig (an exact match, falling back to a case-insensitive one). If the clip isn't in the model, it returns `false` and nothing plays. Use this when you know what's in the rig — for instance, if you've baked a `WaveLoop` clip yourself.
-**`agent.playAnimationByHint(hint)`** — looks for any clip whose name contains the hint, case-insensitive. `playAnimationByHint('wave')` matches `WaveLoop`, `Mixamo_Wave`, `wave_friendly` — all of them. This is the resilient one. Use it when you don't know the exact naming convention of the loaded GLB.
+**`agent.playEmote(name)`** — the resilient one. Instead of a clip name it takes an intent — `'celebrate'`, `'cheer'`, or `'flinch'` — and walks a fallback chain of clips until one exists in the rig (`celebrate` → `wave`; `cheer` → `celebrate` → `wave`; `flinch` → `defeated` → `concern` → `shake`). If none of them are present, it finishes with a small head-bob, so it's guaranteed to do *something* regardless of the rig.
-For day-to-day work, prefer the hint version:
+For product moments, prefer the emote version:
```js
document.getElementById('btn-celebrate').addEventListener('click', async () => {
await whenReady(agent);
- // Tries 'celebrate' first; if that's not in the rig, falls through to playEmote's chain.
+ // Tries the 'celebrate' clip first; falls back to 'wave', then a head-bob.
agent.playEmote('celebrate');
});
```
-`playEmote(name)` is a higher-level wrapper that tries a named emote, then falls back through a chain (`celebrate` → `cheer` → `wave`), and finally to a small head-bob if none of them exist. This is what you want for product moments — guaranteed to do *something* regardless of the rig.
+Reach for `play(name)` only when you control the GLB and want one specific clip, no substitutes.
Convenience shortcuts: `agent.wave()`, `agent.lookAt('camera' | 'user' | 'model')`.
@@ -276,52 +271,42 @@ Every one of these is a hook for your app. A few common patterns:
## Step 7 — Sequencing: do A, then B, then C
-A common pitfall: fire `speak` and `playAnimation` back-to-back, and they overlap. The animation steps on the talking gesture, the speech gets queued behind itself, things look broken.
-
-The clean fix is to wait for the right events between steps. `voice:speech-end` is your friend here — it tells you the spoken sentence is done.
+A common pitfall: fire `speak` and `play` back-to-back, and they overlap. The second clip steps on the talking gesture and things look broken.
-A small helper that turns the event into a promise:
-
-```js
-function speakAndWait(el, text) {
- return new Promise((resolve) => {
- const on = () => {
- el.removeEventListener('voice:speech-end', on);
- resolve();
- };
- el.addEventListener('voice:speech-end', on);
- el.speak(text);
- });
-}
-```
-
-Now you can chain:
+For LLM turns the clean fix is `ask()` — it resolves only after the reply is complete (including its speech, when `voice` is on), so a plain `await` sequences everything:
```js
async function intro() {
await whenReady(agent);
agent.wave();
- await speakAndWait(agent, 'Welcome to the tour.');
+ await agent.ask('Welcome the visitor to the tour in one short sentence.');
agent.lookAt('user');
- await speakAndWait(agent, 'I will keep this brief.');
+ await agent.ask('Tell them you will keep this brief.');
agent.playEmote('cheer');
}
```
Each line waits for the previous one to land before the next runs. The result feels deliberate — not a stuttering pile-up.
-For the `say()` (LLM-driven) version, you'd wait on `brain:message` instead, since `say` returns when the message is complete:
+For the silent `speak()` gesture there is no completion event — but its duration is deterministic (0.3s per word, minimum 1.5s), so you can mirror it:
```js
-async function thoughtfulIntro() {
- await whenReady(agent);
- agent.wave();
- await agent.say('Greet me by name and ask what I want to learn.');
- agent.playEmote('cheer');
+function gestureAndWait(el, text) {
+ el.speak(text);
+ const secs = Math.max(1.5, text.split(' ').length * 0.3);
+ return new Promise((resolve) => setTimeout(resolve, secs * 1000));
}
```
-`agent.say(text)` already returns a promise that resolves on completion, so no extra event-wrapper needed.
+And if you're reacting to real speech (an LLM reply being voiced), `voice:speech-end` is still the event to wait on — it fires when the spoken sentence is done:
+
+```js
+function nextSpeechEnd(el) {
+ return new Promise((resolve) => {
+ el.addEventListener('voice:speech-end', resolve, { once: true });
+ });
+}
+```
---
@@ -345,18 +330,19 @@ function getAgent() {
Or use a small reactive wrapper if you're inside a framework — see the [Web Component end-to-end tutorial](/tutorials/web-component-end-to-end) for React and Vue patterns.
-**LLM errors during `say()`.** Network glitch, brain provider rate-limit, no API key. `agent.say(text)` rejects in those cases. Wrap it:
+**LLM errors during a turn.** Network glitch, brain provider rate-limit, no API key. `say()` never rejects — it shows the error in the chat bubble and fires an `agent:error` event. When you need to handle the failure programmatically, use `ask()`, which rejects:
```js
try {
- await agent.say(userText);
+ await agent.ask(userText);
} catch (err) {
console.error('Brain call failed:', err);
- agent.speak('Sorry — something hiccupped on my end. Try that again?');
+ showRetryToast('Something hiccupped. Try that again?'); // your own UI
+ agent.speak('Sorry about that.'); // concerned talking gesture, no brain needed
}
```
-The fallback `agent.speak(...)` does *not* go through the brain, so it works even when the LLM path is broken.
+The fallback `agent.speak(...)` does *not* go through the brain (it's a silent gesture), so it works even when the LLM path is broken — pair it with your own on-page error message for the words.
---
@@ -384,7 +370,7 @@ The HTML:
The JS:
```js
-import './app.js'; // assumes whenReady, speakAndWait are exported there
+import './app.js'; // assumes whenReady is exported there
const form = document.getElementById('order-form');
const agent = document.getElementById('agent');
@@ -398,7 +384,7 @@ form.addEventListener('submit', async (e) => {
// In a real app, you'd post to your backend here and only proceed on success.
const ok = await placeOrder({ name, item });
if (!ok) {
- agent.speak("That didn't go through. Try again in a moment?");
+ agent.say("Tell the customer their order didn't go through and to try again in a moment.");
return;
}
@@ -409,8 +395,10 @@ async function celebrate({ name, item }) {
await whenReady(agent);
agent.lookAt('user');
agent.playEmote('celebrate');
- await speakAndWait(agent, `Thanks, ${name}!`);
- await speakAndWait(agent, `Your ${item} is on the way.`);
+ await agent.ask(
+ `The customer ${name} just completed an order for "${item}". ` +
+ `Thank them by name and confirm it's on the way, in one short sentence.`
+ );
agent.wave();
}
@@ -459,10 +447,10 @@ And the methods you'll reach for most:
- `agent.speak(text)` for cheap, deterministic lines
- `agent.say(text)` for full LLM-driven turns
- `agent.wave()`, `agent.lookAt(target)`, `agent.playEmote(name)` for visual beats
-- `agent.play(name)` and `agent.playAnimationByHint(hint)` for direct clip control
+- `agent.play(name)` for direct, exact-clip control
- `agent.clearConversation()` to reset rolling memory
-The `whenReady`, `speakAndWait`, and try/catch patterns are small but they remove almost every gotcha. Steal them.
+The `whenReady`, awaited-`ask()`, and try/catch patterns are small but they remove almost every gotcha. Steal them.
## Next steps
diff --git a/docs/tutorials/mcp-server-for-your-agent.md b/docs/tutorials/mcp-server-for-your-agent.md
index 3da8d188e..ca8240d80 100644
--- a/docs/tutorials/mcp-server-for-your-agent.md
+++ b/docs/tutorials/mcp-server-for-your-agent.md
@@ -15,7 +15,7 @@ This is shorter than the other Advanced tutorials because the protocol is small
**Prerequisites:**
-- A deployed agent with a working chat endpoint. If you're using the platform, your agent already has one at `https://three.ws/api/chat?agent=<agentId>`. If you've forked the platform ([self-host-agent-backend](/tutorials/self-host-agent-backend)), use your own equivalent.
+- A deployed agent with a working chat endpoint. If you're using the platform, your agent already has one: `POST https://three.ws/api/chat` with a JSON body of `{ agentId, message, history }`, answered as an SSE stream (Step 4 shows the exact shapes). If you've forked the platform ([self-host-agent-backend](/tutorials/self-host-agent-backend)), use your own equivalent.
- Node.js 24.x and a deployed function host (Vercel/Cloudflare/your own server)
- Familiarity with JSON-RPC 2.0 (`jsonrpc: "2.0"`, `method`, `params`, `id`)
- A test MCP client. Claude Desktop is the most forgiving; Cursor is stricter; `npx @modelcontextprotocol/inspector` is the dev-loop tool
@@ -251,7 +251,16 @@ The `description` is what the *calling* LLM reads to decide when to invoke the t
The dispatch already routes `tools/call` to `onToolCall`. Implement it:
+The platform's `/api/chat` (`api/chat.js`) contract, which this handler targets:
+
+- **Request:** `POST` with a JSON body of `{ agentId, message, history }`. `agentId` is the agent's UUID, `message` is the single new user turn (a string, max 4000 chars), and `history` is an array of up to 20 prior `{ role: 'user' | 'assistant', content }` turns. There is no `messages` array, no `session_id`, and no `stream: false` switch.
+- **Response:** always an SSE stream (`Content-Type: text/event-stream`). Each event is a `data: {...}` JSON line: `{ type: 'chunk', text }` for incremental reply text, then a final `{ type: 'done', reply, actions, ... }` carrying the complete reply, or `{ type: 'error', message }` if the stream fails mid-way.
+
+`/api/chat` is stateless per request — conversation context travels in `history`. To honor the tool's optional `session_id`, keep a per-session history on the MCP server. In-memory works for a tutorial (it survives only as long as the function instance stays warm); use Redis or a database row for real multi-instance continuity.
+
```js
+const SESSIONS = new Map(); // session_id → [{ role, content }, ...]
+
async function onToolCall(params) {
const { name, arguments: args = {} } = params || {};
if (name !== 'chat_with_agent') throw rpcError(-32602, `unknown tool: ${name}`);
@@ -261,17 +270,17 @@ async function onToolCall(params) {
const message = String(args.message || '').trim();
if (!message) throw rpcError(-32602, 'message is required');
const sessionId = args.session_id ? String(args.session_id) : null;
+ const history = sessionId ? SESSIONS.get(sessionId) || [] : [];
- // Call your agent's chat endpoint. For the platform, this is /api/chat.
+ // Call your agent's chat endpoint. For the platform, this is POST /api/chat.
// For your own fork or stack, swap the URL.
const upstream = await fetch('https://three.ws/api/chat', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
- agent: agentId,
- messages: [{ role: 'user', content: message }],
- session_id: sessionId,
- stream: false,
+ agentId,
+ message,
+ history: history.slice(-20),
}),
signal: AbortSignal.timeout(60_000),
});
@@ -281,10 +290,36 @@ async function onToolCall(params) {
throw rpcError(-32603, `agent endpoint ${upstream.status}: ${text.slice(0, 200)}`);
}
- const data = await upstream.json();
- const reply = data?.message?.content || data?.content || data?.text || '';
+ // MCP's tools/call returns a single result, so buffer the whole SSE stream
+ // and take the `reply` field from the final `done` event. The accumulated
+ // `chunk` text is the fallback if the stream is cut off before `done`.
+ const raw = await upstream.text();
+ let reply = '';
+ let chunks = '';
+ for (const line of raw.split('\n')) {
+ if (!line.startsWith('data: ')) continue;
+ let evt;
+ try {
+ evt = JSON.parse(line.slice('data: '.length));
+ } catch {
+ continue;
+ }
+ if (evt.type === 'chunk') chunks += evt.text || '';
+ else if (evt.type === 'done') reply = (evt.reply || '').trim();
+ else if (evt.type === 'error') {
+ throw rpcError(-32603, `agent stream error: ${evt.message || 'stream interrupted'}`);
+ }
+ }
+ if (!reply) reply = chunks.trim();
if (!reply) throw rpcError(-32603, 'agent returned empty response');
+ if (sessionId) {
+ SESSIONS.set(
+ sessionId,
+ [...history, { role: 'user', content: message }, { role: 'assistant', content: reply }].slice(-20),
+ );
+ }
+
// MCP tool results are an array of content blocks. For a plain text reply:
return {
content: [{ type: 'text', text: reply }],
@@ -295,7 +330,7 @@ async function onToolCall(params) {
The `content` array is the canonical MCP tool response shape. Each block has a `type` ("text", "image", "resource"). For an agent chat, one text block is right.
-If your agent endpoint streams (SSE or chunked), buffer it on the server here. MCP's `tools/call` returns a single result; the client doesn't expect a stream from `tools/call` in the same way it expects a stream from a top-level LLM call. If you want streaming, that's the SSE channel on the GET endpoint — more complex and rarely worth the trouble for an agent tool.
+Buffering the upstream SSE on the server, as above, is the right default: MCP's `tools/call` returns a single result; the client doesn't expect a stream from `tools/call` in the same way it expects a stream from a top-level LLM call. If you want streaming, that's the SSE channel on the GET endpoint — more complex and rarely worth the trouble for an agent tool.
---
diff --git a/docs/tutorials/multi-agent-coordination.md b/docs/tutorials/multi-agent-coordination.md
index 7fda1687e..5c7d01e19 100644
--- a/docs/tutorials/multi-agent-coordination.md
+++ b/docs/tutorials/multi-agent-coordination.md
@@ -16,8 +16,8 @@ This tutorial assumes you've built at least one agent ([first-agent](/tutorials/
**Prerequisites:**
- Two saved agents in your dashboard at `https://three.ws/dashboard`. They can be variants of the same avatar or two completely different characters.
-- A live web page where you can drop two `<script>` tags and own the surrounding HTML/JS. A static `.html` file served by `npx serve .` is enough to get started.
-- Familiarity with the embed JS API (`speak`, `playAnimation`, events like `brain:message`, `voice:speech-end`, `agent:ready`). The reference is in [js-api-events](/tutorials/js-api-events) and the source of truth is `https://three.ws/cdn/agent-3d.js`.
+- A live web page where you can add a `<script>` tag and two `<agent-3d>` elements, and own the surrounding HTML/JS. A static `.html` file served by `npx serve .` is enough to get started.
+- Familiarity with the embed JS API (`say`, `ask`, `play`, events like `brain:message`, `voice:speech-end`, `agent:ready`). The reference is in [js-api-events](/tutorials/js-api-events) and the source of truth is the published bundle at `https://three.ws/agent-3d/1.5.2/agent-3d.js`.
- Each agent has a personality configured. See [agent-personality](/tutorials/agent-personality) if either of yours doesn't yet — they need distinct voices for the handoff to feel coherent.
---
@@ -65,6 +65,7 @@ A two-agent layout where both characters are always visible. Riley on the left,
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Pricing — talk to Riley and Devon</title>
+ <script type="module" src="https://three.ws/agent-3d/1.5.2/agent-3d.js"></script>
<style>
body { margin: 0; font-family: system-ui, sans-serif; background: #0b0b10; color: #fff; }
.stage { display: grid; grid-template-columns: 1fr 1fr; height: 60vh; gap: 1rem; padding: 1rem; }
@@ -82,11 +83,13 @@ A two-agent layout where both characters are always visible. Riley on the left,
<div class="stage">
<div id="riley-stage" class="active">
<h3>Riley · Sales</h3>
- <script src="https://three.ws/cdn/agent-3d.js" data-agent-id="<RILEY_AGENT_ID>" id="riley"></script>
+ <agent-3d id="riley" agent-id="<RILEY_AGENT_ID>" avatar-chat="off" voice eager
+ style="width:100%;height:100%"></agent-3d>
</div>
<div id="devon-stage">
<h3>Devon · Engineering</h3>
- <script src="https://three.ws/cdn/agent-3d.js" data-agent-id="<DEVON_AGENT_ID>" id="devon"></script>
+ <agent-3d id="devon" agent-id="<DEVON_AGENT_ID>" avatar-chat="off" voice eager
+ style="width:100%;height:100%"></agent-3d>
</div>
</div>
<div class="chat">
@@ -98,7 +101,7 @@ A two-agent layout where both characters are always visible. Riley on the left,
</html>
```
-Two `<script>` tags, two `data-agent-id` attributes pointing at your saved agents. `coordinator.js` is the file we'll write next.
+One loader `<script>` in the `<head>` registers the `<agent-3d>` element; two tags with `agent-id` attributes point at your saved agents. Three attribute choices matter here: `avatar-chat="off"` hides each agent's built-in chat input (this page has its own shared composer), `voice` enables text-to-speech so the avatars actually speak their replies (and fire the `voice:speech-start`/`voice:speech-end` events we lean on later), and `eager` boots both agents immediately instead of waiting for them to scroll into view. `coordinator.js` is the file we'll write next.
Replace `<RILEY_AGENT_ID>` and `<DEVON_AGENT_ID>` with the actual agent IDs from your dashboard. They're displayed under each agent in `https://three.ws/dashboard`.
@@ -152,7 +155,10 @@ function onReady(name, el) {
appendLog('system', `${name} ready.`);
if (state.ready.riley && state.ready.devon) {
setActive(riley);
- riley.speak("Hi! I'm Riley. Devon's here too if you have technical questions. What can I help with?");
+ riley.say(
+ "Introduce yourself to the visitor in one or two sentences: you're Riley " +
+ "from sales, and your colleague Devon is on hand for deep technical questions."
+ );
}
};
}
@@ -161,13 +167,13 @@ riley.addEventListener('agent:ready', onReady('riley', riley));
devon.addEventListener('agent:ready', onReady('devon', devon));
```
-This boots both agents, marks both `agent:ready`, then has Riley introduce the pair. Devon stands by silently.
+This boots both agents, marks both `agent:ready`, then has Riley introduce the pair. Devon stands by silently. `say(text)` pushes a message into the agent's conversation exactly as if the visitor typed it — here it carries a stage direction, and Riley's brain generates the actual greeting, which arrives via the `brain:message` event we wire next.
---
## Step 5 — Routing user input
-The shared input box sends to the active agent. The embed bundle exposes a `chat()` method that pushes a message into the agent's conversation as if the user typed it directly:
+The shared input box sends to the active agent via the same `say()` method we used for the greeting — it pushes a message into the agent's conversation as if the user typed it directly:
```js
input.addEventListener('keydown', (e) => {
@@ -177,7 +183,7 @@ input.addEventListener('keydown', (e) => {
if (!state.active) return; // not ready yet
appendLog('you', text);
state.scratch.push({ role: 'user', content: text });
- state.active.chat(text);
+ state.active.say(text);
});
```
@@ -212,7 +218,7 @@ Two ways to detect that the current agent wants to hand off:
We'll use (a) because it works with any LLM, any agent, no skill bundle required.
-In Riley's system prompt (set via the agent's "Personality" tab in the editor, or via the manifest's `system_prompt` field), append:
+In Riley's system prompt (set via the agent's "Personality" tab in the editor, or via the manifest's `instructions.md` file), append:
```
You are Riley, the sales lead on this pricing page. Devon, our staff
@@ -267,9 +273,8 @@ function considerHandoff(speakerName, text) {
setActive(targetEl);
appendLog('system', `→ handoff to ${target}`);
- // Inject the brief as a "user" message tagged with the system role marker
- // the runtime supports for stage directions.
- targetEl.chat(brief, { role: 'system' });
+ // Inject the brief into the new active agent's conversation.
+ targetEl.say(brief);
}
function buildBrief(scratch, target) {
@@ -290,7 +295,7 @@ function buildBrief(scratch, target) {
}
```
-`targetEl.chat(brief, { role: 'system' })` is a stage-direction message: it goes into the agent's conversation but is not appended to the user-visible transcript. The agent treats it as context and responds with its next visitor-facing message.
+`targetEl.say(brief)` pushes the brief into the target agent's conversation as an ordinary message — there is no separate system-role channel, which is exactly why `buildBrief` wraps the transcript in an explicit `[Stage director: …]` framing: the model reads the bracketed preamble as direction rather than visitor speech, and responds with its next visitor-facing message. Because both elements run with `avatar-chat="off"`, the brief never renders anywhere the visitor can see; the only transcript on the page is the one your `brain:message` handler builds in the log.
---
@@ -321,7 +326,7 @@ The `state.scratch` keeps the raw text (so the brief built in `buildBrief` is fa
## Step 8 — Speech-end synchronization
-The agent's `speak` method drives the 3D character's lip-sync and ambient animations. The `voice:speech-end` event fires when the avatar finishes saying its line. Use this to gate the next user input:
+Because both elements carry the `voice` attribute from Step 3, every reply is spoken aloud: the runtime fires `voice:speech-start` when TTS begins and `voice:speech-end` when the avatar finishes saying its line (without `voice`, neither event fires). Use the pair to gate the next user input:
```js
let speaking = false;
@@ -336,7 +341,7 @@ wireSpeechGate(devon);
Without this, an eager visitor types over the avatar's spoken response and the conversation tangles. With it, each turn completes cleanly.
-For a handoff specifically, you want the OLD agent's `voice:speech-end` to fire *before* the NEW agent starts speaking. The event order is naturally correct because the coordinator calls `targetEl.chat(brief, ...)` immediately, but the new agent doesn't start speaking until its LLM responds — which is well after the old agent finished its last syllable. No extra coordination needed in practice.
+For a handoff specifically, you want the OLD agent's `voice:speech-end` to fire *before* the NEW agent starts speaking. The event order is naturally correct because the coordinator calls `targetEl.say(brief)` immediately, but the new agent doesn't start speaking until its LLM responds — which is well after the old agent finished its last syllable. No extra coordination needed in practice.
---
@@ -353,7 +358,7 @@ If any of those fail, the typical causes:
- **Riley doesn't hand off.** The system prompt isn't strong enough. Make the trigger list more concrete or use few-shot examples in the prompt.
- **Devon answers technical questions Riley should have answered.** Check that the handoff topics list in Riley's prompt is *exclusive* — explicitly say "do NOT hand off when the visitor asks X."
-- **Both agents speak at once.** The `voice:speech-start`/`voice:speech-end` gate isn't wired, or one of the agents is mis-receiving the chat input. Confirm `state.active` is correctly set and the `chat()` call only goes to `state.active`.
+- **Both agents speak at once.** The `voice:speech-start`/`voice:speech-end` gate isn't wired, or one of the agents is mis-receiving the chat input. Confirm `state.active` is correctly set and the `say()` call only goes to `state.active`.
---
@@ -361,43 +366,40 @@ If any of those fail, the typical causes:
The example so far is **sequential delegation** — one agent speaks at a time. The other big multi-agent pattern is **parallel fan-out**: two agents work simultaneously on different parts of a task and the coordinator joins the results.
-A concrete example: a research agent and a copy-editor agent. The visitor asks "draft a 200-word blog post on the new feature." The research agent fetches facts; the copy-editor agent drafts the prose using those facts.
+A concrete example: a research agent and a copy-editor agent. The visitor asks "draft a 200-word blog post on the new feature." The research agent gathers facts; the copy-editor agent drafts the prose using those facts.
-The shape:
+The primitive that makes this work is `ask()` — the promise-returning sibling of `say()`. It sends a message into the agent's conversation and resolves with the assistant's reply text, so the coordinator can `await` both agents at once and join the results:
```js
async function parallelTask(userPrompt) {
- // Both agents accept tool calls via a hidden interface — chat() with a
- // role of 'tool-call' wraps the prompt so the agent's tool runner picks it up
- // without rendering as a visitor message.
- const [facts, draftScaffold] = await Promise.all([
- callAgentTool(researcher, 'gather_facts', { topic: userPrompt }),
- callAgentTool(writer, 'draft_outline', { topic: userPrompt }),
+ const [facts, outline] = await Promise.all([
+ researcher.ask(
+ `List the verifiable facts we can cite about: ${userPrompt}. Bullet points only.`
+ ),
+ writer.ask(
+ `Draft a tight outline for a 200-word blog post on: ${userPrompt}. Headings only.`
+ ),
]);
- // Now hand the combined result back to the writer to finalize.
- return callAgentTool(writer, 'finalize_post', { outline: draftScaffold, facts });
+ // Join: hand the researcher's facts to the writer for the final pass.
+ return writer.ask(
+ `Write the final 200-word post from your outline, using only these facts.\n\n` +
+ `Facts:\n${facts}\n\nOutline:\n${outline}`
+ );
}
```
-`callAgentTool` is a small helper that wraps `el.chat(...)` and listens for a single `tool-result` event:
+If either agent does its part through tools — a skill bundle that fetches a feed, hits an API, reads a knowledge base — you can observe every call from the page via the `skill:tool-start` and `skill:tool-called` events:
```js
-function callAgentTool(el, toolName, args) {
- return new Promise((resolve, reject) => {
- const id = crypto.randomUUID();
- const onResult = (e) => {
- if (e.detail?.toolCallId !== id) return;
- el.removeEventListener('tool-result', onResult);
- if (e.detail.error) reject(new Error(e.detail.error));
- else resolve(e.detail.result);
- };
- el.addEventListener('tool-result', onResult);
- el.invokeTool({ id, name: toolName, args });
- });
-}
+researcher.addEventListener('skill:tool-called', (e) => {
+ const { tool, result } = e.detail;
+ console.log('researcher ran', tool, result);
+});
```
-This requires each agent to expose the tools you're calling. Build them as skills (see [custom-skill](/tutorials/custom-skill)). The orchestration logic stays in the coordinator on the page.
+Build the tools themselves as skills (see [custom-skill](/tutorials/custom-skill)); the orchestration logic stays in the coordinator on the page.
+
+There's also a platform-native alternative to page-level orchestration: the `<agent-stage>` element. A stage hosts every child `<agent-3d>` in one shared WebGL scene (with a `formation` attribute — `row`, `circle`, or `freeform`), exposes `getAgents()`, `broadcast(fromId, event)`, and `routeMessage(fromId, toId, text)` to your code, and grants each staged agent two extra built-in tools — `observe_agents` (who else is on stage) and `say_to_agent` (address a colleague directly) — so the LLMs can delegate to each other without any coordinator glue. When the agents, not the page, should decide who does what, reach for the stage. The full patterns are in [Multi-Agent Scenes](../multi-agent.md).
Parallel fan-out is **harder to debug** than sequential delegation because errors are non-deterministic in order and any latency outlier blocks the join. Use it when the wall-clock saving is worth the complexity. For a chat UX with a human in the loop, sequential is almost always the right default.
@@ -458,34 +460,23 @@ The runtime cannot fix prompts that contradict each other. Catch contradictions
## Step 13 — Pattern: turn-taking with no human
-Sometimes the two agents are talking to each other, with the human watching. A debate, a roleplay, a brainstorm. This is the cleanest pattern in terms of code (no human input gate; turns alternate on `voice:speech-end`) and the hardest pattern in terms of LLM behavior (without grounding in real user input, both agents drift into hallucinated agreement after about six turns).
+Sometimes the two agents are talking to each other, with the human watching. A debate, a roleplay, a brainstorm. This is the cleanest pattern in terms of code (no human input gate; each turn feeds the previous reply to the other agent) and the hardest pattern in terms of LLM behavior (without grounding in real user input, both agents drift into hallucinated agreement after about six turns).
-Concrete loop:
+Concrete loop — `ask()` does all the sequencing for you, because with `voice` enabled it resolves only after the reply has been generated *and* spoken:
```js
async function autoplay(topic, turns = 6) {
- setActive(riley);
- riley.speak(`Let's debate this: ${topic}. I'll go first.`);
- await waitForSpeakEnd(riley);
- let speaker = riley, other = devon;
+ let speaker = riley;
+ let prompt = `Let's debate this: ${topic}. Open with your position in two sentences.`;
for (let i = 0; i < turns; i++) {
setActive(speaker);
- const lastFromOther = state.scratch.filter((m) => m.name === otherName(other)).slice(-1)[0]?.content || topic;
- speaker.chat(lastFromOther);
- await waitForChatMessage(speaker);
- await waitForSpeakEnd(speaker);
- [speaker, other] = [other, speaker];
+ const reply = await speaker.ask(prompt);
+ prompt = `The other debater said: "${reply}". Respond in two sentences.`;
+ speaker = speaker === riley ? devon : riley;
+ // Brief beat between turns so the handover doesn't feel robotic.
+ await new Promise((r) => setTimeout(r, 800));
}
}
-
-function waitForSpeakEnd(el) {
- return new Promise((res) => el.addEventListener('voice:speech-end', () => res(), { once: true }));
-}
-function waitForChatMessage(el) {
- return new Promise((res) => el.addEventListener('brain:message', (e) => {
- if (e.detail?.role === 'assistant') res();
- }, { once: true }));
-}
```
For a demo this is great. For anything load-bearing, cap `turns` aggressively and have a third "moderator" agent (or just code-as-moderator) stop the loop when the conversation stops making progress.
@@ -518,20 +509,22 @@ When you go from a demo to production, two-agent pages introduce real concerns:
**Latency.** The handoff cost is one extra LLM round trip (the brief injected as a stage direction triggers a response). Visible to the user as ~1.5 extra seconds. Acceptable for a substantive question, intolerable for trivial ones — which is why the handoff list in Riley's prompt must be restrictive.
-**Failure modes.** Devon's LLM provider goes down. Now Riley still works but the handoff lands on a dead agent. Mitigation: a try/catch around `targetEl.chat(brief, ...)` with a fallback that has Riley apologize and answer best-effort.
+**Failure modes.** Devon's LLM provider goes down. Now Riley still works but the handoff lands on a dead agent. Mitigation: deliver the brief with `ask()` instead of `say()` — same send, but it returns a promise you can race against a timeout — and fall back to Riley on failure. Note the fallback message is a stage direction, not a scripted line: Riley's brain generates the actual apology in Riley's voice.
```js
async function safeHandoff(targetEl, brief, fallbackEl, originalQuestion) {
try {
await Promise.race([
- handoffWithTimeout(targetEl, brief, 8000),
- timeoutGuard(8000),
+ targetEl.ask(brief),
+ new Promise((_, reject) =>
+ setTimeout(() => reject(new Error('handoff timed out')), 8000)),
]);
} catch (err) {
setActive(fallbackEl);
- fallbackEl.speak(
- "Devon's tied up right now — let me take a shot at this myself, and " +
- "I'll get a fuller answer in writing afterwards. " + originalQuestion
+ fallbackEl.say(
+ "Devon is unavailable right now. Apologize briefly, take your best shot at " +
+ "the visitor's technical question yourself, and offer a written follow-up. " +
+ "The question was: " + originalQuestion
);
}
}
@@ -539,7 +532,7 @@ async function safeHandoff(targetEl, brief, fallbackEl, originalQuestion) {
**Observability.** Log every handoff (which agent, which topic, what the user asked next). Over a week, you'll have data on whether Riley is over- or under-handing-off. Tune the prompt accordingly.
-**Embeds on third-party sites.** If you ship this two-agent page as an embed, both `data-agent-id`s are visible in the page source — anyone can see which agents you're using. That's by design; the agents are public artifacts. If you don't want them publicly identifiable, mark them as unlisted in the dashboard (they remain reachable by ID but don't appear in `/explore`).
+**Embeds on third-party sites.** If you ship this two-agent page as an embed, both `agent-id`s are visible in the page source — anyone can see which agents you're using. That's by design; the agents are public artifacts. If you don't want them publicly identifiable, mark them as unlisted in the dashboard (they remain reachable by ID but don't appear in `/explore`).
---
diff --git a/docs/tutorials/personal-ai-site.md b/docs/tutorials/personal-ai-site.md
index be07f0f45..a0f14ff40 100644
--- a/docs/tutorials/personal-ai-site.md
+++ b/docs/tutorials/personal-ai-site.md
@@ -280,23 +280,23 @@ Here is the full page. Replace the placeholder values in brackets and swap in yo
const input = document.getElementById('chat-input');
function ask(text) {
- agent.sendMessage(text);
+ agent.say(text);
}
function sendMessage() {
const text = input.value.trim();
if (!text) return;
input.value = '';
- agent.sendMessage(text);
+ agent.say(text);
}
input.addEventListener('keypress', e => {
if (e.key === 'Enter') sendMessage();
});
- agent.addEventListener('ready', () => {
+ agent.addEventListener('agent:ready', () => {
// Auto-greet after a short pause so the avatar has time to settle
- setTimeout(() => agent.sendMessage('__greet'), 2000);
+ setTimeout(() => agent.say('__greet'), 2000);
});
</script>
@@ -306,6 +306,8 @@ Here is the full page. Replace the placeholder values in brackets and swap in yo
The layout uses CSS Grid — left column for your static content, right column for the agent panel. On mobile it flips to a vertical stack with the agent taking the top 60% of the screen.
+`agent.say(text)` is the element's message-send method: it pushes the text into the agent's conversation exactly as if the visitor had typed it into the built-in chat. If you need the reply text back as a string (for your own UI), use `await agent.ask(text)` instead — same send, but it resolves with the assistant's response.
+
---
## Step 5: Configure the greeting
@@ -435,39 +437,25 @@ Add structured data to the `<head>`:
For the Open Graph image, generate a screenshot of your avatar against a clean background and save it as `maya-og.png`. The `og:image` tag in the full HTML above already references it.
-If you want to automate OG image generation:
-
-```js
-agent.addEventListener('ready', () => {
- setTimeout(async () => {
- const png = await agent.screenshot();
- // POST to your backend to store as the OG image
- // or pre-generate and commit it to your repo
- console.log('OG image captured, length:', png.length);
- }, 3000); // give the avatar time to finish its greeting pose
-});
-```
+The element has no screenshot API, so this is a one-time manual step rather than something you automate on page load: open your deployed page, let the greeting animation settle, and capture the agent panel with your browser's screenshot tooling. In Chrome DevTools, select the `<agent-3d>` element in the Elements panel, then run **Capture node screenshot** from the command menu (Cmd/Ctrl+Shift+P). Crop to 1200×630, commit the file next to `index.html`, and the meta tag does the rest. Re-capture whenever you change the avatar.
---
## Step 9: Analytics — understand what people ask
-Standard pageview analytics misses what matters most: what are people actually asking your agent? Add event tracking on agent responses:
+Standard pageview analytics misses what matters most: what are people actually asking your agent? The `brain:message` event fires for both sides of the conversation — once with `role: "user"` when a question goes in, once with `role: "assistant"` when the reply comes back — so a single listener tracks the whole exchange:
```js
-agent.addEventListener('agent-speak', e => {
- // e.detail.text is the full response — trim before sending
- if (typeof gtag !== 'undefined') {
- gtag('event', 'agent_response', {
- response_preview: e.detail.text.slice(0, 80)
- });
- }
-});
-
-agent.addEventListener('agent-message', e => {
- if (typeof gtag !== 'undefined') {
+agent.addEventListener('brain:message', e => {
+ const { role, content } = e.detail;
+ if (!content || typeof gtag === 'undefined') return;
+ if (role === 'user') {
gtag('event', 'user_question', {
- question_preview: e.detail.text.slice(0, 80)
+ question_preview: content.slice(0, 80)
+ });
+ } else if (role === 'assistant') {
+ gtag('event', 'agent_response', {
+ response_preview: content.slice(0, 80)
});
}
});
diff --git a/docs/tutorials/self-host-agent-backend.md b/docs/tutorials/self-host-agent-backend.md
index 3cd985be4..7ac2fe66c 100644
--- a/docs/tutorials/self-host-agent-backend.md
+++ b/docs/tutorials/self-host-agent-backend.md
@@ -4,6 +4,8 @@ By the end of this tutorial you have a fully independent three.ws stack running
This is the heaviest tutorial in the Advanced tier. It's worth doing in full if you need data residency, custom compliance, fork-friendly customizations, or simply the freedom to ship a feature without waiting for the upstream maintainers.
+> **Note:** the hosted three.ws platform itself moved off Vercel to Google Cloud Run on 2026-07-07 (one container, `server/index.mjs`, deployed with `npm run deploy:gcp`). This tutorial keeps the Vercel path because it's the lowest-friction way to self-host a fork; everything here works the same, and `vercel.json` remains the live route table either way.
+
**What you'll build:**
- A local development setup running the full stack (front-end + Vercel functions + Cloudflare workers + database)
@@ -49,7 +51,7 @@ The platform is intentionally composed of small, independently deployable servic
**SDKs (`sdk/`, `agent-payments-sdk/`, `solana-agent-sdk/`).** Published as npm packages. These are not deployed; they're built and published independently for skill authors to consume.
-**CDN (`/cdn/agent-3d.js`).** A single-file embed bundle built by `npm run build` and served from the same Vercel deployment. Third-party sites embed this script tag and your domain ends up in their `<script src="...">`.
+**Embed bundle (`/agent-3d/<version>/agent-3d.js`, also `/dist-lib/agent-3d.js`).** The `<agent-3d>` custom-element bundle, built by `npm run build:lib` from `src/lib.js` into `dist-lib/` and served from the same deployment. Third-party sites load this script tag and your domain ends up in their `<script src="...">`.
Everything except the database and Cloudflare workers can live on a single Vercel project. The minimum production deployment is: 1 Vercel project, 1 Cloudflare worker, 1 Postgres database, 1 R2 bucket.
@@ -276,17 +278,19 @@ If you're running the Pump.fun feed, repeat for `workers/pump-fun-mcp/`.
Confirm the production build works before deploying:
```bash
-npm run build
+npm run build # Vite front-end into dist/
+npm run build:lib # <agent-3d> embed bundle into dist-lib/
```
+(`npm run build:all` runs both plus the chat sub-app build in one go.)
+
This builds:
-- The Vite front-end into `dist/`
-- The `agent-3d.js` CDN bundle into `dist/cdn/agent-3d.js`
-- The chat sub-app into `dist/chat/`
-- The artifact viewer into `dist/artifact-viewer/`
+- The Vite front-end into `dist/` (all page entries, plus everything in `public/` — including the artifact viewer at `dist/artifact/`)
+- The `<agent-3d>` embed bundle into `dist-lib/agent-3d.js` (ES module; `npm run build:lib:full` adds the UMD build)
+- The chat sub-app into `dist/chat/` (via `npm run build:chat`)
-Look at `dist/` — there should be an `index.html`, a hashed bundle, the `cdn/` folder, and the various sub-apps. If the build prints warnings about missing env vars (e.g., `VITE_*` vars that the front-end reads at build time), set them before re-running:
+Look at `dist/` — there should be an `index.html`, hashed bundles, and the various sub-apps, with the embed bundle in `dist-lib/`. If the build prints warnings about missing env vars (e.g., `VITE_*` vars that the front-end reads at build time), set them before re-running:
```bash
VITE_API_BASE=https://<your-domain>.vercel.app npm run build
@@ -360,19 +364,11 @@ See [deploy-to-vercel-custom-domain](/tutorials/deploy-to-vercel-custom-domain)
## Step 11 — Swap the CDN domain
-Up to this point, anyone embedding an agent from your platform is including `<script src="https://three.ws/cdn/agent-3d.js" ...>`. The script tag is generated by the editor's "Copy embed" button, which by default emits the three.ws URL.
-
-For *your* deployment, the embed should point at *your* CDN. Two changes:
-
-**1. Front-end build constant.** The embed-generator UI reads its CDN base from a build-time constant. Set `VITE_CDN_BASE` to your domain when building:
-
-```bash
-VITE_CDN_BASE=https://agent.yourcompany.com npm run build
-```
+Up to this point, anyone embedding an agent from your platform is loading the bundle from the platform's own origin. Two facts make the domain swap automatic:
-Re-deploy. Now every "Copy embed" output from your dashboard emits `<script src="https://agent.yourcompany.com/cdn/agent-3d.js" ...>`.
+**1. The embed generator derives its URL from the page origin.** The "Copy embed" output is built by `src/editor/publish.js`, which emits `` `${origin}/dist-lib/agent-3d.js` `` from the origin the dashboard is running on. Once your fork is served from `agent.yourcompany.com`, every copied snippet already points at your domain — no build constant to set.
-**2. The script itself self-locates.** Open `src/embed/agent-3d-bundle.js` (or the equivalent in your fork — the file the build emits to `dist/cdn/agent-3d.js`). The bundle reads its own `currentScript.src` to derive the API base for fetches. This means a third party who pastes your embed on `their-site.com` will have the script fetch agents from *your* domain, not theirs, and you can move infrastructure later without breaking existing embeds.
+**2. The bundle itself self-locates.** The element derives its API base from the script's own URL (`new URL(import.meta.url).origin`, see `src/element.js:123`), falling back to the page origin, and can be overridden per element with the `api-base` attribute. A third party who pastes your embed on `their-site.com` will have the script fetch agents from *your* domain, not theirs, and you can move infrastructure later without breaking existing embeds.
Verify with a smoke test: create a static HTML file and paste your embed:
@@ -380,11 +376,11 @@ Verify with a smoke test: create a static HTML file and paste your embed:
<!doctype html>
<html>
<body>
- <script
- src="https://agent.yourcompany.com/cdn/agent-3d.js"
- data-agent-id="your-test-agent-id"
- id="test-embed"
- ></script>
+ <script type="module" src="https://agent.yourcompany.com/dist-lib/agent-3d.js"></script>
+ <agent-3d
+ agent-id="your-test-agent-id"
+ style="width: 360px; height: 480px"
+ ></agent-3d>
</body>
</html>
```
diff --git a/docs/tutorials/trigger-from-page-events.md b/docs/tutorials/trigger-from-page-events.md
index 596ea7626..28fc87f0f 100644
--- a/docs/tutorials/trigger-from-page-events.md
+++ b/docs/tutorials/trigger-from-page-events.md
@@ -32,7 +32,7 @@ Every recipe in this tutorial assumes you have an agent on the page. The simples
section:nth-child(even) { background: #fff; }
h2 { font-size: 2rem; margin: 0 0 16px; letter-spacing: -0.02em; }
</style>
- <script type="module" src="https://three.ws/cdn/agent-3d.js"></script>
+ <script type="module" src="https://three.ws/agent-3d/latest/agent-3d.js"></script>
</head>
<body>
<section><h2>Hero</h2><p>Headline copy here.</p></section>
diff --git a/docs/tutorials/upload-custom-glb.md b/docs/tutorials/upload-custom-glb.md
index 9b0f68b24..0b2ff38fe 100644
--- a/docs/tutorials/upload-custom-glb.md
+++ b/docs/tutorials/upload-custom-glb.md
@@ -358,11 +358,11 @@ Once uploaded:
4. In a browser console, fire each clip by name:
```js
-const agent = document.querySelector('agent-3d') || document.querySelector('[data-agent-id]');
-await agent.wave();
-agent.playAnimationByHint('cheer');
-agent.playAnimationByHint('talk');
-agent.playAnimationByHint('idle');
+const agent = document.querySelector('agent-3d');
+agent.wave();
+agent.play('Cheer'); // exact clip name (case-insensitive fallback); returns false if missing
+agent.play('Talk');
+agent.play('Idle');
```
Each one should trigger the corresponding clip. If a clip you expect doesn't fire, run `agent._scene.clips.map(c => c.name)` in the console — that prints the actual clip names the runtime sees. Compare against the names you set in Step 9.
diff --git a/docs/tutorials/walk-companion.md b/docs/tutorials/walk-companion.md
index d44e42072..0404d91e1 100644
--- a/docs/tutorials/walk-companion.md
+++ b/docs/tutorials/walk-companion.md
@@ -98,7 +98,7 @@ The `allow="accelerometer; gyroscope"` attribute lets the joystick respond to de
## Step 2: Drive the embed from the host page (postMessage)
-The embed isn't a black box — it speaks a versioned `postMessage` contract so your page can tell the avatar where to walk, what to say, and which environment to show. The contract is defined in [src/walk-embed-events.js](src/walk-embed-events.js) and documented interactively at [/docs/walk-embed-api](/docs/walk-embed-api).
+The embed isn't a black box — it speaks a versioned `postMessage` contract so your page can tell the avatar where to walk, what to say, and which environment to show. The contract is defined in [src/walk-embed-events.js](../../src/walk-embed-events.js) and documented interactively at [/docs/walk-embed-api](/docs/walk-embed-api).
Every message is namespaced to the `three-walk` channel and carries a protocol version, so it never collides with other `message` listeners on your page.
diff --git a/docs/tutorials/web-component-end-to-end.md b/docs/tutorials/web-component-end-to-end.md
index a0c2e61a6..96015097c 100644
--- a/docs/tutorials/web-component-end-to-end.md
+++ b/docs/tutorials/web-component-end-to-end.md
@@ -1,8 +1,8 @@
# Use the &lt;agent-3d&gt; web component end-to-end
-The script tag is convenient. One line, agent on the page. But once your site has a component system — React, Vue, Svelte, a design system — that single-line script starts to feel like a stranger in the codebase. You want the agent to be a real component, with props, refs, lifecycle, and a place in your component library.
+The iframe snippet is convenient. Paste it, agent on the page. But once your site has a component system — React, Vue, Svelte, a design system — that opaque iframe starts to feel like a stranger in the codebase. You want the agent to be a real component, with props, refs, lifecycle, and a place in your component library.
-That's what `<agent-3d>` is for. It's a standards-based custom element that drops cleanly into any framework, gives you the same JavaScript API the script tag uses under the hood, and supports reactive attribute changes — you can swap the loaded agent at runtime by changing one prop.
+That's what `<agent-3d>` is for. It's a standards-based custom element that drops cleanly into any framework, exposes the full JavaScript API (methods, events, live attributes), and supports reactive attribute changes — you can swap the loaded agent at runtime by changing one prop.
By the end of this tutorial you'll know the spec well enough to pick the right embed style for any project, wire the element into React and Vue with refs and reactivity, slot your own UI alongside the avatar, and react to attribute changes after mount.
@@ -27,41 +27,48 @@ A custom element is a tag your browser doesn't ship by default. Someone (us, in
Three things make custom elements powerful:
1. **Attributes are the API.** Like `<input type="text">`, you configure the element with HTML attributes. The element watches the ones it cares about (via `observedAttributes`) and reacts when they change.
-2. **Methods and properties.** Once you have an element reference, you can call methods on it (`el.speak('hi')`) and read/set properties just like any DOM node.
+2. **Methods and properties.** Once you have an element reference, you can call methods on it (`el.say('hi')`) and read/set properties just like any DOM node.
3. **Events.** The element dispatches custom events you subscribe to with `addEventListener`. These bubble out of the shadow DOM so framework event handlers can pick them up.
-`<agent-3d>` uses all three. It's registered to the global `customElements` registry the moment the CDN script loads:
+`<agent-3d>` uses all three. It's registered to the global `customElements` registry the moment the runtime script loads:
```html
-<script type="module" src="https://three.ws/cdn/agent-3d.js"></script>
+<script type="module" src="https://three.ws/agent-3d/1.5.2/agent-3d.js"></script>
```
From that point on, `<agent-3d>` is a real tag in the document. No further setup needed.
---
-## Step 2 — Script-tag embed vs the custom element
+## Step 2 — iframe embed vs the custom element
-The CDN exposes two forms of the same thing. They share the underlying code and the same JS API. The differences are ergonomic.
+The platform offers two embed styles for the same agent. The differences are ergonomic.
-**Script-tag form** — terse, declarative, one line. The script tag *is* the agent:
+**iframe form** — sandboxed, self-contained, no script tag on your page:
```html
-<script src="https://three.ws/cdn/agent-3d.js" data-agent-id="YOUR_AGENT_ID" id="my-agent"></script>
+<iframe
+ src="https://three.ws/a/8453/42/embed"
+ width="320"
+ height="420"
+ frameborder="0"
+ allow="microphone"
+ style="border-radius: 16px;"
+></iframe>
```
-The script tag mounts an `<agent-3d>` element in place of itself. Data attributes on the script tag (`data-size`, `data-position`, `data-greeting`, etc.) become attributes on the mounted element. You get a reference to the resulting element with `document.getElementById('my-agent')`.
+The agent runs entirely inside the iframe. You can't call methods on it or listen to its events from your page — the trade for that isolation is zero integration surface.
This is the right embed when:
-- You're on a no-code platform (Webflow, Squarespace, Substack) where you can paste a snippet but not a complex HTML tree
-- You want a single line in your repo
-- You're not using a framework that needs JSX or template syntax
+- You're on a no-code platform (Webflow, Squarespace, Notion, Substack) where you can paste a snippet but not control the `<head>`
+- You want strict sandboxing between the agent and your page
+- You don't need to drive the agent from your own JavaScript
**Custom element form** — explicit, structured, framework-friendly:
```html
-<script type="module" src="https://three.ws/cdn/agent-3d.js"></script>
+<script type="module" src="https://three.ws/agent-3d/1.5.2/agent-3d.js"></script>
<agent-3d
agent-id="YOUR_AGENT_ID"
@@ -72,15 +79,15 @@ This is the right embed when:
></agent-3d>
```
-You separate "load the runtime" from "place the agent". The agent can appear anywhere in your tree, with explicit attributes you can read from a build system, type-check, or template.
+You separate "load the runtime" from "place the agent". The agent can appear anywhere in your tree, with explicit attributes you can read from a build system, type-check, or template — and you get the full JS API: `say()`, `ask()`, `wave()`, `play()`, and the event stream.
This is the right embed when:
-- You're inside a framework where `<script>` injection feels wrong (React, Vue, Angular, Svelte)
+- You're inside a framework with a component tree (React, Vue, Angular, Svelte)
- You want multiple agents on the same page
-- You need precise control over the surrounding DOM
+- You need to call the agent's methods or subscribe to its events
-The rest of this tutorial uses the custom-element form, because that's the one that benefits from a wrapper.
+The rest of this tutorial uses the custom-element form, because that's the one that benefits from a wrapper. (The [embedding guide](./embed-on-website.md) covers the iframe path and the no-code platforms in depth.)
---
@@ -116,13 +123,11 @@ Here's the full list of attributes the element observes, in the categories you'l
| `voice` | Set to `livekit` to opt into LiveKit-backed real-time voice |
| `avatar-chat` | Set to `off` to hide the built-in chat input |
| `avatar-walk` | Set to `off` to disable the walk-when-talking behaviour |
-| `face-camera` | Lock the avatar to face the camera |
+| `framing` | Set to `portrait` for a head-and-shoulders camera framing; the default frames the full body |
| `eager` | Skip the lazy-load wait — boot immediately even when off-screen |
| `api-key` | Override the brain API key (use sparingly; backends are safer) |
| `key-proxy` | URL of your own proxy that vends scoped keys |
-**Data attributes from the script-tag form** — `data-size`, `data-background-color`, `data-position`, `data-rotation-speed`, `data-greeting`, `data-name` — all map onto the equivalent regular attributes when the script tag mounts the element. If you're using the element form directly, drop the `data-` prefix.
-
Every observed attribute can be changed after mount. Step 6 shows what that looks like in practice.
---
@@ -152,7 +157,7 @@ function ensureRuntime() {
if (existing) { resolve(); return; }
const s = document.createElement('script');
s.type = 'module';
- s.src = 'https://three.ws/cdn/agent-3d.js';
+ s.src = 'https://three.ws/agent-3d/1.5.2/agent-3d.js';
s.dataset.agent3dRuntime = '';
s.onload = resolve;
s.onerror = reject;
@@ -168,7 +173,6 @@ export default function Agent3D({
position = 'bottom-right',
background = 'transparent',
mode = 'inline',
- greeting,
name,
onReady,
onMessage,
@@ -213,8 +217,7 @@ export default function Agent3D({
mode={mode}
position={position}
background={background}
- data-greeting={greeting}
- data-name={name}
+ name={name}
/>
);
}
@@ -248,7 +251,7 @@ A few notes on what the wrapper does:
- **Runtime loaded once.** `ensureRuntime()` guards against re-injecting the script on every mount. It checks for an existing tag with `data-agent-3d-runtime` and resolves immediately if found.
- **Events bound in `useEffect`.** Custom event names map to props (`onReady`, `onMessage`). The cleanup function unbinds them, so the wrapper plays nicely with strict mode and unmount.
- **No camelCase attribute names.** Custom elements use dash-case (`agent-id`, not `agentId`). React passes attributes through as-is — `agent-id` is fine in JSX.
-- **`useRef` is the API handle.** If you need to call `ref.current.speak('hi')` from a parent, expose the ref via `forwardRef` or pass an `apiRef` prop in.
+- **`useRef` is the API handle.** If you need to call `ref.current.say('hi')` from a parent, expose the ref via `forwardRef` or pass an `apiRef` prop in.
For TypeScript, drop this in a `.d.ts`:
@@ -328,7 +331,7 @@ const eventMap = [
const handlers = [];
onMounted(async () => {
- await import('https://three.ws/cdn/agent-3d.js');
+ await import('https://three.ws/agent-3d/1.5.2/agent-3d.js');
const el = root.value;
if (!el) return;
for (const [domEvent, vueEvent] of eventMap) {
@@ -346,11 +349,10 @@ onBeforeUnmount(() => {
defineExpose({
// Forward common methods so the parent can call them via template refs.
- speak: (text) => root.value?.speak(text),
say: (text) => root.value?.say(text),
+ ask: (text) => root.value?.ask(text),
wave: () => root.value?.wave(),
- playAnimation: (name) => root.value?.play(name),
- playAnimationByHint: (hint) => root.value?.playAnimationByHint?.(hint),
+ playAnimation: (name, opts) => root.value?.play(name, opts),
});
</script>
@@ -378,7 +380,7 @@ const agent = ref(null);
function onReady(detail) {
console.log('Agent ready:', detail.manifest?.name);
- agent.value.speak('Welcome in.');
+ agent.value.say('Greet the visitor with a one-sentence welcome.');
}
function onMessage(detail) {
@@ -398,7 +400,7 @@ function onMessage(detail) {
</template>
```
-The `defineExpose` block matters: without it, the parent's `agent.value.speak(...)` would be undefined. Vue 3 SFCs are private by default, and you have to opt methods into the public surface.
+The `defineExpose` block matters: without it, the parent's `agent.value.say(...)` would be undefined. Vue 3 SFCs are private by default, and you have to opt methods into the public surface.
---
@@ -493,7 +495,7 @@ Two parts to this.
if (!text) return;
input.value = '';
try {
- await agent.say(text);
+ await agent.ask(text);
} catch (err) {
console.error('Agent failed:', err);
}
@@ -576,7 +578,7 @@ Pick an agent from the dropdown, the active one swaps in place, and the event lo
You can now treat `<agent-3d>` as a real component in any framework. The big takeaways:
-- The script-tag and custom-element forms are interchangeable — pick by ergonomics, not features
+- The iframe and custom-element embeds serve different jobs — sandboxed drop-in vs a full-API component; reach for the element whenever your own code needs to drive the agent
- Attribute changes are reactive; you can swap agents, modes, and layouts at runtime
- React works fine once you bind events in `useEffect`; remember dash-case attribute names
- Vue works fine once you flag the tag as a custom element in the compiler config
diff --git a/docs/web-component.md b/docs/web-component.md
index d81fe2fc8..0adf0817c 100644
--- a/docs/web-component.md
+++ b/docs/web-component.md
@@ -60,15 +60,12 @@ Using `body` with no manifest creates an ad-hoc agent. Its name, instructions, a
| Attribute | Type | Default | Description |
|-----------|------|---------|-------------|
-| `environment` | preset name or HDRI URL | `neutral` | IBL environment. Accepts built-in preset names or an HDRI URL. |
-| `auto-rotate` | boolean | off | Slowly rotates the model around the Y-axis. |
-| `camera-controls` | boolean | off | Enables orbit, pan, and zoom with mouse/touch. |
-| `ar` | boolean | off | Shows an AR launch button. Automatically selects the best available method: iOS Quick Look (Safari), Android Scene Viewer (Chrome), or WebXR immersive-ar. Button is hidden on desktop and on unsupported browsers. Requires HTTPS. See [AR & WebXR guide](/docs/ar). |
-| `shadows` | boolean | on | Enables contact and soft shadows. |
-| `exposure` | number | `1.0` | Tone-mapping exposure multiplier. |
| `background` | `transparent` \| `dark` \| `light` | `transparent` | Canvas clear color. `transparent` lets the page background show through. |
-| `skybox` | URL | — | HDRI rendered as visible sky behind the model. |
| `poster` | URL | — | Image shown while the model loads. Fades out on completion. |
+| `framing` | `full` \| `portrait` | `full` | Camera framing. `portrait` frames the head and shoulders. |
+| `clip` | clip name | — | Animation clip to play on load. |
+
+Lighting, camera orbit, and environment are managed by the built-in viewer; they are not attribute-configurable. For AR placement, use the dedicated AR surfaces described in [AR](#ar) below.
### Brain (LLM runtime)
@@ -78,23 +75,18 @@ Using `body` with no manifest creates an ad-hoc agent. Its name, instructions, a
| `instructions` | URL or inline text | from manifest | System prompt. Can be a URL ending in `.md` or an inline string. Overrides `manifest.brain.instructions`. |
| `api-key` | string | — | API key injected directly. **Development use only.** Prefer `key-proxy` for any page that will be public. |
| `key-proxy` | URL | — | URL of your backend that injects API keys into outbound LLM requests. |
-| `thinking` | `auto` \| `always` \| `never` | `auto` | Extended thinking hint passed to the provider. |
### Voice
| Attribute | Type | Default | Description |
|-----------|------|---------|-------------|
-| `voice` | boolean | on if manifest configures voice | Master on/off switch for speech I/O. |
-| `tts` | provider ID | `browser` | Text-to-speech provider. Overrides the manifest. |
-| `stt` | provider ID | `browser` | Speech-to-text provider. Overrides the manifest. |
-| `mic` | `push-to-talk` \| `continuous` \| `off` | `push-to-talk` | Microphone activation policy. |
+| `voice` | string | on if manifest configures voice | Voice mode. Set to `livekit` for the LiveKit realtime voice pipeline; TTS/STT providers otherwise come from the manifest. |
### Skills and memory
| Attribute | Type | Default | Description |
|-----------|------|---------|-------------|
-| `skills` | comma-separated URIs | — | Additional skill URIs to install on top of (or instead of) manifest skills. |
-| `skills-only` | boolean | off | When set, ignores manifest skills and uses only the `skills` attribute. |
+| `skills` | comma-separated URIs | — | Additional skill URIs to install on top of manifest skills. |
| `skill-trust` | `any` \| `whitelist` \| `owned-only` | from manifest | Controls which skill URIs are allowed to install. `owned-only` allows only skills whose author matches the agent's `ownerAddress`. |
| `memory` | `local` \| `ipfs` \| `encrypted-ipfs` \| `none` | from manifest | Memory storage mode. |
| `memory-key` | string | agent ID or name | Namespace under which memory is persisted. Useful when embedding the same agent in multiple contexts. |
@@ -114,7 +106,6 @@ Using `body` with no manifest creates an ad-hoc agent. Its name, instructions, a
| Attribute | Type | Description |
|-----------|------|-------------|
-| `chain` | `base` \| `base-sepolia` \| `ethereum` | Overrides the chain in `src="agent://…"`. |
| `chain-id` | number | Numeric chain ID, e.g. `8453`. Required when `agent-id` is a bare number. |
| `registry` | `0x` address | Override the deployed registry contract (for CAIP-10 precision). |
@@ -124,7 +115,6 @@ Using `body` with no manifest creates an ad-hoc agent. Its name, instructions, a
|-----------|-------------|
| `eager` | Boot immediately on DOM connection, bypassing the IntersectionObserver lazy-load. |
| `kiosk` | Hides all UI chrome: chat input, mic button, validator panel, editor links. Use for display contexts where end users should not interact. |
-| `debug` | Overlays scene graph stats, tool-call log, and memory inspector in the shadow DOM. |
| `name-plate` | Controls the name overlay. Set to `"off"` to hide it. |
---
@@ -383,32 +373,14 @@ All events bubble and are `composed: true`, meaning they cross shadow DOM bounda
|-------|--------|------|
| `memory:write` | `{ key, type }` | A memory entry was written. |
-### AR events
-
-| Event | Detail | When |
-|-------|--------|------|
-| `ar-status` | `{ status }` | AR session lifecycle. `status` is one of `"session-started"`, `"object-placed"`, `"failed"`, `"not-presenting"`. |
-
-```js
-el.addEventListener('ar-status', (e) => {
- if (e.detail.status === 'object-placed') {
- console.log('Agent anchored in real world');
- }
-});
-```
-
-**`el.canActivateAR`** — boolean property. `true` when the model is loaded and at least one AR method (Quick Look, Scene Viewer, or WebXR) is available on the current device. Always `false` on desktop.
+### AR
-**`el.activateAR()`** — async method. Triggers the best available AR method. Resolves when the session starts (WebXR) or immediately (Quick Look / Scene Viewer). Throws if `canActivateAR` is `false`.
+`<agent-3d>` itself does not expose an AR API. AR placement lives on the platform's dedicated AR surfaces:
-```js
-const el = document.querySelector('agent-3d');
-if (el.canActivateAR) {
- await el.activateAR();
-}
-```
+- **`/avatars/:id/ar`** — every avatar has a full-screen AR page. It selects the right method per device automatically: iOS Quick Look (with in-browser GLB→USDZ conversion when no pre-generated USDZ exists), Android Scene Viewer, or WebXR.
+- **Viewer AR button** — the avatar viewer and Forge result toolbar include a **View in AR** control; on desktop it shows a QR code that opens the AR session on a phone.
-For full API reference, platform compatibility, and troubleshooting, see the [AR & WebXR guide](/docs/ar).
+To offer AR from a page that embeds the component, link to the avatar's `/avatars/:id/ar` page. For methods, platform compatibility, and troubleshooting, see the [AR & WebXR guide](/docs/ar).
### Listening example
@@ -626,7 +598,6 @@ The `kiosk` attribute strips all interactive chrome: the chat input, mic button,
<agent-3d
src="agent://base/42"
kiosk
- auto-rotate
style="width:100%;height:600px"
></agent-3d>
```
diff --git a/mcp-server/src/tools/crypto-news-archive.js b/mcp-server/src/tools/crypto-news-archive.js
index b6f1d74b7..a363bf4c2 100644
--- a/mcp-server/src/tools/crypto-news-archive.js
+++ b/mcp-server/src/tools/crypto-news-archive.js
@@ -25,7 +25,8 @@ const TOOL_DESCRIPTION =
'collapse. For today\'s coverage use crypto_news or crypto_news_digest. stats and trending modes are ' +
'always free; search includes a free daily quota (60/day per IP, no key or wallet needed), then ' +
'$0.001 USDC per search via x402 — an exhausted quota returns a payment_required envelope with the ' +
- 'price and accepted networks.';
+ 'price and accepted networks. Heavy users: a monthly Premium pass (paid on Solana in $THREE at 20% ' +
+ 'off, SOL, or USDC — see three.ws/docs/premium) replaces per-search payments with an API key.';
const inputZodShape = {
mode: z
diff --git a/pages/dashboard-next/billing.html b/pages/dashboard-next/billing.html
new file mode 100644
index 000000000..9c5bd60ef
--- /dev/null
+++ b/pages/dashboard-next/billing.html
@@ -0,0 +1,16 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>Billing &amp; Passes · Dashboard · three.ws</title>
+ <meta name="description" content="Manage your three.ws subscriptions and paid services — Premium pass status, on-chain payment history, API keys, and creator subscriptions in one place." />
+ <link rel="icon" href="/favicon.ico" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <link rel="stylesheet" href="/dashboard-next/shell.css" />
+</head>
+<body>
+ <script src="/embed.js"></script>
+ <script type="module" src="/src/dashboard-next/pages/billing.js"></script>
+</body>
+</html>
diff --git a/pages/dashboard-next/data-api.html b/pages/dashboard-next/data-api.html
new file mode 100644
index 000000000..95044693c
--- /dev/null
+++ b/pages/dashboard-next/data-api.html
@@ -0,0 +1,16 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>Data API · Dashboard · three.ws</title>
+ <meta name="description" content="Developer console for the three.ws Data API — buy the Premium pass with $THREE, SOL, or USDC, manage your API key, watch usage, and copy working quickstarts." />
+ <link rel="icon" href="/favicon.ico" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <link rel="stylesheet" href="/dashboard-next/shell.css" />
+</head>
+<body>
+ <script src="/embed.js"></script>
+ <script type="module" src="/src/dashboard-next/pages/data-api.js"></script>
+</body>
+</html>
diff --git a/public/changelog.json b/public/changelog.json
index 5f6ff9422..a3d4c9ac2 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,11 +1,31 @@
{
- "generated_at": "2026-07-11T03:45:18.108Z",
+ "generated_at": "2026-07-11T04:07:32.412Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
"url": "https://three.ws"
},
"entries": [
+ {
+ "date": "2026-07-11",
+ "type": "launch",
+ "title": "Dashboard · Billing & Passes",
+ "summary": "Manage subscriptions and paid services — Premium pass status, on-chain payment history, API keys, and creator subscriptions.",
+ "link": "/dashboard/billing",
+ "tags": [
+ "launch"
+ ]
+ },
+ {
+ "date": "2026-07-11",
+ "type": "launch",
+ "title": "Dashboard · Data API",
+ "summary": "Developer console for the three.ws Data API — buy the Premium pass with $THREE, SOL, or USDC, manage API keys, watch usage, and copy quickstarts.",
+ "link": "/dashboard/data-api",
+ "tags": [
+ "launch"
+ ]
+ },
{
"date": "2026-07-11",
"type": "launch",
@@ -16,6 +36,37 @@
"launch"
]
},
+ {
+ "date": "2026-07-11",
+ "type": "launch",
+ "title": "Premium Pass — Monthly Data API Access",
+ "summary": "One Solana payment ($THREE at 20% off, SOL, or USDC) buys 30 days of unmetered Data API access with an API key — no per-call x402 payments.",
+ "link": "/docs/premium",
+ "tags": [
+ "launch"
+ ]
+ },
+ {
+ "date": "2026-07-11",
+ "type": "update",
+ "title": "Documentation accuracy pass: every tutorial verified against the shipped platform",
+ "summary": "We cross-referenced all 300+ docs and specs against the actual codebase and fixed everything that had drifted. The embed snippet in ten tutorials now uses the real two-line form that works on any site, four tutorials that demonstrated retired or never-shipped APIs were rewritten against the live component, the troubleshooting guide now reflects the current Cloud Run production stack with the correct session and storage details, and the manifest, quick-start, and API references now list exactly the providers, attributes, and endpoints that exist today. Every code sample in the affected docs runs as written.",
+ "link": "/docs/tutorials/embed-in-30-seconds",
+ "tags": [
+ "docs",
+ "fix"
+ ]
+ },
+ {
+ "date": "2026-07-11",
+ "type": "update",
+ "title": "Premium: one monthly pass instead of paying per call",
+ "summary": "Go Premium for $9.99/30 days and stop paying the Data API per search: one Solana payment — in $THREE at 20% off, SOL, or USDC — mints an API key with unmetered archive search and lets your wallet sign in on the archive page instead of paying. Two new dashboard surfaces ship with it: a developer console at /dashboard/data-api (buy or renew the pass, manage and rotate API keys, live usage, copy-paste quickstarts) and Billing & Passes at /dashboard/billing (pass status, on-chain payment history, your subscriptions and paid services in one place). Renewals stack — renewing early adds 30 days to the end, never losing time.",
+ "link": "/docs/premium",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-07-11",
"type": "update",
@@ -27,6 +78,17 @@
"improvement"
]
},
+ {
+ "date": "2026-07-11",
+ "type": "update",
+ "title": "The news page becomes Your Briefing",
+ "summary": "/markets/news is redesigned as a daily briefing: a breaking-news ticker for stories under 45 minutes old, a collapsible Today's AI Briefing card built from the digest engine, a Featured tab covering the major outlets, a Trending tab ranking the day's most-covered narratives, a Top-stories hero with a compact headline rail, and a star on every story that saves it to a personal Saved tab. Article preview images were also overhauled — thumbnails blocked by publishers now load through a same-origin proxy, and stories whose feed ships no image pull the publisher's own social preview automatically, so cards no longer show blank tiles.",
+ "link": "/markets/news",
+ "tags": [
+ "feature",
+ "improvement"
+ ]
+ },
{
"date": "2026-07-10",
"type": "launch",
diff --git a/public/changelog.xml b/public/changelog.xml
index a042289b3..1114db28f 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -6,6 +6,22 @@
<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/>
<description>What's new on three.ws — features, improvements, and releases, newest first.</description>
<language>en</language>
+ <item>
+ <title>Dashboard · Billing &amp; Passes</title>
+ <link>https://three.ws/dashboard/billing</link>
+ <guid isPermaLink="false">2026-07-11:Dashboard · Billing &amp; Passes</guid>
+ <pubDate>Sat, 11 Jul 2026 12:00:00 GMT</pubDate>
+ <category>launch</category>
+ <description>Manage subscriptions and paid services — Premium pass status, on-chain payment history, API keys, and creator subscriptions.</description>
+ </item>
+ <item>
+ <title>Dashboard · Data API</title>
+ <link>https://three.ws/dashboard/data-api</link>
+ <guid isPermaLink="false">2026-07-11:Dashboard · Data API</guid>
+ <pubDate>Sat, 11 Jul 2026 12:00:00 GMT</pubDate>
+ <category>launch</category>
+ <description>Developer console for the three.ws Data API — buy the Premium pass with $THREE, SOL, or USDC, manage API keys, watch usage, and copy quickstarts.</description>
+ </item>
<item>
<title>DeFi Yields Explorer</title>
<link>https://three.ws/yields</link>
@@ -14,6 +30,30 @@
<category>launch</category>
<description>Explore roughly 15,000 live DeFi yield pools across every chain and protocol — filter by chain, project, stablecoin exposure, and minimum TVL, sort by APY or TVL, and open any pool to see its full APY and TVL history. Live from DeFiLlama, no key required.</description>
</item>
+ <item>
+ <title>Premium Pass — Monthly Data API Access</title>
+ <link>https://three.ws/docs/premium</link>
+ <guid isPermaLink="false">2026-07-11:Premium Pass — Monthly Data API Access</guid>
+ <pubDate>Sat, 11 Jul 2026 12:00:00 GMT</pubDate>
+ <category>launch</category>
+ <description>One Solana payment ($THREE at 20% off, SOL, or USDC) buys 30 days of unmetered Data API access with an API key — no per-call x402 payments.</description>
+ </item>
+ <item>
+ <title>Documentation accuracy pass: every tutorial verified against the shipped platform</title>
+ <link>https://three.ws/docs/tutorials/embed-in-30-seconds</link>
+ <guid isPermaLink="false">2026-07-11:Documentation accuracy pass: every tutorial verified against the shipped platform</guid>
+ <pubDate>Sat, 11 Jul 2026 12:00:00 GMT</pubDate>
+ <category>docs</category>
+ <description>We cross-referenced all 300+ docs and specs against the actual codebase and fixed everything that had drifted. The embed snippet in ten tutorials now uses the real two-line form that works on any site, four tutorials that demonstrated retired or never-shipped APIs were rewritten against the live component, the troubleshooting guide now reflects the current Cloud Run production stack with the correct session and storage details, and the manifest, quick-start, and API references now list exactly the providers, attributes, and endpoints that exist today. Every code sample in the affected docs runs as written.</description>
+ </item>
+ <item>
+ <title>Premium: one monthly pass instead of paying per call</title>
+ <link>https://three.ws/docs/premium</link>
+ <guid isPermaLink="false">2026-07-11:Premium: one monthly pass instead of paying per call</guid>
+ <pubDate>Sat, 11 Jul 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Go Premium for $9.99/30 days and stop paying the Data API per search: one Solana payment — in $THREE at 20% off, SOL, or USDC — mints an API key with unmetered archive search and lets your wallet sign in on the archive page instead of paying. Two new dashboard surfaces ship with it: a developer console at /dashboard/data-api (buy or renew the pass, manage and rotate API keys, live usage, copy-paste quickstarts) and Billing &amp; Passes at /dashboard/billing (pass status, on-chain payment history, your subscriptions and paid services in one place). Renewals stack — renewing early adds 30 days to the end, never losing time.</description>
+ </item>
<item>
<title>Richer coin pages, plus new exchange, category, and DeFi-yields detail pages</title>
<link>https://three.ws/yields</link>
@@ -22,6 +62,14 @@
<category>feature</category>
<description>Every coin page now shows far more of what the data already offers: a 1h-to-1y price-performance matrix, a circulating-vs-max supply bar with the market-cap/FDV ratio, all-time high and low with the drawdown and recovery multiple, the community bullish/bearish sentiment split, GitHub and social activity, and a full exchange-listings table with spread, order-book depth, and a trust rating for each venue. Exchanges and crypto categories, which used to only send you off-site or filter a table, now have their own detail pages — an exchange page with a trust badge, wash-volume-adjusted volume, a volume-history chart, and its markets, and a category page with the sector's rank, stats, and full coin list. And a brand-new DeFi Yields explorer covers roughly 15,000 live pools across every chain and protocol, filterable and sortable, each with its own APY and TVL history chart. All of it is real, key-free data.</description>
</item>
+ <item>
+ <title>The news page becomes Your Briefing</title>
+ <link>https://three.ws/markets/news</link>
+ <guid isPermaLink="false">2026-07-11:The news page becomes Your Briefing</guid>
+ <pubDate>Sat, 11 Jul 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>/markets/news is redesigned as a daily briefing: a breaking-news ticker for stories under 45 minutes old, a collapsible Today's AI Briefing card built from the digest engine, a Featured tab covering the major outlets, a Trending tab ranking the day's most-covered narratives, a Top-stories hero with a compact headline rail, and a star on every story that saves it to a personal Saved tab. Article preview images were also overhauled — thumbnails blocked by publishers now load through a same-origin proxy, and stories whose feed ships no image pull the publisher's own social preview automatically, so cards no longer show blank tiles.</description>
+ </item>
<item>
<title>Crypto News</title>
<link>https://three.ws/markets/news</link>
diff --git a/public/features.json b/public/features.json
index ebe8de838..3b6369763 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-11T03:45:18.092Z",
+ "generated_at": "2026-07-11T04:07:32.399Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
@@ -2080,6 +2080,26 @@
"tags": [],
"showcase": false
},
+ {
+ "path": "/dashboard/data-api",
+ "title": "Dashboard · Data API",
+ "description": "Developer console for the three.ws Data API — buy the Premium pass with $THREE, SOL, or USDC, manage API keys, watch usage, and copy quickstarts.",
+ "added": "2026-07-11",
+ "auth": "required",
+ "indexable": false,
+ "tags": [],
+ "showcase": false
+ },
+ {
+ "path": "/dashboard/billing",
+ "title": "Dashboard · Billing & Passes",
+ "description": "Manage subscriptions and paid services — Premium pass status, on-chain payment history, API keys, and creator subscriptions.",
+ "added": "2026-07-11",
+ "auth": "required",
+ "indexable": false,
+ "tags": [],
+ "showcase": false
+ },
{
"path": "/dashboard/analytics",
"title": "Dashboard · Analytics",
@@ -2277,6 +2297,16 @@
"tags": [],
"showcase": false
},
+ {
+ "path": "/docs/premium",
+ "title": "Premium Pass — Monthly Data API Access",
+ "description": "One Solana payment ($THREE at 20% off, SOL, or USDC) buys 30 days of unmetered Data API access with an API key — no per-call x402 payments.",
+ "added": "2026-07-11",
+ "auth": null,
+ "indexable": true,
+ "tags": [],
+ "showcase": false
+ },
{
"path": "/docs/x402-endpoints",
"title": "Docs · x402 Paid Endpoints",
diff --git a/public/llms-full.txt b/public/llms-full.txt
index dade2c4fe..8ae3bc8e0 100644
--- a/public/llms-full.txt
+++ b/public/llms-full.txt
@@ -1266,6 +1266,22 @@ Indexable: no (excluded from sitemap)
Manage connected wallets, SNS, delegation, and action log.
+### Dashboard · Data API
+
+URL: https://three.ws/dashboard/data-api
+Auth: required (sign-in)
+Indexable: no (excluded from sitemap)
+
+Developer console for the three.ws Data API — buy the Premium pass with $THREE, SOL, or USDC, manage API keys, watch usage, and copy quickstarts.
+
+### Dashboard · Billing & Passes
+
+URL: https://three.ws/dashboard/billing
+Auth: required (sign-in)
+Indexable: no (excluded from sitemap)
+
+Manage subscriptions and paid services — Premium pass status, on-chain payment history, API keys, and creator subscriptions.
+
### Dashboard · Analytics
URL: https://three.ws/dashboard/analytics
@@ -1390,6 +1406,12 @@ URL: https://three.ws/docs/x402
How three.ws implements x402 HTTP 402 paid agent skills — the challenge, verify, and settle mechanics.
+### Premium Pass — Monthly Data API Access
+
+URL: https://three.ws/docs/premium
+
+One Solana payment ($THREE at 20% off, SOL, or USDC) buys 30 days of unmetered Data API access with an API key — no per-call x402 payments.
+
### Docs · x402 Paid Endpoints
URL: https://three.ws/docs/x402-endpoints
diff --git a/public/llms.txt b/public/llms.txt
index 6314cbe14..081f685eb 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -252,6 +252,7 @@ Docs, tutorials, and reference.
- [Docs · Agent Reputation](https://three.ws/docs/agent-reputation): Why autonomous agents need verifiable trust, and how three.ws delivers portable on-chain reputation.
- [Docs · Trust Primitives](https://three.ws/docs/trust-primitives): Cross-chain Agent Reputation — score any wallet, mint, or agent id (Solana or EVM) 0–100 from real on-chain evidence before your agent pays, trades, or delegates.
- [Docs · x402 Protocol](https://three.ws/docs/x402): How three.ws implements x402 HTTP 402 paid agent skills — the challenge, verify, and settle mechanics.
+- [Premium Pass — Monthly Data API Access](https://three.ws/docs/premium): One Solana payment ($THREE at 20% off, SOL, or USDC) buys 30 days of unmetered Data API access with an API key — no per-call x402 payments.
- [Docs · x402 Paid Endpoints](https://three.ws/docs/x402-endpoints): The catalog of three.ws's own paid HTTP endpoints — what each charges, the price-override scheme, and what it returns.
- [Docs · x402 Revenue & Receipts](https://three.ws/docs/x402-revenue): Where settled x402 payments are recorded (x402_audit_log), how to read endpoint revenue, and how signed receipts work.
- [Docs · Pump Launcher](https://three.ws/docs/pump-launcher): Deploy a brand-new pump.fun token in one paid call — no SOL, no wallet, no account. Inputs, outputs, pricing, correctness guarantees, and the free symbol-check → launch → launch-feed funnel.
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index 93941e8df..07602d647 100644
--- a/public/sitemap/index.html
+++ b/public/sitemap/index.html
@@ -56,25 +56,6 @@
.sm-brand img { width: 24px; height: 24px; border-radius: 5px; }
.sm-brand:hover { text-decoration: none; }
</style>
-
- <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1">
- <meta property="og:type" content="website">
- <meta property="og:site_name" content="three.ws">
- <meta property="og:locale" content="en_US">
- <meta property="og:title" content="Sitemap · three.ws">
- <meta property="og:description" content="Human-readable index of every page on three.ws.">
- <meta property="og:url" content="https://three.ws/sitemap">
- <meta property="og:image" content="https://three.ws/api/page-og?s=main&amp;t=Sitemap&amp;d=Human-readable+index+of+every+page+on+three.ws.&amp;p=%2Fsitemap">
- <meta property="og:image:width" content="1200">
- <meta property="og:image:height" content="630">
- <meta property="og:image:type" content="image/png">
- <meta property="og:image:alt" content="Sitemap — three.ws">
- <meta name="twitter:card" content="summary_large_image">
- <meta name="twitter:site" content="@trythreews">
- <meta name="twitter:title" content="Sitemap · three.ws">
- <meta name="twitter:description" content="Human-readable index of every page on three.ws.">
- <meta name="twitter:image" content="https://three.ws/api/page-og?s=main&amp;t=Sitemap&amp;d=Human-readable+index+of+every+page+on+three.ws.&amp;p=%2Fsitemap">
- <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","name":"Sitemap","description":"Human-readable index of every page on three.ws.","url":"https://three.ws/sitemap","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"},"primaryImageOfPage":"https://three.ws/api/page-og?s=main&t=Sitemap&d=Human-readable+index+of+every+page+on+three.ws.&p=%2Fsitemap"}]}</script>
</head>
<body>
<header class="sm-topbar">
@@ -84,7 +65,7 @@
<main class="sm-wrap">
<div class="sm-hero">
<h1>Sitemap</h1>
- <p>All 416 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
+ <p>All 419 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>
@@ -96,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 416 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
+ <input id="sm-filter-input" type="search" placeholder="Filter 419 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>
@@ -1532,7 +1513,7 @@
<section class="sm-section" id="account">
<header>
- <h2>Account<span class="sm-count" data-count>10</span></h2>
+ <h2>Account<span class="sm-count" data-count>12</span></h2>
<p class="sm-section-desc">Sign-in, dashboard, billing.</p>
</header>
<ul class="sm-list">
@@ -1585,6 +1566,20 @@
<span class="sm-desc">Manage connected wallets, SNS, delegation, and action log.</span>
</a>
</li>
+ <li>
+ <a href="/dashboard/data-api">
+ <span class="sm-title">Dashboard · Data API<span class="sm-badge sm-badge-auth">sign-in</span><span class="sm-badge sm-badge-internal">internal</span></span>
+ <span class="sm-path">/dashboard/data-api</span>
+ <span class="sm-desc">Developer console for the three.ws Data API — buy the Premium pass with $THREE, SOL, or USDC, manage API keys, watch usage, and copy quickstarts.</span>
+ </a>
+ </li>
+ <li>
+ <a href="/dashboard/billing">
+ <span class="sm-title">Dashboard · Billing &amp; Passes<span class="sm-badge sm-badge-auth">sign-in</span><span class="sm-badge sm-badge-internal">internal</span></span>
+ <span class="sm-path">/dashboard/billing</span>
+ <span class="sm-desc">Manage subscriptions and paid services — Premium pass status, on-chain payment history, API keys, and creator subscriptions.</span>
+ </a>
+ </li>
<li>
<a href="/dashboard/analytics">
<span class="sm-title">Dashboard · Analytics<span class="sm-badge sm-badge-auth">sign-in</span><span class="sm-badge sm-badge-internal">internal</span></span>
@@ -1611,7 +1606,7 @@
<section class="sm-section" id="learn">
<header>
- <h2>Learn<span class="sm-count" data-count>61</span></h2>
+ <h2>Learn<span class="sm-count" data-count>62</span></h2>
<p class="sm-section-desc">Docs, tutorials, and reference.</p>
</header>
<ul class="sm-list">
@@ -1727,6 +1722,13 @@
<span class="sm-desc">How three.ws implements x402 HTTP 402 paid agent skills — the challenge, verify, and settle mechanics.</span>
</a>
</li>
+ <li>
+ <a href="/docs/premium">
+ <span class="sm-title">Premium Pass — Monthly Data API Access</span>
+ <span class="sm-path">/docs/premium</span>
+ <span class="sm-desc">One Solana payment ($THREE at 20% off, SOL, or USDC) buys 30 days of unmetered Data API access with an API key — no per-call x402 payments.</span>
+ </a>
+ </li>
<li>
<a href="/docs/x402-endpoints">
<span class="sm-title">Docs · x402 Paid Endpoints</span>
diff --git a/scripts/check-head-tmp.mjs b/scripts/check-head-tmp.mjs
deleted file mode 100644
index 7f834bd86..000000000
--- a/scripts/check-head-tmp.mjs
+++ /dev/null
@@ -1,10 +0,0 @@
-import { chromium } from 'playwright';
-const browser = await chromium.launch();
-const page = await browser.newPage({ viewport: { width: 1440, height: 1100 } });
-await page.goto('http://localhost:8090/markets/news', { waitUntil: 'domcontentloaded', timeout: 60000 });
-await page.waitForTimeout(1500);
-console.log(await page.evaluate(() => {
- const box = (sel) => { const el = document.querySelector(sel); if (!el) return null; const r = el.getBoundingClientRect(); const cs = getComputedStyle(el); return { sel, top: Math.round(r.top), h: Math.round(r.height), mt: cs.marginTop, mb: cs.marginBottom, ai: cs.alignItems, pos: cs.position }; };
- return JSON.stringify([box('.nwb-head'), box('.nwb-head-id'), box('.nwb-head .cv-h1'), box('.nwb-head-tools'), box('.nwb-search'), box('.nwb-search input'), box('.nwb-controls'), box('.cv-crumbs')], null, 1);
-}));
-await browser.close();
diff --git a/scripts/check-news-tmp.mjs b/scripts/check-news-tmp.mjs
deleted file mode 100644
index 08f734d3e..000000000
--- a/scripts/check-news-tmp.mjs
+++ /dev/null
@@ -1,63 +0,0 @@
-import { chromium } from 'playwright';
-
-const BASE = 'http://localhost:8090';
-const OUT = '/tmp/claude-1000/-workspaces-three-ws/7202a201-2f6a-47fa-a984-64069f93d10d/scratchpad';
-const browser = await chromium.launch();
-const errors = [];
-const page = await browser.newPage({ viewport: { width: 1440, height: 1100 } });
-page.on('console', (m) => {
- if (m.type() === 'error') errors.push(m.text().slice(0, 200));
-});
-page.on('pageerror', (e) => errors.push(`PAGEERROR: ${e.message.slice(0, 200)}`));
-
-await page.goto(`${BASE}/markets/news`, { waitUntil: 'networkidle', timeout: 60000 });
-await page.waitForTimeout(3000);
-await page.screenshot({ path: `${OUT}/news-desktop.png`, fullPage: false });
-
-// Count real vs fallback media
-const stats = await page.evaluate(() => {
- const imgs = [...document.querySelectorAll('.nw-media img, .nw-hero-media img')];
- return {
- title: document.querySelector('.cv-h1')?.textContent,
- date: document.getElementById('nwb-date')?.textContent,
- tabs: [...document.querySelectorAll('.nwb-tab span')].map((s) => s.textContent),
- breakingVisible: !document.getElementById('nwb-breaking').hidden,
- briefVisible: !document.getElementById('nwb-brief').hidden,
- briefPoints: document.querySelectorAll('.nwb-brief-list li').length,
- heroCount: document.querySelectorAll('.nw-hero').length,
- railRows: document.querySelectorAll('.nwb-rail .nw-row').length,
- gridCards: document.querySelectorAll('.nw-grid .nw-card').length,
- imgsLoaded: imgs.filter((i) => i.complete && i.naturalWidth > 0).length,
- imgsTotal: imgs.length,
- fallbackTiles: document.querySelectorAll('.nw-fallback').length,
- stars: document.querySelectorAll('.nw-star').length,
- };
-});
-console.log(JSON.stringify(stats, null, 1));
-
-// Exercise tabs: featured, trending, saved
-for (const tab of ['featured', 'trending', 'saved', 'all']) {
- await page.click(`[data-tab="${tab}"]`);
- await page.waitForTimeout(tab === 'trending' ? 8000 : 2500);
- await page.screenshot({ path: `${OUT}/news-${tab}.png` });
- console.log(tab, 'url:', page.url());
-}
-// star a story then check saved
-await page.click('[data-tab="headlines"]');
-await page.waitForTimeout(2500);
-await page.click('.nw-star');
-await page.click('[data-tab="saved"]');
-await page.waitForTimeout(500);
-console.log('saved rows after star:', await page.locator('.nwb-saved .nw-row').count());
-await page.screenshot({ path: `${OUT}/news-saved-after-star.png` });
-
-// mobile
-const mob = await browser.newPage({ viewport: { width: 375, height: 800 } });
-await mob.goto(`${BASE}/markets/news`, { waitUntil: 'networkidle', timeout: 60000 });
-await mob.waitForTimeout(2500);
-await mob.screenshot({ path: `${OUT}/news-mobile.png`, fullPage: false });
-const hscroll = await mob.evaluate(() => document.documentElement.scrollWidth > document.documentElement.clientWidth + 1);
-console.log('mobile horizontal scroll:', hscroll);
-
-console.log('CONSOLE ERRORS:', errors.length ? errors : 'none');
-await browser.close();
diff --git a/scripts/check-overflow-tmp.mjs b/scripts/check-overflow-tmp.mjs
deleted file mode 100644
index d13965902..000000000
--- a/scripts/check-overflow-tmp.mjs
+++ /dev/null
@@ -1,22 +0,0 @@
-import { chromium } from 'playwright';
-const browser = await chromium.launch();
-const page = await browser.newPage({ viewport: { width: 375, height: 800 } });
-await page.goto('http://localhost:8090/markets/news', { waitUntil: 'networkidle', timeout: 60000 });
-await page.waitForTimeout(2500);
-const r = await page.evaluate(() => {
- const doc = document.documentElement;
- const main = document.querySelector('main');
- const out = { docScrollW: doc.scrollWidth, clientW: doc.clientWidth, mainW: main.getBoundingClientRect().width };
- // scrollWidth > clientWidth per element = internal overflow that may spill
- out.spillers = [...document.querySelectorAll('body *')]
- .filter((el) => el.scrollWidth > el.clientWidth + 2 && getComputedStyle(el).overflowX === 'visible')
- .slice(0, 10)
- .map((el) => `${el.tagName}.${[...el.classList].join('.')} scrollW=${el.scrollWidth} clientW=${el.clientWidth}`);
- const sel = document.getElementById('nw-source');
- out.sourceSelW = sel ? sel.getBoundingClientRect().width : null;
- const brk = document.getElementById('nwb-breaking');
- out.breakW = brk && !brk.hidden ? brk.scrollWidth + '/' + brk.clientWidth : 'hidden';
- return out;
-});
-console.log(JSON.stringify(r, null, 1));
-await browser.close();
diff --git a/scripts/check-overflow2-tmp.mjs b/scripts/check-overflow2-tmp.mjs
deleted file mode 100644
index e13f4ea89..000000000
--- a/scripts/check-overflow2-tmp.mjs
+++ /dev/null
@@ -1,7 +0,0 @@
-import { chromium } from 'playwright';
-const browser = await chromium.launch();
-const page = await browser.newPage({ viewport: { width: 375, height: 800 } });
-await page.goto('http://localhost:8090/coins', { waitUntil: 'domcontentloaded', timeout: 60000 });
-await page.waitForTimeout(2500);
-console.log('coins:', await page.evaluate(() => `${document.documentElement.scrollWidth} vs ${document.documentElement.clientWidth}, boxSizing(main)=${getComputedStyle(document.querySelector('main')).boxSizing}`));
-await browser.close();
diff --git a/src/dashboard-next/nav.js b/src/dashboard-next/nav.js
index fc76eeba8..b9d5e6da1 100644
--- a/src/dashboard-next/nav.js
+++ b/src/dashboard-next/nav.js
@@ -28,6 +28,7 @@ export const NAV = [
{ path: '/dashboard/walk', label: 'Walk Companion', icon: 'walk', group: 'Distribute', tags: ['walk', 'companion', 'mascot', 'avatar', 'sdk', '@three-ws/walk', 'playground', 'greeting', 'picker', 'embed'] },
{ path: '/dashboard/api', label: 'API & Embed', icon: 'code', group: 'Distribute', tags: ['keys', 'token', 'mcp', 'snippets', 'embed-policy'] },
{ path: '/dashboard/developers', label: 'Developer Hub', icon: 'devhub', group: 'Distribute', tags: ['render', 'webhooks', 'sdk', 'unity', 'unreal', 'integration', 'api', 'partner'] },
+ { path: '/dashboard/data-api', label: 'Data API', icon: 'database', group: 'Distribute', tags: ['premium', 'pass', 'news', 'archive', 'api key', 'x402', 'usage', '$three', 'subscription', 'crypto news', 'data'] },
{ path: '/marketplace', label: 'Marketplace', icon: 'market', group: 'Distribute', tags: ['browse', 'buy', 'sell', 'agents', 'avatars', 'directory'], external: true },
{ path: '/skills', label: 'Skills', icon: 'skills', group: 'Distribute', tags: ['tool', 'pack', 'capability', 'install', 'browse', 'skill'], external: true },
@@ -68,6 +69,7 @@ export const NAV = [
{ path: '/dashboard/account', label: 'Account', icon: 'user', group: 'Account', tags: ['wallets', 'sns', 'delegation', 'profile', 'action log', 'provider keys'] },
{ path: '/dashboard/referrals', label: 'Referrals', icon: 'gift', group: 'Account', tags: ['referral', 'invite', 'membership', 'card', 'refer a friend', 'share', 'rewards', 'position', 'score'] },
{ path: '/dashboard/wallet-grinder', label: 'Wallet Grinder', icon: 'sparkle', group: 'Account', tags: ['vanity', 'grind', 'keypair', 'wallet', 'solana', 'evm', 'ethereum', 'base', 'polygon', 'address', 'prefix', 'suffix'] },
+ { path: '/dashboard/billing', label: 'Billing & Passes', icon: 'receipt', group: 'Account', tags: ['billing', 'premium', 'pass', 'subscription', 'payments', 'invoices', 'paid services', 'renew', 'api keys'] },
{ path: '/dashboard/settings', label: 'Settings', icon: 'settings', group: 'Account', tags: ['sessions', 'notifications', 'preferences', 'storage', 'llm usage', 'vanity'] },
{ path: '/onchain', label: 'On-chain (ERC-8004)', icon: 'chain', group: 'Account', tags: ['erc8004', 'registry', 'onchain', 'identity'], external: true },
];
@@ -104,6 +106,7 @@ export const ICONS = {
chart: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M3 17V7l4 3 3-6 4 4 3-3v12H3z"/><path d="M3 17h14"/></svg>',
skills: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="14" height="14" rx="3"/><path d="M7 7h6M7 10h4M7 13h5"/></svg>',
devhub: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="3" width="16" height="12" rx="2"/><path d="M6 7l-2 2.5L6 12M14 7l2 2.5L14 12M9 13l2-8"/></svg>',
+ database: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><ellipse cx="10" cy="4.5" rx="6.5" ry="2.5"/><path d="M3.5 4.5v11c0 1.4 2.9 2.5 6.5 2.5s6.5-1.1 6.5-2.5v-11"/><path d="M3.5 10c0 1.4 2.9 2.5 6.5 2.5s6.5-1.1 6.5-2.5"/></svg>',
landscape: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><circle cx="6" cy="8" r="2"/><circle cx="14" cy="6" r="2"/><circle cx="10" cy="14" r="2"/><path d="M8 8l2 5M12 7l-2 6"/><path d="M3 3h14v14H3z" stroke-dasharray="2 2" opacity="0.3"/></svg>',
oracle: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><circle cx="10" cy="9" r="5.5"/><path d="M6.5 9a3.5 3.5 0 007 0"/><circle cx="10" cy="9" r="1.2" fill="currentColor" stroke="none"/><path d="M10 14.5v2.5M7 16.5h6"/></svg>',
bounty: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><circle cx="10" cy="10" r="7.5"/><path d="M10 6v8M7 8l3-2 3 2M7 12l3 2 3-2"/></svg>',
diff --git a/src/dashboard-next/pages/billing.js b/src/dashboard-next/pages/billing.js
new file mode 100644
index 000000000..9de3eadb8
--- /dev/null
+++ b/src/dashboard-next/pages/billing.js
@@ -0,0 +1,242 @@
+// dashboard-next — Billing & Passes (the user-side money page).
+//
+// One place to see everything you PAY for on three.ws (the mirror of
+// /dashboard/monetize, which is what you EARN): the Premium pass with its
+// on-chain purchase history, the API keys those passes minted, creator
+// subscriptions you hold, and jump-offs to invoices, partner x402 keys, and
+// the full transaction ledger.
+//
+// Data: /api/premium/mine (session-linked passes + keys), /api/subscriptions/mine
+// (creator subscriptions). Both render independently — one failing never
+// blanks the other.
+
+import { mountShell } from '../shell.js';
+import { requireUser, get, esc, relTime } from '../api.js';
+import {
+ skeletonHTML,
+ emptyStateHTML,
+ errorStateHTML,
+ ensureStateKitStyles,
+} from '../../shared/state-kit.js';
+
+const $ = (id) => document.getElementById(id);
+
+function fmtDate(iso) {
+ const d = new Date(iso);
+ return Number.isNaN(d.getTime())
+ ? '—'
+ : d.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' });
+}
+function daysLeft(iso) {
+ return Math.max(0, Math.ceil((new Date(iso).getTime() - Date.now()) / 86_400_000));
+}
+function assetAmount(p) {
+ const decimals = p.asset === 'SOL' ? 9 : 6;
+ const n = Number(p.amount_atomics) / 10 ** decimals;
+ const v = n >= 1000 ? Math.round(n).toLocaleString() : n.toLocaleString(undefined, { maximumSignificantDigits: 4 });
+ return `${v} ${p.asset === 'THREE' ? '$THREE' : p.asset}`;
+}
+const solscan = (sig) => `https://solscan.io/tx/${encodeURIComponent(sig)}`;
+
+// ── Premium section ──────────────────────────────────────────────────────────
+
+function renderPremium(data) {
+ const el = $('bl-premium');
+ if (!data) {
+ el.innerHTML = errorStateHTML({ title: 'Couldn’t load your passes', body: 'The premium endpoint is unreachable — retry in a moment.' });
+ return;
+ }
+ const { active, passes, keys, plan } = data;
+
+ const hero = active
+ ? `
+ <div class="bl-hero bl-hero-active">
+ <div>
+ <div class="bl-kicker">Premium pass</div>
+ <div class="bl-title"><span class="bl-dot"></span> Active — ${daysLeft(active.expires_at)} days left</div>
+ <p class="bl-sub">Wallet <code>${esc(active.wallet.slice(0, 4))}…${esc(active.wallet.slice(-4))}</code> · runs until ${esc(fmtDate(active.expires_at))} · $${Number(plan.usd).toFixed(2)}/${plan.days} days</p>
+ </div>
+ <a class="dn-btn primary" href="/dashboard/data-api">Manage &amp; renew</a>
+ </div>`
+ : `
+ <div class="bl-hero">
+ <div>
+ <div class="bl-kicker">Premium pass</div>
+ <div class="bl-title">No active pass</div>
+ <p class="bl-sub">Premium unlocks unmetered Data-API search and an API key for $${Number(plan.usd).toFixed(2)}/${plan.days} days — payable in $THREE (cheapest), SOL, or USDC on Solana.</p>
+ </div>
+ <a class="dn-btn primary" href="/dashboard/data-api">Go Premium</a>
+ </div>`;
+
+ const history = passes.length
+ ? `
+ <div class="bl-scroll">
+ <table class="bl-table">
+ <thead><tr><th>Purchased</th><th>Paid</th><th class="bl-num">USD</th><th>Period</th><th>Transaction</th></tr></thead>
+ <tbody>
+ ${passes.map((p) => `
+ <tr>
+ <td>${esc(fmtDate(p.created_at))}</td>
+ <td>${esc(assetAmount(p))}</td>
+ <td class="bl-num">$${Number(p.usd_price).toFixed(2)}</td>
+ <td>${esc(fmtDate(p.started_at))} → ${esc(fmtDate(p.expires_at))}</td>
+ <td><a href="${esc(solscan(p.tx_signature))}" target="_blank" rel="noopener">${esc(p.tx_signature.slice(0, 8))}…</a></td>
+ </tr>`).join('')}
+ </tbody>
+ </table>
+ </div>`
+ : `<p class="bl-note">No purchases yet.</p>`;
+
+ const keyRows = keys.length
+ ? `
+ <div class="bl-scroll">
+ <table class="bl-table">
+ <thead><tr><th>Key</th><th>Status</th><th>Wallet</th><th>Expires</th><th class="bl-num">Calls granted</th><th>Last used</th></tr></thead>
+ <tbody>
+ ${keys.map((k) => `
+ <tr>
+ <td><code>${esc(k.key_prefix)}…</code></td>
+ <td>${k.status === 'active' ? '<span class="bl-ok">active</span>' : `<span class="bl-bad">${esc(k.status)}</span>`}</td>
+ <td>${k.wallet ? `<code>${esc(k.wallet.slice(0, 4))}…${esc(k.wallet.slice(-4))}</code>` : '—'}</td>
+ <td>${esc(fmtDate(k.expires_at))}</td>
+ <td class="bl-num">${Number(k.usage.granted).toLocaleString()}</td>
+ <td>${k.usage.last_seen ? esc(relTime(k.usage.last_seen)) : '—'}</td>
+ </tr>`).join('')}
+ </tbody>
+ </table>
+ </div>
+ <p class="bl-note">Rotate or revoke keys on the <a href="/dashboard/data-api">Data API console</a>.</p>`
+ : '';
+
+ el.innerHTML = `
+ ${hero}
+ <section class="dn-panel">
+ <div class="bl-panel-head"><h2>Payment history</h2><span class="bl-tagline">every purchase is one on-chain Solana transaction</span></div>
+ ${history}
+ </section>
+ ${keys.length ? `<section class="dn-panel"><div class="bl-panel-head"><h2>API keys from your passes</h2></div>${keyRows}</section>` : ''}`;
+}
+
+// ── Creator subscriptions ────────────────────────────────────────────────────
+
+function renderSubscriptions(subs) {
+ const el = $('bl-subs');
+ if (subs === null) {
+ // Endpoint failed — say so quietly, don't fake an empty state.
+ el.innerHTML = `
+ <section class="dn-panel">
+ <div class="bl-panel-head"><h2>Creator subscriptions</h2></div>
+ <p class="bl-note">Couldn’t load your creator subscriptions right now — they’re unaffected; retry in a moment.</p>
+ </section>`;
+ return;
+ }
+ const list = Array.isArray(subs) ? subs : subs?.subscriptions || subs?.data || [];
+ if (!list.length) {
+ el.innerHTML = `
+ <section class="dn-panel">
+ <div class="bl-panel-head"><h2>Creator subscriptions</h2></div>
+ ${emptyStateHTML({
+ icon: '💫',
+ title: 'No creator subscriptions',
+ body: 'When you subscribe to a creator or an agent’s skill plan, it shows up here with its renewal date.',
+ actions: [{ label: 'Browse the marketplace', href: '/marketplace' }],
+ })}
+ </section>`;
+ return;
+ }
+ const rows = list.map((s) => `
+ <tr>
+ <td>${esc(s.plan_name || s.name || s.plan_id || 'plan')}</td>
+ <td>${esc(s.creator_handle || s.creator_id || s.agent_id || '—')}</td>
+ <td>${esc(String(s.status || '—'))}</td>
+ <td>${s.current_period_ends_at ? esc(fmtDate(s.current_period_ends_at)) : '—'}</td>
+ <td class="bl-num">${s.price_usd != null ? `$${Number(s.price_usd).toFixed(2)}` : '—'}</td>
+ </tr>`).join('');
+ el.innerHTML = `
+ <section class="dn-panel">
+ <div class="bl-panel-head"><h2>Creator subscriptions</h2></div>
+ <div class="bl-scroll">
+ <table class="bl-table">
+ <thead><tr><th>Plan</th><th>Creator</th><th>Status</th><th>Renews</th><th class="bl-num">Price</th></tr></thead>
+ <tbody>${rows}</tbody>
+ </table>
+ </div>
+ </section>`;
+}
+
+function renderLinks() {
+ $('bl-links').innerHTML = `
+ <section class="dn-panel">
+ <div class="bl-panel-head"><h2>More money surfaces</h2></div>
+ <div class="bl-linkgrid">
+ <a class="bl-link" href="/dashboard/transactions"><strong>Transactions</strong><span>Full ledger of purchases and sales, with CSV export.</span></a>
+ <a class="bl-link" href="/billing"><strong>Invoices</strong><span>Statements and invoice history.</span></a>
+ <a class="bl-link" href="/billing/keys"><strong>Partner x402 keys</strong><span>AWS Marketplace and partner subscription keys.</span></a>
+ <a class="bl-link" href="/dashboard/monetize"><strong>Monetize</strong><span>The other direction — what you earn, payouts, and plans you sell.</span></a>
+ </div>
+ </section>`;
+}
+
+function injectStyles() {
+ if (document.getElementById('bl-styles')) return;
+ ensureStateKitStyles();
+ const s = document.createElement('style');
+ s.id = 'bl-styles';
+ s.textContent = `
+ .bl-root { display: flex; flex-direction: column; gap: 1.25rem; padding-bottom: 3rem; }
+ .bl-hero { display: flex; align-items: center; justify-content: space-between; gap: 1rem; flex-wrap: wrap; background: var(--nxt-glass); border: 1px solid var(--nxt-stroke); border-radius: var(--nxt-radius-sm); padding: 1.2rem 1.4rem; }
+ .bl-hero-active { border-left: 3px solid var(--nxt-success); }
+ .bl-kicker { font-size: .7rem; text-transform: uppercase; letter-spacing: .08em; color: var(--nxt-ink-fade); }
+ .bl-title { font-size: 1.3rem; font-weight: 680; color: var(--nxt-ink); margin: .2rem 0; display: flex; align-items: center; gap: .5rem; }
+ .bl-sub { margin: 0; font-size: .84rem; color: var(--nxt-ink-dim); line-height: 1.5; }
+ .bl-dot { width: 9px; height: 9px; border-radius: 50%; background: var(--nxt-success); box-shadow: 0 0 8px var(--nxt-success); display: inline-block; }
+ .bl-panel-head { display: flex; align-items: baseline; justify-content: space-between; gap: .75rem; flex-wrap: wrap; margin-bottom: .8rem; }
+ .bl-panel-head h2 { margin: 0; font-size: .95rem; font-weight: 650; color: var(--nxt-ink); }
+ .bl-tagline { font-size: .74rem; color: var(--nxt-ink-fade); }
+ .bl-note { margin: .6rem 0 0; font-size: .8rem; color: var(--nxt-ink-dim); }
+ .bl-note a { color: var(--nxt-accent); }
+ .bl-scroll { overflow-x: auto; }
+ .bl-table { width: 100%; border-collapse: collapse; font-size: .82rem; }
+ .bl-table th { text-align: left; font-weight: 600; color: var(--nxt-ink-fade); font-size: .7rem; text-transform: uppercase; letter-spacing: .05em; padding: .35rem .5rem; border-bottom: 1px solid var(--nxt-stroke); white-space: nowrap; }
+ .bl-table td { padding: .45rem .5rem; border-bottom: 1px solid color-mix(in srgb, var(--nxt-stroke) 55%, transparent); color: var(--nxt-ink); }
+ .bl-table a { color: var(--nxt-accent); }
+ .bl-num { text-align: right; font-variant-numeric: tabular-nums; }
+ .bl-ok { color: var(--nxt-success); font-weight: 600; }
+ .bl-bad { color: var(--nxt-danger); font-weight: 600; }
+ .bl-linkgrid { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 220px), 1fr)); gap: .7rem; }
+ .bl-link { display: flex; flex-direction: column; gap: .25rem; border: 1px solid var(--nxt-stroke); border-radius: var(--nxt-radius-sm); padding: .8rem .9rem; text-decoration: none; transition: border-color .15s ease, transform .15s ease; }
+ .bl-link:hover { border-color: var(--nxt-stroke-strong); transform: translateY(-1px); }
+ .bl-link:focus-visible { outline: 2px solid var(--nxt-accent); outline-offset: 2px; }
+ .bl-link strong { color: var(--nxt-ink); font-size: .86rem; }
+ .bl-link span { color: var(--nxt-ink-fade); font-size: .74rem; line-height: 1.4; }
+ `;
+ document.head.appendChild(s);
+}
+
+(async function boot() {
+ const main = await mountShell();
+ await requireUser();
+ injectStyles();
+
+ main.innerHTML = `
+ <div style="margin-bottom:1.5rem">
+ <h1 class="dn-h1" style="margin-bottom:.25rem">Billing &amp; Passes</h1>
+ <p class="dn-h1-sub" style="margin:0">Everything you pay for on three.ws — your Premium pass, on-chain payment history, API keys, and subscriptions.</p>
+ </div>
+ <div class="bl-root">
+ <div id="bl-premium"><div class="dn-panel">${skeletonHTML(3, 'row')}</div></div>
+ <div id="bl-subs"><div class="dn-panel">${skeletonHTML(2, 'row')}</div></div>
+ <div id="bl-links"></div>
+ </div>`;
+
+ renderLinks();
+ const [premium, subs] = await Promise.all([
+ get('/api/premium/mine').catch(() => null),
+ get('/api/subscriptions/mine').catch(() => null),
+ ]);
+ renderPremium(premium);
+ renderSubscriptions(subs);
+})().catch((err) => {
+ const main = document.querySelector('.dn-main-inner') || document.body;
+ main.innerHTML = `<h1 class="dn-h1">Billing &amp; Passes</h1><div class="dn-panel"><div class="dn-panel-title" style="color:var(--nxt-danger)">Failed to load</div><div class="dn-panel-sub">${String(err?.message || 'unknown').replace(/</g, '&lt;')}</div></div>`;
+});
diff --git a/src/dashboard-next/pages/data-api.js b/src/dashboard-next/pages/data-api.js
new file mode 100644
index 000000000..07ee551d0
--- /dev/null
+++ b/src/dashboard-next/pages/data-api.js
@@ -0,0 +1,467 @@
+// dashboard-next — Data API developer console.
+//
+// The premium developer surface: buy/renew the monthly Premium pass on Solana
+// ($THREE at a discount, SOL, or USDC), manage the x402_live_ API key it
+// mints, watch usage, and copy working quickstarts against the news-archive
+// Data API. Purchase is fully on-chain from the visitor's own wallet: quote →
+// sign in Phantom → poll /api/premium/subscribe until the pass lands.
+//
+// Session-authed like every dashboard page (requireUser), and the purchase is
+// additionally wallet-bound — the session link is what enables key
+// rotate/revoke on this page.
+
+import { mountShell } from '../shell.js';
+import { requireUser, get, post, esc } from '../api.js';
+import {
+ skeletonHTML,
+ errorStateHTML,
+ ensureStateKitStyles,
+ attachRetry,
+} from '../../shared/state-kit.js';
+
+const WALLET_LS = 'threews:premium:wallet';
+
+const state = {
+ plans: null,
+ wallet: localStorage.getItem(WALLET_LS) || null,
+ status: null, // /api/premium/status for state.wallet
+ buying: null, // asset symbol while a purchase is in flight
+ freshKey: null, // plaintext shown exactly once after purchase/rotate
+};
+
+const $ = (id) => document.getElementById(id);
+
+function fmtDate(iso) {
+ const d = new Date(iso);
+ return Number.isNaN(d.getTime())
+ ? '—'
+ : d.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' });
+}
+function daysLeft(iso) {
+ return Math.max(0, Math.ceil((new Date(iso).getTime() - Date.now()) / 86_400_000));
+}
+function amountLabel(a) {
+ const n = Number(a.amount_atomics) / 10 ** a.decimals;
+ const rounded = n >= 1000 ? Math.round(n).toLocaleString() : n.toLocaleString(undefined, { maximumSignificantDigits: 4 });
+ return `${rounded} ${a.asset === 'THREE' ? '$THREE' : a.asset}`;
+}
+
+function solanaProvider() {
+ return window.phantom?.solana || window.solana || null;
+}
+
+// ── Purchase flow ────────────────────────────────────────────────────────────
+
+async function connectWallet() {
+ const provider = solanaProvider();
+ if (!provider) {
+ throw new Error('No Solana wallet found — install Phantom (phantom.com) and reload.');
+ }
+ const conn = await provider.connect();
+ const wallet = (conn?.publicKey || provider.publicKey)?.toString();
+ if (!wallet) throw new Error('Wallet did not return a public key.');
+ state.wallet = wallet;
+ localStorage.setItem(WALLET_LS, wallet);
+ return { provider, wallet };
+}
+
+async function pollSubscribe(quoteId, signature) {
+ // Confirmation usually lands in a few seconds; give it 90.
+ for (let i = 0; i < 30; i++) {
+ const out = await post('/api/premium/subscribe', { quote_id: quoteId, tx_signature: signature });
+ if (out?.pass) return out;
+ setBuyNote(`Payment sent — waiting for Solana confirmation… (${i + 1})`);
+ await new Promise((r) => setTimeout(r, 3000));
+ }
+ throw new Error(`Transaction ${signature.slice(0, 8)}… did not confirm in time. Your funds are safe — reopen this page and the pass activates automatically once it lands.`);
+}
+
+function setBuyNote(text, isError = false) {
+ const el = $('da-buy-note');
+ if (!el) return;
+ el.textContent = text || '';
+ el.style.color = isError ? 'var(--nxt-danger)' : 'var(--nxt-ink-dim)';
+}
+
+async function buy(asset) {
+ if (state.buying) return;
+ state.buying = asset;
+ renderPricing();
+ try {
+ setBuyNote('Connecting wallet…');
+ const { provider, wallet } = await connectWallet();
+ setBuyNote('Locking the price and building your payment…');
+ const { quote, tx_base64 } = await post('/api/premium/quote', { asset, wallet });
+ setBuyNote('Confirm the payment in your wallet…');
+ const { VersionedTransaction } = await import('@solana/web3.js');
+ const bytes = Uint8Array.from(atob(tx_base64), (c) => c.charCodeAt(0));
+ const tx = VersionedTransaction.deserialize(bytes);
+ const sent = await provider.signAndSendTransaction(tx);
+ const signature = typeof sent === 'string' ? sent : sent?.signature;
+ if (!signature) throw new Error('Wallet did not return a transaction signature.');
+ const out = await pollSubscribe(quote.id, signature);
+ state.freshKey = out.api_key || null;
+ setBuyNote('');
+ await loadStatus();
+ } catch (err) {
+ if (!/user rejected|cancell?ed/i.test(err?.message || '')) {
+ setBuyNote(err?.message || 'Purchase failed — nothing was charged beyond the on-chain transaction you approved.', true);
+ } else {
+ setBuyNote('');
+ }
+ } finally {
+ state.buying = null;
+ renderPricing();
+ }
+}
+
+// ── Key management ───────────────────────────────────────────────────────────
+
+async function keyAction(action, id) {
+ const verb = action === 'revoke' ? 'Revoke this API key? Anything using it stops working immediately.' : null;
+ if (verb && !window.confirm(verb)) return;
+ try {
+ const out = await post('/api/premium/keys', { action, id });
+ if (out?.api_key) state.freshKey = out.api_key;
+ await loadStatus();
+ } catch (err) {
+ setBuyNote(err?.message === 'key_not_found' || err?.code === 'key_not_found'
+ ? 'This key isn’t linked to your account — keys bought without being signed in are managed via the API only.'
+ : (err?.message || 'Key action failed.'), true);
+ }
+}
+
+// ── Rendering ────────────────────────────────────────────────────────────────
+
+function renderStatusCard() {
+ const el = $('da-status');
+ if (!el) return;
+ if (!state.wallet) {
+ el.innerHTML = `
+ <div class="da-hero">
+ <div>
+ <div class="da-hero-kicker">Premium pass</div>
+ <div class="da-hero-title">Not connected</div>
+ <p class="da-hero-sub">Connect the Solana wallet you'll pay with to see your pass status, or buy below — the pass follows the wallet, the key follows your account.</p>
+ </div>
+ <button class="dn-btn primary" id="da-connect" type="button">Connect wallet</button>
+ </div>`;
+ $('da-connect')?.addEventListener('click', async () => {
+ try { await connectWallet(); await loadStatus(); } catch (e) { setBuyNote(e.message, true); }
+ });
+ return;
+ }
+ const s = state.status;
+ const short = `${state.wallet.slice(0, 4)}…${state.wallet.slice(-4)}`;
+ if (!s) {
+ el.innerHTML = `<div class="da-hero">${skeletonHTML(2, 'row')}</div>`;
+ return;
+ }
+ if (!s.active) {
+ el.innerHTML = `
+ <div class="da-hero">
+ <div>
+ <div class="da-hero-kicker">Premium pass · ${esc(short)}</div>
+ <div class="da-hero-title">No active pass</div>
+ <p class="da-hero-sub">Pick an asset below — one on-chain payment activates 30 days of unmetered archive search plus an API key. Paying in $THREE is the cheapest way in.</p>
+ </div>
+ <button class="dn-btn ghost" id="da-switch" type="button">Switch wallet</button>
+ </div>`;
+ } else {
+ const left = daysLeft(s.pass.expires_at);
+ el.innerHTML = `
+ <div class="da-hero da-hero-active">
+ <div>
+ <div class="da-hero-kicker">Premium pass · ${esc(short)}</div>
+ <div class="da-hero-title"><span class="da-dot"></span> Active — ${left} day${left === 1 ? '' : 's'} left</div>
+ <p class="da-hero-sub">Runs until ${esc(fmtDate(s.pass.expires_at))}. Renewing now appends 30 days to the end — no lost time. Browser searches: choose “sign with wallet” in the payment dialog on <a href="/markets/archive">/markets/archive</a>.</p>
+ </div>
+ <button class="dn-btn ghost" id="da-switch" type="button">Switch wallet</button>
+ </div>`;
+ }
+ $('da-switch')?.addEventListener('click', async () => {
+ localStorage.removeItem(WALLET_LS);
+ state.wallet = null;
+ state.status = null;
+ renderStatusCard();
+ try { await connectWallet(); await loadStatus(); } catch { /* stays disconnected */ }
+ });
+}
+
+function renderPricing() {
+ const el = $('da-pricing');
+ if (!el || !state.plans) return;
+ const { plan, assets } = state.plans;
+ const active = Boolean(state.status?.active);
+ const cards = assets.map((a) => {
+ const highlight = a.asset === 'THREE';
+ const buyLabel = state.buying === a.asset
+ ? 'Processing…'
+ : active ? `Renew with ${a.asset === 'THREE' ? '$THREE' : a.asset}` : `Pay with ${a.asset === 'THREE' ? '$THREE' : a.asset}`;
+ if (!a.available) {
+ return `
+ <div class="da-card" aria-disabled="true">
+ <div class="da-card-asset">${a.asset === 'THREE' ? '$THREE' : esc(a.asset)}</div>
+ <div class="da-card-amount">—</div>
+ <div class="da-card-usd">${esc(a.reason || 'temporarily unavailable')}</div>
+ <button class="dn-btn" type="button" disabled>Unavailable</button>
+ </div>`;
+ }
+ return `
+ <div class="da-card ${highlight ? 'da-card-hot' : ''}">
+ ${highlight ? `<div class="da-card-badge">−${Math.round((a.discount || 0) * 100)}% · platform coin</div>` : ''}
+ <div class="da-card-asset">${a.asset === 'THREE' ? '$THREE' : esc(a.asset)}</div>
+ <div class="da-card-amount">${esc(amountLabel(a))}</div>
+ <div class="da-card-usd">≈ $${Number(a.usd).toFixed(2)} · ${plan.days} days</div>
+ <button class="dn-btn ${highlight ? 'primary' : ''}" type="button" data-buy="${esc(a.asset)}" ${state.buying ? 'disabled' : ''}>${esc(buyLabel)}</button>
+ </div>`;
+ }).join('');
+ el.innerHTML = `
+ <div class="dn-panel">
+ <div class="da-panel-head">
+ <h2>${state.status?.active ? 'Renew' : 'Go Premium'} — $${Number(plan.usd).toFixed(2)}/${plan.days} days</h2>
+ <span class="da-tagline">Solana only · one transaction · no card, no account required to pay</span>
+ </div>
+ <div class="da-cards">${cards}</div>
+ <p class="da-note" id="da-buy-note" role="status" aria-live="polite"></p>
+ </div>`;
+ el.querySelectorAll('[data-buy]').forEach((b) =>
+ b.addEventListener('click', () => buy(b.dataset.buy)),
+ );
+}
+
+function renderFreshKey() {
+ const el = $('da-freshkey');
+ if (!el) return;
+ if (!state.freshKey) { el.innerHTML = ''; return; }
+ el.innerHTML = `
+ <div class="dn-panel da-fresh">
+ <div class="da-panel-head"><h2>Your API key — copy it now</h2></div>
+ <p class="da-note">This is the only time the full key is shown. It is already active.</p>
+ <div class="da-keyrow">
+ <code class="da-keycode" id="da-key-plain">${esc(state.freshKey)}</code>
+ <button class="dn-btn primary" id="da-key-copy" type="button">Copy</button>
+ </div>
+ </div>`;
+ $('da-key-copy')?.addEventListener('click', async () => {
+ await navigator.clipboard.writeText(state.freshKey).catch(() => {});
+ $('da-key-copy').textContent = 'Copied ✓';
+ setTimeout(() => { const b = $('da-key-copy'); if (b) b.textContent = 'Copy'; }, 1500);
+ });
+}
+
+function renderKeys() {
+ const el = $('da-keys');
+ if (!el) return;
+ const keys = state.status?.keys || [];
+ if (!state.wallet || !keys.length) {
+ el.innerHTML = `
+ <div class="dn-panel">
+ <div class="da-panel-head"><h2>API key</h2></div>
+ <p class="da-note">No key yet — buying a pass mints one automatically (<code>x402_live_…</code>). It bypasses the per-call x402 charge on every premium endpoint via the <code>X-API-Key</code> header.</p>
+ </div>`;
+ return;
+ }
+ const rows = keys.map((k) => `
+ <tr>
+ <td><code>${esc(k.key_prefix)}…</code></td>
+ <td>${k.status === 'active' ? '<span class="da-ok">active</span>' : `<span class="da-bad">${esc(k.status)}</span>`}</td>
+ <td class="da-num">${k.rate_limit_per_minute}/min</td>
+ <td>${esc(fmtDate(k.expires_at))}</td>
+ <td class="da-num">${Number(k.usage.granted).toLocaleString()}</td>
+ <td class="da-num">${Number(k.usage.denied).toLocaleString()}</td>
+ <td>${k.usage.last_seen ? esc(fmtDate(k.usage.last_seen)) : '—'}</td>
+ <td class="da-actions">
+ <button class="dn-btn ghost" type="button" data-rotate="${esc(k.id)}">Rotate</button>
+ <button class="dn-btn danger" type="button" data-revoke="${esc(k.id)}">Revoke</button>
+ </td>
+ </tr>`).join('');
+ el.innerHTML = `
+ <div class="dn-panel">
+ <div class="da-panel-head"><h2>API key</h2><span class="da-tagline">usage from the access log — granted vs denied calls</span></div>
+ <div class="da-scroll">
+ <table class="da-table">
+ <thead><tr><th>Key</th><th>Status</th><th class="da-num">Rate limit</th><th>Expires</th><th class="da-num">Granted</th><th class="da-num">Denied</th><th>Last used</th><th></th></tr></thead>
+ <tbody>${rows}</tbody>
+ </table>
+ </div>
+ </div>`;
+ el.querySelectorAll('[data-rotate]').forEach((b) => b.addEventListener('click', () => keyAction('rotate', b.dataset.rotate)));
+ el.querySelectorAll('[data-revoke]').forEach((b) => b.addEventListener('click', () => keyAction('revoke', b.dataset.revoke)));
+}
+
+function renderQuickstart() {
+ const el = $('da-quickstart');
+ if (!el) return;
+ const key = state.status?.keys?.[0]?.key_prefix ? `${state.status.keys[0].key_prefix}…` : 'x402_live_YOUR_KEY';
+ const snippets = {
+ curl: `curl "https://three.ws/api/news/archive?q=bitcoin+etf&start_date=2024-01-01&end_date=2024-03-31&limit=50" \\
+ -H "X-API-Key: ${key}"`,
+ javascript: `const res = await fetch(
+ 'https://three.ws/api/news/archive?' + new URLSearchParams({
+ ticker: 'BTC', sentiment: 'negative', start_date: '2022-11-01', end_date: '2022-11-30',
+ }),
+ { headers: { 'X-API-Key': '${key}' } },
+);
+const { articles, scanned } = await res.json();`,
+ mcp: `// claude_desktop_config.json / .mcp.json — crypto_news_archive tool
+{
+ "mcpServers": {
+ "three-ws": { "command": "npx", "args": ["-y", "@three-ws/mcp-server"] }
+ }
+}`,
+ };
+ const tabs = Object.keys(snippets).map((t) =>
+ `<button class="da-tab" type="button" data-tab="${t}" aria-pressed="${t === 'curl'}">${t === 'javascript' ? 'JavaScript' : t.toUpperCase()}</button>`,
+ ).join('');
+ el.innerHTML = `
+ <div class="dn-panel">
+ <div class="da-panel-head"><h2>Quickstart</h2><span class="da-tagline">works the moment your pass is active</span></div>
+ <div class="da-tabs" role="tablist">${tabs}</div>
+ <pre class="da-code" id="da-snippet"><code>${esc(snippets.curl)}</code></pre>
+ <button class="dn-btn ghost" id="da-snippet-copy" type="button">Copy snippet</button>
+ </div>`;
+ let current = 'curl';
+ el.querySelectorAll('.da-tab').forEach((b) =>
+ b.addEventListener('click', () => {
+ current = b.dataset.tab;
+ el.querySelectorAll('.da-tab').forEach((x) => x.setAttribute('aria-pressed', String(x === b)));
+ $('da-snippet').innerHTML = `<code>${esc(snippets[current])}</code>`;
+ }),
+ );
+ $('da-snippet-copy')?.addEventListener('click', async () => {
+ await navigator.clipboard.writeText(snippets[current]).catch(() => {});
+ $('da-snippet-copy').textContent = 'Copied ✓';
+ setTimeout(() => { const b = $('da-snippet-copy'); if (b) b.textContent = 'Copy snippet'; }, 1500);
+ });
+}
+
+function renderCatalog() {
+ const el = $('da-catalog');
+ if (!el) return;
+ const rows = [
+ ['GET /api/news/archive', 'Search 660k+ articles back to 2017 — keyword, ticker, source, date, sentiment, language', 'Premium · 60/day free · $0.001/search'],
+ ['GET /api/news/archive?stats=true', 'Corpus statistics + month range', 'Free'],
+ ['GET /api/news/archive?trending=true', 'Most-covered tickers of the newest archive weeks', 'Free'],
+ ['GET /api/news/feed', 'Live headlines from 192 publisher feeds', 'Free'],
+ ['GET /api/news/digest', 'Last 1–72 h clustered into narratives with stance + tickers', 'Free'],
+ ].map(([ep, what, access]) => `
+ <tr><td><code>${esc(ep)}</code></td><td>${esc(what)}</td><td>${esc(access)}</td></tr>`).join('');
+ el.innerHTML = `
+ <div class="dn-panel">
+ <div class="da-panel-head"><h2>Endpoints</h2><a class="da-tagline" href="/docs/api-reference">full API reference →</a></div>
+ <div class="da-scroll">
+ <table class="da-table">
+ <thead><tr><th>Endpoint</th><th>What it does</th><th>Access</th></tr></thead>
+ <tbody>${rows}</tbody>
+ </table>
+ </div>
+ </div>`;
+}
+
+function renderAll() {
+ renderStatusCard();
+ renderPricing();
+ renderFreshKey();
+ renderKeys();
+ renderQuickstart();
+ renderCatalog();
+}
+
+// ── Data ─────────────────────────────────────────────────────────────────────
+
+async function loadStatus() {
+ if (!state.wallet) { renderAll(); return; }
+ try {
+ state.status = await get(`/api/premium/status?wallet=${encodeURIComponent(state.wallet)}`);
+ } catch {
+ state.status = null;
+ }
+ renderAll();
+}
+
+function injectStyles() {
+ if (document.getElementById('da-styles')) return;
+ ensureStateKitStyles();
+ const s = document.createElement('style');
+ s.id = 'da-styles';
+ s.textContent = `
+ .da-root { display: flex; flex-direction: column; gap: 1.25rem; padding-bottom: 3rem; }
+ .da-hero { display: flex; align-items: center; justify-content: space-between; gap: 1rem; flex-wrap: wrap; background: var(--nxt-glass); border: 1px solid var(--nxt-stroke); border-radius: var(--nxt-radius-sm); padding: 1.2rem 1.4rem; }
+ .da-hero-active { border-left: 3px solid var(--nxt-success); }
+ .da-hero-kicker { font-size: .7rem; text-transform: uppercase; letter-spacing: .08em; color: var(--nxt-ink-fade); }
+ .da-hero-title { font-size: 1.35rem; font-weight: 680; color: var(--nxt-ink); margin: .2rem 0; display: flex; align-items: center; gap: .5rem; }
+ .da-hero-sub { margin: 0; font-size: .85rem; color: var(--nxt-ink-dim); line-height: 1.55; max-width: 60ch; }
+ .da-hero-sub a { color: var(--nxt-accent); }
+ .da-dot { width: 9px; height: 9px; border-radius: 50%; background: var(--nxt-success); box-shadow: 0 0 8px var(--nxt-success); display: inline-block; }
+ .da-panel-head { display: flex; align-items: baseline; justify-content: space-between; gap: .75rem; flex-wrap: wrap; margin-bottom: .9rem; }
+ .da-panel-head h2 { margin: 0; font-size: .95rem; font-weight: 650; color: var(--nxt-ink); }
+ .da-tagline { font-size: .74rem; color: var(--nxt-ink-fade); }
+ .da-cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 200px), 1fr)); gap: .9rem; }
+ .da-card { position: relative; border: 1px solid var(--nxt-stroke); border-radius: var(--nxt-radius-sm); padding: 1.1rem 1rem .9rem; display: flex; flex-direction: column; gap: .3rem; transition: border-color .15s ease, transform .15s ease; }
+ .da-card:hover { border-color: var(--nxt-stroke-strong); transform: translateY(-1px); }
+ .da-card[aria-disabled="true"] { opacity: .55; }
+ .da-card-hot { border-color: color-mix(in srgb, var(--nxt-accent) 55%, transparent); background: color-mix(in srgb, var(--nxt-accent) 6%, transparent); }
+ .da-card-badge { position: absolute; top: -.6rem; left: .8rem; font-size: .62rem; font-weight: 700; text-transform: uppercase; letter-spacing: .05em; color: var(--nxt-accent); background: var(--nxt-bg-0); border: 1px solid color-mix(in srgb, var(--nxt-accent) 55%, transparent); padding: .12rem .5rem; border-radius: var(--nxt-radius-pill); }
+ .da-card-asset { font-size: .78rem; color: var(--nxt-ink-dim); font-weight: 600; }
+ .da-card-amount { font-size: 1.3rem; font-weight: 700; color: var(--nxt-ink); letter-spacing: -.01em; }
+ .da-card-usd { font-size: .74rem; color: var(--nxt-ink-fade); margin-bottom: .55rem; }
+ .da-note { margin: .8rem 0 0; font-size: .8rem; color: var(--nxt-ink-dim); line-height: 1.5; min-height: 1em; }
+ .da-fresh { border-color: color-mix(in srgb, var(--nxt-success) 50%, transparent); }
+ .da-keyrow { display: flex; gap: .6rem; align-items: center; flex-wrap: wrap; margin-top: .6rem; }
+ .da-keycode { font-family: var(--nxt-mono, ui-monospace, monospace); font-size: .82rem; background: color-mix(in srgb, var(--nxt-ink) 7%, transparent); padding: .5rem .7rem; border-radius: 6px; word-break: break-all; user-select: all; }
+ .da-scroll { overflow-x: auto; }
+ .da-table { width: 100%; border-collapse: collapse; font-size: .82rem; }
+ .da-table th { text-align: left; font-weight: 600; color: var(--nxt-ink-fade); font-size: .7rem; text-transform: uppercase; letter-spacing: .05em; padding: .35rem .5rem; border-bottom: 1px solid var(--nxt-stroke); white-space: nowrap; }
+ .da-table td { padding: .45rem .5rem; border-bottom: 1px solid color-mix(in srgb, var(--nxt-stroke) 55%, transparent); color: var(--nxt-ink); vertical-align: middle; }
+ .da-num { text-align: right; font-variant-numeric: tabular-nums; }
+ .da-ok { color: var(--nxt-success); font-weight: 600; }
+ .da-bad { color: var(--nxt-danger); font-weight: 600; }
+ .da-actions { white-space: nowrap; display: flex; gap: .4rem; }
+ .da-tabs { display: flex; gap: .4rem; margin-bottom: .6rem; }
+ .da-tab { background: none; border: 1px solid var(--nxt-stroke); color: var(--nxt-ink-dim); border-radius: var(--nxt-radius-pill); font-size: .74rem; padding: .3rem .8rem; cursor: pointer; transition: all .12s ease; }
+ .da-tab[aria-pressed="true"] { color: var(--nxt-ink); border-color: var(--nxt-stroke-strong); background: color-mix(in srgb, var(--nxt-ink) 6%, transparent); }
+ .da-tab:focus-visible, .da-card button:focus-visible { outline: 2px solid var(--nxt-accent); outline-offset: 2px; }
+ .da-code { background: color-mix(in srgb, var(--nxt-ink) 6%, transparent); border: 1px solid var(--nxt-stroke); border-radius: var(--nxt-radius-sm); padding: .9rem 1rem; overflow-x: auto; font-size: .78rem; line-height: 1.55; margin: 0 0 .7rem; }
+ .da-code code { font-family: var(--nxt-mono, ui-monospace, monospace); white-space: pre; }
+ `;
+ document.head.appendChild(s);
+}
+
+(async function boot() {
+ const main = await mountShell();
+ await requireUser();
+ injectStyles();
+
+ main.innerHTML = `
+ <div style="margin-bottom:1.5rem">
+ <h1 class="dn-h1" style="margin-bottom:.25rem">Data API</h1>
+ <p class="dn-h1-sub" style="margin:0">The 660k-article crypto-news archive as a developer product — one monthly pass, paid on Solana in $THREE, SOL, or USDC, instead of a payment per call.</p>
+ </div>
+ <div class="da-root" id="da-root">
+ <div id="da-status"></div>
+ <div id="da-freshkey"></div>
+ <div id="da-pricing">${`<div class="dn-panel">${skeletonHTML(3, 'row')}</div>`}</div>
+ <div id="da-keys"></div>
+ <div id="da-quickstart"></div>
+ <div id="da-catalog"></div>
+ </div>`;
+
+ attachRetry($('da-root'), () => boot2());
+ async function boot2() {
+ try {
+ state.plans = await get('/api/premium/plans');
+ } catch (err) {
+ $('da-pricing').innerHTML = errorStateHTML({
+ title: 'Couldn’t load pricing',
+ body: esc(err?.message || 'The pricing endpoint is unreachable — retry in a moment.'),
+ });
+ return;
+ }
+ await loadStatus();
+ }
+ await boot2();
+})().catch((err) => {
+ const main = document.querySelector('.dn-main-inner') || document.body;
+ main.innerHTML = `<h1 class="dn-h1">Data API</h1><div class="dn-panel"><div class="dn-panel-title" style="color:var(--nxt-danger)">Failed to load</div><div class="dn-panel-sub">${String(err?.message || 'unknown').replace(/</g, '&lt;')}</div></div>`;
+});
diff --git a/src/news-archive.js b/src/news-archive.js
index a4de93adf..fffe56948 100644
--- a/src/news-archive.js
+++ b/src/news-archive.js
@@ -197,9 +197,11 @@ function renderPaywall({ append, challenge }) {
el.innerHTML = `
<div class="cv-empty">
<p><strong>Today’s free archive searches are used up.</strong></p>
- <p>Free searches reset daily. Keep digging now for ${esc(price)} USDC per search, paid straight from your wallet via x402 — or come back tomorrow.</p>
- <p><button class="arc-btn" type="button" id="arc-pay">Pay ${esc(price)} &amp; search</button></p>
- <p class="arc-coverage" style="margin:0">Corpus stats, months, and trending tickers stay free — only deep search is metered.</p>
+ <p>Free searches reset daily. Keep digging now for ${esc(price)} USDC per search (each payment unlocks a 15-minute session), or go
+ <a href="/dashboard/data-api"><strong>Premium</strong></a> — a monthly pass paid in $THREE, SOL, or USDC with unmetered search and an API key.</p>
+ <p><button class="arc-btn" type="button" id="arc-pay">Pay ${esc(price)} &amp; search</button>
+ <a class="arc-btn" href="/dashboard/data-api" style="text-decoration:none">Get Premium</a></p>
+ <p class="arc-coverage" style="margin:0">Corpus stats, months, and trending tickers stay free — only deep search is metered. Premium members: the payment dialog offers “sign with wallet” instead of paying.</p>
</div>`;
$('arc-coverage').textContent = '';
document.getElementById('arc-pay')?.addEventListener('click', async () => {
diff --git a/tests/mcp-tool-result.test.js b/tests/mcp-tool-result.test.js
index 5f1ffba0d..f28804218 100644
--- a/tests/mcp-tool-result.test.js
+++ b/tests/mcp-tool-result.test.js
@@ -72,7 +72,9 @@ describe('buildToolResult — MCP CallToolResult envelope', () => {
describe('MCP tool surface', () => {
// Tools the platform offers at zero cost — exempt from the paid-price
// assertion below, and asserted to advertise their free-ness instead.
- const FREE_TOOLS = new Set(['forge_free']);
+ // (crypto_news_archive is freemium: its description quotes the over-quota
+ // $ price, so it stays under the paid assertion.)
+ const FREE_TOOLS = new Set(['forge_free', 'crypto_news', 'crypto_news_digest']);
it('builds every tool descriptor with a complete, unique contract', async () => {
const tools = await buildTools();
diff --git a/tests/news-archive-api.test.js b/tests/news-archive-api.test.js
index 239c0d5a6..1038a8ba9 100644
--- a/tests/news-archive-api.test.js
+++ b/tests/news-archive-api.test.js
@@ -282,6 +282,16 @@ describe('freemium x402 gate (query mode)', () => {
expect(body.articles[0].tickers).toContain('JTO');
});
+ it('the paid rail declares SIWX so premium-pass wallets re-enter by signature', async () => {
+ limits.newsArchiveFreeIp.mockResolvedValueOnce({ success: false, remaining: 0 });
+ await call('/api/news/archive?limit=10');
+ expect(x402Mock.spec.siwx).toBeTruthy();
+ expect(x402Mock.spec.siwx.statement).toContain('premium');
+ // per-call payments earn a bounded session, never a permanent grant
+ expect(x402Mock.spec.siwx.ttlSeconds).toBeGreaterThan(0);
+ expect(x402Mock.spec.siwx.ttlSeconds).toBeLessThanOrEqual(3600);
+ });
+
it('the paid rail rejects bad input with a clean 400-shaped throw', async () => {
limits.newsArchiveFreeIp.mockResolvedValueOnce({ success: false, remaining: 0 });
await call('/api/news/archive?limit=10');
diff --git a/tests/premium-pass.test.js b/tests/premium-pass.test.js
new file mode 100644
index 000000000..e8698ab14
--- /dev/null
+++ b/tests/premium-pass.test.js
@@ -0,0 +1,261 @@
+// Coverage for api/_lib/premium.js — the monthly premium pass.
+//
+// Guards the money paths:
+// - USD → asset conversion for all three assets ($THREE discount included),
+// - quote creation builds a deserializable unsigned Solana transaction,
+// - on-chain verification (balance-delta, signer check, SOL + SPL lanes,
+// failed/pending transactions),
+// - activation: period append on renewal, key mint vs extend, SIWX grants,
+// and idempotency when the same tx is claimed twice.
+//
+// DB, oracles, RPC, key mint, and SIWX storage are mocked; @solana/web3.js and
+// @solana/spl-token run for real so the built transaction is genuine.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { Keypair, VersionedTransaction } from '@solana/web3.js';
+
+const TREASURY = 'wwwwwDxFWRn7grgr3Esrsg5C6NvDoDHSA4gaCffccrU';
+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+const USDC_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+const BUYER = Keypair.generate().publicKey.toBase58();
+
+const db = vi.hoisted(() => ({ handlers: [], calls: [] }));
+const rpcMock = vi.hoisted(() => ({ getParsedTransaction: null }));
+const siwxCalls = vi.hoisted(() => []);
+const keyMints = vi.hoisted(() => []);
+
+vi.mock('../api/_lib/db.js', () => ({
+ sql: async (strings, ...values) => {
+ const text = strings.join(' $ ').replace(/\s+/g, ' ');
+ db.calls.push({ text, values });
+ for (const h of db.handlers) {
+ if (h.match.test(text)) return h.result(values, text);
+ }
+ return [];
+ },
+}));
+vi.mock('../api/_lib/env.js', () => ({
+ env: {
+ X402_PAY_TO_SOLANA: 'wwwwwDxFWRn7grgr3Esrsg5C6NvDoDHSA4gaCffccrU',
+ X402_ASSET_MINT_SOLANA: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ THREE_TOKEN_MINT: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',
+ THREE_TOKEN_DECIMALS: 6,
+ },
+}));
+vi.mock('../api/_lib/sol-price.js', () => ({ solPriceUsd: async () => 150 }));
+vi.mock('../api/_lib/token/price.js', () => ({
+ getTokenPriceUsd: async () => ({ priceUsd: 0.002, source: 'test-oracle' }),
+}));
+vi.mock('../api/_lib/x402/api-keys.js', () => ({
+ createSubscription: async (opts) => {
+ keyMints.push(opts);
+ return { id: `sub_${keyMints.length}`, key_prefix: 'x402_live_TESTKE', token: 'x402_live_TESTKEY_PLAINTEXT' };
+ },
+ revokeSubscription: async () => ({}),
+}));
+vi.mock('../api/_lib/siwx-storage.js', () => ({
+ siwxStorage: { recordPayment: async (...args) => { siwxCalls.push(args); } },
+}));
+vi.mock('../api/_lib/solana/connection.js', () => ({
+ solanaConnection: () => ({
+ getLatestBlockhash: async () => ({ blockhash: '9sHcv6xwn9YkB8nxTUGKDwPwNnmqVp5oAXxU8Fdkm4J6' }),
+ }),
+}));
+vi.mock('../api/_lib/solana/rpc-fallback.js', () => ({
+ rpcFallbackFromEnv: () => ({ withFallback: (fn) => fn(rpcMock) }),
+}));
+
+const premium = await import('../api/_lib/premium.js');
+
+beforeEach(() => {
+ db.handlers.length = 0;
+ db.calls.length = 0;
+ siwxCalls.length = 0;
+ keyMints.length = 0;
+ rpcMock.getParsedTransaction = null;
+ delete process.env.PREMIUM_PASS_USD;
+ delete process.env.PREMIUM_PASS_THREE_DISCOUNT;
+});
+
+// ── Pricing ──────────────────────────────────────────────────────────────────
+
+describe('priceAsset', () => {
+ it('USDC is parity: $9.99 → 9990000 atomics', async () => {
+ const p = await premium.priceAsset('USDC');
+ expect(p.atomics).toBe(9_990_000n);
+ expect(p.priceSource).toBe('parity');
+ });
+
+ it('SOL converts at the oracle price', async () => {
+ const p = await premium.priceAsset('SOL');
+ expect(p.atomics).toBe(BigInt(Math.ceil((9.99 / 150) * 1e9)));
+ expect(p.assetUsd).toBe(150);
+ });
+
+ it('$THREE gets the discount: $9.99 −20% at $0.002 → 3,995 THREE', async () => {
+ const p = await premium.priceAsset('THREE');
+ // 9.99 * 0.8 = 7.992 → rounded to 7.99 USD, / 0.002 = 3995 THREE
+ expect(p.usd).toBe(7.99);
+ expect(p.atomics).toBe(BigInt(Math.ceil((7.99 / 0.002) * 1e6)));
+ });
+
+ it('rejects unknown assets and malformed wallets', async () => {
+ await expect(premium.priceAsset('DOGE')).rejects.toMatchObject({ code: 'bad_asset' });
+ expect(() => premium.assertWallet('not-a-wallet')).toThrow();
+ });
+});
+
+// ── Quote ────────────────────────────────────────────────────────────────────
+
+describe('createQuote', () => {
+ it('persists the locked quote and returns a deserializable unsigned tx', async () => {
+ db.handlers.push({
+ match: /insert into premium_quotes/,
+ result: (values) => [{
+ id: 'q-1', wallet: BUYER, plan: 'premium', asset: 'THREE',
+ amount_atomics: values[3], usd_price: values[4], expires_at: 'soon',
+ }],
+ });
+ const { quote, tx_base64 } = await premium.createQuote({ wallet: BUYER, asset: 'THREE' });
+ expect(quote.id).toBe('q-1');
+ const tx = VersionedTransaction.deserialize(Buffer.from(tx_base64, 'base64'));
+ // buyer is the fee payer; ATA-idempotent + transferChecked instructions
+ expect(tx.message.staticAccountKeys[0].toBase58()).toBe(BUYER);
+ expect(tx.message.compiledInstructions.length).toBe(2);
+ });
+
+ it('native SOL quote is a single SystemProgram transfer', async () => {
+ db.handlers.push({
+ match: /insert into premium_quotes/,
+ result: () => [{ id: 'q-sol', wallet: BUYER, asset: 'SOL', amount_atomics: '66600000', usd_price: 9.99, expires_at: 'soon' }],
+ });
+ const { tx_base64 } = await premium.createQuote({ wallet: BUYER, asset: 'SOL' });
+ const tx = VersionedTransaction.deserialize(Buffer.from(tx_base64, 'base64'));
+ expect(tx.message.compiledInstructions.length).toBe(1);
+ });
+});
+
+// ── Verification ─────────────────────────────────────────────────────────────
+
+function parsedSplTx({ delta = 1000n, signer = BUYER, err = null, mint = THREE_MINT, owner = TREASURY } = {}) {
+ return {
+ meta: {
+ err,
+ preTokenBalances: [{ mint, owner, uiTokenAmount: { amount: '5000' } }],
+ postTokenBalances: [{ mint, owner, uiTokenAmount: { amount: String(5000n + delta) } }],
+ },
+ transaction: { message: { accountKeys: [{ pubkey: signer, signer: true }, { pubkey: TREASURY, signer: false }] } },
+ };
+}
+
+describe('verifyPassPayment', () => {
+ const quote = { wallet: BUYER, asset: 'THREE', amount_atomics: '1000' };
+
+ it('accepts a landed SPL transfer that covers the quote', async () => {
+ rpcMock.getParsedTransaction = async () => parsedSplTx({ delta: 1000n });
+ expect(await premium.verifyPassPayment(quote, 'sig')).toEqual({ ok: true });
+ });
+
+ it('rejects when the treasury delta is short', async () => {
+ rpcMock.getParsedTransaction = async () => parsedSplTx({ delta: 999n });
+ const v = await premium.verifyPassPayment(quote, 'sig');
+ expect(v.ok).toBe(false);
+ expect(v.reason).toContain('need 1000');
+ });
+
+ it('rejects when the quoted wallet did not sign (someone else’s tx)', async () => {
+ rpcMock.getParsedTransaction = async () => parsedSplTx({ signer: Keypair.generate().publicKey.toBase58() });
+ const v = await premium.verifyPassPayment(quote, 'sig');
+ expect(v.ok).toBe(false);
+ expect(v.reason).toContain('did not sign');
+ });
+
+ it('reports pending (not failure) while the tx is unconfirmed', async () => {
+ rpcMock.getParsedTransaction = async () => null;
+ const v = await premium.verifyPassPayment(quote, 'sig');
+ expect(v.ok).toBe(false);
+ expect(v.pending).toBe(true);
+ });
+
+ it('rejects a reverted transaction', async () => {
+ rpcMock.getParsedTransaction = async () => parsedSplTx({ err: { InstructionError: [0, 'Custom'] } });
+ const v = await premium.verifyPassPayment(quote, 'sig');
+ expect(v.ok).toBe(false);
+ });
+
+ it('verifies native SOL by lamport delta to the treasury', async () => {
+ rpcMock.getParsedTransaction = async () => ({
+ meta: { err: null, preBalances: [500, 100], postBalances: [400, 200] },
+ transaction: { message: { accountKeys: [{ pubkey: BUYER, signer: true }, { pubkey: TREASURY, signer: false }] } },
+ });
+ const solQuote = { wallet: BUYER, asset: 'SOL', amount_atomics: '100' };
+ expect(await premium.verifyPassPayment(solQuote, 'sig')).toEqual({ ok: true });
+ const short = await premium.verifyPassPayment({ ...solQuote, amount_atomics: '101' }, 'sig');
+ expect(short.ok).toBe(false);
+ });
+});
+
+// ── Activation ───────────────────────────────────────────────────────────────
+
+const QUOTE = {
+ id: 'q-1', wallet: BUYER, plan: 'premium', asset: 'THREE',
+ amount_atomics: '3995000000', usd_price: 7.99, user_id: null,
+};
+
+describe('activatePass', () => {
+ it('first purchase: claims the quote, mints a key, inserts the pass, records SIWX grants', async () => {
+ db.handlers.push(
+ { match: /update premium_quotes/, result: () => [{ id: 'q-1' }] },
+ { match: /select \* from premium_passes where wallet/, result: () => [] },
+ { match: /insert into premium_passes/, result: (v) => [{ id: 'pass-1', wallet: BUYER, expires_at: v[10] }] },
+ );
+ const out = await premium.activatePass({ quote: QUOTE, txSignature: 'sig-1' });
+ expect(out.pass.id).toBe('pass-1');
+ expect(out.apiKey).toBe('x402_live_TESTKEY_PLAINTEXT');
+ expect(out.renewed).toBe(false);
+ expect(keyMints[0].meta).toMatchObject({ source: 'premium-pass', wallet: BUYER });
+ // one SIWX grant per premium resource, TTL ≈ 30 days
+ expect(siwxCalls.length).toBe(premium.PREMIUM_RESOURCES.length);
+ const [resource, address, opts] = siwxCalls[0];
+ expect(premium.PREMIUM_RESOURCES).toContain(resource);
+ expect(address).toBe(BUYER);
+ expect(opts.ttlSeconds).toBeGreaterThan(29 * 86400);
+ });
+
+ it('renewal: appends the period at the previous expiry and extends the existing key', async () => {
+ const prevExpiry = new Date(Date.now() + 5 * 86400_000).toISOString();
+ db.handlers.push(
+ { match: /update premium_quotes/, result: () => [{ id: 'q-1' }] },
+ { match: /select \* from premium_passes where wallet/, result: () => [{ id: 'pass-0', wallet: BUYER, expires_at: prevExpiry, api_subscription_id: 'sub_prev' }] },
+ { match: /update x402_subscriptions/, result: () => [{ id: 'sub_prev' }] },
+ { match: /insert into premium_passes/, result: (v) => [{ id: 'pass-2', started_at: v[9], expires_at: v[10] }] },
+ );
+ const out = await premium.activatePass({ quote: QUOTE, txSignature: 'sig-2' });
+ expect(out.renewed).toBe(true);
+ expect(out.apiKey).toBeNull(); // existing key extended, no new plaintext
+ expect(keyMints.length).toBe(0);
+ // the new period starts where the old one ended — no lost days
+ expect(new Date(out.pass.started_at).toISOString()).toBe(prevExpiry);
+ expect(new Date(out.pass.expires_at).getTime()).toBe(new Date(prevExpiry).getTime() + 30 * 86400_000);
+ });
+
+ it('same tx claimed twice returns the already-issued pass, never a second key', async () => {
+ db.handlers.push(
+ { match: /update premium_quotes/, result: () => [] }, // claim lost
+ { match: /select \* from premium_passes where tx_signature/, result: () => [{ id: 'pass-1', wallet: BUYER }] },
+ );
+ const out = await premium.activatePass({ quote: QUOTE, txSignature: 'sig-1' });
+ expect(out.pass.id).toBe('pass-1');
+ expect(out.apiKey).toBeNull();
+ expect(keyMints.length).toBe(0);
+ });
+
+ it('a claimed quote with no matching pass is a hard conflict', async () => {
+ db.handlers.push(
+ { match: /update premium_quotes/, result: () => [] },
+ { match: /select \* from premium_passes where tx_signature/, result: () => [] },
+ );
+ await expect(premium.activatePass({ quote: QUOTE, txSignature: 'sig-x' }))
+ .rejects.toMatchObject({ code: 'quote_used' });
+ });
+});
diff --git a/vercel.json b/vercel.json
index 1745edb8f..4299ba2f4 100644
--- a/vercel.json
+++ b/vercel.json
@@ -1833,6 +1833,14 @@
"src": "/dashboard/developers/?",
"dest": "/dashboard-next/developers.html"
},
+ {
+ "src": "/dashboard/data-api/?",
+ "dest": "/dashboard-next/data-api.html"
+ },
+ {
+ "src": "/dashboard/billing/?",
+ "dest": "/dashboard-next/billing.html"
+ },
{
"src": "/dashboard/three-token/?",
"dest": "/dashboard-next/three-token.html"
diff --git a/vite.config.js b/vite.config.js
index ff38b7891..36fa43c7d 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -1527,7 +1527,10 @@ support: resolve(__dirname, 'pages/support.html'),
// /dashboard/<tab> and /dashboard/edit/<id> → pages/dashboard-next/index.html (new SPA)
else if (
!filePath &&
- /^\/dashboard\/(?:agents|avatars|create|upload|animations|widgets|embed|keys|mcp|monetization|payments|subscriptions|billing|revenue|withdrawals|earnings|account)\/?$/.test(
+ // `billing` left out on purpose: /dashboard/billing is a real
+ // dashboard-next page (pages/dashboard-next/billing.html), not a
+ // legacy SPA tab.
+ /^\/dashboard\/(?:agents|avatars|create|upload|animations|widgets|embed|keys|mcp|monetization|payments|subscriptions|revenue|withdrawals|earnings|account)\/?$/.test(
path,
)
)