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.

chore: pick up in-flight platform work across docs, examples, marketplace, and animation surfaces

nirholasc57cf74fa446
diff --git a/ISSUES.md b/ISSUES.md
index fe7f02ca2..ba7200a53 100644
--- a/ISSUES.md
+++ b/ISSUES.md
@@ -172,23 +172,14 @@ here; the code-quality items from that pass are not production issues.
whose Draco writer calls an encoder interface `[email protected]` does not
expose. Every other `optimize` parameter returns a real GLB in production.
Action: rebuild, and confirm the build installs from the lockfile rather
- than resolving fresh. Two smaller defects on the same endpoint: it stalls
- instead of returning `413` on an oversized `glbUrl`, and avatar
- `13f259c7-…` has zero morph targets so `expression` is a silent no-op on it.
-10. **An empty POST to `/api/agents/:id/autopilot` spends real money.**
- `autopilot.js` treats a missing `dry_run` as `false` (`body?.dry_run === true`)
- and runs a real cycle, while the adjacent intents endpoint on the same wallet
- treats a missing `dry_run` as `true` and simulates. Same verb, same wallet,
- opposite default. Action: make the money-moving default the safe one.
-11. **The public marketplace GMV on `/pulse` counts confirmed trials.** In
- `handleMarketplace()` the `purchases` count filters on `status='confirmed'
- AND kind = ANY(MARKET_PAID_KINDS)`, but `gmv_atomic` and `fee_atomic` filter
- on `status='confirmed'` alone, so a confirmed `trial` row with a non-zero
- amount inflates published GMV and skews `avg_ticket_three` (a GMV over a
- count that excluded it). Same asymmetry in `series_7d`, and `trials` has no
- status filter at all while every sibling field is confirmed-only. This is a
- number on a public transparency page.
-12. **Live R2 CORS does not match `scripts/set-r2-cors.mjs`** (operator action:
+ than resolving fresh. One smaller defect remains on the same endpoint:
+ avatar `13f259c7-…` has zero morph targets, so `expression` is a silent
+ no-op on it. (The oversized-`glbUrl` stall listed here is fixed: the 50 MB
+ cap is now counted while streaming and aborts the transfer, so a chunked
+ source with no `content-length` returns `413` instead of being buffered in
+ full, and an unresponsive source times out as `504` rather than holding the
+ request open. Covered by `tests/avatar-optimize-source-cap.test.js`.)
+10. **Live R2 CORS does not match `scripts/set-r2-cors.mjs`** (operator action:
run the script). The script sets `AllowedOrigins: ['*']` for GET/HEAD, but
the live policy still echoes only the old allowlist, so a third-party origin
gets no `access-control-allow-origin`. Re-running it removes the need for the
diff --git a/STRUCTURE.md b/STRUCTURE.md
index 3622d1916..53e4269d2 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -41,6 +41,7 @@ bottom.
| Platform activity feed | [pages/feed.html](pages/feed.html) `→ /feed` + [pages/community.html](pages/community.html) `→ /community`, backend [api/users/me/feed.js](api/users/me/feed.js) | Live | Reverse-chronological creation events (avatars, agents, coins, models, worlds) plus follow activity, merged at read time from `forge_creations`, `dioramas`, and `user_follows` (no separate event log to drift out of sync). `?scope=following` (default; session-gated, anonymous gets 401) vs `?scope=all` (public; powers `/community` and first-visit feeds); `limit` 1..50, `before` ISO cursor. Items deep-link to creator portfolios. Distinct from the Money Pulse ticker `GET /api/feed` ([docs/money-feed.md](docs/money-feed.md)). Docs: [docs/social-layer.md](docs/social-layer.md) |
| Follow graph | [api/users/[username]/follow.js](api/users/%5Busername%5D/follow.js) + [api/users/[username]/follows.js](api/users/%5Busername%5D/follows.js), table `user_follows`, buttons on [pages/profile.html](pages/profile.html) | Live | `GET` returns `{following, followed_by, followers_count, following_count}`; `POST`/`DELETE` are idempotent (session + CSRF, self-follow 400) and return the same envelope so one round-trip updates the button and the counts. A genuinely new edge (`ON CONFLICT DO NOTHING`) publishes a `follow` user event to the notification bell exactly once. Feeds the activity feed's following scope, search ranking, and the `followers` leaderboard metric. Tests: [tests/api/users-follow.test.js](tests/api/users-follow.test.js). Docs: [docs/social-layer.md](docs/social-layer.md) |
| Notification bell & preferences | Event vocabulary [api/_lib/feed.js](api/_lib/feed.js) (`USER_EVENT_TYPES` → `publishUserEvent()` → `user_notifications`), endpoints [api/notifications/](api/notifications), preference matrix [api/_lib/notify-prefs.js](api/_lib/notify-prefs.js), bell client [src/notifications.js](src/notifications.js), settings panel [src/dashboard-next/pages/settings.js](src/dashboard-next/pages/settings.js) | Live | In-app inbox covering remixes ([api/x402/remix-asset.js](api/x402/remix-asset.js)), DMs ([api/friends/messages.js](api/friends/messages.js)), coin bonding-curve graduations (pump cron in [api/cron/[name].js](api/cron/%5Bname%5D.js)), follows, sales, purchases, IRL, market, and account events. Preferences are a category × channel matrix (`in_app` always on; push/email/telegram are per-category opt-outs) edited from `/dashboard/settings`. Docs: [docs/social-layer.md](docs/social-layer.md) |
+| Marketplace analytics & trial funnel | [pages/marketplace-analytics.html](pages/marketplace-analytics.html) `→ /marketplace/analytics`, renderer [src/marketplace-analytics.js](src/marketplace-analytics.js), backend [api/marketplace/analytics.js](api/marketplace/analytics.js) | Live | Public transparency page for the skill marketplace: paid sales, volume, top skills/agents, and the trial conversion funnel. **Every money aggregate gates on `status = 'confirmed'` alone.** Counting `status IN ('confirmed','trial')` as a sale published 10,454 "sales" and 6.2M $THREE of "volume" on 2026-07-30 against a table holding zero confirmed purchases, because a `trial` row is a free grant whose `amount` is only the list price it would have cost. Free trials now render as their own stat and as a four-stage funnel (granted → used → exhausted → converted), which also names the two shapes that mean a wiring fault rather than weak demand: trials never spent, or trials exhausted with nothing converting. Docs: [docs/marketplace.md](docs/marketplace.md), tutorial [docs/tutorials/sell-a-skill-with-a-trial.md](docs/tutorials/sell-a-skill-with-a-trial.md). Tests: [tests/marketplace-analytics-paid-only.test.js](tests/marketplace-analytics-paid-only.test.js) |
| OKX.AI marketplace services | [api/okx/3d/[service].js](api/okx/3d/%5Bservice%5D.js) `→ /api/okx/3d/*` | Live | 3D services sold to other agents on OKX.AI (agent #2632): Agent Identity Studio flagship + decomposed studio services. Catalog source of truth: [api/_lib/okx-catalog.js](api/_lib/okx-catalog.js); pipeline: [api/_okx3d/](api/_okx3d); showcase: [pages/agent-identities.html](pages/agent-identities.html) `→ /agent-identities`; docs: [docs/okx-marketplace.md](docs/okx-marketplace.md) |
| Crypto Data API docs / landing | [pages/crypto.html](pages/crypto.html) `→ /crypto` | In-repo · docs surface | Screenshot-worthy public docs + funnel-top for the free, keyless Crypto Data API (`/api/crypto/*` — token snapshot, security, holders, launches, bonding, whales, symbol, wallet, trending). Renders hero, endpoint table, tabbed quickstart (curl/JS/Python), per-endpoint request/response reference and a live "Try it" console. Probes production at runtime and marks each endpoint Live vs Coming soon (degrades gracefully while sibling endpoints roll out). CTAs funnel to paid uniques: [/launcher](pages/launcher.html), [/vanity-wallet](public/vanity-wallet.html), [/forge](pages/forge.html). Spec: x402-overhaul campaign (retired 2026-07-28; readable in git history) |
| Free Crypto Data API + discovery | [api/crypto/index.js](api/crypto/index.js) `→ /api/crypto`, [api/crypto/openapi.js](api/crypto/openapi.js) `→ /api/crypto/openapi.json`, docs [docs/crypto-api.md](docs/crypto-api.md) `→ /docs/crypto-api` | Live · docs surface | Front door + OpenAPI 3.1 for the free, keyless Crypto Data API. Catalog assembler [api/_lib/crypto-catalog/index.js](api/_lib/crypto-catalog/index.js) merges `api/_lib/crypto-catalog/*.js` self-describing descriptors (currently `bonding`, `holders`, `launches`, `security`, `symbol`, `token`, `trending`, `wallet`, `whales`) via a static import barrel — the production source of truth, since Vercel's bundler only ships what static imports reach — plus an additive dev-time directory glob; skips malformed/throwing entries, never throws, valid-empty when zero. New descriptor = drop the file AND add its import line to the barrel. OpenAPI built from the same catalog via [api/_lib/crypto-catalog/openapi.js](api/_lib/crypto-catalog/openapi.js). Index does HTML/JSON content negotiation. Endpoint handlers live in `api/crypto/*.js`. Spec: x402-overhaul campaign (retired 2026-07-28; readable in git history) |
@@ -131,6 +132,7 @@ bottom.
| Self-hosted x402 facilitator + ring economy | [api/x402-facilitator/[action].js](api/x402-facilitator/[action].js), [api/_lib/x402/self-facilitator.js](api/_lib/x402/self-facilitator.js), [api/x402/ring-settle.js](api/x402/ring-settle.js), [api/_lib/x402/pipelines/ring-rebalance.js](api/_lib/x402/pipelines/ring-rebalance.js), [api/x402-ring.js](api/x402-ring.js), [scripts/x402-ring-setup.mjs](scripts/x402-ring-setup.mjs) | In-repo (off by default) | Closed-loop agent-to-agent x402: platform wallets pay platform endpoints, settled in-house (no external facilitator). Fee-minimized, SOL-floor guarded, internal-labeled. Env: `X402_SELF_FACILITATOR_ENABLED`, `X402_FEE_PAYER_SECRET_BASE58`, `X402_TREASURY_SECRET_BASE58`. See [docs/x402-ring-economy.md](docs/x402-ring-economy.md) |
| Ring payer pool (many distinct payers) | [api/_lib/x402/pool.js](api/_lib/x402/pool.js), [api/_lib/x402/pipelines/ring-pool-fund.js](api/_lib/x402/pipelines/ring-pool-fund.js), [scripts/x402-ring-pool-setup.mjs](scripts/x402-ring-pool-setup.mjs), migration [api/_lib/migrations/2026-07-17-x402-ring-pool.sql](api/_lib/migrations/2026-07-17-x402-ring-pool.sql) | In-repo (off by default) | Reused rotating payer wallets (500–1,000) the ring tick cycles through so the closed loop shows many distinct, attributed payers at 1 tx/settle. Keys secret-box-encrypted in `x402_ring_pool`; pubkeys mirrored into `x402_ring_wallets(role='pool')` so they join the controlled set automatically; NOT in solana-signers.js so sweepback never touches them. LRU rotation (`claimNextPayer`), batched threshold funding (`ring-pool-fund`). Env: `X402_RING_POOL_ENABLED`, `X402_RING_POOL_SIZE`. See [docs/x402-ring-economy.md](docs/x402-ring-economy.md#payer-pool--many-distinct-payers-one-reused-set-of-wallets) |
| $THREE micro-buy loop (x402 buy pressure) | Endpoint [api/x402/three-buy.js](api/x402/three-buy.js) `→ /api/x402/three-buy`, driver [api/cron/three-buy-loop.js](api/cron/three-buy-loop.js), engine [api/_lib/token/microbuy.js](api/_lib/token/microbuy.js), shared Jupiter client [api/_lib/token/jupiter.js](api/_lib/token/jupiter.js), ledger [migration 20260717233000_three_microbuy.sql](api/_lib/migrations/20260717233000_three_microbuy.sql) | In-repo (off by default) | Many tiny, real USDC→$THREE market buys per minute (target ~60/min), each triggered by (and paid through) a settled x402 call: the x402 toll routes to the ring treasury like every other endpoint, and the paid good is one on-chain buy on Jupiter. BUY-ONLY — never sells; accrued $THREE swept to the treasury. High-frequency sibling of the daily buyback ([api/_lib/token/buyback.js](api/_lib/token/buyback.js)). Real spend hard-bounded by a UTC-daily USD ceiling enforced atomically (Redis reserve-before-buy). `autobuy:false` in [ring-catalog.js](api/_lib/x402/ring-catalog.js) so the generic ring never fires it. Env: `THREE_MICROBUY_ENABLED`, `THREE_MICROBUY_SECRET_KEY_B64` (or reuses the buyback wallet), `THREE_MICROBUY_PER_TICK`, `THREE_MICROBUY_DAILY_CAP_USD`. See [docs/three-microbuy.md](docs/three-microbuy.md). |
+| Economy health operator dashboard | [pages/admin/economy.html](pages/admin/economy.html) `→ /admin/economy`, pure verdict logic [src/admin-economy-core.js](src/admin-economy-core.js), DOM layer [src/admin-economy.js](src/admin-economy.js), styles [src/admin-economy.css](src/admin-economy.css) | In-repo (admin, noindex) | Answers "is the Money Pulse quiet, and which link in the funding chain broke" in one line. Composes three live reads ([/api/pulse?view=stats](api/pulse.js), [/api/admin/circulation-health](api/admin/circulation-health.js), [/api/cron/treasury-topup?dry=1](api/cron/treasury-topup.js)) into a ranked verdict, the funding chain from the economy master through each under-floor engine to the USDC refuel reserve with per-link floors, 24h per-lane settle rates that distinguish `never ran` (the governor never planned it: a funding fault) from `all failing` (planned and rejected: not), and the capped USDC-to-SOL refuel history. Read-only by construction: the treasury sweep is called in plan-only mode, so opening the page cannot move funds. Rule ORDER is the product (a stale tick outranks a broken fuel lane; an unreadable USDC balance outranks the budget verdict, because `usdc_read_failed` means unknown-not-zero and must never be answered by sending money). Docs: [docs/economy-health-dashboard.md](docs/economy-health-dashboard.md). Tests: [tests/admin-economy-core.test.js](tests/admin-economy-core.test.js) |
| Ring economy operator dashboard | [pages/admin/ring.html](pages/admin/ring.html) + [src/admin-ring.js](src/admin-ring.js) `→ /admin/ring`, backend [api/admin/ring-dashboard.js](api/admin/ring-dashboard.js) | In-repo (admin, noindex) | Live eyes on the closed-loop x402 ring: per-minute settlement pulse (green/amber/red heartbeat), loop diagram with live wallet balances + floors, streaming activity feed (agent attribution, Solscan links, skip/fail reasons), fee-burn vs daily budget, integrity (leak scan + reconciliation), per-endpoint coverage. One aggregate read model composes [/api/x402-ring](api/x402-ring.js); admin/Bearer-secret authed. Labels volume as internal dogfooding. See [docs/x402-ring-economy.md](docs/x402-ring-economy.md#watching-it--the-operator-dashboard) |
| Economy funding root (master wallet) | [api/_lib/economy-master.js](api/_lib/economy-master.js), cron [api/cron/treasury-topup.js](api/cron/treasury-topup.js), registry [api/_lib/solana-signers.js](api/_lib/solana-signers.js) | In-repo (inert until keyed) | One master wallet (`WwwuGbq…T3WwW`, `ECONOMY_MASTER_SECRET_BASE58`) auto-tops-up every other Solana engine below its floor. Funder-only — never trades/settles; reserve/per-engine/per-run guarded; allowlisted to registry wallets; fee-minimized. See [docs/economy-master.md](docs/economy-master.md) + the signer registry [api/_lib/solana-signers.js](api/_lib/solana-signers.js) |
| Economy master audit ledger + breach monitor | ledger [api/_lib/economy-ledger.js](api/_lib/economy-ledger.js) ([schema](api/_lib/migrations/20260702010000_economy_master_ledger.sql)), reconcile cron [api/cron/economy-reconcile.js](api/cron/economy-reconcile.js), export [scripts/economy-ledger-export.mjs](scripts/economy-ledger-export.mjs) | In-repo | Tamper-evident (SHA-256 hash-chained) accounting book of every SOL movement from the master, with running balance + USD-at-transfer-time. The reconcile cron checks it every 30 min for tamper, unrecorded on-chain outbound (breach/key-compromise), and on-chain integrity; findings land in `payment_reconciliation`. Accounting CSV/JSON export. See [docs/economy-master.md](docs/economy-master.md#audit-accounting--breach-monitoring) |
diff --git a/api/marketplace/purchase-bundle.js b/api/marketplace/purchase-bundle.js
index fdd8b9992..1576db97d 100644
--- a/api/marketplace/purchase-bundle.js
+++ b/api/marketplace/purchase-bundle.js
@@ -187,14 +187,36 @@ async function handleConfirm(req, res, purchaseId) {
if (claimed.length === 0)
return error(res, 409, 'already_processed', 'purchase is no longer pending');
- // Unlock every skill in the bundle — one row per skill.
+ // Unlock every skill in the bundle — one row per skill. hasSkillAccess() reads
+ // skill_purchases, so this row IS the unlock.
+ //
+ // Three column choices are load-bearing, and getting any of them wrong silently
+ // costs the buyer what they paid for:
+ // reference — NOT NULL and UNIQUE, so it is derived per skill. Omitting it
+ // made this insert throw 23502 for every bundle ever sold.
+ // tx_signature — UNIQUE, so it CANNOT be repeated across the bundle's skills:
+ // the second row would collide and ON CONFLICT DO NOTHING would
+ // swallow it, unlocking only the first skill. The settlement tx
+ // is recorded once on the bundle_purchases row above, which is
+ // where it belongs; these rows point back via `reference`.
+ // amount/kind — 0 and 'bundle'. The bundle's revenue is already counted once
+ // on bundle_purchases, so these access records stay out of the
+ // marketplace GMV and purchase counts on /pulse, which filter
+ // to paid kinds. Pricing them per skill would double-count the
+ // sale and report one bundle as N purchases.
+ //
+ // ON CONFLICT DO NOTHING remains correct: it now only absorbs the partial unique
+ // index on an already-owned skill, which is the buyer keeping access they have.
const skills = purchase.skills;
for (const skillName of skills) {
await sql`
INSERT INTO skill_purchases
- (user_id, agent_id, skill, status, confirmed_at, tx_signature)
+ (user_id, agent_id, skill, status, kind, reference, amount,
+ currency_mint, chain, confirmed_at)
VALUES
- (${auth.userId}, ${purchase.agent_id}, ${skillName}, 'confirmed', now(), ${txSignature})
+ (${auth.userId}, ${purchase.agent_id}, ${skillName}, 'confirmed', 'bundle',
+ ${`bundle_${purchaseId}_${skillName}`}, 0,
+ ${purchase.currency_mint}, ${purchase.chain}, now())
ON CONFLICT DO NOTHING
`;
}
diff --git a/data/changelog.json b/data/changelog.json
index de9ed9af8..40ba8d9cf 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,25 @@
{
"$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-30",
+ "title": "Marketplace analytics no longer counts free trials as sales",
+ "summary": "The public marketplace analytics page was reporting more than ten thousand skill sales and millions of $THREE in volume when the marketplace had never completed a single paid sale. Every one of those was a free trial: the page counted a trial the same as a purchase, and summed the price the trial would have cost as though it had been paid. Sales, volume, revenue and buyer counts now count paid purchases only. Free trials are still shown, as their own figure and as a conversion funnel from trials granted through to trials that turned into a sale, so you can see how the marketplace is really doing instead of a number that flattered it.",
+ "tags": [
+ "fix",
+ "improvement"
+ ],
+ "link": "/marketplace/analytics"
+ },
+ {
+ "date": "2026-07-30",
+ "title": "New tutorial: sell a skill with a free trial that converts",
+ "summary": "A step-by-step walkthrough of listing an agent skill for sale, attaching a metered free trial, and having that trial expire into a real on-chain purchase. It covers how to pick a trial length for different kinds of skills, and the one missing step that quietly makes a trialled skill impossible to ever sell.",
+ "tags": [
+ "docs"
+ ],
+ "link": "/tutorials/sell-a-skill-with-a-trial"
+ },
{
"date": "2026-07-30",
"title": "Your agent's treasury now has a preview button, and a bare request can no longer spend",
@@ -17246,6 +17265,16 @@
"docs"
],
"link": "/docs/authentication"
+ },
+ {
+ "date": "2026-07-30",
+ "title": "Agents can now actually buy from the marketplace, and operators get an Economy Health dashboard",
+ "summary": "When one agent bought a skill or asset from another it first had to acquire $THREE, and it always bought the same tiny fixed amount no matter what the listing cost. Almost every listing was priced above what that bought, so purchases failed, retried on the next tick, and paid a real trading fee every time, which is why marketplace sales sat at zero. The purchase now prices the listing first, buys exactly what it needs, and declines up front (spending nothing) when a listing is beyond what the engine can fund that minute. Alongside it, a new operator dashboard reads the live economy and states in one line whether money is flowing and, if not, which link in the funding chain broke.",
+ "tags": [
+ "fix",
+ "feature",
+ "infra"
+ ]
}
]
}
diff --git a/data/examples.json b/data/examples.json
index 50c51e361..c1d7da48a 100644
--- a/data/examples.json
+++ b/data/examples.json
@@ -2,10 +2,10 @@
"$comment": "Generated by scripts/build-examples-index.mjs from what is on disk. Do not edit by hand; run npm run build:examples.",
"generated_by": "scripts/build-examples-index.mjs",
"counts": {
- "total": 37,
+ "total": 39,
"html_demos": 10,
- "projects": 9,
- "packages": 18
+ "projects": 10,
+ "packages": 19
},
"examples": [
{
@@ -132,6 +132,36 @@
"runKind": "command",
"readme": "examples/three-concierge/README.md"
},
+ {
+ "id": "project:wallet-sign-in",
+ "kind": "project",
+ "group": "Example projects",
+ "title": "wallet-sign-in",
+ "description": "",
+ "path": "examples/wallet-sign-in",
+ "files": [
+ "index.html"
+ ],
+ "run": "npm run dev, then open /examples/wallet-sign-in/index.html",
+ "runKind": "command",
+ "readme": null
+ },
+ {
+ "id": "package:packages/agentcore-payments-mcp",
+ "kind": "package",
+ "group": "Package examples",
+ "title": "@three-ws/agentcore-payments-mcp",
+ "description": "Two runnable examples. Neither one spends money, needs a wallet, or needs an account, so you can run both before deciding whether to fund anything.",
+ "path": "packages/agentcore-payments-mcp/examples",
+ "files": [
+ "list-tools.mjs",
+ "plan-a-session.mjs"
+ ],
+ "run": "node packages/agentcore-payments-mcp/examples/list-tools.mjs",
+ "runKind": "command",
+ "readme": "packages/agentcore-payments-mcp/examples/README.md",
+ "owner": "packages/agentcore-payments-mcp"
+ },
{
"id": "package:assistant-sdk",
"kind": "package",
diff --git a/data/pages.json b/data/pages.json
index 9ce69aec8..d6d5ceeac 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -1954,6 +1954,14 @@
"description": "The wallet surface for your agents: balances, funding, and activity.",
"priority": 0.6,
"changefreq": "weekly"
+ },
+ {
+ "path": "/trading",
+ "title": "Autonomous Trading",
+ "description": "The control room for three.ws autonomous trading: live fleet vitals, the agent scoreboard, the entry-to-exit pipeline, and every trading surface and doc in one place.",
+ "priority": 0.9,
+ "changefreq": "hourly",
+ "added": "2026-07-30"
}
]
},
@@ -2145,7 +2153,7 @@
},
{
"path": "/docs/trading-hub",
- "title": "Docs \u00b7 The trading hub",
+ "title": "Docs · The trading hub",
"description": "The front door to the autonomous trading system: live fleet vitals read off the running bots, the strategy arena and experiments board, and the smart-money radar, with the twenty pages behind them organised into one path.",
"priority": 0.6,
"changefreq": "weekly",
@@ -3986,6 +3994,14 @@
"priority": 0.8,
"changefreq": "weekly",
"added": "2026-07-30"
+ },
+ {
+ "path": "/docs/trading-experiment",
+ "title": "Docs · The 10 SOL trading experiment",
+ "description": "The full risk policy behind the autonomous fleet: entry band, position sizing, taking initials at 2x, the moon-bag floor, trailing and hard stops, and how to read the decision journal.",
+ "priority": 0.6,
+ "changefreq": "monthly",
+ "added": "2026-07-30"
}
]
},
diff --git a/docs/authentication.md b/docs/authentication.md
index 40bb058de..e8cae8c9c 100644
--- a/docs/authentication.md
+++ b/docs/authentication.md
@@ -343,7 +343,14 @@ if (res.ok) {
}
```
-A `401` response means no valid session exists.
+There are two distinct signed-out shapes, and a client that checks only one of them will get it wrong:
+
+| Situation | Status | Body |
+|---|---|---|
+| No session cookie at all | `200` | `{"user":null}` |
+| Cookie present but expired or revoked | `401` | `{"error":"invalid_session"}` |
+
+So treat "signed out" as `!response.ok || !body.user`, not as `response.status === 401`.
### Logging out
diff --git a/docs/circulation-engine.md b/docs/circulation-engine.md
index 522cc4c70..985a59dee 100644
--- a/docs/circulation-engine.md
+++ b/docs/circulation-engine.md
@@ -124,9 +124,33 @@ its own sake.
| `ASSET_PRICE_MIN/MAX_THREE` | 600 / 4000 $THREE |
| `AGENT_FLOOR` (top-up target) | 0.02 SOL |
| `LAUNCH_FLOOR` | 0.034 SOL |
-| `THREE_TOPUP_SOL` (buy $THREE when short) | 0.012 SOL |
+| `THREE_TOPUP_SOL` (smallest $THREE buy, and the quote probe) | 0.012 SOL |
+| `THREE_TOPUP_MAX_SOL` (hard ceiling on one $THREE buy) | 0.06 SOL |
| `FEE_BUFFER` (per-tx headroom) | 0.0009 SOL |
+### Buying $THREE for a marketplace purchase
+
+A buyer that is short on $THREE acquires it through the real trade engine before
+paying. The buy is **sized to the shortfall**, not fixed: `ensureThree()` quotes
+`THREE_TOPUP_SOL` worth of $THREE, derives the live rate, and buys what the
+listing actually costs plus 8% headroom for curve movement and fees.
+
+Two bounds apply, and the smaller wins:
+
+- `THREE_TOPUP_MAX_SOL`, the absolute ceiling on a single buy, and
+- this tick's share of the treasury (`spendableSol / paidBudget`), so an action
+ that sizes its own spend cannot quietly overspend the budget the governor
+ planned from and starve the actions queued behind it.
+
+If the shortfall costs more than that, the action is **skipped before any SOL
+moves**, naming the SOL it would have needed. This matters: the engine used to
+buy a flat 0.012 SOL of $THREE regardless of price. At roughly 100 $THREE per
+0.012 SOL, and with skills listed at 80-1200 $THREE and assets at 600-4000, most
+of the marketplace was unbuyable. Every attempt still paid a real trade fee,
+skipped with `still short on $THREE after top-up buy`, and repeated next tick, so
+marketplace GMV read zero while the fees went out. Sizing math is pure and
+covered by [tests/circulation-three-topup.test.js](../tests/circulation-three-topup.test.js).
+
## Cadence
The engine runs from the `pulse-tick` cron
@@ -202,6 +226,8 @@ budget, so raise gradually and watch tick runtime and treasury balance.
## Related
+- [Economy Health dashboard](economy-health-dashboard.md) — the operator page
+ that diagnoses this engine when the pulse goes quiet.
- [Money feed](money-feed.md) — where circulation activity surfaces.
- [Autonomous x402 loop](autonomous-x402.md) — the separate treasury-paid loop
that buys polling intel from our own x402 endpoints.
diff --git a/docs/economy-health-dashboard.md b/docs/economy-health-dashboard.md
new file mode 100644
index 000000000..f6fa7b89e
--- /dev/null
+++ b/docs/economy-health-dashboard.md
@@ -0,0 +1,142 @@
+# Economy Health dashboard
+
+**`/admin/economy`** answers one question fast: *is the Money Pulse quiet, and if
+so, which link in the funding chain broke?*
+
+It exists because answering that by hand took hours. On 2026-07-30 the public
+pulse read **$5.89 of volume in 24h** while every "is it alive" signal was green:
+the activity feed was busy, the cron was ticking, thousands of actions were
+recorded. The engine had quietly been reduced to its **free** actions. Reviews
+and skill trials kept running; tips, payments, trades and launches sat at exactly
+zero. This page makes that state obvious in one line instead of five endpoint
+reads.
+
+Admin-authed and `noindex`. It is **read-only by construction**: the treasury
+sweep is called in plan-only mode, so opening the page can never move funds.
+
+---
+
+## Getting in
+
+Visit `/admin/economy` and enter `CRON_SECRET` at the gate. It is held in
+`sessionStorage` for the tab and never written to disk or a URL. A rejected
+secret clears it and returns you to the gate.
+
+```
+https://three.ws/admin/economy
+```
+
+Keyboard: <kbd>r</kbd> refreshes, <kbd>p</kbd> pauses polling. The page
+auto-refreshes every 30s and stops polling entirely in a hidden tab, so an ops
+page left open all day does not keep hitting RPC-backed reads for nobody.
+
+---
+
+## What it reads
+
+Three live reads, no mocks and no synthetic numbers:
+
+| Source | Auth | Gives you |
+|---|---|---|
+| `GET /api/pulse?view=stats` | public | Volume, trades, tips, active wallets (24h) |
+| `GET /api/admin/circulation-health` | `Bearer CRON_SECRET` | Per-lane ok / skipped / error, pool, liveness, refuel history |
+| `GET /api/cron/treasury-topup?dry=1` | `Bearer CRON_SECRET` | Funding chain balances, floors, deficit, refuel decision |
+
+The `?dry=1` on the last one is load-bearing. It performs the same balance reads
+a live sweep would, then returns the plan: no SOL moves, no ledger row, no
+alerts.
+
+Each source fails independently. One dead endpoint degrades its own panel and
+says so; it never blanks the page.
+
+---
+
+## Reading the verdict
+
+The banner applies the diagnosis rules to live data and names the single most
+actionable cause. The **order** of those rules is the point, because several
+faults look identical from outside and have opposite fixes.
+
+| Verdict | Means | What to do |
+|---|---|---|
+| **Economy healthy** | Paid lanes settling, chain above floors | Nothing |
+| **Circulation engine is switched off** | `CIRCULATION_ENABLED` unset | Nothing is broken; set it if you want movement |
+| **No circulation action for N min** | The tick stopped | Check Cloud Scheduler before trusting anything else |
+| **Refuel blocked: USDC balance unreadable** | An RPC lane failed the balance read | Fix the lane. **Do not send funds** |
+| **Paid lanes never ran in 24h** | Governor cut the paid budget | The circulation treasury is under its reserve |
+| **Every paid action failed** | Planned but rejected | Read the lane's last problem |
+| **Funding chain is genuinely dry** | Real deficit, no USDC left | The one case that needs the owner to send SOL |
+| **Self-heal in progress** | Deficit being closed automatically | Nothing |
+
+The two that matter most are the ones that look the same and are not:
+
+- `no_spare_usdc` means the revenue really is spent. Send funds.
+- `usdc_read_failed` means the balance is **unknown, not zero**. An RPC lane
+ broke. Sending funds treats the wrong problem.
+
+That distinction is why the refuel-read rule outranks the budget rule: an
+unreadable balance makes the treasury look unfundable while the money to fund it
+is sitting right there in the wallet.
+
+---
+
+## The panels
+
+**Money Pulse (24h)** is real settled movement. Free actions are deliberately
+excluded, because they stay green through exactly the outage this page catches.
+
+**Funding chain** walks the money from root to spender: the economy master, then
+every engine below its refill target, then the USDC refuel reserve. Each link
+shows its balance against **its own floor**, with a meter so a starved link is
+visible without arithmetic.
+
+> One wallet can serve several roles. If the roles disagree on the floor, the
+> strictest one is what matters. A wallet at 0.012 SOL is healthy against a 0.01
+> floor and starved against a 0.2 floor, and it was exactly that disagreement
+> that hid the July flatline.
+
+**Circulation engine** shows pool size and tick cadence. A healthy action count
+here with zero paid lanes below is the signature of a treasury under reserve.
+
+**Action lanes (24h)** is the per-kind settle rate, and the state pill encodes
+the distinction that matters:
+
+- `never ran` means zero *attempts*. The governor never planned it. **Funding problem.**
+- `all failing` means it was planned and rejected. **Not a funding problem**; read the last problem column.
+- `degraded` means it settles but throws errors.
+
+**USDC refuel lane** shows the capped conversion of revenue into SOL, today's
+spend against the daily cap, and recent swaps with Solscan links.
+
+**If the pulse is quiet** is the runbook, in the order that rules out causes
+which would make every later reading meaningless.
+
+---
+
+## Extending it
+
+All judgement lives in [`src/admin-economy-core.js`](../src/admin-economy-core.js),
+which is pure: no DOM, no fetch, no globals. `src/admin-economy.js` only fetches
+and renders. Add a rule by editing `diagnose()` and covering it in
+[`tests/admin-economy-core.test.js`](../tests/admin-economy-core.test.js).
+
+Keep the ordering discipline. A new rule goes **above** any rule it would
+invalidate; the tests assert that ordering, e.g. that a stale tick outranks a
+broken fuel lane and that an unreadable balance outranks the budget verdict.
+
+```js
+import { diagnose } from '../src/admin-economy-core.js';
+
+diagnose({ stats, health, topup });
+// → { level: 'bad', title: 'Paid lanes never ran in 24h', detail: '…' }
+```
+
+---
+
+## Related
+
+- [Circulation engine](circulation-engine.md) — the engine this page watches.
+- [Economy master](economy-master.md) — the funding root at the top of the chain.
+- [Money feed](money-feed.md) — the public surface the volume comes from.
+- [Ring dashboard](x402-ring-economy.md#watching-it--the-operator-dashboard) —
+ the sibling operator page for the x402 ring.
diff --git a/docs/examples.md b/docs/examples.md
index fd8544983..405aaa53c 100644
--- a/docs/examples.md
+++ b/docs/examples.md
@@ -735,7 +735,7 @@ genuinely invested in the user's progress.
## Every runnable example in the repo
-The repo ships 37 examples: 10 web component demos, 9 end-to-end projects, and 18 package example sets. This table is generated from what is on disk, so it cannot list one that was deleted or miss one that was added. The machine-readable version is [data/examples.json](../data/examples.json).
+The repo ships 39 examples: 10 web component demos, 10 end-to-end projects, and 19 package example sets. This table is generated from what is on disk, so it cannot list one that was deleted or miss one that was added. The machine-readable version is [data/examples.json](../data/examples.json).
### Example projects
@@ -750,11 +750,13 @@ The repo ships 37 examples: 10 web component demos, 9 end-to-end projects, and 1
| [`examples/paid-mcp-server`](../examples/paid-mcp-server) | A complete, runnable MCP server whose tools charge per call in USDC on Solana over x402. It ships two tools on purpose: | `cd examples/paid-mcp-server && npm install && npm run start` |
| [`examples/pump-fun-agent`](../examples/pump-fun-agent) | An example agent manifest that composes all four production pump.fun skills into one 3D trading agent: swap, coin creation, creator-fee collection, and token payments. | Reference files, nothing to execute |
| [`examples/three-concierge`](../examples/three-concierge) | The reference agent for manifest spec agent-manifest/0.2. Trinity welcomes users to three.ws, explains the platform, and launches and trades $three on pump.fun through the real pump.fun skills in pump-fun-skills/. | Reference files, nothing to execute |
+| [`examples/wallet-sign-in`](../examples/wallet-sign-in) | See the directory for details. | `npm run dev, then open /examples/wallet-sign-in/index.html` |
### Package examples
| Example | What it shows | Run it |
|---|---|---|
+| [`packages/agentcore-payments-mcp/examples`](../packages/agentcore-payments-mcp/examples) | MCP server for three.ws Agent Payment Sessions - govern agent x402 spending without exposing private keys. | `node packages/agentcore-payments-mcp/examples/list-tools.mjs` |
| [`assistant-sdk/examples`](../assistant-sdk/examples) | A 3D avatar assistant for any website, in one script tag. A floating launcher opens a real, animated 3D avatar in a panel, standing directly on your page (transparent), or against a color or gradient. It has two modes: | `npm run dev, then open /assistant-sdk/examples/index.html` |
| [`avatar-sdk/examples`](../avatar-sdk/examples) | A self-contained page, no build step. It loads the SDK's @three-ws/avatar/agent entry from a CDN, awaits ensureAgent3D() to register the <agent-3d> element, and renders the real three.ws default avatar using the documented src and kiosk attributes. | `npm run dev, then open /avatar-sdk/examples/index.html` |
| [`packages/avatar-schema/examples`](../packages/avatar-schema/examples) | JSON Schema and validator for three.ws on-chain avatar manifests - the canonical, hash-anchored format any cross-chain client can use to resolve an avatar. | Reference files, nothing to execute |
diff --git a/docs/in-game-economy.md b/docs/in-game-economy.md
new file mode 100644
index 000000000..5b547b812
--- /dev/null
+++ b/docs/in-game-economy.md
@@ -0,0 +1,230 @@
+# The in-game economy
+
+The `/play` open world runs a real economy. You gather materials, sell them to a
+vendor for cash, buy better tools, bank what you cannot afford to lose, and
+optionally spend `$THREE` on cosmetics that settle on Solana.
+
+This page is the complete reference: every currency, vendor, gate and settlement
+path, plus the wire format if you want to read the catalogs from code.
+
+**Live numbers:** [three.ws/play/economy](https://three.ws/play/economy) renders
+everything below from the running server. Prefer it over any figure quoted here,
+because that page reads the game's own tables and this document is prose.
+
+---
+
+## Two currencies that never mix
+
+The single most important thing to understand about this economy is that it has
+two currencies and they are deliberately kept apart.
+
+| | **Cash** | **`$THREE`** |
+| --- | --- | --- |
+| What it is | A game resource | The platform's coin |
+| Where it lives | Your character profile, server-side | Solana |
+| How you get it | Gathering, fishing, combat, selling to vendors | Buy it, or already hold it |
+| What it buys | Tools, consumables, ammo, armor | Premium cosmetics, paid wheel spins |
+| Can you cash it out? | No. Never. | It is already a token |
+
+Cash is not a token, is not tradable between players for real value, and never
+touches a blockchain. `$THREE` is never awarded by gameplay. That separation is
+enforced in the code, not by convention: the two paths live in different modules
+and settle through different systems.
+
+The practical consequence: **you cannot farm the game for money, and you cannot
+buy your way past the gameplay.** Cosmetics bought with `$THREE` are visual only.
+
+---
+
+## The general store
+
+Walk up to the clerk NPC and press <kbd>E</kbd>.
+
+### What it pays you for
+
+Only gathered and looted goods are sellable. Tools, weapons, mounts and your
+starter kit are deliberately excluded from the sell table, so nobody can dump
+their kit for cash or farm a buy-then-sell arbitrage loop.
+
+The sellable set is wood, stone, coal, fish, cooked fish, bones and hide. Cooking
+a fish before selling it is worth noticeably more than selling it raw, which is
+the intended reason to level cooking.
+
+### What it sells you
+
+Tools (rod, axe, pickaxe, hammer), a melee weapon, health potions, the armor
+vest, and ammo in bundles. Ammo and arrows are sold in stacks, so their per-unit
+price is lower than the sticker price suggests.
+
+### Why prices cannot drift
+
+`multiplayer/src/shop.js` holds one price table. The authoritative server prices
+every trade against it, and the client renders its store UI from the same import.
+There is no second copy to fall out of sync, so the price you are shown is
+always the price you are charged.
+
+Every trade is validated server-side. The client sends an intent; the server
+prices it, checks your inventory and purse, mutates the profile, and streams the
+result back. The UI never assumes a trade landed until the server confirms it.
+
+---
+
+## The bank
+
+Walk up to the teller NPC and press <kbd>E</kbd> to move cash between your
+**carried purse** and your **banked balance**.
+
+This is the only real risk decision in the economy:
+
+- **Carried cash drops when you die.** So do carried items. They go into a
+ tombstone.
+- **Banked cash survives.** Always.
+
+That asymmetry is the entire point of the bank existing. If you are about to go
+somewhere dangerous, deposit first. The walk back to the bank is the cost.
+
+---
+
+## The `$THREE` boutique
+
+The boutique sells premium wardrobe cosmetics for real, on-chain `$THREE` paid
+from your connected Solana wallet. It is the only part of the world economy that
+touches a blockchain.
+
+### How a purchase settles
+
+1. **Quote.** The server prices the charge from its own catalog. A client-supplied
+ price is never trusted.
+2. **Sign.** You sign one split transaction from your wallet.
+3. **Verify.** The server re-fetches the confirmed transaction from Solana RPC and
+ checks the destination and amount before granting the cosmetic. Settled quote
+ nonces are retained, so a transaction cannot be replayed for a second item.
+
+You are never granted an item on the strength of a client claiming it paid.
+
+### Where the money goes
+
+Every paid `$THREE` sale splits **50% to the holder-rewards sink and 50% to the
+treasury**. Paid wheel spins use the same split and the same verified settlement
+primitives.
+
+### What it is not
+
+This is **not** the same rail as the USDC cosmetics shop for the standalone
+character creator, which sells a different catalog through
+[x402](x402.md) and is surfaced publicly at [/fits](https://three.ws/fits).
+Two catalogs, two currencies, two rails. Do not confuse them.
+
+---
+
+## Fortune's Folly (the wheel)
+
+A landmark in the plaza. Walk up and press <kbd>E</kbd>.
+
+- **One free spin every 12 hours.** The cooldown is persisted on your profile, so
+ it survives a disconnect. You cannot reset it by rejoining.
+- **Or pay $3 worth of `$THREE`** for a spin, split 50/50 to holder rewards and
+ treasury, verified on-chain before any prize is granted.
+- **Gated at average skill level 3.** A light anti-farm floor, not a grind. You
+ start at level 1, so this asks for a little real play.
+
+The wheel has 20 wedges and **all of them are equal odds by design**. That is not
+an implementation detail to be tuned away: the client renders a fixed-angle wheel,
+so the visual and the probability must stay identical or the wheel would lie.
+
+Before a spin is offered or paid for, the server checks there is inventory room
+for **any** item prize the wheel can award. A win can never be lost to a full
+pack, and you can never pay for a spin whose prize would be discarded.
+
+The full paytable with real per-outcome odds is on
+[three.ws/play/economy](https://three.ws/play/economy).
+
+---
+
+## Progression
+
+The economy is tuned against five skills: **combat, woodcutting, mining, fishing
+and cooking**, each capped at level 99. You carry 24 inventory slots and a 6-slot
+hotbar, with stackable items reaching 999 per stack.
+
+Gathering skills feed the sell table, cooking multiplies what fish are worth, and
+combat determines what you can survive long enough to loot. The wheel's level
+gate reads the average across all five, so there is no single skill to rush.
+
+---
+
+## Reading the catalogs from code
+
+Everything above is published as JSON.
+
+### `GET /api/play/economy`
+
+Public, no authentication, no session. Returns the complete reference: both
+currencies, the store's buy and sell catalogs, the bank rule, the boutique
+listings, the wheel's gates and paytable, and the progression constants.
+
+```bash
+curl -s https://three.ws/api/play/economy | jq '.generalStore.sell'
+```
+
+```json
+[
+ { "item": "wood", "label": "Wood", "price": 2 },
+ { "item": "cookedFish", "label": "Cooked Fish", "price": 9 }
+]
+```
+
+The response is static configuration, so it is cached hard at the edge and only
+changes when the game's own tables change, which ships as a deploy.
+
+A few fields worth knowing:
+
+| Field | Meaning |
+| --- | --- |
+| `currencies.cash.onchain` | Always `false`. Cash never leaves the game. |
+| `currencies.token.onchain` | Always `true`, with `chain: "solana"`. |
+| `generalStore.buy[].unitPrice` | Per-unit cost, derived for bundled entries like ammo. |
+| `boutique.rewardsBps` / `treasuryBps` | The split in basis points. They sum to `10000`. |
+| `wheel.paytable[].wedges` | How many of the 20 wedges award this exact prize. |
+| `wheel.paytable[].oddsPct` | Summed odds for that prize, not a single wedge's. |
+
+Identical wedges are grouped in `paytable`, with their odds summed, so a client
+can render "4 wedges, 20%" instead of four near-identical rows. The odds are
+summed from each wedge's own `oddsPct` rather than assumed uniform, so the
+numbers stay correct if the wheel is ever re-weighted.
+
+### Why this endpoint exists
+
+A reference that restates the game's numbers drifts the moment someone retunes a
+price, and a stale price table is worse than none. So this endpoint does not
+restate anything: it imports the same modules the multiplayer server prices
+trades with (`multiplayer/src/shop.js`, `items.js`, `cosmetics-catalog.js`,
+`spin-wheel.js`, `economy.js`) and serializes them. There is exactly one copy of
+every number in this system.
+
+---
+
+## Where the code lives
+
+| Piece | Location |
+| --- | --- |
+| Price tables (store + boutique) | [multiplayer/src/shop.js](../multiplayer/src/shop.js) |
+| Purse, bank, inventory, skills, death drop | [multiplayer/src/economy.js](../multiplayer/src/economy.js) |
+| On-chain quote, split, verification | [multiplayer/src/game-token.js](../multiplayer/src/game-token.js) |
+| Wheel paytable, gates, handlers | [multiplayer/src/spin-wheel.js](../multiplayer/src/spin-wheel.js) |
+| Server message handlers | [multiplayer/src/rooms/WalkRoom.js](../multiplayer/src/rooms/WalkRoom.js) |
+| Store and bank UI | [src/game/economy-ui.js](../src/game/economy-ui.js) |
+| Vendor NPCs | [src/game/npc/economy-npcs.js](../src/game/npc/economy-npcs.js) |
+| Boutique purchase flow | [src/game/boutique-purchase.js](../src/game/boutique-purchase.js) |
+| Public reference endpoint | [api/play/economy.js](../api/play/economy.js) |
+
+---
+
+## Next
+
+- **[Earn and spend in /play](tutorials/earn-and-spend-in-play.md)** walks the
+ whole loop end to end, from your first gathered log to a cosmetic unlock.
+- **[three.ws/play/economy](https://three.ws/play/economy)** is the live reference
+ with the current catalogs and odds.
+- **[Coin communities](coin-pages.md)** covers the worlds themselves: how a coin
+ becomes a walkable 3D space.
diff --git a/docs/nav.json b/docs/nav.json
index 61636f52f..b7a0a4915 100644
--- a/docs/nav.json
+++ b/docs/nav.json
@@ -399,30 +399,6 @@
{
"label": "Oracle (the conviction engine)",
"path": "oracle"
- },
- {
- "label": "Meta-Allocator",
- "path": "meta-allocator"
- },
- {
- "label": "The three.ws launchpad",
- "path": "native-launchpad"
- },
- {
- "label": "Memetic Launcher",
- "path": "memetic-launcher"
- },
- {
- "label": "Repo to coin launcher",
- "path": "pump-launch-repos"
- },
- {
- "label": "Robinhood Chain markets",
- "path": "robinhood-chain-markets"
- },
- {
- "label": "The 10 SOL trading experiment",
- "path": "trading-experiment"
}
]
},
@@ -506,10 +482,6 @@
"label": "The social layer",
"path": "social-layer"
},
- {
- "label": "Agora (agent + human economy)",
- "path": "agora"
- },
{
"label": "Trust primitives",
"path": "trust-primitives"
@@ -643,18 +615,6 @@
"label": "The autonomous economy",
"path": "autonomous-economy"
},
- {
- "label": "Money map",
- "path": "money-map"
- },
- {
- "label": "Economy heartbeat",
- "path": "economy-heartbeat"
- },
- {
- "label": "The master wallet",
- "path": "economy-master"
- },
{
"label": "Closed-loop x402 ring economy",
"path": "x402-ring-economy"
@@ -667,10 +627,6 @@
"label": "Paid plans (USDC, SOL, $THREE)",
"path": "plan-checkout"
},
- {
- "label": "Paid API provider listing",
- "path": "pay-skills-listing"
- },
{
"label": "Vanity addresses",
"path": "vanity"
@@ -687,10 +643,6 @@
"label": "Token-gated 3D embeds",
"path": "token-gated-3d-embeds"
},
- {
- "label": "Financial controls & audit",
- "path": "financial-controls"
- },
{
"label": "Real-funds risk acknowledgment",
"path": "risk-acknowledgment"
@@ -897,10 +849,6 @@
{
"label": "Shared utilities",
"path": "shared-utilities"
- },
- {
- "label": "Avatar CLI",
- "path": "avatar-cli"
}
]
},
@@ -939,10 +887,6 @@
"label": "MCP: x402 Bazaar server",
"path": "mcp-x402-bazaar"
},
- {
- "label": "MCP on the Cloudflare edge",
- "path": "pump-fun-mcp-edge"
- },
{
"label": "AR in ChatGPT",
"path": "chatgpt-ar"
@@ -951,22 +895,10 @@
"label": "The 3D Studio custom GPT",
"path": "chatgpt-3d-studio-gpt"
},
- {
- "label": "OKX.AI marketplace",
- "path": "okx-marketplace"
- },
- {
- "label": "BNB Chain world",
- "path": "bnb-world"
- },
{
"label": "Sketchfab showcase",
"path": "sketchfab"
},
- {
- "label": "News-feed syndication",
- "path": "syndication"
- },
{
"label": "NVIDIA Inception",
"path": "nvidia-inception"
@@ -1055,6 +987,10 @@
{
"label": "Read a Solana agent's reputation",
"path": "tutorials/solana-agent-reputation"
+ },
+ {
+ "label": "Read the trading fleet",
+ "path": "tutorials/read-the-trading-fleet"
}
]
},
@@ -1120,14 +1056,6 @@
{
"label": "Publisher rights (news reader)",
"path": "news-rights"
- },
- {
- "label": "Pump.fun platform fee",
- "path": "pump-platform-fee"
- },
- {
- "label": "Demo routes",
- "path": "demo-routes"
}
]
}
diff --git a/docs/tutorials/earn-and-spend-in-play.md b/docs/tutorials/earn-and-spend-in-play.md
new file mode 100644
index 000000000..db6f7d3cf
--- /dev/null
+++ b/docs/tutorials/earn-and-spend-in-play.md
@@ -0,0 +1,197 @@
+# Earn and spend in /play
+
+By the end of this tutorial you'll have run the full economic loop in the three.ws
+open world: **gather raw materials, sell them to a vendor for cash, buy a better
+tool, bank the rest so death can't take it, and spin the wheel.** You'll also
+understand the one decision the economy actually asks of you, and how the
+optional on-chain side works if you want a premium cosmetic.
+
+Along the way you'll learn why the world has two currencies that never touch,
+and why the server, not your client, decides every price.
+
+**Prerequisites:** a modern browser. No account, no wallet, and no crypto are
+needed for anything except the final optional section, which spends `$THREE`.
+
+---
+
+## What you're building toward
+
+```
+ gather ──► sell at the store ──► cash ──► buy a better tool
+ │ │
+ ▼ ▼
+ the bank gather faster
+ (survives death)
+```
+
+That loop is the whole game economy. Everything else, including the wheel and the
+cosmetics boutique, hangs off it.
+
+---
+
+## Step 1: Get into the world
+
+Open [three.ws/play](https://three.ws/play). You'll drop into a coin world as a
+walkable 3D character.
+
+Controls you need for this tutorial:
+
+| Key | Does |
+| --- | --- |
+| <kbd>W</kbd> <kbd>A</kbd> <kbd>S</kbd> <kbd>D</kbd> | Move |
+| Mouse | Look |
+| <kbd>E</kbd> | Interact with whatever you're standing next to |
+
+Everything below is triggered by walking up to something and pressing
+<kbd>E</kbd>. There is no menu to hunt through.
+
+---
+
+## Step 2: Gather something worth selling
+
+Find a tree or a rock and gather from it. You'll pick up **wood** or **stone**,
+and the matching skill (woodcutting, mining) will start earning experience.
+
+Only gathered and looted goods can be sold. That's deliberate, and it's worth
+understanding now rather than discovering later:
+
+> The store will **not** buy your tools, weapons, mounts or starter kit. If it
+> did, you could buy a rod for 45 and sell it back for something, and the whole
+> economy would collapse into a buy-then-sell loop. The sell list is short on
+> purpose.
+
+The sellable set is wood, stone, coal, fish, cooked fish, bones and hide.
+
+**Fishing is the highest-value early loop**, but only if you cook first. A raw
+fish sells for 3. Cooking it turns it into a cooked fish worth 9, which is a
+three-times return for one extra step. This is the intended reason to level
+cooking, and it is the single best-paying thing a new player can do.
+
+Gather a stack of something before moving on. Twenty logs is plenty.
+
+---
+
+## Step 3: Sell to the general store
+
+Find the **general store clerk** NPC and press <kbd>E</kbd>.
+
+The store panel has two sides: what it buys from you, and what it sells. Sell
+your stack.
+
+Watch what happens under the hood, because it explains the whole design:
+
+1. Your client sends an *intent*: "sell 20 wood."
+2. The **server** prices it against its own table, checks you actually have 20
+ wood, mutates your profile, and streams back the result.
+3. Only then does the UI update.
+
+Your client never decides a price and never assumes a trade landed. If you edited
+the price in your browser, the server would price it correctly anyway. This is
+why the number you see is always the number you're charged: there is exactly one
+price table, and both the server and the client render from it.
+
+---
+
+## Step 4: Buy a better tool
+
+Still at the store, switch to what it sells. You'll see tools (rod, axe,
+pickaxe, hammer), a sword, health potions, an armor vest, and ammo.
+
+Buy the tool matching whatever you've been gathering. This is the reinvestment
+step, and it's what makes the loop compound: better tool, faster gathering, more
+cash.
+
+**Watch the bundles.** Ammo and arrows are sold in stacks, so compare per-unit
+cost rather than sticker price. The live reference at
+[three.ws/play/economy](https://three.ws/play/economy) shows the per-unit price
+for every bundled entry, which is the honest number to compare.
+
+---
+
+## Step 5: Bank what you can't afford to lose
+
+Find the **bank teller** and press <kbd>E</kbd>. Deposit your remaining cash.
+
+This is the one genuine decision the economy asks of you:
+
+| | Carried purse | Banked |
+| --- | --- | --- |
+| Dying | **Drops into a tombstone** | **Survives** |
+| Spending at a vendor | Immediate | Withdraw first |
+
+Carried cash and carried items drop when you die. Banked cash never does. The
+cost of safety is the walk back to the teller.
+
+The practical rule: **bank before you go anywhere dangerous, carry only what you
+plan to spend.** New players almost always learn this the expensive way.
+
+---
+
+## Step 6: Spin the wheel
+
+Find **Fortune's Folly** in the plaza and press <kbd>E</kbd>.
+
+You get **one free spin every 12 hours**. The cooldown lives on your profile
+server-side, so logging out and back in does not reset it.
+
+Two things worth knowing before you spin:
+
+- **All 20 wedges have equal odds.** The client draws a fixed-angle wheel, so the
+ visual and the real probability are the same by construction. Most wedges are
+ modest gather resources; a few are cash; one is a jackpot.
+- **You need average skill level 3.** It reads the average across all five skills
+ (combat, woodcutting, mining, fishing, cooking), so no single skill can be
+ rushed to unlock it. If you did steps 2 through 4, you're close.
+
+The server also checks there's inventory room for any prize the wheel could award
+*before* offering the spin, so a win can never be lost to a full pack.
+
+The full paytable, with the real odds for each outcome, is published at
+[three.ws/play/economy](https://three.ws/play/economy).
+
+---
+
+## Optional: buy a cosmetic with `$THREE`
+
+Everything so far used **cash**, which is a pure game resource. It never leaves
+the world, is not a token, and cannot be cashed out.
+
+The boutique is the one place the world touches a blockchain. Premium wardrobe
+cosmetics are unlocked with real `$THREE` from your connected Solana wallet.
+
+> **This spends real money.** Nothing in the gathering loop above can earn
+> `$THREE`, and nothing you buy here affects gameplay. Cosmetics are visual only.
+
+If you want one, open your wardrobe and pick a premium fit. The flow is:
+
+1. **Quote.** The server prices the charge from its own catalog. Your client
+ cannot propose a price.
+2. **Sign.** You approve one split transaction in your wallet.
+3. **Verify.** The server re-fetches the confirmed transaction from Solana RPC
+ and checks the destination and amount before granting anything. A settled
+ quote can't be replayed for a second item.
+
+Every paid sale splits 50% to the holder-rewards sink and 50% to the treasury.
+
+---
+
+## What you learned
+
+- The world has **two currencies that never mix.** Cash is earned and spent
+ in-game and can't be cashed out; `$THREE` is on-chain and can't be farmed.
+- **The server prices everything.** One table, imported by both sides, so the
+ displayed price and the charged price cannot disagree.
+- **The bank is the real decision.** Carried cash drops on death, banked cash
+ doesn't.
+- **Cook before you sell.** A cooked fish is worth three times a raw one.
+- **The wheel is honest by construction:** equal-odds wedges matching a
+ fixed-angle render, with pack space checked before you're allowed to spin.
+
+## Next
+
+- **[The in-game economy](../in-game-economy.md)** is the full reference: every
+ catalog, gate, settlement path, and the JSON wire format.
+- **[three.ws/play/economy](https://three.ws/play/economy)** shows the live
+ catalogs and odds, read from the running server.
+- **[Coin communities](../coin-pages.md)** explains the worlds themselves, and how
+ any coin becomes a walkable 3D space.
diff --git a/docs/tutorials/read-the-trading-fleet.md b/docs/tutorials/read-the-trading-fleet.md
new file mode 100644
index 000000000..215677c04
--- /dev/null
+++ b/docs/tutorials/read-the-trading-fleet.md
@@ -0,0 +1,206 @@
+# Read the Trading Fleet: Telling a Working Strategy From a Lucky One
+
+Arming an agent is the easy part. Knowing whether it is actually any good is the
+part that costs people money, because the numbers that feel most convincing are
+the ones that lie most often.
+
+By the end of this tutorial you can look at [/trading](/trading), the
+[leaderboard](/leaderboard), and the [experiments board](/sniper/experiments) and
+say out loud what the fleet is doing, which strategies have earned trust, and
+which are still noise. You will also be able to tell the difference between a
+fleet that is losing and a fleet that is broken, which look identical on a
+dashboard and need completely different responses.
+
+If you have not armed an agent yet, start with
+[Arm an autonomous sniper](/tutorials/arm-an-agent-sniper). You can follow this
+tutorial without arming anything: every number below is public and read-only.
+
+**What you will learn:**
+
+- Which single number tells you the fleet is alive, and why uptime is not it
+- Why realized profit is the only profit, and what an open position is worth (nothing, yet)
+- How to read win rate, profit factor, and drawdown together instead of one at a time
+- The sample size below which a leaderboard rank means nothing
+- How to spot a broken fleet that still shows a green light
+
+---
+
+## Step 1: Check that the fleet can trade at all
+
+Open [/trading](/trading) and read the vitals row before you look at any profit
+number. Profit from a fleet that stopped trading two days ago is history, not
+performance.
+
+```bash
+curl -s https://three.ws/api/sniper/status \
+ | jq '{mode, strategies, openPositions, feedLive, feedSilent, lastEventAgeMs, bootAt}'
+```
+
+Four things have to be true for the fleet to be able to take a trade:
+
+| Field | Healthy | What it means when it is not |
+|---|---|---|
+| `mode` | `live` | `simulate` means real quotes and zero broadcasts. Nothing will ever fill. |
+| `strategies` | 1 or more | Nothing is armed. |
+| `feedLive` | `true` | The worker is not receiving launches, so it sees nothing to score. |
+| `feedSilent` | `false` | Connected, but no launches are arriving. Same practical result as a dead feed. |
+
+**The trap.** `feedLive: true` with `feedSilent: true` is the one that catches
+people. The connection is up, the process is healthy, every status check is
+green, and the fleet is seeing nothing. This is why the hub reports feed health
+as its own tile instead of folding it into a single indicator.
+
+## Step 2: Do not trust uptime as a health signal
+
+`bootAt` tells you how long the worker process has been running. A large number
+here feels reassuring and is not:
+
+```bash
+curl -s https://three.ws/api/sniper/status | jq '.bootAt'
+```
+
+A process that has been up for days is running whatever code it booted with. If
+fixes have shipped since, they are sitting in the repository, not in the running
+fleet. A long uptime next to a recurring problem is a strong hint that the fix
+exists and has not been deployed, rather than that the problem is hard.
+
+Treat uptime as "how long since this was last changed," not as "how healthy this
+is."
+
+## Step 3: Count only realized profit
+
+```bash
+curl -s 'https://three.ws/api/sniper/leaderboard?window=all&sort=score' \
+ | jq '.leaderboard[] | {agent_name, closed, open_positions, realized_pnl_sol, roi_pct}'
+```
+
+`realized_pnl_sol` is the only profit figure on the platform, and it comes
+exclusively from closed positions. An open position contributes nothing, however
+far up it is, because an unrealized gain is a price quote and not a result. Every
+surface follows this rule, so a strategy holding a coin that has tripled still
+reads as zero until it exits.
+
+This is deliberately unflattering and it is the correct way round. The failure
+mode it prevents is the strategy that looks brilliant for a week because it never
+closes a loser, then gives it all back in one exit.
+
+Note `open_positions` alongside `closed`. An agent with many open and very few
+closed is not a proven strategy; it is a strategy that has not finished making
+its case yet.
+
+## Step 4: Read the three performance numbers together
+
+No single metric survives on its own. Read these as a set:
+
+**Win rate** is the share of closed trades that made money. It is the most
+quoted and the least informative. A strategy that wins 90% of the time and loses
+everything on the tenth trade is a losing strategy with a beautiful win rate.
+
+**Profit factor** is gross wins divided by gross losses. Above 1.0 the strategy
+makes money overall. This is the number that survives contact with reality,
+because it weighs how much each side was worth instead of just counting sides.
+
+**Max drawdown** is the worst peak-to-trough fall. It tells you what holding this
+strategy actually felt like, and whether you would have switched it off before it
+recovered.
+
+The combination to trust is a **profit factor above 1** with a **drawdown you
+could live through**. A high win rate with a profit factor near or below 1 means
+the strategy is harvesting many small wins and paying for them with rare large
+losses.
+
+The fleet's laddered exit is built around exactly this asymmetry: it recovers the
+stake at roughly two times entry and lets the remainder ride on a trailing stop,
+so a single large winner is not cut short to protect the win-rate statistic. Read
+[the 10 SOL experiment](/docs/trading-experiment) for the full policy.
+
+## Step 5: Respect sample size
+
+A leaderboard rank built on a handful of trades is close to meaningless. Sort by
+profit and you will often find the top agent has closed five trades, one of which
+was lucky.
+
+```bash
+curl -s 'https://three.ws/api/sniper/leaderboard?window=all&sort=score' \
+ | jq '[.leaderboard[] | select(.closed >= 30)]'
+```
+
+Rough guidance for these strategies:
+
+- **Under 10 closed trades:** noise. Do not rank, do not conclude, do not copy.
+- **10 to 30:** a hint. Worth watching, not worth funding.
+- **30 or more:** a signal worth acting on, if the profit factor agrees.
+
+This is also why [the experiments board](/sniper/experiments) exists. It runs
+deliberately different rule sets against the same market at the same time, so the
+comparison controls for market conditions instead of comparing a strategy that
+ran in a good week against one that ran in a bad one.
+
+## Step 6: Tell "losing" apart from "broken"
+
+Both show a flat or falling line. They need opposite responses: a losing strategy
+should be retuned or switched off, a broken one should be repaired and left
+alone. Check for broken before you conclude losing.
+
+Signals that a fleet is broken rather than unprofitable:
+
+- **Attempts with no fills.** The strategy count is healthy, the feed is live, and
+ closed trades are not increasing. Entries are being blocked somewhere in the
+ gate chain rather than losing money in the market.
+- **An agent stuck at the same open position for hours** against a much shorter
+ configured hold time. Its slot is occupied, so it cannot take new trades even
+ though it looks armed and idle.
+- **Funding that has stopped.** `funding.lastFundAt` far in the past while agent
+ wallets sit near empty means the fleet cannot afford to trade, regardless of
+ how good its rules are.
+
+```bash
+curl -s https://three.ws/api/sniper/status | jq '.funding'
+```
+
+A losing strategy produces a steady stream of closed trades with a profit factor
+below 1. A broken one produces very few closed trades at all. The clearest tell is
+the ratio of attempts to fills: healthy strategies fill regularly, and a strategy
+that never fills is not being cautious, it is stuck.
+
+## Step 7: Verify anything you doubt on-chain
+
+Every fill is signed by the agent's own wallet, so nothing here has to be taken
+on trust. The leaderboard exposes each agent's wallet and an explorer link:
+
+```bash
+curl -s 'https://three.ws/api/sniper/leaderboard?window=all' \
+ | jq '.leaderboard[] | {agent_name, wallet, wallet_explorer_url}'
+```
+
+Open the explorer link and the transactions are there in the order the platform
+claims. If a number on a three.ws page ever disagrees with the chain, the chain is
+right and it is a bug worth reporting.
+
+---
+
+## What to do with this
+
+- **Evaluating your own agent:** wait for 30 closed trades before you conclude
+ anything. Check profit factor before win rate. Check that it is filling at all
+ before you retune its rules.
+- **Choosing an agent to copy:** filter to 30 or more closed trades, require a
+ profit factor above 1, and look at max drawdown to decide whether you could
+ actually hold it. Then read [copy trading](/docs/copy-trading).
+- **Watching the fleet:** [/trading](/trading) for the state of everything,
+ [the arena](/play/arena) for live positions, and
+ [the experiments board](/sniper/experiments) for which style of decision making
+ is currently winning.
+
+Trading newly launched coins can lose the entire position, and the safety rails
+filter provable rugs rather than making bad coins good. Read the
+[risk acknowledgment](/docs/risk-acknowledgment) before arming anything with real
+funds.
+
+## Related
+
+- [Arm an autonomous sniper](/tutorials/arm-an-agent-sniper), the setup this tutorial measures
+- [The trading hub](/docs/trading-hub), where each number on /trading comes from
+- [Agent Sniper](/docs/agent-sniper), how the trader is wired
+- [The 10 SOL experiment](/docs/trading-experiment), the risk policy behind the exits
+- [Earned autonomy](/docs/sniper-autonomy), how an agent earns more freedom
diff --git a/docs/user-wallet.md b/docs/user-wallet.md
index 7f85d8e92..39c25664e 100644
--- a/docs/user-wallet.md
+++ b/docs/user-wallet.md
@@ -8,6 +8,17 @@ Everything on this page moves real money. Read [Safety: this is a spend surface]
Code: `api/user/wallet/index.js`, `send.js`, `fund-agent.js`, `history.js`.
+## The page: [three.ws/wallet](https://three.ws/wallet)
+
+If you just want to use your wallet rather than script it, **[/wallet](https://three.ws/wallet)** is the whole feature in a browser. Sign in and it shows your balances across Solana and Base, your two addresses with copy buttons and explorer links, and three actions: send, fund an agent, and history. If you have never provisioned a wallet, the page offers to create one and explains exactly what gets generated first.
+
+Two things about that page are worth knowing before you use it:
+
+- **Sending is two-step by design.** When you submit the send form, the page does not sign anything. It calls `POST /api/user/wallet/send` with `simulate: true`, which runs the real balance, rent, and fee checks on the server and returns what the transfer would actually cost. Only after you read back the amount, recipient, asset, and network, and press **Confirm and send**, does anything get signed and broadcast. A transfer cannot be reversed, so nothing leaves your wallet without you seeing the final numbers.
+- **It is the same API documented below.** The page has no privileged path: it is a session-authenticated client over these four endpoints, so anything it can do, the `curl` examples on this page can do too.
+
+Page code: `pages/wallet.html`, `src/master-wallet.js` (controller), `src/wallet-api.js` (the client), `public/master-wallet.css`. Not to be confused with `src/wallet.js`, which connects an **external** wallet such as Phantom and has nothing to do with the custodial master wallet.
+
## Master wallet vs agent wallet
They are different wallets with different jobs, and mixing them up is the single most common mistake here.
@@ -41,7 +52,7 @@ CSRF=$(curl -s -b cookies.txt https://three.ws/api/csrf-token | python3 -c 'impo
## Provisioning: lazy, and idempotent
-No wallet exists until you ask for one. `GET /api/user/wallet` on an account that has never provisioned returns `{"wallet": null}`, which is the signal for a UI to offer a "create wallet" action rather than an error state.
+No wallet exists until you ask for one. `GET /api/user/wallet` on an account that has never provisioned returns `{"wallet": null}`, which is the signal for a UI to offer a "create wallet" action rather than an error state. That is exactly what [/wallet](https://three.ws/wallet) renders for a new account.
`POST /api/user/wallet` creates the pair: a Solana keypair and an EVM keypair, both generated server-side, both encrypted at rest with AES-256-GCM under the dedicated `WALLET_ENCRYPTION_KEY` (the same secret box that protects agent wallets, deliberately not the session signing secret). There is no seed phrase for you to write down.
diff --git a/examples/README.md b/examples/README.md
index 50feca317..74c2670ef 100644
--- a/examples/README.md
+++ b/examples/README.md
@@ -44,6 +44,7 @@ The demos import the framework source directly (`../src/element.js`, `../src/lib
| [agent-native-3d/](./agent-native-3d/) | A Node script that drives the free `/api/mcp-studio` MCP server end to end: generate a mesh, rig it, save it as a persistent agent persona, speak through it, and emit every distribution snippet. |
| [agenc-task-roundtrip/](./agenc-task-roundtrip/) | End-to-end AgenC coordination-protocol demo on Solana devnet: two wallets register, post, claim, and complete a task with real on-chain transactions. |
| [metamask-agent-wallet/](./metamask-agent-wallet/) | A localhost bridge plus single page that gives an agent a real server-side wallet through the authenticated MetaMask Agentic CLI. |
+| [paid-mcp-server/](./paid-mcp-server/) | An MCP server whose tools charge per call in USDC on Solana over x402: one free orientation tool, one paid glTF/GLB inspector. The seller side of the agent economy, with the verify-work-settle ordering that means a failed call never takes money. |
| [monicas-apartment/](./monicas-apartment/) | A walkable first-person Three.js scene in one self-contained HTML file: procedural textures, AABB collision, pointer-lock controls. |
More SDK-specific examples live next to their SDKs: [concierge-sdk/examples/](../concierge-sdk/examples/) and [assistant-sdk/examples/](../assistant-sdk/examples/).
diff --git a/examples/wallet-sign-in/index.html b/examples/wallet-sign-in/index.html
new file mode 100644
index 000000000..53ffb0f6e
--- /dev/null
+++ b/examples/wallet-sign-in/index.html
@@ -0,0 +1,557 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>Wallet sign-in · three.ws example</title>
+ <meta
+ name="description"
+ content="A runnable Sign-In with Solana (SIWS) and Sign-In with Ethereum (SIWE) demo against the three.ws auth API."
+ />
+ <style>
+ /* Self-contained on purpose: this file runs with no build step and no
+ stylesheet from the platform. Values mirror public/tokens.css so the
+ demo looks native next to the rest of three.ws. */
+ :root {
+ --bg-0: #0a0a0a;
+ --bg-1: #1a1a1a;
+ --surface-1: rgba(255, 255, 255, 0.03);
+ --stroke: rgba(255, 255, 255, 0.08);
+ --stroke-strong: rgba(255, 255, 255, 0.14);
+ --ink: #e8e8e8;
+ --ink-bright: #ffffff;
+ --ink-dim: #888888;
+ --ink-faint: rgba(255, 255, 255, 0.55);
+ --ok: #4ade80;
+ --warn: #fbbf24;
+ --bad: #ff7a7a;
+ --radius-md: 10px;
+ --radius-lg: 14px;
+ color-scheme: dark;
+ }
+ @media (prefers-color-scheme: light) {
+ :root {
+ --bg-0: #ffffff;
+ --bg-1: #f3f4f6;
+ --surface-1: rgba(15, 18, 28, 0.035);
+ --stroke: rgba(15, 18, 28, 0.1);
+ --stroke-strong: rgba(15, 18, 28, 0.16);
+ --ink: #1d212b;
+ --ink-bright: #0a0c12;
+ --ink-dim: #5a616f;
+ --ink-faint: rgba(15, 18, 28, 0.62);
+ --ok: #15803d;
+ --warn: #a16207;
+ --bad: #b91c1c;
+ color-scheme: light;
+ }
+ }
+
+ * { box-sizing: border-box; }
+
+ body {
+ margin: 0;
+ min-height: 100vh;
+ padding: clamp(16px, 5vw, 56px) 16px;
+ background: var(--bg-0);
+ color: var(--ink);
+ font: 400 15px/1.6 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
+ display: flex;
+ justify-content: center;
+ }
+
+ .wrap { width: 100%; max-width: 720px; }
+
+ header { margin-bottom: 28px; }
+
+ h1 {
+ margin: 0 0 8px;
+ font-size: clamp(1.5rem, 4vw, 1.9rem);
+ line-height: 1.2;
+ letter-spacing: -0.02em;
+ color: var(--ink-bright);
+ }
+
+ .sub { margin: 0; color: var(--ink-dim); font-size: 0.9rem; }
+ .sub a { color: var(--ink); text-underline-offset: 3px; }
+
+ .card {
+ background: var(--surface-1);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-lg);
+ padding: 20px;
+ margin-bottom: 16px;
+ }
+
+ .card h2 {
+ margin: 0 0 4px;
+ font-size: 0.95rem;
+ font-weight: 600;
+ color: var(--ink-bright);
+ }
+
+ .card p.hint {
+ margin: 0 0 16px;
+ font-size: 0.82rem;
+ color: var(--ink-dim);
+ }
+
+ .btn-row { display: flex; gap: 10px; flex-wrap: wrap; }
+
+ button {
+ flex: 1 1 200px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+ min-height: 44px;
+ padding: 0 18px;
+ font: inherit;
+ font-size: 0.875rem;
+ font-weight: 500;
+ color: var(--ink-bright);
+ background: var(--bg-1);
+ border: 1px solid var(--stroke-strong);
+ border-radius: var(--radius-md);
+ cursor: pointer;
+ transition: background 0.15s ease, border-color 0.15s ease, transform 0.1s ease;
+ }
+ button:hover:not(:disabled) {
+ background: color-mix(in srgb, var(--bg-1) 80%, var(--ink) 20%);
+ border-color: var(--ink-dim);
+ }
+ button:active:not(:disabled) { transform: translateY(1px); }
+ button:focus-visible { outline: 2px solid var(--ink-bright); outline-offset: 2px; }
+ button:disabled { opacity: 0.45; cursor: default; }
+
+ button svg { flex: none; }
+
+ /* Status region: every state is designed, including the empty one. */
+ #status {
+ margin-top: 16px;
+ padding: 12px 14px;
+ border-radius: var(--radius-md);
+ border: 1px solid var(--stroke);
+ background: var(--surface-1);
+ font-size: 0.82rem;
+ color: var(--ink-dim);
+ display: flex;
+ align-items: flex-start;
+ gap: 10px;
+ transition: border-color 0.2s ease, color 0.2s ease;
+ }
+ #status[data-state="working"] { color: var(--ink); border-color: var(--stroke-strong); }
+ #status[data-state="ok"] { color: var(--ok); border-color: color-mix(in srgb, var(--ok) 40%, transparent); }
+ #status[data-state="error"] { color: var(--bad); border-color: color-mix(in srgb, var(--bad) 40%, transparent); }
+
+ .spinner {
+ flex: none;
+ width: 13px; height: 13px;
+ margin-top: 3px;
+ border: 2px solid currentColor;
+ border-right-color: transparent;
+ border-radius: 50%;
+ animation: spin 0.7s linear infinite;
+ display: none;
+ }
+ #status[data-state="working"] .spinner { display: block; }
+ @keyframes spin { to { transform: rotate(360deg); } }
+ @media (prefers-reduced-motion: reduce) { .spinner { animation-duration: 2.4s; } }
+
+ .dot { flex: none; width: 7px; height: 7px; margin-top: 6px; border-radius: 50%; background: currentColor; }
+ #status[data-state="working"] .dot { display: none; }
+
+ /* Signed-in panel */
+ #account { display: none; }
+ #account[data-visible="true"] { display: block; }
+
+ dl.kv { margin: 0; display: grid; grid-template-columns: minmax(90px, auto) 1fr; gap: 8px 16px; }
+ dl.kv dt { color: var(--ink-dim); font-size: 0.78rem; }
+ dl.kv dd {
+ margin: 0;
+ font-size: 0.8rem;
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
+ word-break: break-all;
+ color: var(--ink-bright);
+ }
+
+ /* Request log: the whole point of the demo is watching the real calls. */
+ #log {
+ margin: 0;
+ padding: 0;
+ list-style: none;
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
+ font-size: 0.75rem;
+ }
+ #log:empty::before {
+ content: "No requests yet. Pick a wallet above and the calls will appear here.";
+ color: var(--ink-faint);
+ font-family: inherit;
+ font-size: 0.8rem;
+ }
+ #log li {
+ display: flex;
+ gap: 10px;
+ padding: 7px 0;
+ border-bottom: 1px solid var(--stroke);
+ animation: slide-in 0.25s ease both;
+ }
+ #log li:last-child { border-bottom: 0; }
+ @keyframes slide-in { from { opacity: 0; transform: translateY(-3px); } to { opacity: 1; transform: none; } }
+ @media (prefers-reduced-motion: reduce) { #log li { animation: none; } }
+
+ #log .code { flex: none; width: 3ch; font-weight: 600; }
+ #log .code.s2 { color: var(--ok); }
+ #log .code.s4, #log .code.s5 { color: var(--bad); }
+ #log .url { color: var(--ink-dim); word-break: break-all; }
+
+ pre.msg {
+ margin: 14px 0 0;
+ padding: 12px;
+ background: var(--bg-1);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-md);
+ font-size: 0.72rem;
+ line-height: 1.5;
+ white-space: pre-wrap;
+ word-break: break-word;
+ color: var(--ink);
+ max-height: 260px;
+ overflow: auto;
+ }
+ pre.msg:empty { display: none; }
+
+ footer { margin-top: 24px; font-size: 0.78rem; color: var(--ink-faint); }
+ footer a { color: var(--ink-dim); }
+ </style>
+ </head>
+ <body>
+ <div class="wrap">
+ <header>
+ <h1>Wallet sign-in</h1>
+ <p class="sub">
+ A real Sign-In with Solana (SIWS) and Sign-In with Ethereum (SIWE) round trip against the
+ three.ws auth API. Every request below is live. Signing is free and never touches a
+ transaction. Read the
+ <a href="https://three.ws/docs/authentication">Authentication guide</a> for the full contract.
+ </p>
+ </header>
+
+ <section class="card">
+ <h2>1. Sign in with a wallet</h2>
+ <p class="hint">
+ Solana is the home chain and the default. The EVM button uses the platform's own SIWE rail,
+ not the Privy one.
+ </p>
+ <div class="btn-row">
+ <button type="button" id="solana-btn">
+ <svg width="14" height="14" viewBox="0 0 24 24" aria-hidden="true">
+ <path fill="currentColor" d="M4.7 15.8h14.1a.6.6 0 0 1 .43 1.02l-2.62 2.63a.9.9 0 0 1-.63.26H1.88a.6.6 0 0 1-.43-1.02l2.62-2.63a.9.9 0 0 1 .63-.26Z"/>
+ <path fill="currentColor" d="M4.7 4.29h14.1a.6.6 0 0 0 .43 1.02l-2.62 2.63a.9.9 0 0 1-.63.26H1.88a.6.6 0 0 1-.43-1.02L4.07 4.55a.9.9 0 0 1 .63-.26Z"/>
+ <path fill="currentColor" d="M19.3 10.04H5.2a.9.9 0 0 0-.63.26l-2.62 2.63a.6.6 0 0 0 .43 1.02h14.1a.9.9 0 0 0 .63-.26l2.62-2.63a.6.6 0 0 0-.43-1.02Z"/>
+ </svg>
+ <span id="solana-label">Continue with Solana</span>
+ </button>
+ <button type="button" id="evm-btn">
+ <svg width="14" height="14" viewBox="0 0 24 24" aria-hidden="true">
+ <path fill="currentColor" d="M12 2 5.5 12.3 12 16.2l6.5-3.9L12 2Z"/>
+ <path fill="currentColor" d="m12 17.5-6.5-3.9L12 22l6.5-8.4-6.5 3.9Z"/>
+ </svg>
+ <span id="evm-label">Continue with EVM</span>
+ </button>
+ </div>
+
+ <div id="status" data-state="idle" role="status" aria-live="polite">
+ <span class="spinner" aria-hidden="true"></span>
+ <span class="dot" aria-hidden="true"></span>
+ <span id="status-text">Ready. Install Phantom, Backpack, Solflare, or MetaMask, then pick a chain.</span>
+ </div>
+
+ <pre class="msg" id="signed-message" aria-label="The message your wallet signed"></pre>
+ </section>
+
+ <section class="card" id="account">
+ <h2>2. Your session</h2>
+ <p class="hint">
+ Returned by <code>GET /api/auth/me</code> using the <code>__Host-sid</code> cookie the
+ verify call just set.
+ </p>
+ <dl class="kv" id="account-kv"></dl>
+ <div class="btn-row" style="margin-top: 16px">
+ <button type="button" id="logout-btn">Sign out</button>
+ </div>
+ </section>
+
+ <section class="card">
+ <h2>Request log</h2>
+ <p class="hint">Every call this page makes, in order, with its real status code.</p>
+ <ul id="log"></ul>
+ </section>
+
+ <footer>
+ Source:
+ <a href="https://github.com/nirholas/three.ws/tree/main/examples/wallet-sign-in">examples/wallet-sign-in</a>.
+ See the <a href="https://three.ws/docs/tutorials/wallet-sign-in">tutorial</a> for a line-by-line
+ walkthrough.
+ </footer>
+ </div>
+
+ <script type="module">
+ // ─────────────────────────────────────────────────────────────────────
+ // Where the API lives. Same-origin by default, so this file works both
+ // on three.ws itself and behind a dev proxy that forwards /api/* there.
+ // Override with ?api=https://three.ws to point a local page at prod.
+ // ─────────────────────────────────────────────────────────────────────
+ const API = new URLSearchParams(location.search).get('api') || '';
+
+ const statusEl = document.getElementById('status');
+ const statusText = document.getElementById('status-text');
+ const logEl = document.getElementById('log');
+ const msgEl = document.getElementById('signed-message');
+ const accountEl = document.getElementById('account');
+ const accountKv = document.getElementById('account-kv');
+ const solanaBtn = document.getElementById('solana-btn');
+ const evmBtn = document.getElementById('evm-btn');
+ const logoutBtn = document.getElementById('logout-btn');
+
+ function setStatus(state, text) {
+ statusEl.dataset.state = state;
+ statusText.textContent = text;
+ }
+
+ function logCall(status, method, url) {
+ const li = document.createElement('li');
+ const code = document.createElement('span');
+ code.className = `code s${String(status)[0]}`;
+ code.textContent = status;
+ const label = document.createElement('span');
+ label.className = 'url';
+ label.textContent = `${method} ${url}`;
+ li.append(code, label);
+ logEl.append(li);
+ }
+
+ // Every network call goes through here so the log is complete by
+ // construction rather than by remembering to add a line.
+ async function call(path, init = {}) {
+ const res = await fetch(API + path, { credentials: 'include', ...init });
+ logCall(res.status, init.method || 'GET', path);
+ return res;
+ }
+
+ function setBusy(busy) {
+ solanaBtn.disabled = busy;
+ evmBtn.disabled = busy;
+ }
+
+ // ── Wallet detection ────────────────────────────────────────────────
+ // Ordered the same way src/privy-login.js does it, so a Seeker/Seed
+ // Vault wallet that shadows window.solana still resolves correctly.
+ function getSolanaProvider() {
+ if (window.threeWsWallet?.isThreeWs) return window.threeWsWallet;
+ if (window.solana?.isThreeWs) return window.solana;
+ if (window.phantom?.solana?.isPhantom) return window.phantom.solana;
+ if (window.solana?.isPhantom) return window.solana;
+ if (window.backpack?.solana) return window.backpack.solana;
+ if (window.solflare?.isSolflare) return window.solflare;
+ return null;
+ }
+
+ const STATEMENT =
+ 'Sign in to three.ws. This request will not trigger any blockchain transaction or cost ' +
+ 'any fees. By signing, you agree to the Terms of Service (https://three.ws/legal/tos) and ' +
+ 'Privacy Policy (https://three.ws/legal/privacy).';
+
+ // ── Sign-In with Solana ─────────────────────────────────────────────
+ solanaBtn.addEventListener('click', async () => {
+ const provider = getSolanaProvider();
+ if (!provider) {
+ setStatus('error', 'No Solana wallet found. Install Phantom, Backpack, or Solflare.');
+ return;
+ }
+ setBusy(true);
+ msgEl.textContent = '';
+ try {
+ setStatus('working', 'Connecting to your wallet…');
+ const { publicKey } = await provider.connect();
+ const address = publicKey.toString();
+
+ setStatus('working', 'Requesting a nonce…');
+ const nonceRes = await call('/api/auth/siws/nonce');
+ if (!nonceRes.ok) throw new Error('Could not get a nonce.');
+ const { nonce, csrf, domain, uri } = await nonceRes.json();
+
+ // Build from the SERVER's domain/uri, never location.host: that is
+ // what lets a proxied dev page produce a message the deployment
+ // accepts. See docs/authentication.md.
+ const message = [
+ `${domain} wants you to sign in with your Solana account:`,
+ address,
+ '',
+ STATEMENT,
+ '',
+ `URI: ${uri}`,
+ 'Version: 1',
+ 'Chain ID: mainnet',
+ `Nonce: ${nonce}`,
+ `Issued At: ${new Date().toISOString()}`,
+ `Expiration Time: ${new Date(Date.now() + 5 * 60 * 1000).toISOString()}`,
+ ].join('\n');
+ msgEl.textContent = message;
+
+ setStatus('working', 'Approve the signature in your wallet…');
+ const { signature: sigBytes } = await provider.signMessage(
+ new TextEncoder().encode(message),
+ 'utf8',
+ );
+ const signature = btoa(String.fromCharCode(...sigBytes));
+
+ setStatus('working', 'Verifying the signature…');
+ const verifyRes = await call('/api/auth/siws/verify', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', 'x-csrf-token': csrf },
+ body: JSON.stringify({ message, signature, tosAccepted: true }),
+ });
+ const data = await verifyRes.json().catch(() => ({}));
+ if (!verifyRes.ok) throw new Error(describe(data));
+
+ setStatus('ok', `Signed in as ${address.slice(0, 4)}…${address.slice(-4)}.`);
+ await loadAccount();
+ } catch (err) {
+ setStatus('error', friendly(err));
+ } finally {
+ setBusy(false);
+ }
+ });
+
+ // ── Sign-In with Ethereum ───────────────────────────────────────────
+ evmBtn.addEventListener('click', async () => {
+ if (!window.ethereum) {
+ setStatus('error', 'No EVM wallet found. Install MetaMask or another browser wallet.');
+ return;
+ }
+ setBusy(true);
+ msgEl.textContent = '';
+ try {
+ setStatus('working', 'Connecting to your wallet…');
+ const [address] = await window.ethereum.request({ method: 'eth_requestAccounts' });
+ if (!address) throw new Error('No account returned from the wallet.');
+ const chainId = parseInt(await window.ethereum.request({ method: 'eth_chainId' }), 16);
+
+ setStatus('working', 'Requesting a nonce…');
+ const nonceRes = await call('/api/auth/siwe/nonce');
+ if (!nonceRes.ok) throw new Error('Could not get a nonce.');
+ const { nonce, csrf, expiresAt, domain, uri } = await nonceRes.json();
+
+ const host = domain || location.host;
+ const origin = uri || location.origin;
+ const message = [
+ `${host} wants you to sign in with your Ethereum account:`,
+ address,
+ '',
+ STATEMENT,
+ '',
+ `URI: ${origin}`,
+ 'Version: 1',
+ `Chain ID: ${chainId}`,
+ `Nonce: ${nonce}`,
+ `Issued At: ${new Date().toISOString()}`,
+ ...(expiresAt ? [`Expiration Time: ${expiresAt}`] : []),
+ ].join('\n');
+ msgEl.textContent = message;
+
+ setStatus('working', 'Approve the signature in your wallet…');
+ const signature = await window.ethereum.request({
+ method: 'personal_sign',
+ params: [message, address],
+ });
+
+ setStatus('working', 'Verifying the signature…');
+ const verifyRes = await call('/api/auth/siwe/verify', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', 'x-csrf-token': csrf },
+ body: JSON.stringify({ message, signature, tosAccepted: true }),
+ });
+ const data = await verifyRes.json().catch(() => ({}));
+ if (!verifyRes.ok) throw new Error(describe(data));
+
+ setStatus('ok', `Signed in as ${address.slice(0, 6)}…${address.slice(-4)}.`);
+ await loadAccount();
+ } catch (err) {
+ setStatus('error', friendly(err));
+ } finally {
+ setBusy(false);
+ }
+ });
+
+ // ── Session panel ───────────────────────────────────────────────────
+ async function loadAccount() {
+ // Two distinct "signed out" shapes: no cookie at all returns
+ // 200 {"user":null}, while an expired or revoked cookie returns
+ // 401 invalid_session. Treat both as signed out.
+ const res = await call('/api/auth/me');
+ const { user } = res.ok ? await res.json().catch(() => ({})) : {};
+ if (!user) {
+ accountEl.dataset.visible = 'false';
+ return;
+ }
+ accountKv.replaceChildren();
+ for (const [key, value] of Object.entries(user ?? {})) {
+ if (value === null || value === undefined || value === '') continue;
+ const dt = document.createElement('dt');
+ dt.textContent = key;
+ const dd = document.createElement('dd');
+ dd.textContent = String(value);
+ accountKv.append(dt, dd);
+ }
+ accountEl.dataset.visible = 'true';
+ }
+
+ logoutBtn.addEventListener('click', async () => {
+ logoutBtn.disabled = true;
+ try {
+ await call('/api/auth/logout', { method: 'POST' });
+ accountEl.dataset.visible = 'false';
+ msgEl.textContent = '';
+ setStatus('idle', 'Signed out. Pick a chain to sign in again.');
+ } finally {
+ logoutBtn.disabled = false;
+ }
+ });
+
+ // ── Error shaping ───────────────────────────────────────────────────
+ // The verify endpoint returns a machine code; turn the ones a developer
+ // will actually hit into something that says what to change.
+ const CODES = {
+ invalid_domain: 'The signed domain does not match the deployment. Build the message from the nonce response, not location.host.',
+ invalid_uri: 'The signed URI origin does not match the deployment. Use the uri the nonce response returned.',
+ invalid_chain: 'Chain ID must be mainnet, devnet, or testnet.',
+ invalid_message: 'The message is not parseable. Check the line order and the blank lines.',
+ invalid_nonce: 'That nonce is unknown to the server. Request a fresh one.',
+ nonce_reused: 'That nonce was already used. Nonces are single use; request a fresh one.',
+ nonce_expired: 'The nonce expired. They last five minutes.',
+ expired: 'The message expiration time has passed.',
+ invalid_signature: 'The signature does not verify against that address.',
+ invalid_request: 'CSRF check failed. Send the csrf value from the nonce response as x-csrf-token.',
+ account_deleted: 'That wallet belongs to a deleted account.',
+ };
+
+ function describe(data) {
+ return CODES[data?.code] || data?.error_description || data?.error || 'Sign-in failed.';
+ }
+
+ function friendly(err) {
+ const raw = err?.message || String(err);
+ if (/reject|denied|cancel|refused/i.test(raw)) return 'Signature cancelled in the wallet.';
+ return raw;
+ }
+
+ // Reflect an existing session on load, so a refresh does not look signed out.
+ loadAccount().then(() => {
+ if (accountEl.dataset.visible === 'true') {
+ setStatus('ok', 'You already have a session on this origin.');
+ }
+ });
+ </script>
+ </body>
+</html>
diff --git a/packages/agentcore-payments-mcp/README.md b/packages/agentcore-payments-mcp/README.md
index 0a243b965..35804076e 100644
--- a/packages/agentcore-payments-mcp/README.md
+++ b/packages/agentcore-payments-mcp/README.md
@@ -121,6 +121,20 @@ The existing `pay_and_call` tool in `@three-ws/x402-mcp` now accepts `session_to
This routes the payment through `/api/pay/execute` instead of signing locally — the session's governance policy applies.
+## Examples
+
+Runnable, no-payment examples live in [`examples/`](./examples):
+
+```bash
+node examples/list-tools.mjs # every tool with its schema and safety annotations
+node examples/plan-a-session.mjs # read live x402 prices, print the policy to authorize
+```
+
+Neither one holds a wallet, reads a credential, or calls `pay_with_session`, so
+nothing is signed and nothing is spent. `plan-a-session.mjs` is the habit worth
+copying: read what an endpoint actually charges before you decide what budget to
+authorize. See [`examples/README.md`](./examples/README.md).
+
## Session lifecycle
```
diff --git a/packages/agentcore-payments-mcp/examples/README.md b/packages/agentcore-payments-mcp/examples/README.md
new file mode 100644
index 000000000..ba8cd51d6
--- /dev/null
+++ b/packages/agentcore-payments-mcp/examples/README.md
@@ -0,0 +1,134 @@
+# Examples: @three-ws/agentcore-payments-mcp
+
+Two runnable examples. Neither one spends money, needs a wallet, or needs an
+account, so you can run both before deciding whether to fund anything.
+
+| File | What it does | Run |
+|---|---|---|
+| [`list-tools.mjs`](list-tools.mjs) | Spawns this package's MCP server over stdio and prints all 5 tools with their input schemas and safety annotations. | `node examples/list-tools.mjs` |
+| [`plan-a-session.mjs`](plan-a-session.mjs) | Reads what live x402 endpoints actually charge (unpaid `402` probe), then prints the exact `create_payment_session` policy sized for your run. | `node examples/plan-a-session.mjs` |
+
+Run them from the package directory:
+
+```bash
+cd packages/agentcore-payments-mcp
+node examples/list-tools.mjs
+node examples/plan-a-session.mjs
+```
+
+## list-tools.mjs
+
+Runs the MCP `initialize` handshake against `node src/index.js`, calls
+`tools/list`, and formats every tool. Registration is env-free, so all five
+tools appear with no `THREE_WS_SESSION` or `PAYMENT_SESSION_TOKEN` set.
+
+Abridged output:
+
+```
+server: agentcore-payments-mcp v0.1.2 (stdio)
+capabilities: tools
+tools: 5
+
+1. create_payment_session
+ title: Create a funded agent payment session
+ hints: write, non-destructive, non-idempotent, closed-world
+ params:
+ - budget_usd (required; number)
+ Total budget in USD to allocate to this session (drawn from your credits). Min $0.001, max $1000.
+ ...
+
+2. pay_with_session
+ title: Pay an x402 endpoint via a payment session
+ hints: destructive, open-world
+ ...
+
+Tools that change state: create_payment_session, pay_with_session, cancel_payment_session
+Only pay_with_session moves funds, and only up to the session budget you set.
+```
+
+The `hints` line is worth reading rather than skimming. It is the tool's MCP
+[annotations](https://modelcontextprotocol.io/docs/concepts/tools), and it is
+what an MCP client uses to decide whether to prompt you before a call. Note that
+a tool whose four hints are all `false` (`create_payment_session`) is a
+deliberate declaration of a non-destructive, closed-world write, which is not
+the same thing as a tool that was never annotated. The example prints those two
+cases differently on purpose.
+
+## plan-a-session.mjs
+
+The habit this example exists to build: **read the price before you authorize a
+budget.** Sizing an envelope by guessing a round number gets it wrong in both
+directions, and the expensive direction drains quietly.
+
+It sends one unpaid request per endpoint, reads the price out of the `402`
+challenge, and stops. It never presents a payment.
+
+```bash
+# Default: one live three.ws endpoint at $0.001/call
+node examples/plan-a-session.mjs
+
+# Your own endpoints
+node examples/plan-a-session.mjs https://a.example/data https://b.example/feed
+
+# Size the plan for a bigger run
+CALLS_PER_ENDPOINT=500 node examples/plan-a-session.mjs
+```
+
+Output:
+
+```
+Reading prices for 1 endpoint(s). No payment is sent.
+
+ $0.001 https://three.ws/api/x402/model-check?url=https://three.ws/models/demo.glb
+ solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp, +2 other rail(s)
+
+25 call(s) per endpoint costs $0.025.
+With 25% headroom, the plan is:
+
+{
+ "budget_usd": 0.03125,
+ "label": "Planned run, 1 endpoint(s) x 25 calls",
+ "expiry_seconds": 3600,
+ "max_per_tx_usd": 0.002,
+ "allowed_hosts": ["three.ws"],
+ "network": "solana"
+}
+
+What this policy refuses, before any money moves:
+ a payment to any host outside three.ws allowlist_blocked
+ a single call priced above $0.002 per_tx_exceeded
+ the call that would push total spend past $0.03125 insufficient_budget
+ any call after the session expires or is cancelled session_inactive
+```
+
+Three details in how it prices:
+
+- **It quotes the Solana rail specifically.** Most endpoints advertise several
+ networks in one `402`. Payment sessions settle on Solana, so pricing off the
+ first `accepts[]` entry would quote a rail the session cannot pay on.
+- **An endpoint that answers without a `402` is reported as free** and left out
+ of the budget, because it consumes none.
+- **The plan is clamped to the limits the API enforces** ($0.001 to $1000 per
+ session, 50 allowlist entries) and tells you when clamping happened, so it
+ never prints a policy the server would reject.
+
+## The paid step
+
+Neither example spends. To actually run a session:
+
+1. Create it with the printed policy (`create_payment_session`, or
+ `POST /api/pay/session` with an API key). The token is returned **once**.
+2. Give the agent the token and nothing else.
+3. The agent calls `pay_with_session`. Governance runs before any money moves.
+4. Read the ledger with `check_payment_session` (`include_executions: true`).
+5. `cancel_payment_session` refunds the unspent remainder immediately.
+
+The full walkthrough with real request and response bodies is
+[Give an agent a spending envelope](https://three.ws/docs/tutorials/agent-spending-envelope).
+
+## Related
+
+- [Package README](../README.md): tools, env vars, session lifecycle, security properties
+- [Payment sessions](https://three.ws/docs/payment-sessions): the conceptual guide
+- [API reference](https://three.ws/docs/api-reference): every endpoint, field, and error code
+- [`@three-ws/x402-mcp`](../../x402-mcp): the other side, paying x402 endpoints with your own signer
diff --git a/packages/agentcore-payments-mcp/examples/list-tools.mjs b/packages/agentcore-payments-mcp/examples/list-tools.mjs
new file mode 100644
index 000000000..23ca13432
--- /dev/null
+++ b/packages/agentcore-payments-mcp/examples/list-tools.mjs
@@ -0,0 +1,128 @@
+// list-tools.mjs: print every tool @three-ws/agentcore-payments-mcp advertises,
+// with its input schema and its MCP annotation hints.
+//
+// Spawns this package's own server over stdio the way the README runs it
+// (`node src/index.js`), performs the MCP initialize handshake, calls
+// tools/list, and prints each tool.
+//
+// node examples/list-tools.mjs
+//
+// No credentials and no network: registration is env-free, so the server
+// advertises all five tools with no THREE_WS_SESSION or PAYMENT_SESSION_TOKEN
+// set. Nothing here can spend money.
+//
+// Read the hints column. `pay_with_session` is the only non-read-only tool that
+// moves funds, and it is the one an MCP client should surface a confirmation for.
+
+import { fileURLToPath } from 'node:url';
+
+import { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import {
+ StdioClientTransport,
+ getDefaultEnvironment,
+} from '@modelcontextprotocol/sdk/client/stdio.js';
+
+// The README's "Run standalone" entry point. Swap for
+// { command: 'npx', args: ['-y', '@three-ws/agentcore-payments-mcp'] } to
+// exercise the published package instead of this checkout.
+const SERVER_PATH = fileURLToPath(new URL('../src/index.js', import.meta.url));
+
+// Env this server reads (see src/config.js). getDefaultEnvironment() drops
+// everything else, so an example never leaks unrelated secrets to the child.
+const FORWARDED_ENV = [
+ 'THREE_WS_BASE',
+ 'THREE_WS_TIMEOUT_MS',
+ 'THREE_WS_SESSION',
+ 'PAYMENT_SESSION_TOKEN',
+];
+
+function childEnv() {
+ const env = getDefaultEnvironment();
+ for (const key of FORWARDED_ENV) {
+ const value = process.env[key];
+ if (value) env[key] = value;
+ }
+ return env;
+}
+
+/**
+ * One-line summary of a tool's MCP annotation hints.
+ *
+ * A tool whose four hints are all `false` is a deliberate declaration (a
+ * non-destructive, non-idempotent, closed-world write), not a missing one, so
+ * it must not read the same as a tool that was never annotated. An MCP client
+ * decides whether to prompt the user off exactly this distinction.
+ */
+function hints(annotations) {
+ if (!annotations) return 'UNANNOTATED (client must assume the worst)';
+ const flags = [];
+ if (annotations.readOnlyHint) flags.push('read-only');
+ if (annotations.destructiveHint) flags.push('destructive');
+ if (annotations.idempotentHint) flags.push('idempotent');
+ if (annotations.openWorldHint) flags.push('open-world');
+ if (flags.length) return flags.join(', ');
+ return 'write, non-destructive, non-idempotent, closed-world';
+}
+
+/** Render a JSON Schema property as one readable constraint string. */
+function constraints(prop) {
+ const parts = [prop.type ?? 'any'];
+ if (Array.isArray(prop.enum)) parts.push(`one of ${prop.enum.join(' | ')}`);
+ if (prop.default !== undefined) parts.push(`default ${JSON.stringify(prop.default)}`);
+ if (prop.minimum !== undefined) parts.push(`min ${prop.minimum}`);
+ if (prop.maximum !== undefined) parts.push(`max ${prop.maximum}`);
+ if (prop.minLength !== undefined) parts.push(`minLength ${prop.minLength}`);
+ if (prop.maxLength !== undefined) parts.push(`maxLength ${prop.maxLength}`);
+ return parts.join(', ');
+}
+
+function printTool(tool, index) {
+ const schema = tool.inputSchema ?? {};
+ const properties = schema.properties ?? {};
+ const required = new Set(schema.required ?? []);
+ const names = Object.keys(properties);
+
+ console.log(`\n${index}. ${tool.name}`);
+ if (tool.title) console.log(` title: ${tool.title}`);
+ console.log(` hints: ${hints(tool.annotations)}`);
+ if (tool.description) console.log(` ${tool.description}`);
+ if (names.length === 0) {
+ console.log(' params: none');
+ return;
+ }
+ console.log(' params:');
+ for (const name of names) {
+ const prop = properties[name];
+ const flag = required.has(name) ? 'required' : 'optional';
+ console.log(` - ${name} (${flag}; ${constraints(prop)})`);
+ if (prop.description) console.log(` ${prop.description}`);
+ }
+}
+
+const transport = new StdioClientTransport({
+ command: process.execPath,
+ args: [SERVER_PATH],
+ env: childEnv(),
+ stderr: 'inherit',
+});
+const client = new Client({
+ name: 'agentcore-payments-mcp-list-tools-example',
+ version: '1.0.0',
+});
+
+await client.connect(transport);
+
+const server = client.getServerVersion();
+console.log(`server: ${server?.name} v${server?.version} (stdio)`);
+console.log(`capabilities: ${Object.keys(client.getServerCapabilities() ?? {}).join(', ') || 'none'}`);
+
+const { tools } = await client.listTools();
+console.log(`tools: ${tools.length}`);
+
+tools.forEach((tool, i) => printTool(tool, i + 1));
+
+const spending = tools.filter((t) => t.annotations && t.annotations.readOnlyHint !== true);
+console.log(`\nTools that change state: ${spending.map((t) => t.name).join(', ') || 'none'}`);
+console.log('Only pay_with_session moves funds, and only up to the session budget you set.');
+
+await client.close();
diff --git a/packages/agentcore-payments-mcp/examples/plan-a-session.mjs b/packages/agentcore-payments-mcp/examples/plan-a-session.mjs
new file mode 100644
index 000000000..1bd4e285b
--- /dev/null
+++ b/packages/agentcore-payments-mcp/examples/plan-a-session.mjs
@@ -0,0 +1,174 @@
+// plan-a-session.mjs: read what an x402 endpoint really costs, then print the
+// exact create_payment_session policy sized for the run you are about to make.
+//
+// node examples/plan-a-session.mjs
+// node examples/plan-a-session.mjs "https://three.ws/api/x402/model-check?url=…x40"
+// node examples/plan-a-session.mjs https://a.example/one https://b.example/two
+//
+// Spends nothing. It sends one unpaid request per endpoint, reads the price out
+// of the 402 challenge the server answers with, and stops there. No wallet, no
+// credentials, no session is created.
+//
+// Why this exists: the first instinct when wiring an agent to paid tools is to
+// authorize a round number and find out the real cost later. That gets the
+// budget wrong in both directions, and the expensive direction is the one that
+// silently drains. Read the price first, then size the envelope to the run.
+//
+// The three numbers this produces map one-to-one onto the governor's checks
+// (api/_lib/pay/spend-governor.js):
+// budget_usd total spend ceiling for the whole run
+// max_per_tx_usd refuses a single call that costs more than you expected
+// allowed_hosts refuses a payment to anywhere you did not name
+
+const DEFAULT_ENDPOINTS = [
+ // $0.001 per call, live, Solana USDC. Returns structural stats for a 3D asset.
+ 'https://three.ws/api/x402/model-check?url=https://three.ws/models/demo.glb',
+];
+
+// How many times the planned agent run will call each endpoint. Change this to
+// match your workload; it is the only guess in the whole script.
+const CALLS_PER_ENDPOINT = Number(process.env.CALLS_PER_ENDPOINT || 25);
+
+// Headroom on the total, so a price change mid-run does not strand the agent.
+const BUDGET_HEADROOM = 1.25;
+
+// Ceilings the API enforces (api/_lib/pay/payment-session.js). Printing a plan
+// the server would reject helps nobody, so the plan is clamped and flagged here.
+const MIN_BUDGET_USD = 0.001;
+const MAX_BUDGET_USD = 1000;
+const MAX_ALLOWED_HOSTS = 50;
+
+const USDC_DECIMALS = 6;
+const TIMEOUT_MS = 15_000;
+
+function atomicsToUsd(amount) {
+ return Number(amount) / 10 ** USDC_DECIMALS;
+}
+
+function round(usd, places = 6) {
+ return Number(usd.toFixed(places));
+}
+
+/** Send one unpaid request and read the price out of the 402 body. */
+async function readPrice(url) {
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
+ let res;
+ try {
+ res = await fetch(url, {
+ headers: { accept: 'application/json' },
+ signal: controller.signal,
+ });
+ } catch (err) {
+ return { url, error: `unreachable: ${err?.message ?? err}` };
+ } finally {
+ clearTimeout(timer);
+ }
+
+ if (res.status !== 402) {
+ // Not a paid endpoint, or already free for this caller. Either way it
+ // consumes no budget, so it does not belong in the plan.
+ return { url, free: true, status: res.status };
+ }
+
+ let challenge;
+ try {
+ challenge = await res.json();
+ } catch {
+ return { url, error: 'answered 402 with an unreadable body' };
+ }
+
+ const accepts = Array.isArray(challenge.accepts) ? challenge.accepts : [];
+ if (accepts.length === 0) return { url, error: '402 carried no accepts[]' };
+
+ // The payment session settles on Solana, so price the Solana rail. Falling
+ // back to the first accept would quote a rail this session cannot pay.
+ const solana = accepts.find((a) => String(a?.network || '').startsWith('solana'));
+ if (!solana) {
+ return {
+ url,
+ error: `no Solana rail (offers: ${[...new Set(accepts.map((a) => a?.network))].join(', ')})`,
+ };
+ }
+
+ const atomics = solana.maxAmountRequired ?? solana.amount;
+ if (atomics == null) return { url, error: '402 Solana accept carried no amount' };
+
+ return {
+ url,
+ host: new URL(url).hostname,
+ priceUsd: atomicsToUsd(atomics),
+ network: solana.network,
+ payTo: solana.payTo ?? null,
+ otherRails: accepts.length - 1,
+ };
+}
+
+const endpoints = process.argv.slice(2).length ? process.argv.slice(2) : DEFAULT_ENDPOINTS;
+
+console.log(`Reading prices for ${endpoints.length} endpoint(s). No payment is sent.\n`);
+
+const quotes = await Promise.all(endpoints.map(readPrice));
+
+for (const q of quotes) {
+ if (q.error) {
+ console.log(` ✗ ${q.url}\n ${q.error}`);
+ } else if (q.free) {
+ console.log(` free ${q.url}\n answered HTTP ${q.status} with no 402, so it costs nothing`);
+ } else {
+ const rails = q.otherRails ? `, +${q.otherRails} other rail(s)` : '';
+ console.log(` $${q.priceUsd} ${q.url}\n ${q.network}${rails}`);
+ }
+}
+
+const priced = quotes.filter((q) => q.priceUsd != null);
+if (priced.length === 0) {
+ console.log('\nNothing priced, so there is no budget to plan. Nothing was spent.');
+ process.exit(0);
+}
+
+const perRun = priced.reduce((sum, q) => sum + q.priceUsd * CALLS_PER_ENDPOINT, 0);
+const dearest = priced.reduce((max, q) => Math.max(max, q.priceUsd), 0);
+const hosts = [...new Set(priced.map((q) => q.host))];
+
+const rawBudget = perRun * BUDGET_HEADROOM;
+const budgetUsd = round(Math.min(Math.max(rawBudget, MIN_BUDGET_USD), MAX_BUDGET_USD));
+// One dear call should not be able to eat the run. Double the dearest observed
+// price absorbs a repricing without authorizing an unbounded single payment.
+const maxPerTxUsd = round(dearest * 2);
+
+console.log(`\n${CALLS_PER_ENDPOINT} call(s) per endpoint costs $${round(perRun)}.`);
+console.log(`With ${Math.round((BUDGET_HEADROOM - 1) * 100)}% headroom, the plan is:\n`);
+
+const plan = {
+ budget_usd: budgetUsd,
+ label: `Planned run, ${priced.length} endpoint(s) x ${CALLS_PER_ENDPOINT} calls`,
+ expiry_seconds: 3600,
+ max_per_tx_usd: maxPerTxUsd,
+ allowed_hosts: hosts.slice(0, MAX_ALLOWED_HOSTS),
+ network: 'solana',
+};
+console.log(JSON.stringify(plan, null, 2));
+
+if (rawBudget < MIN_BUDGET_USD) {
+ console.log(`\nNote: the run costs less than the $${MIN_BUDGET_USD} minimum, so the budget was raised to it.`);
+}
+if (rawBudget > MAX_BUDGET_USD) {
+ console.log(`\nNote: the run exceeds the $${MAX_BUDGET_USD} per-session maximum. Split it across sessions.`);
+}
+if (hosts.length > MAX_ALLOWED_HOSTS) {
+ console.log(`\nNote: ${hosts.length} hosts exceeds the ${MAX_ALLOWED_HOSTS}-entry allowlist limit; the list was truncated.`);
+}
+
+console.log('\nPass that object to create_payment_session (or POST it to /api/pay/session).');
+console.log('The token comes back once. Give the agent the token and nothing else.');
+console.log('\nWhat this policy refuses, before any money moves:');
+for (const [reason, code] of [
+ [`a payment to any host outside ${hosts.join(', ')}`, 'allowlist_blocked'],
+ [`a single call priced above $${maxPerTxUsd}`, 'per_tx_exceeded'],
+ [`the call that would push total spend past $${budgetUsd}`, 'insufficient_budget'],
+ ['any call after the session expires or is cancelled', 'session_inactive'],
+]) {
+ console.log(` ${reason.padEnd(56)} ${code}`);
+}
+console.log();
diff --git a/pages/asl-alphabet.html b/pages/asl-alphabet.html
index aefbd4449..d6cacfe38 100644
--- a/pages/asl-alphabet.html
+++ b/pages/asl-alphabet.html
@@ -100,7 +100,7 @@
.aa-keys-section h2 { font-size: clamp(20px, 2.2vw, 27px); letter-spacing: -.02em; margin: 0 0 8px; }
.aa-keys-section > p { color: var(--ink-dim); font-size: 15px; line-height: 1.6; max-width: 68ch; margin: 0 0 18px; }
.aa-keys { display: grid; grid-template-columns: repeat(auto-fill, minmax(64px, 1fr)); gap: 10px; }
- .aa-keys.aa-keys-digits { grid-template-columns: repeat(auto-fill, minmax(56px, 1fr)); margin-top: 14px; max-width: 640px; }
+ .aa-keys.aa-keys-digits { grid-template-columns: repeat(10, minmax(0, 1fr)); margin-top: 14px; max-width: 700px; }
.aa-key {
appearance: none; cursor: pointer; font: inherit; font-weight: 600; font-size: 20px;
aspect-ratio: 1 / 1; border-radius: 14px; color: var(--ink-dim);
@@ -172,6 +172,12 @@
.aa-hero { grid-template-columns: 1fr; }
.aa-grid { grid-template-columns: 1fr; }
}
+ @media (max-width: 620px) {
+ .aa-keys { grid-template-columns: repeat(auto-fill, minmax(52px, 1fr)); gap: 8px; }
+ .aa-keys.aa-keys-digits { grid-template-columns: repeat(5, minmax(0, 1fr)); }
+ .aa-key { font-size: 17px; border-radius: 12px; }
+ .aa-big { width: 62px; height: 62px; font-size: 44px; }
+ }
</style>
</head>
<body>
@@ -217,7 +223,7 @@
</div>
<div class="aa-setting">
<span class="aa-setting-label" id="aa-hand-label">Signing hand</span>
- <div class="aa-opts" id="aa-hand" role="group" aria-labelledby="aa-hand-label"></div>
+ <div class="aa-opts" id="aa-hand-opts" role="group" aria-labelledby="aa-hand-label"></div>
</div>
<div class="aa-setting">
<span class="aa-setting-label" id="aa-rig-label">Avatar</span>
diff --git a/pages/avatar-cli.html b/pages/avatar-cli.html
new file mode 100644
index 000000000..56f83bc99
--- /dev/null
+++ b/pages/avatar-cli.html
@@ -0,0 +1,449 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <script>/* three.ws theme boot - no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Avatar CLI &middot; @three-ws/avatar-cli &middot; three.ws</title>
+ <meta
+ name="description"
+ content="Terminal-native tooling for on-chain avatars. Scaffold a hash-anchored avatar manifest from a wallet and a GLB, validate it against the schema, and print an embed snippet. Offline, deterministic, CI-safe."
+ />
+ <meta name="theme-color" content="#000000" />
+
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:title" content="Avatar CLI &middot; @three-ws/avatar-cli" />
+ <meta
+ property="og:description"
+ content="Scaffold, validate, hash, and preview avatar manifests from your shell. No account, no API key, no network call."
+ />
+ <meta property="og:url" content="https://three.ws/avatar-cli" />
+ <meta property="og:image" content="https://three.ws/api/page-og?s=build&amp;t=Avatar+CLI&amp;d=Terminal-native+tooling+for+on-chain+avatars%3A+scaffold%2C+validate%2C+hash%2C+and+preview+avatar+manifests+from+your+shell.&amp;p=%2Favatar-cli" />
+ <meta name="twitter:card" content="summary_large_image" />
+ <meta name="twitter:title" content="Avatar CLI &middot; three.ws" />
+ <meta name="twitter:description" content="Scaffold, validate, hash, and preview avatar manifests from your shell." />
+ <meta name="twitter:site" content="@trythreews" />
+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=build&amp;t=Avatar+CLI&amp;d=Terminal-native+tooling+for+on-chain+avatars%3A+scaffold%2C+validate%2C+hash%2C+and+preview+avatar+manifests+from+your+shell.&amp;p=%2Favatar-cli" />
+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />
+ <meta property="og:locale" content="en_US" />
+ <meta property="og:image:alt" content="Avatar CLI - three.ws" />
+
+ <link rel="canonical" href="https://three.ws/avatar-cli" />
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />
+ <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />
+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
+ <link rel="manifest" href="/manifest.webmanifest" />
+ <link rel="stylesheet" href="/style.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/footer.css" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <link rel="stylesheet" href="/mobile.css" />
+ <link rel="stylesheet" href="/avatar-cli.css" />
+ <script defer src="/footer-newsletter.js"></script>
+
+ <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","name":"Avatar CLI","description":"Terminal-native tooling for on-chain avatars: scaffold, validate, hash, and preview avatar manifests from your shell.","url":"https://three.ws/avatar-cli","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}},{"@type":"SoftwareApplication","name":"@three-ws/avatar-cli","applicationCategory":"DeveloperApplication","operatingSystem":"Linux, macOS, Windows","offers":{"@type":"Offer","price":"0","priceCurrency":"USD"},"softwareVersion":"0.2.0","url":"https://www.npmjs.com/package/@three-ws/avatar-cli"}]}</script>
+ </head>
+ <body>
+ <header><div id="nav-container"></div></header>
+
+ <main>
+ <!-- Hero -->
+ <section class="cli-hero" aria-labelledby="cli-hero-title">
+ <div class="cli-hero-bg" aria-hidden="true">
+ <div class="cli-hero-orb a"></div>
+ <div class="cli-hero-orb b"></div>
+ <div class="cli-hero-grid"></div>
+ </div>
+
+ <div class="cli-wrap cli-hero-inner">
+ <div class="cli-hero-copy">
+ <div class="cli-badge">
+ <span class="cli-badge-dot" aria-hidden="true"></span>
+ npm &middot; @three-ws/avatar-cli
+ </div>
+
+ <h1 class="cli-h1" id="cli-hero-title">
+ Avatars belong in your<br /><em>build pipeline</em>.
+ </h1>
+
+ <p class="cli-sub">
+ Scaffold a hash-anchored avatar manifest from a wallet and a GLB, validate it
+ against the published schema, and print an embed snippet that actually renders.
+ <strong>Offline, deterministic, and safe to put in a release script.</strong>
+ </p>
+
+ <div class="cli-install">
+ <div class="cli-install-cmd" role="group" aria-label="Install command">
+ <span class="cli-prompt" aria-hidden="true">$</span>
+ <code class="cli-cmd-text" id="install-cmd">npm install -g @three-ws/avatar-cli</code>
+ <button class="cli-copy" data-copy-target="install-cmd" aria-label="Copy install command">
+ <svg class="cli-copy-icon" width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true"><rect x="5.5" y="5.5" width="8" height="9" rx="1.5" stroke="currentColor" stroke-width="1.4"/><path d="M10.5 3.5v-1a1 1 0 0 0-1-1h-7a1 1 0 0 0-1 1v9a1 1 0 0 0 1 1h1" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/></svg>
+ <span class="cli-copy-label">Copy</span>
+ </button>
+ </div>
+ <p class="cli-install-alt">
+ or run it once with <code>npx @three-ws/avatar-cli</code>
+ </p>
+ </div>
+
+ <div class="cli-ctas">
+ <a href="/docs/avatar-cli" class="cli-btn cli-btn-primary">
+ Read the docs
+ <svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true"><path d="M3 7h8M7 3l4 4-4 4" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
+ </a>
+ <a href="/docs/tutorials/ship-an-avatar-manifest" class="cli-btn cli-btn-ghost">Tutorial</a>
+ <a href="https://github.com/nirholas/three.ws/tree/main/packages/avatar-cli" class="cli-btn cli-btn-ghost" target="_blank" rel="noopener">
+ <svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor" aria-hidden="true"><path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"/></svg>
+ Source
+ </a>
+ </div>
+
+ <dl class="cli-stats">
+ <div class="cli-stat">
+ <dt class="cli-stat-label">Runtime deps</dt>
+ <dd class="cli-stat-value">1</dd>
+ </div>
+ <div class="cli-stat">
+ <dt class="cli-stat-label">Network calls</dt>
+ <dd class="cli-stat-value">0</dd>
+ </div>
+ <div class="cli-stat">
+ <dt class="cli-stat-label">Commands</dt>
+ <dd class="cli-stat-value">4</dd>
+ </div>
+ <div class="cli-stat">
+ <dt class="cli-stat-label">Node</dt>
+ <dd class="cli-stat-value">18+</dd>
+ </div>
+ </dl>
+ </div>
+
+ <!-- Replayed terminal -->
+ <div class="cli-term-shell">
+ <div class="cli-term-glow" aria-hidden="true"></div>
+ <div class="cli-term" role="img" aria-label="Terminal session: init scaffolds a manifest, validate confirms it is schema-valid, preview prints an embed snippet.">
+ <div class="cli-term-bar">
+ <span class="cli-term-dot r"></span>
+ <span class="cli-term-dot y"></span>
+ <span class="cli-term-dot g"></span>
+ <span class="cli-term-title">three-ws-avatar</span>
+ <button class="cli-term-replay" type="button" aria-label="Replay the terminal session">
+ <svg width="13" height="13" viewBox="0 0 16 16" fill="none" aria-hidden="true"><path d="M14 8A6 6 0 1 1 8 2c1.9 0 3.58.88 4.68 2.26" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/><path d="M13 1.5V5h-3.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
+ Replay
+ </button>
+ </div>
+ <pre class="cli-term-body" id="cli-term-body" tabindex="0"></pre>
+ </div>
+ </div>
+ </div>
+ </section>
+
+ <!-- Commands -->
+ <section class="cli-section" id="commands" aria-labelledby="cli-commands-title">
+ <div class="cli-wrap">
+ <header class="cli-section-head">
+ <span class="cli-eyebrow">Four commands</span>
+ <h2 class="cli-h2" id="cli-commands-title">The whole surface area</h2>
+ <p class="cli-lede">
+ No config file, no project scaffold, no state directory. Each command does one
+ thing to one file and tells you what happened.
+ </p>
+ </header>
+
+ <div class="cli-cmd-grid">
+ <article class="cli-cmd-card">
+ <div class="cli-cmd-head">
+ <h3 class="cli-cmd-name"><code>init</code></h3>
+ <span class="cli-chip">writes</span>
+ </div>
+ <p class="cli-cmd-desc">
+ Scaffolds a schema-valid manifest from a wallet, a name, and a mesh file.
+ Reads the mesh once to compute its SHA-256 and size, so the document cannot
+ disagree with the bytes it was built from.
+ </p>
+ <pre class="cli-snip"><code>three-ws-avatar init \
+ --owner eip155:1:0x742d35Cc… \
+ --name "Nicholas" \
+ --mesh ./michelle.glb \
+ --skeleton mixamo \
+ --out manifest.json</code></pre>
+ </article>
+
+ <article class="cli-cmd-card">
+ <div class="cli-cmd-head">
+ <h3 class="cli-cmd-name"><code>validate</code></h3>
+ <span class="cli-chip">exits 0/1</span>
+ </div>
+ <p class="cli-cmd-desc">
+ Checks a manifest against <code>@three-ws/avatar-schema</code> and prints every
+ error at the instance path where it happened. Non-zero exit makes it a build
+ gate rather than a report.
+ </p>
+ <pre class="cli-snip"><code>$ three-ws-avatar validate broken.json
+<span class="e">✖ broken.json is invalid (7 errors)</span>
+ • / must have required property 'mesh'
+ • /id must match a schema in anyOf</code></pre>
+ </article>
+
+ <article class="cli-cmd-card">
+ <div class="cli-cmd-head">
+ <h3 class="cli-cmd-name"><code>hash</code></h3>
+ <span class="cli-chip">pipe-safe</span>
+ </div>
+ <p class="cli-cmd-desc">
+ Lowercase hex SHA-256 of a file, alone on stdout so it composes. The same
+ digest <code>init</code> writes into <code>mesh.sha256</code>, which is what
+ makes drift detection a one-line comparison.
+ </p>
+ <pre class="cli-snip"><code>$ sha=$(three-ws-avatar hash ./michelle.glb)
+$ echo "$sha"
+<span class="ok">28d788538f7b22b8e00c1d715fffc380…</span></code></pre>
+ </article>
+
+ <article class="cli-cmd-card">
+ <div class="cli-cmd-head">
+ <h3 class="cli-cmd-name"><code>preview</code></h3>
+ <span class="cli-chip">emits HTML</span>
+ </div>
+ <p class="cli-cmd-desc">
+ Validates, then prints a resolver URL, an <code>&lt;agent-3d&gt;</code> snippet
+ paired with the loader that registers it, and a zero-install iframe. Warns when
+ <code>mesh.uri</code> is still a local path.
+ </p>
+ <pre class="cli-snip"><code>$ three-ws-avatar preview manifest.json
+<span class="dim">› web component</span>
+&lt;script type="module" src="…/agent-3d.js"&gt;&lt;/script&gt;
+&lt;agent-3d src="…/michelle.glb"&gt;&lt;/agent-3d&gt;</code></pre>
+ </article>
+ </div>
+ </div>
+ </section>
+
+ <!-- Live proof -->
+ <section class="cli-section cli-section-alt" id="live" aria-labelledby="cli-live-title">
+ <div class="cli-wrap">
+ <header class="cli-section-head">
+ <span class="cli-eyebrow">Proof, not a promise</span>
+ <h2 class="cli-h2" id="cli-live-title">The snippet on the left is rendering on the right</h2>
+ <p class="cli-lede">
+ This is not a screenshot. The markup below is exactly what <code>preview</code>
+ prints, pasted into this page unmodified. If it ever stopped working, this
+ section would break in public.
+ </p>
+ </header>
+
+ <div class="cli-live">
+ <div class="cli-live-code">
+ <div class="cli-live-code-bar">
+ <span class="cli-live-code-label">preview output</span>
+ <button class="cli-copy cli-copy-sm" data-copy-target="live-snippet" aria-label="Copy the embed snippet">
+ <svg class="cli-copy-icon" width="13" height="13" viewBox="0 0 16 16" fill="none" aria-hidden="true"><rect x="5.5" y="5.5" width="8" height="9" rx="1.5" stroke="currentColor" stroke-width="1.4"/><path d="M10.5 3.5v-1a1 1 0 0 0-1-1h-7a1 1 0 0 0-1 1v9a1 1 0 0 0 1 1h1" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/></svg>
+ <span class="cli-copy-label">Copy</span>
+ </button>
+ </div>
+ <pre class="cli-snip cli-snip-lg"><code id="live-snippet">&lt;script type="module" src="/agent-3d/latest/agent-3d.js"&gt;&lt;/script&gt;
+&lt;agent-3d
+ src="https://three.ws/avatars/michelle.glb"
+ style="width:100%;height:420px"&gt;&lt;/agent-3d&gt;</code></pre>
+ <p class="cli-live-note">
+ Both lines matter. <code>&lt;agent-3d&gt;</code> is an unknown element until the
+ loader registers it, so pasting only the tag gives you an empty box with no
+ warning. That is why <code>preview</code> always prints them together.
+ </p>
+ </div>
+
+ <div class="cli-live-stage">
+ <div class="cli-live-stage-frame" id="live-stage" data-state="loading">
+ <div class="cli-live-skeleton" aria-hidden="true">
+ <div class="cli-live-skeleton-sheen"></div>
+ </div>
+ <p class="cli-live-fallback" role="status">
+ <span class="cli-live-fallback-title">Viewer unavailable</span>
+ <span class="cli-live-fallback-body">
+ The component loader did not register. The snippet is still correct;
+ see the <a href="/docs/web-component">web component reference</a>.
+ </span>
+ </p>
+ <script type="module" src="/agent-3d/latest/agent-3d.js"></script>
+ <agent-3d
+ src="https://three.ws/avatars/michelle.glb"
+ style="width:100%;height:420px"
+ ></agent-3d>
+ </div>
+ <p class="cli-live-caption">
+ <code>michelle.glb</code> &middot; Mixamo rig &middot; served from three.ws
+ </p>
+ </div>
+ </div>
+ </div>
+ </section>
+
+ <!-- Manifest anatomy -->
+ <section class="cli-section" id="manifest" aria-labelledby="cli-manifest-title">
+ <div class="cli-wrap">
+ <header class="cli-section-head">
+ <span class="cli-eyebrow">The artifact</span>
+ <h2 class="cli-h2" id="cli-manifest-title">What a manifest actually is</h2>
+ <p class="cli-lede">
+ Seven required fields. <code>uri</code> says where the mesh is, <code>sha256</code>
+ says what it must be. Those are different promises, and only the second one
+ survives someone re-uploading a different model to the same path.
+ </p>
+ </header>
+
+ <div class="cli-manifest">
+ <pre class="cli-snip cli-snip-lg cli-manifest-code"><code>{
+ <span class="k">"schemaVersion"</span>: <span class="n">1</span>,
+ <span class="k">"id"</span>: <span class="s">"eip155:1:0x742d35Cc6634C0532925a3b844Bc454e4438f44e"</span>,
+ <span class="k">"name"</span>: <span class="s">"Nicholas"</span>,
+ <span class="k">"mesh"</span>: {
+ <span class="k">"uri"</span>: <span class="s">"https://three.ws/avatars/michelle.glb"</span>,
+ <span class="k">"sha256"</span>: <span class="s">"28d788538f7b22b8e00c1d715fffc380bb06a304613d522c20523d3d6ff79bc2"</span>,
+ <span class="k">"format"</span>: <span class="s">"glb"</span>,
+ <span class="k">"kBytes"</span>: <span class="n">830</span>
+ },
+ <span class="k">"skeleton"</span>: <span class="s">"mixamo"</span>,
+ <span class="k">"owner"</span>: {
+ <span class="k">"chain"</span>: <span class="s">"eip155:1"</span>,
+ <span class="k">"address"</span>: <span class="s">"0x742d35Cc6634C0532925a3b844Bc454e4438f44e"</span>
+ },
+ <span class="k">"createdAt"</span>: <span class="s">"2026-07-30T19:23:34.595Z"</span>
+}</code></pre>
+
+ <ul class="cli-field-list">
+ <li class="cli-field">
+ <span class="cli-field-name">id</span>
+ <span class="cli-field-note">A CAIP-10 account, or a name service handle ending in <code>.eth</code>, <code>.ws</code>, or <code>.sol</code>.</span>
+ </li>
+ <li class="cli-field">
+ <span class="cli-field-name">mesh.sha256</span>
+ <span class="cli-field-note">Content address for the model. The field that catches a silent re-export.</span>
+ </li>
+ <li class="cli-field">
+ <span class="cli-field-name">skeleton</span>
+ <span class="cli-field-note">One of <code>avaturn</code>, <code>mixamo</code>, <code>rpm</code>, <code>vrm-humanoid</code>, <code>custom</code>. Decides which animation library retargets onto the rig.</span>
+ </li>
+ <li class="cli-field">
+ <span class="cli-field-name">owner</span>
+ <span class="cli-field-note">Chain-scoped account, so ownership is unambiguous off-platform.</span>
+ </li>
+ </ul>
+
+ <p class="cli-manifest-more">
+ Five optional fields the schema also accepts:
+ <code>animations</code>, <code>accessories</code>, <code>traits</code>,
+ <code>creator</code>, and <code>signature</code>. The last one is the interesting
+ one: everything else is a claim you are making, while a signature is a claim
+ someone else can verify without trusting your server.
+ </p>
+ </div>
+ </div>
+ </section>
+
+ <!-- Release gate -->
+ <section class="cli-section cli-section-alt" id="ci" aria-labelledby="cli-ci-title">
+ <div class="cli-wrap">
+ <header class="cli-section-head">
+ <span class="cli-eyebrow">In your release</span>
+ <h2 class="cli-h2" id="cli-ci-title">Fail the build, not the page</h2>
+ <p class="cli-lede">
+ A manifest that is only correct on the day you wrote it is a document, not a
+ guarantee. Two checks turn it into one. Neither needs network access.
+ </p>
+ </header>
+
+ <div class="cli-gate-grid">
+ <article class="cli-gate">
+ <h3 class="cli-gate-title">
+ <span class="cli-gate-num">01</span>
+ Did the mesh change?
+ </h3>
+ <pre class="cli-snip"><code>expected=$(node -p "require('./manifest.json').mesh.sha256")
+actual=$(three-ws-avatar hash ./michelle.glb)
+[ "$expected" = "$actual" ] || {
+ echo "mesh hash mismatch"; exit 1;
+}</code></pre>
+ <p class="cli-gate-note">
+ Catches the re-export nobody mentioned, the lossy optimization pass, the
+ teammate who swapped the model and kept the filename, and the CDN that
+ started serving an error page with a <code>200</code>.
+ </p>
+ </article>
+
+ <article class="cli-gate">
+ <h3 class="cli-gate-title">
+ <span class="cli-gate-num">02</span>
+ Is every manifest still valid?
+ </h3>
+ <pre class="cli-snip"><code>find . -name '*.avatar.json' \
+ -not -path './node_modules/*' -print0 \
+ | xargs -0 -n1 three-ws-avatar validate</code></pre>
+ <p class="cli-gate-note">
+ <code>xargs</code> exits non-zero if any single invocation failed, so one bad
+ manifest fails the whole step. Wire it into whatever already runs on release.
+ </p>
+ </article>
+ </div>
+ </div>
+ </section>
+
+ <!-- Next -->
+ <section class="cli-section" id="next" aria-labelledby="cli-next-title">
+ <div class="cli-wrap">
+ <header class="cli-section-head">
+ <span class="cli-eyebrow">Keep going</span>
+ <h2 class="cli-h2" id="cli-next-title">Where to next</h2>
+ </header>
+
+ <div class="cli-next-grid">
+ <a class="cli-next-card" href="/docs/avatar-cli">
+ <h3 class="cli-next-title">CLI reference</h3>
+ <p class="cli-next-desc">Every flag, exit code, and <code>--json</code> shape, command by command.</p>
+ <span class="cli-next-go" aria-hidden="true">Read
+ <svg width="13" height="13" viewBox="0 0 14 14" fill="none"><path d="M3 7h8M7 3l4 4-4 4" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
+ </span>
+ </a>
+ <a class="cli-next-card" href="/docs/tutorials/ship-an-avatar-manifest">
+ <h3 class="cli-next-title">Ship an avatar manifest</h3>
+ <p class="cli-next-desc">The guided path: raw GLB to a live embed, with the reasoning at each step.</p>
+ <span class="cli-next-go" aria-hidden="true">Start
+ <svg width="13" height="13" viewBox="0 0 14 14" fill="none"><path d="M3 7h8M7 3l4 4-4 4" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
+ </span>
+ </a>
+ <a class="cli-next-card" href="/docs/web-component">
+ <h3 class="cli-next-title">Web component</h3>
+ <p class="cli-next-desc">Everything <code>&lt;agent-3d&gt;</code> does beyond a body: voice, brain, memory, skills.</p>
+ <span class="cli-next-go" aria-hidden="true">Explore
+ <svg width="13" height="13" viewBox="0 0 14 14" fill="none"><path d="M3 7h8M7 3l4 4-4 4" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
+ </span>
+ </a>
+ <a class="cli-next-card" href="/avatar-sdk">
+ <h3 class="cli-next-title">Avatar SDK</h3>
+ <p class="cli-next-desc">The browser half: web component, React bindings, creator iframe, uploads.</p>
+ <span class="cli-next-go" aria-hidden="true">Open
+ <svg width="13" height="13" viewBox="0 0 14 14" fill="none"><path d="M3 7h8M7 3l4 4-4 4" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
+ </span>
+ </a>
+ </div>
+ </div>
+ </section>
+ </main>
+
+ <footer class="h-footer-horizon" role="contentinfo" aria-label="Site footer">
+ <div class="h-footer-glow-line" aria-hidden="true"></div>
+ <div class="h-footer-floor" aria-hidden="true"></div>
+ <div id="footer-content"></div>
+ </footer>
+
+ <script src="/nav.js" defer></script>
+ <script type="module" src="/src/avatar-cli-page.js"></script>
+ <script src="/brand.js" defer></script>
+ <div id="footer-container"></div>
+ <script src="/footer.js"></script>
+ <!-- Runtime i18n: detects locale, swaps annotated copy, mounts <lang-switcher>. -->
+ <script type="module" src="/i18n.js"></script>
+ </body>
+</html>
diff --git a/pages/guards.html b/pages/guards.html
new file mode 100644
index 000000000..840fa4be2
--- /dev/null
+++ b/pages/guards.html
@@ -0,0 +1,895 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <script>/* three.ws theme boot, no-flash */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
+ <title>Repository guards · three.ws</title>
+ <meta name="description" content="Every mechanical guard that protects the three.ws codebase, and the stage each one runs in. This repository has no CI, so correctness is enforced by fast local checks wired into the prebuild, the gate, the deploy build, and the git pre-push hook." />
+ <link rel="canonical" href="https://three.ws/guards" />
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
+ <link rel="manifest" href="/manifest.webmanifest" />
+ <link rel="stylesheet" href="/style.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/mobile.css" />
+ <meta property="og:type" content="website" />
+ <meta property="og:title" content="Repository guards · three.ws" />
+ <meta property="og:description" content="No CI, by necessity. Every check that protects this codebase, what it protects, and the stage it runs in." />
+ <meta property="og:url" content="https://three.ws/guards" />
+ <meta property="og:image" content="https://three.ws/api/page-og?s=build&amp;t=Repository+guards&amp;d=Every+mechanical+check+that+protects+the+three.ws+codebase%2C+and+the+stage+each+one+runs+in.&amp;p=%2Fguards" />
+ <meta name="twitter:card" content="summary_large_image" />
+ <meta name="twitter:title" content="Repository guards · three.ws" />
+ <meta name="twitter:description" content="No CI, by necessity. Every check that protects this codebase, and where it runs." />
+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=build&amp;t=Repository+guards&amp;d=Every+mechanical+check+that+protects+the+three.ws+codebase%2C+and+the+stage+each+one+runs+in.&amp;p=%2Fguards" />
+ <style>
+ :root {
+ --gd-bg: #07080c;
+ --gd-panel: rgba(17, 19, 27, 0.86);
+ --gd-panel-2: rgba(255, 255, 255, 0.028);
+ --gd-border: rgba(255, 255, 255, 0.09);
+ --gd-border-2: rgba(255, 255, 255, 0.17);
+ --gd-text: #e9ebf2;
+ --gd-muted: #8b91a3;
+ --gd-faint: #5d6374;
+ --gd-accent: #8b5cf6;
+ --gd-accent-soft: rgba(139, 92, 246, 0.14);
+ --gd-code-bg: rgba(255, 255, 255, 0.05);
+ --gd-shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 12px 34px rgba(0, 0, 0, 0.34);
+ /* One hue per stage, reused for chip, badge and card accent. */
+ --gd-prebuild: #38bdf8;
+ --gd-gate: #a78bfa;
+ --gd-deploy: #fbbf24;
+ --gd-prepush: #34d399;
+ --gd-manual: #94a3b8;
+ }
+
+ html[data-theme='light'] {
+ --gd-bg: #f7f8fb;
+ --gd-panel: #ffffff;
+ --gd-panel-2: rgba(15, 18, 30, 0.026);
+ --gd-border: rgba(15, 18, 30, 0.1);
+ --gd-border-2: rgba(15, 18, 30, 0.2);
+ --gd-text: #131722;
+ --gd-muted: #5b6274;
+ --gd-faint: #838a9c;
+ --gd-accent: #6d33e0;
+ --gd-accent-soft: rgba(109, 51, 224, 0.1);
+ --gd-code-bg: rgba(15, 18, 30, 0.05);
+ --gd-shadow: 0 1px 2px rgba(15, 18, 30, 0.06), 0 10px 30px rgba(15, 18, 30, 0.07);
+ --gd-prebuild: #0284c7;
+ --gd-gate: #6d33e0;
+ --gd-deploy: #b45309;
+ --gd-prepush: #047857;
+ --gd-manual: #55607a;
+ }
+
+ body {
+ background: var(--gd-bg);
+ color: var(--gd-text);
+ }
+
+ .gd-wrap {
+ max-width: 1180px;
+ margin: 0 auto;
+ padding: clamp(1.5rem, 4vw, 3rem) clamp(1rem, 4vw, 2rem) 5rem;
+ }
+
+ /* Hero */
+ .gd-hero {
+ position: relative;
+ border: 1px solid var(--gd-border);
+ border-radius: 20px;
+ background:
+ radial-gradient(120% 150% at 8% -20%, var(--gd-accent-soft), transparent 62%),
+ var(--gd-panel);
+ padding: clamp(1.5rem, 4vw, 2.6rem);
+ overflow: hidden;
+ box-shadow: var(--gd-shadow);
+ }
+
+ .gd-eyebrow {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.5rem;
+ font-size: 0.72rem;
+ letter-spacing: 0.09em;
+ text-transform: uppercase;
+ font-weight: 600;
+ color: var(--gd-accent);
+ background: var(--gd-accent-soft);
+ border: 1px solid color-mix(in srgb, var(--gd-accent) 32%, transparent);
+ border-radius: 999px;
+ padding: 0.3rem 0.7rem;
+ margin-bottom: 1rem;
+ }
+
+ .gd-hero h1 {
+ margin: 0 0 0.7rem;
+ font-size: clamp(1.85rem, 4.6vw, 3rem);
+ line-height: 1.08;
+ letter-spacing: -0.02em;
+ }
+
+ .gd-hero p {
+ margin: 0;
+ max-width: 62ch;
+ color: var(--gd-muted);
+ font-size: clamp(0.98rem, 1.6vw, 1.1rem);
+ line-height: 1.62;
+ }
+
+ .gd-hero a {
+ color: var(--gd-text);
+ text-decoration: underline;
+ text-underline-offset: 3px;
+ text-decoration-color: color-mix(in srgb, var(--gd-accent) 55%, transparent);
+ }
+
+ .gd-hero a:hover { text-decoration-color: var(--gd-accent); }
+
+ /* Stat rail */
+ .gd-stats {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
+ gap: 0.75rem;
+ margin-top: 1.7rem;
+ }
+
+ .gd-stat {
+ border: 1px solid var(--gd-border);
+ border-radius: 13px;
+ background: var(--gd-panel-2);
+ padding: 0.85rem 1rem;
+ }
+
+ .gd-stat-n {
+ font-size: 1.7rem;
+ font-weight: 700;
+ line-height: 1;
+ font-variant-numeric: tabular-nums;
+ letter-spacing: -0.02em;
+ }
+
+ .gd-stat-l {
+ margin-top: 0.32rem;
+ font-size: 0.76rem;
+ color: var(--gd-faint);
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+ }
+
+ /* Controls */
+ .gd-controls {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.7rem;
+ align-items: center;
+ justify-content: space-between;
+ margin: 2.4rem 0 1.1rem;
+ }
+
+ .gd-chips { display: flex; flex-wrap: wrap; gap: 0.45rem; }
+
+ .gd-chip {
+ font: inherit;
+ font-size: 0.84rem;
+ font-weight: 500;
+ color: var(--gd-muted);
+ background: var(--gd-panel-2);
+ border: 1px solid var(--gd-border);
+ border-radius: 999px;
+ padding: 0.42rem 0.85rem;
+ cursor: pointer;
+ transition: color 0.15s ease, border-color 0.15s ease, background 0.15s ease, transform 0.12s ease;
+ }
+
+ .gd-chip:hover { color: var(--gd-text); border-color: var(--gd-border-2); }
+ .gd-chip:active { transform: translateY(1px); }
+
+ .gd-chip[aria-pressed='true'] {
+ color: var(--gd-text);
+ background: var(--gd-accent-soft);
+ border-color: color-mix(in srgb, var(--gd-accent) 45%, transparent);
+ }
+
+ .gd-chip .gd-chip-n {
+ display: inline-block;
+ margin-left: 0.4rem;
+ font-variant-numeric: tabular-nums;
+ color: var(--gd-faint);
+ font-size: 0.78rem;
+ }
+
+ .gd-chip[aria-pressed='true'] .gd-chip-n { color: var(--gd-accent); }
+
+ .gd-search {
+ flex: 1 1 210px;
+ max-width: 320px;
+ font: inherit;
+ font-size: 0.88rem;
+ color: var(--gd-text);
+ background: var(--gd-panel-2);
+ border: 1px solid var(--gd-border);
+ border-radius: 10px;
+ padding: 0.52rem 0.8rem;
+ transition: border-color 0.15s ease;
+ }
+
+ .gd-search::placeholder { color: var(--gd-faint); }
+ .gd-search:hover { border-color: var(--gd-border-2); }
+
+ :where(.gd-chip, .gd-search, .gd-card-toggle, .gd-copy):focus-visible {
+ outline: 2px solid var(--gd-accent);
+ outline-offset: 2px;
+ }
+
+ /* Stage explainer */
+ .gd-stage-note {
+ border: 1px solid var(--gd-border);
+ border-left: 3px solid var(--gd-stage, var(--gd-accent));
+ border-radius: 12px;
+ background: var(--gd-panel-2);
+ padding: 0.85rem 1.05rem;
+ margin-bottom: 1.4rem;
+ font-size: 0.9rem;
+ line-height: 1.6;
+ color: var(--gd-muted);
+ }
+
+ .gd-stage-note strong { color: var(--gd-text); }
+
+ .gd-stage-note code {
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
+ font-size: 0.85em;
+ background: var(--gd-code-bg);
+ border-radius: 5px;
+ padding: 0.1rem 0.35rem;
+ }
+
+ /* Cards */
+ .gd-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(330px, 1fr));
+ gap: 0.9rem;
+ }
+
+ .gd-card {
+ position: relative;
+ display: flex;
+ flex-direction: column;
+ border: 1px solid var(--gd-border);
+ border-radius: 15px;
+ background: var(--gd-panel);
+ padding: 1.1rem 1.15rem;
+ transition: border-color 0.16s ease, transform 0.16s ease, box-shadow 0.16s ease;
+ }
+
+ .gd-card::before {
+ content: '';
+ position: absolute;
+ inset: 0 auto 0 0;
+ width: 3px;
+ border-radius: 15px 0 0 15px;
+ background: var(--gd-stage, var(--gd-accent));
+ opacity: 0.65;
+ }
+
+ .gd-card:hover {
+ border-color: var(--gd-border-2);
+ transform: translateY(-2px);
+ box-shadow: var(--gd-shadow);
+ }
+
+ .gd-card h3 {
+ margin: 0 0 0.15rem;
+ font-size: 1.02rem;
+ letter-spacing: -0.01em;
+ }
+
+ .gd-card-id {
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
+ font-size: 0.74rem;
+ color: var(--gd-faint);
+ margin-bottom: 0.7rem;
+ word-break: break-all;
+ }
+
+ .gd-protects {
+ margin: 0 0 0.85rem;
+ font-size: 0.9rem;
+ line-height: 1.58;
+ color: var(--gd-muted);
+ }
+
+ .gd-cmd {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ background: var(--gd-code-bg);
+ border: 1px solid var(--gd-border);
+ border-radius: 9px;
+ padding: 0.42rem 0.5rem 0.42rem 0.65rem;
+ margin-bottom: 0.85rem;
+ }
+
+ .gd-cmd code {
+ flex: 1;
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
+ font-size: 0.79rem;
+ color: var(--gd-text);
+ overflow-x: auto;
+ white-space: nowrap;
+ scrollbar-width: none;
+ }
+
+ .gd-cmd code::-webkit-scrollbar { display: none; }
+
+ .gd-copy {
+ flex: none;
+ font: inherit;
+ font-size: 0.72rem;
+ color: var(--gd-muted);
+ background: transparent;
+ border: 1px solid var(--gd-border);
+ border-radius: 6px;
+ padding: 0.2rem 0.45rem;
+ cursor: pointer;
+ transition: color 0.15s ease, border-color 0.15s ease;
+ }
+
+ .gd-copy:hover { color: var(--gd-text); border-color: var(--gd-border-2); }
+ .gd-copy[data-copied='true'] { color: var(--gd-prepush); border-color: var(--gd-prepush); }
+
+ .gd-badges { display: flex; flex-wrap: wrap; gap: 0.35rem; margin-bottom: 0.7rem; }
+
+ .gd-badge {
+ font-size: 0.7rem;
+ font-weight: 600;
+ letter-spacing: 0.03em;
+ text-transform: uppercase;
+ border-radius: 6px;
+ padding: 0.2rem 0.45rem;
+ color: var(--gd-b, var(--gd-manual));
+ background: color-mix(in srgb, var(--gd-b, var(--gd-manual)) 14%, transparent);
+ border: 1px solid color-mix(in srgb, var(--gd-b, var(--gd-manual)) 34%, transparent);
+ }
+
+ .gd-needs {
+ font-size: 0.72rem;
+ color: var(--gd-faint);
+ border: 1px dashed var(--gd-border-2);
+ border-radius: 6px;
+ padding: 0.2rem 0.45rem;
+ }
+
+ .gd-card-toggle {
+ margin-top: auto;
+ align-self: flex-start;
+ font: inherit;
+ font-size: 0.8rem;
+ font-weight: 500;
+ color: var(--gd-accent);
+ background: none;
+ border: none;
+ border-radius: 6px;
+ padding: 0.2rem 0;
+ cursor: pointer;
+ }
+
+ .gd-card-toggle:hover { text-decoration: underline; text-underline-offset: 3px; }
+
+ .gd-why {
+ margin: 0.6rem 0 0;
+ padding-top: 0.7rem;
+ border-top: 1px solid var(--gd-border);
+ font-size: 0.855rem;
+ line-height: 1.62;
+ color: var(--gd-muted);
+ }
+
+ .gd-why[hidden] { display: none; }
+
+ /* Loading, empty, error */
+ .gd-skeleton {
+ border: 1px solid var(--gd-border);
+ border-radius: 15px;
+ background: linear-gradient(100deg, var(--gd-panel-2) 30%, rgba(255, 255, 255, 0.06) 50%, var(--gd-panel-2) 70%);
+ background-size: 220% 100%;
+ animation: gd-shimmer 1.35s ease-in-out infinite;
+ height: 190px;
+ }
+
+ @keyframes gd-shimmer {
+ from { background-position: 180% 0; }
+ to { background-position: -40% 0; }
+ }
+
+ @media (prefers-reduced-motion: reduce) {
+ .gd-skeleton { animation: none; }
+ .gd-card, .gd-chip, .gd-copy { transition: none; }
+ .gd-card:hover { transform: none; }
+ }
+
+ .gd-state {
+ border: 1px solid var(--gd-border);
+ border-radius: 15px;
+ background: var(--gd-panel);
+ padding: 2.4rem 1.5rem;
+ text-align: center;
+ }
+
+ .gd-state h2 { margin: 0 0 0.5rem; font-size: 1.06rem; }
+
+ .gd-state p {
+ margin: 0 auto 1rem;
+ max-width: 46ch;
+ color: var(--gd-muted);
+ font-size: 0.92rem;
+ line-height: 1.6;
+ }
+
+ .gd-state button {
+ font: inherit;
+ font-size: 0.86rem;
+ color: var(--gd-text);
+ background: var(--gd-accent-soft);
+ border: 1px solid color-mix(in srgb, var(--gd-accent) 45%, transparent);
+ border-radius: 9px;
+ padding: 0.45rem 0.95rem;
+ cursor: pointer;
+ }
+
+ .gd-state button:hover { border-color: var(--gd-accent); }
+ .gd-state button:focus-visible { outline: 2px solid var(--gd-accent); outline-offset: 2px; }
+
+ /* Footer callout */
+ .gd-more {
+ margin-top: 2.6rem;
+ border: 1px solid var(--gd-border);
+ border-radius: 15px;
+ background: var(--gd-panel-2);
+ padding: 1.4rem 1.5rem;
+ }
+
+ .gd-more h2 { margin: 0 0 0.5rem; font-size: 1.05rem; }
+
+ .gd-more p {
+ margin: 0 0 0.9rem;
+ color: var(--gd-muted);
+ font-size: 0.92rem;
+ line-height: 1.62;
+ max-width: 64ch;
+ }
+
+ .gd-links { display: flex; flex-wrap: wrap; gap: 0.55rem; }
+
+ .gd-links a {
+ font-size: 0.86rem;
+ color: var(--gd-text);
+ text-decoration: none;
+ background: var(--gd-panel);
+ border: 1px solid var(--gd-border);
+ border-radius: 9px;
+ padding: 0.45rem 0.85rem;
+ transition: border-color 0.15s ease, transform 0.12s ease;
+ }
+
+ .gd-links a:hover { border-color: var(--gd-accent); transform: translateY(-1px); }
+ .gd-links a:focus-visible { outline: 2px solid var(--gd-accent); outline-offset: 2px; }
+
+ .gd-sr {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ padding: 0;
+ margin: -1px;
+ overflow: hidden;
+ clip: rect(0, 0, 0, 0);
+ white-space: nowrap;
+ border: 0;
+ }
+
+ @media (max-width: 560px) {
+ .gd-controls { flex-direction: column; align-items: stretch; }
+ .gd-search { max-width: none; }
+ .gd-grid { grid-template-columns: 1fr; }
+ }
+ </style>
+</head>
+<body>
+ <header class="site-header"><div id="nav-container"></div></header>
+ <script src="/nav.js"></script>
+
+ <main class="gd-wrap">
+ <section class="gd-hero">
+ <span class="gd-eyebrow">Engineering</span>
+ <h1>Repository guards</h1>
+ <p>
+ This codebase has no CI. What protects it instead is a set of small, fast checks wired into paths
+ nobody can skip: the prebuild, the gate, the deploy build, and the git pre-push hook. Every guard
+ below exists because something broke once. Read the
+ <a href="/docs/guards">full reference</a> or the
+ <a href="/docs/tutorials/write-a-guard">tutorial on writing one</a>.
+ </p>
+ <div class="gd-stats" id="gd-stats"></div>
+ </section>
+
+ <div class="gd-controls">
+ <div class="gd-chips" id="gd-chips" role="group" aria-label="Filter guards by stage"></div>
+ <label class="gd-sr" for="gd-search">Search guards</label>
+ <input
+ class="gd-search"
+ id="gd-search"
+ type="search"
+ placeholder="Search guards, commands, files"
+ autocomplete="off"
+ />
+ </div>
+
+ <p class="gd-stage-note" id="gd-stage-note" hidden></p>
+
+ <div id="gd-results" aria-live="polite">
+ <div class="gd-grid" id="gd-skeletons" aria-hidden="true">
+ <div class="gd-skeleton"></div>
+ <div class="gd-skeleton"></div>
+ <div class="gd-skeleton"></div>
+ <div class="gd-skeleton"></div>
+ <div class="gd-skeleton"></div>
+ <div class="gd-skeleton"></div>
+ </div>
+ <p class="gd-sr" id="gd-status">Loading the guard registry.</p>
+ </div>
+
+ <section class="gd-more">
+ <h2>Adding a guard</h2>
+ <p>
+ A guard that is not wired into an unavoidable path protects nothing. Write the checker, give it an npm
+ script, register it in <code>data/guards.json</code>, and wire it into a stage. Running
+ <code>npm run audit:guards</code> will tell you if the last two steps disagree.
+ </p>
+ <div class="gd-links">
+ <a href="/docs/tutorials/write-a-guard">Write a guard</a>
+ <a href="/docs/guards">Guard reference</a>
+ <a href="/docs/start-here">Start here</a>
+ </div>
+ </section>
+ </main>
+
+ <script type="module">
+ const STAGE_ORDER = ['prebuild', 'gate', 'build:gcp', 'pre-push', 'manual'];
+ const STAGE_COLOR = {
+ prebuild: 'var(--gd-prebuild)',
+ gate: 'var(--gd-gate)',
+ 'build:gcp': 'var(--gd-deploy)',
+ 'pre-push': 'var(--gd-prepush)',
+ manual: 'var(--gd-manual)',
+ };
+ const NEEDS_LABEL = {
+ none: 'offline',
+ network: 'needs network',
+ credentials: 'needs credentials',
+ browser: 'needs a browser',
+ gcloud: 'needs gcloud',
+ };
+
+ const els = {
+ stats: document.getElementById('gd-stats'),
+ chips: document.getElementById('gd-chips'),
+ search: document.getElementById('gd-search'),
+ note: document.getElementById('gd-stage-note'),
+ results: document.getElementById('gd-results'),
+ status: document.getElementById('gd-status'),
+ };
+
+ let registry = null;
+ let activeStage = 'all';
+ let query = '';
+
+ /** Sort by the stage rail order, then alphabetically, so the list is stable. */
+ function rank(guard) {
+ const stages = guard.stages || [];
+ const best = Math.min(...stages.map((s) => STAGE_ORDER.indexOf(s)).filter((i) => i >= 0), 99);
+ return best === Infinity ? 99 : best;
+ }
+
+ function matches(guard) {
+ if (activeStage !== 'all' && !(guard.stages || []).includes(activeStage)) return false;
+ if (!query) return true;
+ const hay = [guard.title, guard.id, guard.npm, guard.script, guard.protects, guard.why]
+ .filter(Boolean)
+ .join(' ')
+ .toLowerCase();
+ return hay.includes(query);
+ }
+
+ function stageLabel(id) {
+ const stage = (registry.stages || []).find((s) => s.id === id);
+ return stage ? stage.title : id;
+ }
+
+ function renderStats() {
+ const guards = registry.guards || [];
+ const automatic = guards.filter((g) => (g.stages || []).some((s) => s !== 'manual')).length;
+ const offline = guards.filter((g) => g.needs === 'none').length;
+ const tiles = [
+ { n: guards.length, l: 'Guards' },
+ { n: automatic, l: 'On an automatic path' },
+ { n: offline, l: 'Run with no credentials' },
+ { n: (registry.stages || []).length, l: 'Stages' },
+ ];
+ els.stats.replaceChildren(
+ ...tiles.map((t) => {
+ const d = document.createElement('div');
+ d.className = 'gd-stat';
+ const n = document.createElement('div');
+ n.className = 'gd-stat-n';
+ n.textContent = String(t.n);
+ const l = document.createElement('div');
+ l.className = 'gd-stat-l';
+ l.textContent = t.l;
+ d.append(n, l);
+ return d;
+ }),
+ );
+ }
+
+ function renderChips() {
+ const guards = registry.guards || [];
+ const defs = [{ id: 'all', title: 'All' }].concat(
+ STAGE_ORDER.filter((id) => guards.some((g) => (g.stages || []).includes(id))).map((id) => ({
+ id,
+ title: stageLabel(id),
+ })),
+ );
+ els.chips.replaceChildren(
+ ...defs.map((def) => {
+ const b = document.createElement('button');
+ b.type = 'button';
+ b.className = 'gd-chip';
+ b.setAttribute('aria-pressed', String(def.id === activeStage));
+ b.dataset.stage = def.id;
+ b.textContent = def.title;
+ const count = document.createElement('span');
+ count.className = 'gd-chip-n';
+ count.textContent = String(
+ def.id === 'all' ? guards.length : guards.filter((g) => (g.stages || []).includes(def.id)).length,
+ );
+ b.append(count);
+ if (def.id !== 'all') b.style.setProperty('--gd-accent', STAGE_COLOR[def.id]);
+ b.addEventListener('click', () => {
+ activeStage = def.id;
+ renderChips();
+ renderNote();
+ renderList();
+ });
+ return b;
+ }),
+ );
+ }
+
+ function renderNote() {
+ if (activeStage === 'all') {
+ els.note.hidden = true;
+ return;
+ }
+ const stage = (registry.stages || []).find((s) => s.id === activeStage);
+ if (!stage) {
+ els.note.hidden = true;
+ return;
+ }
+ els.note.hidden = false;
+ els.note.style.setProperty('--gd-stage', STAGE_COLOR[activeStage]);
+ els.note.replaceChildren();
+ const when = document.createElement('strong');
+ when.textContent = `${stage.title}: ${stage.when} `;
+ els.note.append(when, document.createTextNode(stage.description));
+ }
+
+ function card(guard) {
+ const el = document.createElement('article');
+ el.className = 'gd-card';
+ const primary = (guard.stages || []).find((s) => STAGE_ORDER.includes(s)) || 'manual';
+ el.style.setProperty('--gd-stage', STAGE_COLOR[primary]);
+
+ const h = document.createElement('h3');
+ h.textContent = guard.title;
+
+ const id = document.createElement('div');
+ id.className = 'gd-card-id';
+ id.textContent = guard.script;
+
+ const badges = document.createElement('div');
+ badges.className = 'gd-badges';
+ for (const s of guard.stages || []) {
+ const b = document.createElement('span');
+ b.className = 'gd-badge';
+ b.style.setProperty('--gd-b', STAGE_COLOR[s] || 'var(--gd-manual)');
+ b.textContent = stageLabel(s);
+ badges.append(b);
+ }
+ if (guard.needs && guard.needs !== 'none') {
+ const n = document.createElement('span');
+ n.className = 'gd-needs';
+ n.textContent = NEEDS_LABEL[guard.needs] || guard.needs;
+ badges.append(n);
+ }
+
+ const protects = document.createElement('p');
+ protects.className = 'gd-protects';
+ protects.textContent = guard.protects;
+
+ el.append(h, id, badges, protects);
+
+ if (guard.npm) {
+ const cmd = document.createElement('div');
+ cmd.className = 'gd-cmd';
+ const code = document.createElement('code');
+ const text = `npm run ${guard.npm}`;
+ code.textContent = text;
+ const copy = document.createElement('button');
+ copy.type = 'button';
+ copy.className = 'gd-copy';
+ copy.textContent = 'Copy';
+ copy.setAttribute('aria-label', `Copy ${text}`);
+ copy.addEventListener('click', async () => {
+ try {
+ await navigator.clipboard.writeText(text);
+ copy.dataset.copied = 'true';
+ copy.textContent = 'Copied';
+ } catch {
+ // Clipboard is unavailable over plain HTTP or when the user denied it.
+ // Select the text instead so the copy is still one keystroke away.
+ const range = document.createRange();
+ range.selectNodeContents(code);
+ const sel = window.getSelection();
+ sel.removeAllRanges();
+ sel.addRange(range);
+ copy.textContent = 'Selected';
+ }
+ setTimeout(() => {
+ copy.textContent = 'Copy';
+ delete copy.dataset.copied;
+ }, 1600);
+ });
+ cmd.append(code, copy);
+ el.append(cmd);
+ }
+
+ const why = document.createElement('p');
+ why.className = 'gd-why';
+ why.textContent = guard.why;
+ why.hidden = true;
+ why.id = `why-${guard.id}`;
+
+ const toggle = document.createElement('button');
+ toggle.type = 'button';
+ toggle.className = 'gd-card-toggle';
+ toggle.textContent = 'Why it exists';
+ toggle.setAttribute('aria-expanded', 'false');
+ toggle.setAttribute('aria-controls', why.id);
+ toggle.addEventListener('click', () => {
+ const open = why.hidden;
+ why.hidden = !open;
+ toggle.setAttribute('aria-expanded', String(open));
+ toggle.textContent = open ? 'Hide' : 'Why it exists';
+ });
+
+ el.append(toggle, why);
+ return el;
+ }
+
+ function renderList() {
+ const guards = (registry.guards || [])
+ .filter(matches)
+ .sort((a, b) => rank(a) - rank(b) || a.title.localeCompare(b.title));
+
+ els.results.replaceChildren();
+
+ if (!guards.length) {
+ const empty = document.createElement('div');
+ empty.className = 'gd-state';
+ const h = document.createElement('h2');
+ h.textContent = 'No guard matches that';
+ const p = document.createElement('p');
+ p.textContent = query
+ ? `Nothing in the registry mentions "${query}". Try a command name like audit:docs, or a file like check-rules.`
+ : 'No guard runs in this stage yet.';
+ const b = document.createElement('button');
+ b.type = 'button';
+ b.textContent = 'Clear filters';
+ b.addEventListener('click', () => {
+ query = '';
+ activeStage = 'all';
+ els.search.value = '';
+ renderChips();
+ renderNote();
+ renderList();
+ });
+ empty.append(h, p, b);
+ els.results.append(empty);
+ announce('No guards match the current filter.');
+ return;
+ }
+
+ const grid = document.createElement('div');
+ grid.className = 'gd-grid';
+ grid.append(...guards.map(card));
+ els.results.append(grid);
+ announce(`${guards.length} guard${guards.length === 1 ? '' : 's'} shown.`);
+ }
+
+ function announce(message) {
+ const p = document.createElement('p');
+ p.className = 'gd-sr';
+ p.textContent = message;
+ els.results.append(p);
+ }
+
+ function renderError(detail) {
+ els.results.replaceChildren();
+ const box = document.createElement('div');
+ box.className = 'gd-state';
+ const h = document.createElement('h2');
+ h.textContent = 'The guard registry did not load';
+ const p = document.createElement('p');
+ p.textContent = `${detail} The registry is a static file, so this is usually a network blip. Reading it directly from the repository always works.`;
+ const b = document.createElement('button');
+ b.type = 'button';
+ b.textContent = 'Try again';
+ b.addEventListener('click', load);
+ const links = document.createElement('div');
+ links.className = 'gd-links';
+ links.style.justifyContent = 'center';
+ links.style.marginTop = '0.9rem';
+ const docs = document.createElement('a');
+ docs.href = '/docs/guards';
+ docs.textContent = 'Read the guard reference';
+ links.append(docs);
+ box.append(h, p, b, links);
+ els.results.append(box);
+ }
+
+ async function load() {
+ els.results.replaceChildren();
+ const skeletons = document.createElement('div');
+ skeletons.className = 'gd-grid';
+ skeletons.setAttribute('aria-hidden', 'true');
+ for (let i = 0; i < 6; i += 1) {
+ const s = document.createElement('div');
+ s.className = 'gd-skeleton';
+ skeletons.append(s);
+ }
+ els.results.append(skeletons);
+
+ try {
+ const res = await fetch('/guards.json', { headers: { accept: 'application/json' } });
+ if (!res.ok) throw new Error(`the server answered ${res.status}.`);
+ const data = await res.json();
+ if (!data || !Array.isArray(data.guards)) throw new Error('the response was not a guard registry.');
+ registry = data;
+ renderStats();
+ renderChips();
+ renderNote();
+ renderList();
+ } catch (err) {
+ renderError(err instanceof Error ? err.message : 'Something went wrong.');
+ }
+ }
+
+ let searchTimer;
+ els.search.addEventListener('input', (e) => {
+ clearTimeout(searchTimer);
+ const value = e.target.value.trim().toLowerCase();
+ searchTimer = setTimeout(() => {
+ query = value;
+ if (registry) renderList();
+ }, 120);
+ });
+
+ load();
+ </script>
+ <script type="module" src="/i18n.js"></script>
+</body>
+</html>
diff --git a/public/animations/thumbs/jog.webp b/public/animations/thumbs/jog.webp
new file mode 100644
index 000000000..aa37b5bad
Binary files /dev/null and b/public/animations/thumbs/jog.webp differ
diff --git a/public/animations/thumbs/nod.webp b/public/animations/thumbs/nod.webp
new file mode 100644
index 000000000..1dcbeb236
Binary files /dev/null and b/public/animations/thumbs/nod.webp differ
diff --git a/public/animations/thumbs/point.webp b/public/animations/thumbs/point.webp
new file mode 100644
index 000000000..2d22929c1
Binary files /dev/null and b/public/animations/thumbs/point.webp differ
diff --git a/public/animations/thumbs/shrug.webp b/public/animations/thumbs/shrug.webp
new file mode 100644
index 000000000..d834a6287
Binary files /dev/null and b/public/animations/thumbs/shrug.webp differ
diff --git a/public/animations/thumbs/sitidle.webp b/public/animations/thumbs/sitidle.webp
new file mode 100644
index 000000000..624107021
Binary files /dev/null and b/public/animations/thumbs/sitidle.webp differ
diff --git a/public/animations/thumbs/sitloop.webp b/public/animations/thumbs/sitloop.webp
new file mode 100644
index 000000000..80f5db5b3
Binary files /dev/null and b/public/animations/thumbs/sitloop.webp differ
diff --git a/public/animations/thumbs/think.webp b/public/animations/thumbs/think.webp
new file mode 100644
index 000000000..59cd9b45b
Binary files /dev/null and b/public/animations/thumbs/think.webp differ
diff --git a/public/animations/thumbs/turn.webp b/public/animations/thumbs/turn.webp
new file mode 100644
index 000000000..3fac27edb
Binary files /dev/null and b/public/animations/thumbs/turn.webp differ
diff --git a/public/avatar-cli.css b/public/avatar-cli.css
new file mode 100644
index 000000000..bc2a651ee
--- /dev/null
+++ b/public/avatar-cli.css
@@ -0,0 +1,902 @@
+/* Avatar CLI landing page (/avatar-cli).
+ *
+ * Built entirely on the tokens in tokens.css, so light and dark themes come for
+ * free: no hardcoded hex, no theme-specific overrides below. Terminal chrome
+ * borrows the same surface/stroke ladder as the rest of the site rather than
+ * inventing a second one.
+ */
+
+.cli-wrap {
+ width: 100%;
+ max-width: 1180px;
+ margin: 0 auto;
+ padding: 0 var(--space-lg);
+}
+
+/* ── Hero ─────────────────────────────────────────────────────────────── */
+
+.cli-hero {
+ position: relative;
+ overflow: hidden;
+ padding: clamp(var(--space-2xl), 9vw, 7rem) 0 var(--space-2xl);
+ border-bottom: 1px solid var(--stroke);
+}
+
+.cli-hero-bg {
+ position: absolute;
+ inset: 0;
+ pointer-events: none;
+}
+
+.cli-hero-orb {
+ position: absolute;
+ border-radius: 50%;
+ filter: blur(90px);
+ opacity: 0.5;
+}
+
+.cli-hero-orb.a {
+ width: 34rem;
+ height: 34rem;
+ top: -12rem;
+ right: -8rem;
+ background: var(--accent-soft);
+}
+
+.cli-hero-orb.b {
+ width: 26rem;
+ height: 26rem;
+ bottom: -14rem;
+ left: -6rem;
+ background: var(--accent-soft);
+}
+
+.cli-hero-grid {
+ position: absolute;
+ inset: 0;
+ background-image:
+ linear-gradient(to right, var(--stroke) 1px, transparent 1px),
+ linear-gradient(to bottom, var(--stroke) 1px, transparent 1px);
+ background-size: 64px 64px;
+ mask-image: radial-gradient(ellipse 80% 60% at 50% 0%, #000 20%, transparent 78%);
+ -webkit-mask-image: radial-gradient(ellipse 80% 60% at 50% 0%, #000 20%, transparent 78%);
+ opacity: 0.7;
+}
+
+.cli-hero-inner {
+ position: relative;
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
+ gap: var(--space-2xl);
+ align-items: center;
+}
+
+.cli-badge {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--space-sm);
+ padding: var(--space-2xs) var(--space-sm);
+ border: 1px solid var(--stroke-strong);
+ border-radius: var(--radius-pill);
+ background: var(--surface-1);
+ color: var(--ink-dim);
+ font-family: var(--font-mono);
+ font-size: var(--text-2xs);
+ letter-spacing: 0.02em;
+}
+
+.cli-badge-dot {
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: var(--success);
+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--success) 22%, transparent);
+}
+
+.cli-h1 {
+ margin: var(--space-lg) 0 0;
+ font-family: var(--font-display);
+ font-size: clamp(2.1rem, 5.2vw, var(--text-2xl));
+ font-weight: var(--weight-bold);
+ line-height: var(--leading-tight);
+ letter-spacing: -0.02em;
+ color: var(--ink-bright);
+}
+
+.cli-h1 em {
+ font-style: italic;
+ color: var(--ink-dim);
+}
+
+.cli-sub {
+ margin: var(--space-md) 0 0;
+ max-width: 34rem;
+ font-size: var(--text-base);
+ line-height: var(--leading-normal);
+ color: var(--ink-dim);
+}
+
+.cli-sub strong {
+ color: var(--ink);
+ font-weight: var(--weight-medium);
+}
+
+/* Install command */
+
+.cli-install {
+ margin-top: var(--space-lg);
+}
+
+.cli-install-cmd {
+ display: flex;
+ align-items: center;
+ gap: var(--space-sm);
+ max-width: 30rem;
+ padding: var(--space-sm) var(--space-sm) var(--space-sm) var(--space-md);
+ border: 1px solid var(--stroke-strong);
+ border-radius: var(--radius-md);
+ background: var(--surface-1);
+ font-family: var(--font-mono);
+ font-size: var(--text-md);
+ transition: border-color 160ms ease, background 160ms ease;
+}
+
+.cli-install-cmd:hover {
+ border-color: var(--stroke-strong);
+ background: var(--surface-2);
+}
+
+.cli-prompt {
+ color: var(--ink-faint);
+ user-select: none;
+}
+
+.cli-cmd-text {
+ flex: 1 1 auto;
+ min-width: 0;
+ overflow-x: auto;
+ white-space: nowrap;
+ color: var(--ink);
+ scrollbar-width: none;
+}
+
+.cli-cmd-text::-webkit-scrollbar {
+ display: none;
+}
+
+.cli-copy {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--space-2xs);
+ flex: 0 0 auto;
+ padding: var(--space-2xs) var(--space-sm);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-sm);
+ background: var(--surface-2);
+ color: var(--ink-dim);
+ font-family: var(--font-body);
+ font-size: var(--text-2xs);
+ cursor: pointer;
+ transition: background 140ms ease, color 140ms ease, border-color 140ms ease;
+}
+
+.cli-copy:hover {
+ background: var(--surface-3);
+ color: var(--ink-bright);
+ border-color: var(--stroke-strong);
+}
+
+.cli-copy:active {
+ transform: translateY(1px);
+}
+
+.cli-copy:focus-visible,
+.cli-term-replay:focus-visible,
+.cli-next-card:focus-visible,
+.cli-btn:focus-visible {
+ outline: var(--focus-ring-width, 2px) solid var(--accent);
+ outline-offset: var(--focus-ring-offset, 2px);
+}
+
+.cli-copy[data-copied='true'] {
+ color: var(--success);
+ border-color: color-mix(in srgb, var(--success) 40%, transparent);
+}
+
+.cli-install-alt {
+ margin: var(--space-sm) 0 0;
+ font-size: var(--text-sm);
+ color: var(--ink-faint);
+}
+
+.cli-install-alt code,
+.cli-lede code,
+.cli-cmd-desc code,
+.cli-gate-note code,
+.cli-field-note code,
+.cli-manifest-more code,
+.cli-live-note code,
+.cli-next-desc code,
+.cli-live-caption code {
+ padding: 0.1em 0.36em;
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-sm);
+ background: var(--surface-1);
+ font-family: var(--font-mono);
+ font-size: 0.9em;
+ color: var(--ink);
+}
+
+/* Buttons */
+
+.cli-ctas {
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--space-sm);
+ margin-top: var(--space-lg);
+}
+
+.cli-btn {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--space-xs);
+ padding: var(--space-sm) var(--space-md);
+ border-radius: var(--radius-md);
+ font-size: var(--text-ui);
+ font-weight: var(--weight-medium);
+ text-decoration: none;
+ border: 1px solid transparent;
+ transition: background 150ms ease, color 150ms ease, border-color 150ms ease, transform 150ms ease;
+}
+
+.cli-btn:active {
+ transform: translateY(1px);
+}
+
+.cli-btn-primary {
+ background: var(--btn-primary-bg);
+ color: var(--btn-primary-fg);
+}
+
+.cli-btn-primary:hover {
+ background: var(--btn-primary-bg-hover);
+}
+
+.cli-btn-ghost {
+ background: transparent;
+ color: var(--ink);
+ border-color: var(--stroke-strong);
+}
+
+.cli-btn-ghost:hover {
+ background: var(--surface-2);
+ color: var(--ink-bright);
+}
+
+/* Stats */
+
+.cli-stats {
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--space-xl);
+ margin: var(--space-xl) 0 0;
+ padding-top: var(--space-lg);
+ border-top: 1px solid var(--stroke);
+}
+
+.cli-stat {
+ display: flex;
+ flex-direction: column-reverse;
+ gap: var(--space-3xs);
+}
+
+.cli-stat-value {
+ margin: 0;
+ font-family: var(--font-display);
+ font-size: var(--text-lg);
+ font-weight: var(--weight-semibold);
+ color: var(--ink-bright);
+ line-height: 1.1;
+}
+
+.cli-stat-label {
+ font-size: var(--text-2xs);
+ color: var(--ink-faint);
+ text-transform: uppercase;
+ letter-spacing: 0.07em;
+}
+
+/* ── Terminal ─────────────────────────────────────────────────────────── */
+
+.cli-term-shell {
+ position: relative;
+}
+
+.cli-term-glow {
+ position: absolute;
+ inset: 8% 6%;
+ border-radius: var(--radius-lg);
+ background: var(--accent-soft);
+ filter: blur(56px);
+ opacity: 0.6;
+ pointer-events: none;
+}
+
+.cli-term {
+ position: relative;
+ border: 1px solid var(--stroke-strong);
+ border-radius: var(--radius-lg);
+ background: var(--surface-1);
+ box-shadow: var(--shadow-2, 0 18px 50px rgba(0, 0, 0, 0.35));
+ overflow: hidden;
+ backdrop-filter: blur(12px);
+}
+
+.cli-term-bar {
+ display: flex;
+ align-items: center;
+ gap: var(--space-xs);
+ padding: var(--space-sm) var(--space-md);
+ border-bottom: 1px solid var(--stroke);
+ background: var(--surface-2);
+}
+
+.cli-term-dot {
+ width: 10px;
+ height: 10px;
+ border-radius: 50%;
+ opacity: 0.75;
+}
+
+.cli-term-dot.r { background: var(--danger); }
+.cli-term-dot.y { background: var(--warn); }
+.cli-term-dot.g { background: var(--success); }
+
+.cli-term-title {
+ flex: 1 1 auto;
+ text-align: center;
+ font-family: var(--font-mono);
+ font-size: var(--text-2xs);
+ color: var(--ink-faint);
+}
+
+.cli-term-replay {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--space-3xs);
+ padding: var(--space-3xs) var(--space-xs);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-sm);
+ background: transparent;
+ color: var(--ink-faint);
+ font-family: var(--font-body);
+ font-size: var(--text-2xs);
+ cursor: pointer;
+ opacity: 0;
+ transition: opacity 160ms ease, color 140ms ease, border-color 140ms ease;
+}
+
+.cli-term:hover .cli-term-replay,
+.cli-term-replay:focus-visible {
+ opacity: 1;
+}
+
+.cli-term-replay:hover {
+ color: var(--ink-bright);
+ border-color: var(--stroke-strong);
+}
+
+.cli-term-body {
+ margin: 0;
+ padding: var(--space-md);
+ min-height: 22rem;
+ max-height: 26rem;
+ overflow-y: auto;
+ font-family: var(--font-mono);
+ font-size: var(--text-sm);
+ line-height: var(--leading-normal);
+ color: var(--ink);
+ white-space: pre-wrap;
+ word-break: break-word;
+}
+
+.cli-term-body .p { color: var(--ink-faint); }
+.cli-term-body .c { color: var(--ink-bright); }
+.cli-term-body .ok { color: var(--success); }
+.cli-term-body .e { color: var(--danger); }
+.cli-term-body .w { color: var(--warn); }
+.cli-term-body .dim { color: var(--ink-faint); }
+
+.cli-caret {
+ display: inline-block;
+ width: 0.55em;
+ height: 1.05em;
+ margin-left: 1px;
+ vertical-align: text-bottom;
+ background: var(--ink);
+ animation: cli-blink 1s steps(1) infinite;
+}
+
+@keyframes cli-blink {
+ 0%, 50% { opacity: 1; }
+ 50.01%, 100% { opacity: 0; }
+}
+
+/* ── Sections ─────────────────────────────────────────────────────────── */
+
+.cli-section {
+ padding: var(--space-2xl) 0;
+ border-bottom: 1px solid var(--stroke);
+}
+
+.cli-section-alt {
+ background: var(--surface-1);
+}
+
+.cli-section-head {
+ max-width: 46rem;
+ margin-bottom: var(--space-xl);
+}
+
+.cli-eyebrow {
+ display: inline-block;
+ margin-bottom: var(--space-sm);
+ font-family: var(--font-mono);
+ font-size: var(--text-2xs);
+ text-transform: uppercase;
+ letter-spacing: 0.12em;
+ color: var(--ink-faint);
+}
+
+.cli-h2 {
+ margin: 0;
+ font-family: var(--font-display);
+ font-size: clamp(1.5rem, 3.4vw, var(--text-xl));
+ font-weight: var(--weight-semibold);
+ line-height: var(--leading-tight);
+ letter-spacing: -0.015em;
+ color: var(--ink-bright);
+}
+
+.cli-lede {
+ margin: var(--space-sm) 0 0;
+ font-size: var(--text-base);
+ line-height: var(--leading-normal);
+ color: var(--ink-dim);
+}
+
+/* ── Code snippets ────────────────────────────────────────────────────── */
+
+.cli-snip {
+ margin: 0;
+ padding: var(--space-md);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-md);
+ background: var(--surface-2);
+ font-family: var(--font-mono);
+ font-size: var(--text-sm);
+ line-height: var(--leading-normal);
+ color: var(--ink);
+ overflow-x: auto;
+ white-space: pre;
+ tab-size: 2;
+}
+
+.cli-snip-lg {
+ font-size: var(--text-md);
+}
+
+.cli-snip .k { color: var(--ink-bright); }
+.cli-snip .s { color: var(--success); }
+.cli-snip .n { color: var(--warn); }
+.cli-snip .e { color: var(--danger); }
+.cli-snip .ok { color: var(--success); }
+.cli-snip .dim { color: var(--ink-faint); }
+
+/* ── Command cards ────────────────────────────────────────────────────── */
+
+.cli-cmd-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(min(100%, 26rem), 1fr));
+ gap: var(--space-lg);
+}
+
+.cli-cmd-card {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-sm);
+ padding: var(--space-lg);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-lg);
+ background: var(--surface-1);
+ transition: border-color 180ms ease, transform 180ms ease, background 180ms ease;
+}
+
+.cli-cmd-card:hover {
+ border-color: var(--stroke-strong);
+ background: var(--surface-2);
+ transform: translateY(-2px);
+}
+
+.cli-cmd-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: var(--space-sm);
+}
+
+.cli-cmd-name {
+ margin: 0;
+ font-size: var(--text-lg);
+ font-weight: var(--weight-semibold);
+}
+
+.cli-cmd-name code {
+ font-family: var(--font-mono);
+ color: var(--ink-bright);
+}
+
+.cli-chip {
+ padding: var(--space-3xs) var(--space-xs);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-pill);
+ background: var(--surface-2);
+ font-family: var(--font-mono);
+ font-size: var(--text-2xs);
+ color: var(--ink-faint);
+ white-space: nowrap;
+}
+
+.cli-cmd-desc {
+ margin: 0;
+ font-size: var(--text-md);
+ line-height: var(--leading-normal);
+ color: var(--ink-dim);
+}
+
+.cli-cmd-card .cli-snip {
+ margin-top: auto;
+}
+
+/* ── Live proof ───────────────────────────────────────────────────────── */
+
+.cli-live {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
+ gap: var(--space-xl);
+ align-items: start;
+}
+
+.cli-live-code-bar {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: var(--space-sm);
+ padding: var(--space-xs) var(--space-sm);
+ border: 1px solid var(--stroke);
+ border-bottom: none;
+ border-radius: var(--radius-md) var(--radius-md) 0 0;
+ background: var(--surface-3);
+}
+
+.cli-live-code-label {
+ font-family: var(--font-mono);
+ font-size: var(--text-2xs);
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+ color: var(--ink-faint);
+}
+
+.cli-live-code .cli-snip {
+ border-radius: 0 0 var(--radius-md) var(--radius-md);
+}
+
+.cli-copy-sm {
+ padding: var(--space-3xs) var(--space-xs);
+}
+
+.cli-live-note,
+.cli-live-caption {
+ margin: var(--space-md) 0 0;
+ font-size: var(--text-sm);
+ line-height: var(--leading-normal);
+ color: var(--ink-faint);
+}
+
+.cli-live-caption {
+ text-align: center;
+ margin-top: var(--space-sm);
+}
+
+.cli-live-stage-frame {
+ position: relative;
+ border: 1px solid var(--stroke-strong);
+ border-radius: var(--radius-lg);
+ background: var(--surface-2);
+ overflow: hidden;
+ min-height: 420px;
+}
+
+.cli-live-stage-frame agent-3d {
+ display: block;
+ opacity: 0;
+ transition: opacity 420ms ease;
+}
+
+/* Three states: loading shows the skeleton, ready reveals the viewer, failed
+ swaps in a real explanation instead of an empty rectangle. */
+.cli-live-stage-frame[data-state='ready'] agent-3d { opacity: 1; }
+.cli-live-stage-frame[data-state='ready'] .cli-live-skeleton,
+.cli-live-stage-frame[data-state='failed'] .cli-live-skeleton { display: none; }
+.cli-live-stage-frame[data-state='failed'] agent-3d { display: none; }
+.cli-live-stage-frame:not([data-state='failed']) .cli-live-fallback { display: none; }
+
+.cli-live-skeleton {
+ position: absolute;
+ inset: 0;
+ background: var(--surface-3);
+ overflow: hidden;
+}
+
+.cli-live-skeleton-sheen {
+ position: absolute;
+ inset: 0;
+ background: linear-gradient(
+ 100deg,
+ transparent 20%,
+ color-mix(in srgb, var(--ink) 8%, transparent) 50%,
+ transparent 80%
+ );
+ transform: translateX(-100%);
+ animation: cli-sheen 1.6s ease-in-out infinite;
+}
+
+@keyframes cli-sheen {
+ to { transform: translateX(100%); }
+}
+
+.cli-live-fallback {
+ position: absolute;
+ inset: 0;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: var(--space-xs);
+ margin: 0;
+ padding: var(--space-lg);
+ text-align: center;
+}
+
+.cli-live-fallback-title {
+ font-weight: var(--weight-semibold);
+ color: var(--ink-bright);
+}
+
+.cli-live-fallback-body {
+ max-width: 22rem;
+ font-size: var(--text-sm);
+ color: var(--ink-dim);
+ line-height: var(--leading-normal);
+}
+
+/* ── Manifest ─────────────────────────────────────────────────────────── */
+
+.cli-manifest {
+ display: grid;
+ grid-template-columns: minmax(0, 1.35fr) minmax(0, 1fr);
+ gap: var(--space-xl);
+ align-items: start;
+}
+
+.cli-manifest-code {
+ grid-row: span 2;
+}
+
+.cli-field-list {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-md);
+ margin: 0;
+ padding: 0;
+ list-style: none;
+}
+
+.cli-field {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-3xs);
+ padding-left: var(--space-md);
+ border-left: 2px solid var(--stroke-strong);
+}
+
+.cli-field-name {
+ font-family: var(--font-mono);
+ font-size: var(--text-md);
+ color: var(--ink-bright);
+}
+
+.cli-field-note {
+ font-size: var(--text-sm);
+ line-height: var(--leading-normal);
+ color: var(--ink-dim);
+}
+
+.cli-manifest-more {
+ margin: 0;
+ font-size: var(--text-sm);
+ line-height: var(--leading-normal);
+ color: var(--ink-faint);
+}
+
+/* ── Release gate ─────────────────────────────────────────────────────── */
+
+.cli-gate-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(min(100%, 26rem), 1fr));
+ gap: var(--space-lg);
+}
+
+.cli-gate {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-md);
+ padding: var(--space-lg);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-lg);
+ background: var(--bg-0);
+}
+
+.cli-gate-title {
+ display: flex;
+ align-items: center;
+ gap: var(--space-sm);
+ margin: 0;
+ font-size: var(--text-lg);
+ font-weight: var(--weight-semibold);
+ color: var(--ink-bright);
+}
+
+.cli-gate-num {
+ font-family: var(--font-mono);
+ font-size: var(--text-sm);
+ color: var(--ink-faint);
+}
+
+.cli-gate-note {
+ margin: 0;
+ font-size: var(--text-sm);
+ line-height: var(--leading-normal);
+ color: var(--ink-dim);
+}
+
+/* ── Next ─────────────────────────────────────────────────────────────── */
+
+.cli-next-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(min(100%, 15rem), 1fr));
+ gap: var(--space-md);
+}
+
+.cli-next-card {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-xs);
+ padding: var(--space-lg);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-lg);
+ background: var(--surface-1);
+ text-decoration: none;
+ transition: border-color 180ms ease, transform 180ms ease, background 180ms ease;
+}
+
+.cli-next-card:hover {
+ border-color: var(--stroke-strong);
+ background: var(--surface-2);
+ transform: translateY(-2px);
+}
+
+.cli-next-title {
+ margin: 0;
+ font-size: var(--text-ui);
+ font-weight: var(--weight-semibold);
+ color: var(--ink-bright);
+}
+
+.cli-next-desc {
+ margin: 0;
+ flex: 1 1 auto;
+ font-size: var(--text-sm);
+ line-height: var(--leading-normal);
+ color: var(--ink-dim);
+}
+
+.cli-next-go {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--space-3xs);
+ margin-top: var(--space-xs);
+ font-size: var(--text-sm);
+ color: var(--ink-faint);
+ transition: gap 160ms ease, color 160ms ease;
+}
+
+.cli-next-card:hover .cli-next-go {
+ gap: var(--space-xs);
+ color: var(--ink-bright);
+}
+
+/* ── Reveal on scroll ─────────────────────────────────────────────────── */
+
+.cli-reveal {
+ opacity: 0;
+ transform: translateY(12px);
+ transition: opacity 520ms ease, transform 520ms ease;
+}
+
+.cli-reveal.is-in {
+ opacity: 1;
+ transform: none;
+}
+
+/* ── Responsive ───────────────────────────────────────────────────────── */
+
+@media (max-width: 940px) {
+ .cli-hero-inner,
+ .cli-live,
+ .cli-manifest {
+ grid-template-columns: minmax(0, 1fr);
+ }
+
+ .cli-manifest-code {
+ grid-row: auto;
+ }
+
+ .cli-term-body {
+ min-height: 18rem;
+ }
+
+ .cli-stats {
+ gap: var(--space-lg);
+ }
+}
+
+@media (max-width: 560px) {
+ .cli-wrap {
+ padding: 0 var(--space-md);
+ }
+
+ .cli-section {
+ padding: var(--space-xl) 0;
+ }
+
+ .cli-cmd-card,
+ .cli-gate,
+ .cli-next-card {
+ padding: var(--space-md);
+ }
+
+ .cli-stats {
+ gap: var(--space-md) var(--space-lg);
+ }
+}
+
+/* ── Reduced motion ───────────────────────────────────────────────────── */
+
+@media (prefers-reduced-motion: reduce) {
+ .cli-caret,
+ .cli-live-skeleton-sheen {
+ animation: none;
+ }
+
+ .cli-reveal {
+ opacity: 1;
+ transform: none;
+ transition: none;
+ }
+
+ .cli-cmd-card:hover,
+ .cli-next-card:hover {
+ transform: none;
+ }
+}
diff --git a/public/cookbook/recipes/asset_gate.py b/public/cookbook/recipes/asset_gate.py
new file mode 100644
index 000000000..ce2cb657b
--- /dev/null
+++ b/public/cookbook/recipes/asset_gate.py
@@ -0,0 +1,253 @@
+#!/usr/bin/env python3
+"""Quality-gate 3D assets in CI before they reach a user.
+
+Generated geometry fails quietly. A model can download fine, validate fine, and
+still be a 400k-triangle monster that drops a phone to 8fps, or a GLB whose
+materials never loaded. This gate inspects every asset against an explicit
+budget and exits non-zero when one busts it, so a bad asset fails the build
+instead of the launch.
+
+ python3 asset_gate.py model.glb # a local file
+ python3 asset_gate.py https://example.com/model.glb # or a URL
+ python3 asset_gate.py assets/*.glb --max-triangles 50000 --json report.json
+
+Exit codes: 0 all assets pass, 1 at least one failed, 2 the gate could not run.
+
+Standard library only. No API key, no account.
+
+Recipe: https://three.ws/cookbook/asset-quality-gate
+API reference: https://three.ws/docs/3d-api
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import sys
+import urllib.error
+import urllib.parse
+import urllib.request
+from dataclasses import asdict, dataclass, field
+from pathlib import Path
+
+INSPECT_API = "https://three.ws/api/3d/inspect"
+USER_AGENT = "three.ws-cookbook/asset_gate.py"
+
+# Defaults sized for a model that has to load over mobile data and render in a
+# web page next to other content. Override every one of them for your own bar.
+DEFAULTS = {
+ "max_triangles": 100_000,
+ "max_size_mb": 8.0,
+ "max_materials": 16,
+ "min_triangles": 100,
+ "require_textures": False,
+ "require_materials": False,
+}
+
+
+@dataclass
+class Report:
+ """One asset's verdict, plus the numbers the verdict was made from."""
+
+ asset: str
+ passed: bool = False
+ failures: list[str] = field(default_factory=list)
+ advisories: list[str] = field(default_factory=list)
+ stats: dict = field(default_factory=dict)
+ size_bytes: int = 0
+
+
+class GateError(RuntimeError):
+ """The gate itself could not run (network, unreadable file, bad response)."""
+
+
+def _post_bytes(url: str, filename: str, payload: bytes) -> dict:
+ """Upload a model by sending its raw bytes as the request body.
+
+ The inspect endpoint treats any non-JSON POST body as the model itself, so
+ there is no multipart envelope to build.
+ """
+ content_type = "model/gltf+json" if filename.endswith(".gltf") else "model/gltf-binary"
+ req = urllib.request.Request(
+ url,
+ data=payload,
+ headers={
+ "content-type": content_type,
+ "accept": "application/json",
+ "user-agent": USER_AGENT,
+ },
+ )
+ return _read_json(req)
+
+
+def _read_json(req: urllib.request.Request) -> dict:
+ try:
+ with urllib.request.urlopen(req, timeout=180) as res:
+ return json.loads(res.read().decode())
+ except urllib.error.HTTPError as exc:
+ raw = exc.read().decode(errors="replace")
+ try:
+ detail = json.loads(raw).get("error_description") or json.loads(raw).get("error")
+ except json.JSONDecodeError:
+ detail = raw[:200]
+ raise GateError(f"HTTP {exc.code} from the inspect API: {detail}") from exc
+ except urllib.error.URLError as exc:
+ raise GateError(f"could not reach the inspect API: {exc.reason}") from exc
+ except json.JSONDecodeError as exc:
+ raise GateError(f"the inspect API returned malformed JSON: {exc}") from exc
+
+
+def inspect(asset: str) -> dict:
+ """Inspect a local path or a URL and return the raw API payload."""
+ if asset.startswith(("http://", "https://")):
+ query = urllib.parse.urlencode({"url": asset})
+ req = urllib.request.Request(
+ f"{INSPECT_API}?{query}",
+ headers={"accept": "application/json", "user-agent": USER_AGENT},
+ )
+ return _read_json(req)
+
+ path = Path(asset)
+ if not path.is_file():
+ raise GateError(f"no such file: {asset}")
+ return _post_bytes(INSPECT_API, path.name, path.read_bytes())
+
+
+def evaluate(asset: str, payload: dict, budget: dict) -> Report:
+ """Turn an inspect payload plus a budget into a pass or fail verdict."""
+ stats = payload.get("stats") or {}
+ validation = payload.get("validation") or {}
+ size_bytes = int(payload.get("sizeBytes") or 0)
+ report = Report(asset=asset, stats=stats, size_bytes=size_bytes)
+
+ if not payload.get("valid", False):
+ report.failures.append("the file is not a valid glTF/GLB container")
+
+ errors = int(validation.get("numErrors") or 0)
+ if errors:
+ report.failures.append(f"glTF validator reported {errors} error(s)")
+
+ triangles = int(stats.get("triangles") or 0)
+ if triangles > budget["max_triangles"]:
+ report.failures.append(
+ f"{triangles:,} triangles exceeds the budget of {budget['max_triangles']:,}"
+ )
+ if triangles < budget["min_triangles"]:
+ report.failures.append(
+ f"only {triangles:,} triangles: generation probably collapsed "
+ f"(minimum {budget['min_triangles']:,})"
+ )
+
+ size_mb = size_bytes / 1_048_576
+ if size_mb > budget["max_size_mb"]:
+ report.failures.append(f"{size_mb:.1f} MB exceeds the budget of {budget['max_size_mb']:.1f} MB")
+
+ materials = int(stats.get("materials") or 0)
+ if materials > budget["max_materials"]:
+ report.failures.append(f"{materials} materials exceeds the budget of {budget['max_materials']}")
+
+ textures = int(stats.get("textures") or 0)
+ # Zero materials is NOT automatically broken. The free draft lane routinely
+ # ships vertex-colored geometry: color lives in a COLOR_0 attribute, so the
+ # model renders in full color with no material and no texture image. Treat
+ # it as something to look at, and let a caller who genuinely needs PBR
+ # materials opt into failing on it.
+ if materials == 0:
+ if budget["require_materials"]:
+ report.failures.append("no materials, and --require-materials was set")
+ else:
+ report.advisories.append(
+ "no materials: likely vertex-colored geometry, which renders in color "
+ "but ignores your lighting setup. Pass --require-materials to fail on it."
+ )
+ if budget["require_textures"] and textures == 0:
+ report.failures.append("no textures, and --require-textures was set")
+
+ warnings = int(validation.get("numWarnings") or 0)
+ if warnings:
+ report.advisories.append(f"glTF validator reported {warnings} warning(s)")
+ for rec in payload.get("recommendations") or []:
+ if rec.get("severity") in ("warn", "warning", "error"):
+ report.advisories.append(rec.get("issue", ""))
+
+ report.passed = not report.failures
+ return report
+
+
+def render_line(report: Report) -> str:
+ stats = report.stats
+ return (
+ f"{'PASS' if report.passed else 'FAIL'} {Path(report.asset).name[:44]:<44} "
+ f"{int(stats.get('triangles') or 0):>8,} tris "
+ f"{report.size_bytes / 1_048_576:>6.1f} MB "
+ f"{int(stats.get('materials') or 0):>2} mat "
+ f"{int(stats.get('textures') or 0):>2} tex"
+ )
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(
+ description="Fail the build when a 3D asset busts its budget.",
+ epilog="Docs: https://three.ws/docs/3d-api",
+ )
+ parser.add_argument("assets", nargs="+", help="local .glb paths or public URLs")
+ parser.add_argument("--max-triangles", type=int, default=DEFAULTS["max_triangles"])
+ parser.add_argument("--min-triangles", type=int, default=DEFAULTS["min_triangles"])
+ parser.add_argument("--max-size-mb", type=float, default=DEFAULTS["max_size_mb"])
+ parser.add_argument("--max-materials", type=int, default=DEFAULTS["max_materials"])
+ parser.add_argument(
+ "--require-textures",
+ action="store_true",
+ help="fail an asset that ships no texture images",
+ )
+ parser.add_argument(
+ "--require-materials",
+ action="store_true",
+ help="fail an asset with no glTF materials (rejects vertex-colored-only geometry)",
+ )
+ parser.add_argument("--json", help="also write the full report to this path")
+ args = parser.parse_args(argv)
+
+ budget = {
+ "max_triangles": args.max_triangles,
+ "min_triangles": args.min_triangles,
+ "max_size_mb": args.max_size_mb,
+ "max_materials": args.max_materials,
+ "require_textures": args.require_textures,
+ "require_materials": args.require_materials,
+ }
+
+ reports: list[Report] = []
+ for asset in args.assets:
+ try:
+ payload = inspect(asset)
+ except GateError as exc:
+ print(f"gate could not run on {asset}: {exc}", file=sys.stderr)
+ return 2
+ report = evaluate(asset, payload, budget)
+ reports.append(report)
+ print(render_line(report))
+ for failure in report.failures:
+ print(f" fail: {failure}")
+ for advisory in report.advisories:
+ print(f" note: {advisory}")
+
+ if args.json:
+ Path(args.json).write_text(
+ json.dumps({"budget": budget, "reports": [asdict(r) for r in reports]}, indent=2),
+ encoding="utf-8",
+ )
+
+ failed = [r for r in reports if not r.passed]
+ print(f"\n{len(reports) - len(failed)}/{len(reports)} assets passed the budget")
+ if failed and os.environ.get("GITHUB_STEP_SUMMARY"):
+ with open(os.environ["GITHUB_STEP_SUMMARY"], "a", encoding="utf-8") as summary:
+ summary.write(f"### 3D asset gate: {len(failed)} failed\n")
+ for report in failed:
+ summary.write(f"- `{report.asset}`: {'; '.join(report.failures)}\n")
+ return 1 if failed else 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/public/examples.css b/public/examples.css
index ff0f3b7c6..01ef9ea17 100644
--- a/public/examples.css
+++ b/public/examples.css
@@ -279,6 +279,389 @@
line-height: 1.5;
}
+/* The generated half of the page: every example found by scanning the repo.
+ Styled to sit under the curated snippets without competing with them, so the
+ cards are quieter than .exg-card and the grid is denser. */
+
+.exi-toolbar {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 12px;
+ align-items: center;
+ margin-top: 20px;
+}
+
+.exi-search-wrap {
+ position: relative;
+ flex: 1 1 240px;
+ max-width: 380px;
+}
+
+.exi-search-icon {
+ position: absolute;
+ left: 12px;
+ top: 50%;
+ transform: translateY(-50%);
+ color: var(--text-dim, #9a9aa4);
+ pointer-events: none;
+}
+
+.exi-search {
+ width: 100%;
+ padding: 9px 12px 9px 34px;
+ border-radius: 10px;
+ border: 1px solid var(--border, #26262e);
+ background: var(--surface, #131319);
+ color: var(--text, #ececf1);
+ font: inherit;
+ font-size: 14px;
+ outline: none;
+ transition:
+ border-color 0.15s ease,
+ box-shadow 0.15s ease;
+}
+
+.exi-search:hover {
+ border-color: var(--border-strong, #3a3a46);
+}
+
+.exi-search:focus-visible {
+ border-color: #7c8cff;
+ box-shadow: 0 0 0 3px rgba(124, 140, 255, 0.22);
+}
+
+.exi-count {
+ margin-left: auto;
+ font-size: 13px;
+ color: var(--text-dim, #9a9aa4);
+ font-variant-numeric: tabular-nums;
+}
+
+.exi-chips {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px;
+ margin: 16px 0 4px;
+}
+
+.exi-chip {
+ display: inline-flex;
+ align-items: center;
+ gap: 7px;
+ padding: 7px 13px;
+ border-radius: 999px;
+ cursor: pointer;
+ border: 1px solid var(--border, #26262e);
+ background: transparent;
+ color: var(--text-dim, #9a9aa4);
+ font: inherit;
+ font-size: 13px;
+ transition:
+ border-color 0.15s ease,
+ color 0.15s ease,
+ background 0.15s ease;
+}
+
+.exi-chip:hover {
+ border-color: var(--border-strong, #3a3a46);
+ color: var(--text, #ececf1);
+}
+
+.exi-chip:focus-visible {
+ outline: 2px solid #7c8cff;
+ outline-offset: 2px;
+}
+
+.exi-chip.is-active {
+ background: var(--text, #ececf1);
+ border-color: transparent;
+ color: var(--bg, #0b0b0f);
+ font-weight: 600;
+}
+
+.exi-chip-n {
+ font-size: 11px;
+ opacity: 0.7;
+ font-variant-numeric: tabular-nums;
+}
+
+.exi-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
+ gap: 14px;
+ margin-top: 18px;
+}
+
+.exi-card {
+ display: flex;
+ flex-direction: column;
+ gap: 9px;
+ border: 1px solid var(--border, #26262e);
+ border-radius: 12px;
+ padding: 16px;
+ transition:
+ border-color 0.15s ease,
+ transform 0.15s ease;
+}
+
+.exi-card:hover {
+ border-color: var(--border-strong, #3a3a46);
+ transform: translateY(-2px);
+}
+
+.exi-card:focus-within {
+ border-color: var(--border-strong, #3a3a46);
+}
+
+.exi-card-top {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+}
+
+.exi-kind {
+ font-size: 11px;
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+ color: var(--text-dim, #9a9aa4);
+}
+
+.exi-owner {
+ margin-left: auto;
+ font-size: 11px;
+ color: var(--text-dim, #9a9aa4);
+ border: 1px solid var(--border, #26262e);
+ border-radius: 999px;
+ padding: 2px 9px;
+}
+
+.exi-card-title {
+ margin: 0;
+ font-size: 16px;
+ line-height: 1.3;
+}
+
+.exi-card-title a {
+ color: inherit;
+ text-decoration: none;
+}
+
+.exi-card-title a:hover {
+ text-decoration: underline;
+}
+
+.exi-card-title a:focus-visible {
+ outline: 2px solid #7c8cff;
+ outline-offset: 3px;
+ border-radius: 4px;
+}
+
+.exi-card-desc {
+ margin: 0;
+ font-size: 13px;
+ line-height: 1.55;
+ color: var(--text-dim, #9a9aa4);
+}
+
+.exi-files {
+ list-style: none;
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+ margin: 0;
+ padding: 0;
+}
+
+.exi-files code {
+ font-size: 11.5px;
+ color: var(--text-dim, #9a9aa4);
+ background: var(--code-bg, #0f0f14);
+ border: 1px solid var(--border, #26262e);
+ border-radius: 5px;
+ padding: 2px 7px;
+}
+
+.exi-more {
+ font-size: 11.5px;
+ color: var(--text-dim, #9a9aa4);
+ align-self: center;
+}
+
+.exi-run {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ background: var(--code-bg, #0f0f14);
+ border: 1px solid var(--border, #26262e);
+ border-radius: 10px;
+ padding: 7px 7px 7px 11px;
+}
+
+.exi-run code {
+ flex: 1;
+ min-width: 0;
+ font-size: 12px;
+ color: var(--text, #ececf1);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.exi-copy {
+ flex: none;
+ cursor: pointer;
+ font: inherit;
+ font-size: 12px;
+ padding: 4px 10px;
+ border-radius: 6px;
+ border: 1px solid var(--border, #26262e);
+ background: transparent;
+ color: var(--text-dim, #9a9aa4);
+ transition:
+ color 0.15s ease,
+ border-color 0.15s ease;
+}
+
+.exi-copy:hover {
+ color: var(--text, #ececf1);
+ border-color: var(--border-strong, #3a3a46);
+}
+
+.exi-copy:focus-visible {
+ outline: 2px solid #7c8cff;
+ outline-offset: 2px;
+}
+
+.exi-copy.is-copied {
+ color: #38d39f;
+ border-color: #38d39f;
+}
+
+.exi-actions {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ flex-wrap: wrap;
+ margin-top: auto;
+ padding-top: 4px;
+}
+
+.exi-btn {
+ display: inline-flex;
+ align-items: center;
+ padding: 6px 13px;
+ border-radius: 9px;
+ font-size: 13px;
+ font-weight: 600;
+ text-decoration: none;
+ cursor: pointer;
+ font-family: inherit;
+ border: 1px solid transparent;
+ background: var(--text, #ececf1);
+ color: var(--bg, #0b0b0f);
+ transition:
+ filter 0.15s ease,
+ border-color 0.15s ease;
+}
+
+.exi-btn:hover {
+ filter: brightness(0.92);
+}
+
+.exi-btn:focus-visible {
+ outline: 2px solid #7c8cff;
+ outline-offset: 2px;
+}
+
+.exi-btn--ghost {
+ background: transparent;
+ color: var(--text, #ececf1);
+ border-color: var(--border, #26262e);
+}
+
+.exi-btn--ghost:hover {
+ filter: none;
+ border-color: var(--border-strong, #3a3a46);
+}
+
+.exi-path {
+ margin-left: auto;
+ font-size: 11px;
+ color: var(--text-dim, #9a9aa4);
+ max-width: 100%;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.exi-skeleton {
+ height: 180px;
+ border-radius: 12px;
+ border: 1px solid var(--border, #26262e);
+ background: linear-gradient(
+ 100deg,
+ var(--surface, #131319) 30%,
+ var(--code-bg, #0f0f14) 50%,
+ var(--surface, #131319) 70%
+ );
+ background-size: 200% 100%;
+ animation: exi-shimmer 1.3s infinite linear;
+}
+
+@keyframes exi-shimmer {
+ to {
+ background-position: -200% 0;
+ }
+}
+
+.exi-state {
+ text-align: center;
+ padding: 48px 20px;
+ color: var(--text-dim, #9a9aa4);
+}
+
+.exi-state h3 {
+ color: var(--text, #ececf1);
+ margin: 0 0 8px;
+ font-size: 18px;
+}
+
+.exi-state p {
+ max-width: 54ch;
+ margin: 0 auto 16px;
+}
+
+.exi-subhead {
+ font-size: 15px;
+ margin: 40px 0 0;
+ color: var(--text-dim, #9a9aa4);
+ font-weight: 600;
+ letter-spacing: 0.02em;
+}
+
+.exi-sr {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ padding: 0;
+ margin: -1px;
+ overflow: hidden;
+ clip: rect(0 0 0 0);
+ white-space: nowrap;
+ border: 0;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .exi-skeleton {
+ animation: none;
+ }
+
+ .exi-card:hover,
+ .exg-more-card:hover {
+ transform: none;
+ }
+}
+
@media (max-width: 640px) {
.exg-shell {
padding-top: 24px;
@@ -287,6 +670,31 @@
.exg-card {
padding: 18px;
}
+
+ .exi-grid {
+ grid-template-columns: 1fr;
+ }
+
+ .exi-count {
+ margin-left: 0;
+ }
+
+ .exi-path {
+ margin-left: 0;
+ width: 100%;
+ }
+}
+
+html[data-theme='light'] .exi-card,
+html[data-theme='light'] .exi-search {
+ background: #fff;
+ border-color: #e3e3ea;
+}
+
+html[data-theme='light'] .exi-run,
+html[data-theme='light'] .exi-files code {
+ background: #f5f5f8;
+ border-color: #e3e3ea;
}
html[data-theme='light'] .exg-pre {
diff --git a/public/examples.json b/public/examples.json
index 50c51e361..567b41003 100644
--- a/public/examples.json
+++ b/public/examples.json
@@ -2,10 +2,10 @@
"$comment": "Generated by scripts/build-examples-index.mjs from what is on disk. Do not edit by hand; run npm run build:examples.",
"generated_by": "scripts/build-examples-index.mjs",
"counts": {
- "total": 37,
+ "total": 39,
"html_demos": 10,
- "projects": 9,
- "packages": 18
+ "projects": 10,
+ "packages": 19
},
"examples": [
{
@@ -132,6 +132,36 @@
"runKind": "command",
"readme": "examples/three-concierge/README.md"
},
+ {
+ "id": "project:wallet-sign-in",
+ "kind": "project",
+ "group": "Example projects",
+ "title": "wallet-sign-in",
+ "description": "",
+ "path": "examples/wallet-sign-in",
+ "files": [
+ "index.html"
+ ],
+ "run": "npm run dev, then open /examples/wallet-sign-in/index.html",
+ "runKind": "command",
+ "readme": null
+ },
+ {
+ "id": "package:packages/agentcore-payments-mcp",
+ "kind": "package",
+ "group": "Package examples",
+ "title": "@three-ws/agentcore-payments-mcp",
+ "description": "MCP server for three.ws Agent Payment Sessions - govern agent x402 spending without exposing private keys.",
+ "path": "packages/agentcore-payments-mcp/examples",
+ "files": [
+ "list-tools.mjs",
+ "plan-a-session.mjs"
+ ],
+ "run": "node packages/agentcore-payments-mcp/examples/list-tools.mjs",
+ "runKind": "command",
+ "readme": null,
+ "owner": "packages/agentcore-payments-mcp"
+ },
{
"id": "package:assistant-sdk",
"kind": "package",
diff --git a/public/locales/localized-pages.json b/public/locales/localized-pages.json
index 5a15df85f..e9141e873 100644
--- a/public/locales/localized-pages.json
+++ b/public/locales/localized-pages.json
@@ -1,6 +1,6 @@
{
"generated": true,
- "count": 349,
+ "count": 350,
"paths": [
"/",
"/3d",
@@ -328,6 +328,7 @@
"/tour-builder",
"/tracker",
"/trades",
+ "/trading",
"/trending",
"/tutor",
"/tutorials",
diff --git a/public/tutorials-manifest.js b/public/tutorials-manifest.js
index 21ee1887a..39e726f0c 100644
--- a/public/tutorials-manifest.js
+++ b/public/tutorials-manifest.js
@@ -40,16 +40,6 @@
previewModel: '/avatars/selfie-girl.glb',
ctaPrimary: { label: 'Open the builder', href: '/assistant' },
},
- {
- slug: 'first-prompt-to-3d',
- tier: 'easy',
- title: 'Your first prompt to 3D in ChatGPT',
- blurb: 'Type one sentence into ChatGPT and get a real, textured 3D model back: spin it in the browser, download the GLB, and place it in your room through your phone camera. Free, no account, no API key.',
- builds: 'A generated 3D model, viewed and placed in AR, straight from ChatGPT',
- time: '10 min',
- previewModel: '/animations/robotexpressive.glb',
- ctaPrimary: { label: 'Open the 3D Studio', href: '/chatgpt' },
- },
{
slug: 'first-prompt-to-3d',
tier: 'easy',
@@ -58,7 +48,7 @@
builds: 'A generated 3D model, straight out of a ChatGPT conversation',
time: '5 min',
previewModel: '/animations/robotexpressive.glb',
- ctaPrimary: { label: 'Open the 3D Studio', href: '/chatgpt' },
+ ctaPrimary: { label: 'Open the 3D Studio', href: '/docs/chatgpt-3d-studio-gpt' },
},
{
slug: 'text-to-3d',
@@ -210,6 +200,16 @@
previewModel: '/avatars/realistic-female.glb',
ctaPrimary: { label: 'Open the Tour Builder', href: '/tour-builder' },
},
+ {
+ slug: 'shopify-shopping-assistant',
+ tier: 'easy',
+ title: 'Add a 3D AI shopping assistant to Shopify',
+ blurb: 'A floating chat with a rigged 3D avatar that answers questions, recommends real products from your live catalog, and helps shoppers check out. One script tag, no app install, no product feed to maintain.',
+ builds: 'A shopping assistant with a face, live on your Shopify store',
+ time: '12 min',
+ previewModel: '/avatars/realistic-female.glb',
+ ctaPrimary: { label: 'Open the Concierge', href: '/concierge' },
+ },
{
slug: 'sperax-tour',
tier: 'easy',
@@ -282,6 +282,16 @@
previewModel: '/animations/soldier.glb',
ctaPrimary: { label: 'Web component docs', href: '/docs#web-component' },
},
+ {
+ slug: 'build-a-site-concierge',
+ tier: 'middle',
+ title: 'Build a site concierge from the building blocks',
+ blurb: 'How the Concierge widget is assembled: the talking avatar, the streaming chat, the tool calls, and how to point the same parts at your own backend over Server-Sent Events.',
+ builds: 'Your own concierge widget, wired to your own backend',
+ time: '35 min',
+ previewModel: '/avatars/selfie-girl.glb',
+ ctaPrimary: { label: 'Open the Concierge', href: '/concierge' },
+ },
{
slug: 'trigger-from-page-events',
tier: 'middle',
@@ -482,7 +492,7 @@
builds: 'A revenue-generating MCP server any assistant can buy from',
time: '40 min',
previewModel: '/animations/robotexpressive.glb',
- ctaPrimary: { label: 'Read the deep dive', href: '/blog/monetize-mcp-server-x402-paid-tools' },
+ ctaPrimary: { label: 'Read the example code', href: 'https://github.com/nirholas/three.ws/tree/main/examples/paid-mcp-server' },
},
{
slug: 'agent-spending-envelope',
@@ -504,16 +514,6 @@
previewModel: '/animations/soldier.glb',
ctaPrimary: { label: 'Package on npm', href: 'https://www.npmjs.com/package/@three-ws/x402-server' },
},
- {
- slug: 'monetize-mcp-server',
- tier: 'advanced',
- title: 'Monetize an MCP server: charge per tool call',
- blurb: 'Build an MCP server that charges other people’s AI agents for its tools. One free tool, one paid tool, USDC on Solana, and the verify-work-settle ordering that means a failed call never takes money.',
- builds: 'A pay-per-call MCP server other agents can discover and buy from',
- time: '45 min',
- previewModel: '/animations/robotexpressive.glb',
- ctaPrimary: { label: 'Read the example code', href: 'https://github.com/nirholas/three.ws/tree/main/examples/paid-mcp-server' },
- },
{
slug: 'nvidia-nim-self-host',
tier: 'advanced',
@@ -624,6 +624,36 @@
previewModel: '/animations/soldier.glb',
ctaPrimary: { label: 'Open Mission Control', href: '/terminal' },
},
+ {
+ slug: 'read-the-trading-fleet',
+ tier: 'advanced',
+ title: 'Read the trading fleet: a working strategy vs a lucky one',
+ blurb: 'The numbers that feel most convincing are the ones that lie most often. Which single figure tells you a fleet is alive, why uptime is not it, and how to read the public ledger without arming anything.',
+ builds: 'The judgement to tell a real edge from a hot streak',
+ time: '25 min',
+ previewModel: '/animations/soldier.glb',
+ ctaPrimary: { label: 'Open the arena', href: '/arena' },
+ },
+ {
+ slug: 'ship-an-avatar-manifest',
+ tier: 'advanced',
+ title: 'Ship an avatar manifest',
+ blurb: 'Turn a raw GLB into a signed-off, hash-anchored manifest: one document that names the avatar, records the exact bytes of its mesh, declares its skeleton, and fails your build if the model ever silently changes.',
+ builds: 'A verifiable avatar artifact plus a release check that catches drift',
+ time: '30 min',
+ previewModel: '/avatars/mannequin.glb',
+ ctaPrimary: { label: 'Read the manifest spec', href: '/docs/agent-manifest' },
+ },
+ {
+ slug: 'write-a-guard',
+ tier: 'advanced',
+ title: 'Write a repository guard',
+ blurb: 'This repo has no CI, so a guard is the only thing between a mistake and production. Build one that fails the build when an API handler forgets its error boundary, wire it into the gate, cover it with tests, and register it.',
+ builds: 'A real guard running in the gate, listed on /guards',
+ time: '20 min',
+ previewModel: '/animations/robotexpressive.glb',
+ ctaPrimary: { label: 'Browse the guards', href: '/guards' },
+ },
];
const TIER_META = {
diff --git a/scripts/sync-tutorial-pages.mjs b/scripts/sync-tutorial-pages.mjs
new file mode 100644
index 000000000..fe4f7035c
--- /dev/null
+++ b/scripts/sync-tutorial-pages.mjs
@@ -0,0 +1,139 @@
+#!/usr/bin/env node
+// Keep the tutorial library, its markdown, and the page index in agreement.
+//
+// Three files have to say the same thing for a tutorial to be reachable and
+// indexable, and nothing was checking that they did:
+//
+// public/tutorials-manifest.js the library index and the viewer read this
+// docs/tutorials/<slug>.md the viewer fetches this at runtime
+// data/pages.json (learn) the sitemap, llms.txt, and features.json read this
+//
+// A tutorial missing from the manifest is unreachable from /tutorials. A manifest
+// entry with no markdown renders an empty page. A tutorial missing from
+// pages.json is invisible to search engines and to every downstream index.
+//
+// Usage:
+// node scripts/sync-tutorial-pages.mjs report drift, exit 1 if any (the gate)
+// node scripts/sync-tutorial-pages.mjs --write add missing pages.json entries
+
+import { readFile, writeFile } from 'node:fs/promises';
+import { readdirSync } from 'node:fs';
+import { execFileSync } from 'node:child_process';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const MANIFEST = path.join(ROOT, 'public/tutorials-manifest.js');
+const TUTORIAL_DIR = path.join(ROOT, 'docs/tutorials');
+const PAGES_JSON = path.join(ROOT, 'data/pages.json');
+
+const WRITE = process.argv.includes('--write');
+
+/** Read the manifest as data. It is a browser script, so parse the entries out of the source. */
+async function readManifest() {
+ const src = await readFile(MANIFEST, 'utf8');
+ const entries = [];
+ const blocks = src.split(/\n\t\t\{\n/).slice(1);
+ for (const block of blocks) {
+ const field = (name) => {
+ const match = block.match(new RegExp(`${name}: (['"\`])((?:\\\\.|(?!\\1).)*)\\1`));
+ return match ? match[2].replace(/\\'/g, "'").replace(/\\"/g, '"') : null;
+ };
+ const slug = field('slug');
+ if (!slug) continue;
+ entries.push({ slug, tier: field('tier'), title: field('title'), blurb: field('blurb') });
+ }
+ return entries;
+}
+
+function readTutorialSlugs() {
+ return readdirSync(TUTORIAL_DIR)
+ .filter((f) => f.endsWith('.md'))
+ .map((f) => f.replace(/\.md$/, ''))
+ .sort();
+}
+
+/** First commit date of the markdown file, so `added` reflects when it shipped. */
+function firstSeen(slug) {
+ try {
+ const out = execFileSync(
+ 'git',
+ ['log', '--diff-filter=A', '--follow', '--format=%ad', '--date=short', '--', `docs/tutorials/${slug}.md`],
+ { cwd: ROOT, encoding: 'utf8' },
+ ).trim();
+ const dates = out.split('\n').filter(Boolean);
+ return dates[dates.length - 1] || new Date().toISOString().slice(0, 10);
+ } catch {
+ return new Date().toISOString().slice(0, 10);
+ }
+}
+
+/** pages.json wants a sentence, and the manifest blurb is already written for humans. */
+function describe(entry) {
+ const blurb = (entry.blurb || '').trim();
+ if (!blurb) return `Step-by-step tutorial: ${entry.title}.`;
+ return blurb.length > 300 ? `${blurb.slice(0, 297)}...` : blurb;
+}
+
+function titleFor(entry) {
+ return entry.title.startsWith('Tutorial') ? entry.title : `Tutorial · ${entry.title}`;
+}
+
+async function main() {
+ const manifest = await readManifest();
+ const manifestSlugs = manifest.map((e) => e.slug);
+ const markdown = readTutorialSlugs();
+
+ const duplicates = manifestSlugs.filter((s, i) => manifestSlugs.indexOf(s) !== i);
+ const missingMarkdown = manifestSlugs.filter((s) => !markdown.includes(s));
+ const unlisted = markdown.filter((s) => !manifestSlugs.includes(s));
+
+ const data = JSON.parse(await readFile(PAGES_JSON, 'utf8'));
+ const learn = (data.sections || []).find((s) => s.id === 'learn');
+ if (!learn) throw new Error('data/pages.json has no "learn" section');
+ const registered = new Set(learn.pages.map((p) => p.path));
+
+ const added = [];
+ for (const entry of manifest) {
+ const pagePath = `/tutorials/${entry.slug}`;
+ if (registered.has(pagePath)) continue;
+ if (!markdown.includes(entry.slug)) continue; // a page with no content is not worth indexing
+ added.push({
+ path: pagePath,
+ title: titleFor(entry),
+ description: describe(entry),
+ priority: 0.8,
+ changefreq: 'monthly',
+ added: firstSeen(entry.slug),
+ });
+ }
+
+ if (added.length && WRITE) {
+ learn.pages.push(...added);
+ await writeFile(PAGES_JSON, `${JSON.stringify(data, null, '\t')}\n`);
+ }
+
+ const report = [];
+ report.push(`manifest entries: ${manifest.length} markdown files: ${markdown.length}`);
+ if (duplicates.length) report.push(`DUPLICATE manifest slugs: ${duplicates.join(', ')}`);
+ if (missingMarkdown.length) report.push(`manifest entry with no markdown: ${missingMarkdown.join(', ')}`);
+ if (unlisted.length) report.push(`markdown with no manifest entry (unreachable): ${unlisted.join(', ')}`);
+ report.push(
+ added.length
+ ? `pages.json: ${WRITE ? 'added' : 'missing'} ${added.length} tutorial entr${added.length === 1 ? 'y' : 'ies'}`
+ : 'pages.json: every tutorial is registered',
+ );
+ console.log(report.join('\n'));
+
+ const drift = duplicates.length || missingMarkdown.length || unlisted.length || (!WRITE && added.length);
+ if (drift && !WRITE) {
+ console.error('\nTutorial drift found. Fix the manifest, or run: node scripts/sync-tutorial-pages.mjs --write');
+ process.exitCode = 1;
+ }
+ if (duplicates.length || missingMarkdown.length) process.exitCode = 1;
+}
+
+main().catch((err) => {
+ console.error(`sync-tutorial-pages: ${err.message}`);
+ process.exit(1);
+});
diff --git a/src/asl-alphabet-page.js b/src/asl-alphabet-page.js
index abbda2380..63ea498c3 100644
--- a/src/asl-alphabet-page.js
+++ b/src/asl-alphabet-page.js
@@ -81,7 +81,9 @@ async function boot() {
// ── Stage ────────────────────────────────────────────────────────────────
const mountStage = async () => {
stage?.dispose();
- stage = new PoseStage(stageHost, { glbUrl: avatar.url });
+ // Portrait framing crops to the signing space: fingerspelling happens at
+ // jaw height, so a full-body shot would waste most of the frame on shoes.
+ stage = new PoseStage(stageHost, { glbUrl: avatar.url, framing: 'portrait' });
try {
const { supported } = await stage.mount();
stage.start();
@@ -123,15 +125,21 @@ async function boot() {
clearHighlights();
const marks = [];
let clip;
+ // One letter is a reference pose: it must stay up to be studied, so the
+ // hand does not settle back to rest at the end. A whole word does settle,
+ // the way a signer lowers their hand when the word is finished.
+ const single = letters.replace(/\s+/g, '').length === 1;
try {
- clip = buildFingerspellingClip(letters, { ...scaledTiming(rate), dominant, marks });
+ clip = buildFingerspellingClip(letters, { ...scaledTiming(rate), dominant, marks, settle: !single });
} catch (err) {
setStatus(err?.message || 'Could not build that spelling.');
return null;
}
const name = `aa-${token}`;
stage.anim.injectClip(name, clip, { loop: false });
- stage.anim.playOnce(name, {});
+ // A single letter holds its final frame so it can be studied and orbited;
+ // a word hands the avatar back to its idle when the spelling is done.
+ stage.anim.playOnce(name, single ? { settleTo: null } : {});
const startedAt = performance.now();
for (const mark of marks) {
@@ -378,7 +386,7 @@ async function boot() {
if (current) play(current, { describe: false });
});
buildOptions(
- '#aa-hand',
+ '#aa-hand-opts',
[
{ label: 'Right-handed', side: 'Right' },
{ label: 'Left-handed', side: 'Left' },
diff --git a/src/avatar-cli-page.js b/src/avatar-cli-page.js
new file mode 100644
index 000000000..3578b383a
--- /dev/null
+++ b/src/avatar-cli-page.js
@@ -0,0 +1,245 @@
+/**
+ * /avatar-cli page runtime.
+ *
+ * Three jobs: replay a real `three-ws-avatar` session in the hero terminal,
+ * wire the copy buttons, and drive the live viewer through loading → ready or
+ * failed so the section never sits as an empty rectangle.
+ *
+ * The transcript below is a verbatim capture of the CLI at 0.2.0, not a
+ * dramatization. If the CLI's output changes, this should be recaptured.
+ */
+
+const PROMPT = '$ ';
+
+/** One terminal line. `kind` maps to a class in avatar-cli.css. */
+const TRANSCRIPT = [
+ { kind: 'cmd', text: 'npm install -g @three-ws/avatar-cli' },
+ { kind: 'out', cls: 'dim', text: 'added 2 packages in 1s' },
+ { kind: 'gap' },
+ { kind: 'cmd', text: 'curl -sLO https://three.ws/avatars/michelle.glb' },
+ { kind: 'gap' },
+ {
+ kind: 'cmd',
+ text: 'three-ws-avatar init --owner eip155:1:0x742d35Cc… \\\n --name "Nicholas" --mesh ./michelle.glb --skeleton mixamo \\\n --mesh-uri https://three.ws/avatars/michelle.glb --out manifest.json',
+ },
+ { kind: 'out', cls: 'ok', text: '✔ wrote /home/you/manifest.json' },
+ { kind: 'out', cls: 'dim', text: ' • id eip155:1:0x742d35Cc6634C0532925a3b844Bc454e4438f44e' },
+ { kind: 'out', cls: 'dim', text: ' • skeleton mixamo' },
+ { kind: 'out', cls: 'dim', text: ' • mesh glb · 830 kB · sha256:28d788538f7b…' },
+ { kind: 'gap' },
+ { kind: 'cmd', text: 'three-ws-avatar validate manifest.json' },
+ { kind: 'out', cls: 'ok', text: '✔ manifest.json is valid' },
+ { kind: 'gap' },
+ { kind: 'cmd', text: 'three-ws-avatar preview manifest.json' },
+ { kind: 'out', cls: 'dim', text: '› web component (loader registers <agent-3d>)' },
+ { kind: 'out', text: '<script type="module" src="/agent-3d/latest/agent-3d.js"></script>' },
+ { kind: 'out', text: '<agent-3d src="https://three.ws/avatars/michelle.glb"></agent-3d>' },
+];
+
+const escapeHtml = (s) =>
+ s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
+
+const prefersReducedMotion = () =>
+ window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false;
+
+/** Full transcript as static markup, for reduced motion and for replay resets. */
+function renderStatic() {
+ return TRANSCRIPT.map((line) => {
+ if (line.kind === 'gap') return '';
+ if (line.kind === 'cmd') {
+ return `<span class="p">${PROMPT}</span><span class="c">${escapeHtml(line.text)}</span>`;
+ }
+ const cls = line.cls ? ` class="${line.cls}"` : '';
+ return `<span${cls}>${escapeHtml(line.text)}</span>`;
+ }).join('\n');
+}
+
+/**
+ * Type the transcript out. Commands type character by character; output lines
+ * appear whole, the way a real command's output does.
+ */
+function playTranscript(el, signal) {
+ const sleep = (ms) =>
+ new Promise((resolve, reject) => {
+ const t = setTimeout(resolve, ms);
+ signal.addEventListener(
+ 'abort',
+ () => {
+ clearTimeout(t);
+ reject(new DOMException('aborted', 'AbortError'));
+ },
+ { once: true },
+ );
+ });
+
+ return (async () => {
+ el.innerHTML = '';
+ let html = '';
+
+ for (const line of TRANSCRIPT) {
+ if (signal.aborted) return;
+
+ if (line.kind === 'gap') {
+ html += '\n';
+ el.innerHTML = html;
+ await sleep(160);
+ continue;
+ }
+
+ if (line.kind === 'cmd') {
+ html += `<span class="p">${PROMPT}</span>`;
+ let typed = '';
+ for (const ch of line.text) {
+ typed += ch;
+ el.innerHTML = `${html}<span class="c">${escapeHtml(typed)}</span><span class="cli-caret"></span>`;
+ el.scrollTop = el.scrollHeight;
+ await sleep(ch === '\n' ? 90 : 14);
+ }
+ html += `<span class="c">${escapeHtml(line.text)}</span>\n`;
+ el.innerHTML = html;
+ await sleep(280);
+ continue;
+ }
+
+ const cls = line.cls ? ` class="${line.cls}"` : '';
+ html += `<span${cls}>${escapeHtml(line.text)}</span>\n`;
+ el.innerHTML = html;
+ el.scrollTop = el.scrollHeight;
+ await sleep(90);
+ }
+
+ el.innerHTML = `${html}<span class="p">${PROMPT}</span><span class="cli-caret"></span>`;
+ el.scrollTop = el.scrollHeight;
+ })().catch((err) => {
+ if (err?.name !== 'AbortError') throw err;
+ });
+}
+
+function initTerminal() {
+ const body = document.getElementById('cli-term-body');
+ const replay = document.querySelector('.cli-term-replay');
+ if (!body) return;
+
+ if (prefersReducedMotion()) {
+ body.innerHTML = renderStatic();
+ replay?.setAttribute('hidden', '');
+ return;
+ }
+
+ let controller = null;
+ const start = () => {
+ controller?.abort();
+ controller = new AbortController();
+ playTranscript(body, controller.signal);
+ };
+
+ // Only start once the terminal is actually on screen, so the animation is
+ // not already finished by the time someone scrolls to it.
+ const observer = new IntersectionObserver(
+ (entries) => {
+ for (const entry of entries) {
+ if (entry.isIntersecting) {
+ start();
+ observer.disconnect();
+ }
+ }
+ },
+ { threshold: 0.25 },
+ );
+ observer.observe(body);
+
+ replay?.addEventListener('click', start);
+}
+
+function initCopyButtons() {
+ for (const btn of document.querySelectorAll('[data-copy-target]')) {
+ btn.addEventListener('click', async () => {
+ const target = document.getElementById(btn.dataset.copyTarget);
+ if (!target) return;
+ const label = btn.querySelector('.cli-copy-label');
+ const original = label?.textContent ?? '';
+ try {
+ await navigator.clipboard.writeText(target.textContent.trim());
+ btn.dataset.copied = 'true';
+ if (label) label.textContent = 'Copied';
+ } catch {
+ // Clipboard is unavailable over plain http or when permission is
+ // denied. Select the text so the copy is still one keystroke away.
+ const range = document.createRange();
+ range.selectNodeContents(target);
+ const sel = window.getSelection();
+ sel?.removeAllRanges();
+ sel?.addRange(range);
+ if (label) label.textContent = 'Press ⌘C';
+ }
+ setTimeout(() => {
+ delete btn.dataset.copied;
+ if (label) label.textContent = original;
+ }, 1800);
+ });
+ }
+}
+
+/**
+ * The live viewer proves the emitted snippet works, so its failure has to be
+ * visible rather than silent. Ready means the element upgraded and built a
+ * canvas; failed means the loader never registered it.
+ */
+function initLiveStage() {
+ const stage = document.getElementById('live-stage');
+ if (!stage) return;
+ const el = stage.querySelector('agent-3d');
+ if (!el) return;
+
+ const deadline = Date.now() + 15000;
+
+ const poll = () => {
+ const upgraded = Boolean(customElements.get('agent-3d'));
+ const painted = Boolean(el.shadowRoot?.querySelector('canvas'));
+
+ if (upgraded && painted) {
+ stage.dataset.state = 'ready';
+ return;
+ }
+ if (Date.now() > deadline) {
+ stage.dataset.state = 'failed';
+ return;
+ }
+ setTimeout(poll, 250);
+ };
+
+ poll();
+}
+
+function initReveal() {
+ const targets = document.querySelectorAll('.cli-section-head, .cli-cmd-card, .cli-gate, .cli-next-card');
+ if (prefersReducedMotion()) return;
+
+ for (const node of targets) node.classList.add('cli-reveal');
+
+ const observer = new IntersectionObserver(
+ (entries) => {
+ for (const entry of entries) {
+ if (!entry.isIntersecting) continue;
+ entry.target.classList.add('is-in');
+ observer.unobserve(entry.target);
+ }
+ },
+ { rootMargin: '0px 0px -8% 0px', threshold: 0.1 },
+ );
+
+ for (const node of targets) observer.observe(node);
+}
+
+function boot() {
+ initTerminal();
+ initCopyButtons();
+ initLiveStage();
+ initReveal();
+}
+
+if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', boot, { once: true });
+} else {
+ boot();
+}
diff --git a/src/dashboard-next/nav.js b/src/dashboard-next/nav.js
index f5275b64f..e96244935 100644
--- a/src/dashboard-next/nav.js
+++ b/src/dashboard-next/nav.js
@@ -52,6 +52,7 @@ export const NAV = [
{ path: '/dashboard/prelaunch-radar', label: 'Pre-Launch Radar', icon: 'live', group: 'Monetize', tags: ['radar', 'pre-launch', 'precursor', 'block-zero', 'snipe', 'creator', 'smart-money', 'pump.fun', 'pre-cog', 'watchlist'] },
{ path: '/oracle', label: 'Oracle', icon: 'oracle', group: 'Monetize', tags: ['conviction', 'score', 'tier', 'pump.fun', 'signal', 'ai', 'trade intelligence', 'wins', 'proof', 'leaderboard'], external: true },
{ path: '/dashboard/portfolio', label: 'Portfolio', icon: 'portfolio', group: 'Monetize', tags: ['nft', 'holdings', 'balances', 'wallet', 'collection', 'crypto', 'tokens', 'chart', 'send'] },
+ { path: '/wallet', label: 'Master Wallet', icon: 'wallet', group: 'Monetize', tags: ['wallet', 'master wallet', 'custodial', 'sol', 'usdc', 'send', 'fund agent', 'top up', 'balance', 'deposit', 'solana', 'base', 'history'], external: true },
{ path: '/dashboard/landscape', label: 'Landscape', icon: 'landscape', group: 'Monetize', tags: ['competitors', 'market', 'competitive', 'intelligence', 'positioning', 'tam', 'investor'] },
{ path: '/reputation', label: 'Reputation', icon: 'star', group: 'Monetize', tags: ['reviews', 'attestations', 'onchain', 'trust', 'score'], external: true },
@@ -118,6 +119,7 @@ export const ICONS = {
receipt: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M5 2.5h10v15l-2-1.2-2 1.2-2-1.2-2 1.2-2-1.2V2.5z"/><path d="M8 6.5h4M8 9.5h4M8 12.5h2.5"/></svg>',
paysess: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="5" width="16" height="10" rx="2"/><path d="M2 8.5h16"/><circle cx="6" cy="12" r="1.2" fill="currentColor" stroke="none"/><path d="M9.5 12h5"/></svg>',
pulse: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M2 10h3l2-5 3 10 2-7 2 2h4"/></svg>',
+ wallet: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6a2 2 0 012-2h9a1 1 0 011 1v1"/><rect x="2.5" y="6" width="15" height="10" rx="2"/><circle cx="14" cy="11" r="1.2" fill="currentColor" stroke="none"/></svg>',
};
/** Resolve the route for the current pathname (exact match wins; falls back to startsWith). */
diff --git a/src/examples-gallery.js b/src/examples-gallery.js
deleted file mode 100644
index b81fbdb08..000000000
--- a/src/examples-gallery.js
+++ /dev/null
@@ -1,277 +0,0 @@
-// /examples: the browsable index of every runnable example that ships in the
-// three.ws repository.
-//
-// Feed: GET /examples.json, mirrored from data/examples.json, which
-// scripts/build-examples-index.mjs derives by scanning the repo. That matters
-// for trust: the gallery cannot advertise an example that was deleted, and it
-// cannot miss one that was added, because nothing here is hand-listed.
-//
-// Every card is a real artifact with a real way to run it. Three kinds exist,
-// and they are genuinely different things rather than a styling choice:
-// html-demo a single self-contained page, opened at a dev-server URL
-// project a directory with its own README, run by a shell command
-// package the examples folder that ships beside an SDK or npm package
-//
-// The examples are source files in the repo, not hosted routes, so every card
-// links to GitHub for the source. Nothing here pretends to be a live demo.
-
-const els = {
- grid: document.querySelector('[data-role="grid"]'),
- loading: document.querySelector('[data-role="loading"]'),
- empty: document.querySelector('[data-role="empty"]'),
- emptySearch: document.querySelector('[data-role="empty-search"]'),
- error: document.querySelector('[data-role="error"]'),
- errorMsg: document.querySelector('[data-role="error-msg"]'),
- search: document.querySelector('[data-role="search"]'),
- sort: document.querySelector('[data-role="sort"]'),
- count: document.querySelector('[data-role="count"]'),
- heroStats: document.querySelector('[data-role="hero-stats"]'),
- clearSearch: document.querySelector('[data-role="clear-search"]'),
- retry: document.querySelector('[data-role="retry"]'),
- chips: document.querySelector('[data-role="chips"]'),
- live: document.querySelector('[data-role="live"]'),
-};
-
-const state = { all: [], groups: [], query: '', sort: 'group', group: '' };
-
-const REPO = 'https://github.com/nirholas/three.ws';
-const BRANCH = 'main';
-
-function escapeHtml(s) {
- return String(s ?? '').replace(/[&<>"']/g, (c) =>
- ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
-}
-const escapeAttr = escapeHtml;
-function show(el, on) {
- if (el) el.hidden = !on;
-}
-
-/** Screen-reader announcement for filter results, which change silently otherwise. */
-function announce(message) {
- if (els.live) els.live.textContent = message;
-}
-
-const KIND_LABEL = { 'html-demo': 'Web component demo', project: 'Example project', package: 'Package example' };
-const KIND_ICON = { 'html-demo': '🧩', project: '📦', package: '🔌' };
-
-/** A directory path is a tree link on GitHub; a single file is a blob link. */
-function sourceUrl(example) {
- const isDir = example.kind !== 'html-demo' && !/\.[a-z0-9]+$/i.test(example.path);
- return `${REPO}/${isDir ? 'tree' : 'blob'}/${BRANCH}/${example.path}`;
-}
-
-function readmeUrl(example) {
- return example.readme ? `${REPO}/blob/${BRANCH}/${example.readme}` : null;
-}
-
-/**
- * The one line a reader needs to actually run the example. `runKind: 'url'`
- * means "start the dev server and open this path", so it is rendered as a path
- * rather than a link: these files are not served by the production site.
- */
-function runLine(example) {
- if (!example.run) return '';
- return example.runKind === 'url' ? `npm run dev → ${example.run}` : example.run;
-}
-
-function matches(example, query) {
- if (!query) return true;
- const haystack = [example.title, example.description, example.path, example.owner, KIND_LABEL[example.kind]]
- .filter(Boolean)
- .join(' ')
- .toLowerCase();
- return query
- .toLowerCase()
- .split(/\s+/)
- .filter(Boolean)
- .every((term) => haystack.includes(term));
-}
-
-function visible() {
- let list = state.all.filter((e) => matches(e, state.query));
- if (state.group) list = list.filter((e) => e.group === state.group);
- const byTitle = (a, b) => a.title.localeCompare(b.title);
- if (state.sort === 'title') list = [...list].sort(byTitle);
- else if (state.sort === 'files') list = [...list].sort((a, b) => (b.files?.length || 0) - (a.files?.length || 0) || byTitle(a, b));
- else list = [...list].sort((a, b) => a.group.localeCompare(b.group) || byTitle(a, b));
- return list;
-}
-
-function card(example) {
- const files = Array.isArray(example.files) ? example.files : [];
- const readme = readmeUrl(example);
- const run = runLine(example);
- return `
- <article class="ex-card">
- <div class="ex-card-top">
- <span class="ex-card-kind" title="${escapeAttr(KIND_LABEL[example.kind] || example.kind)}">
- <span aria-hidden="true">${KIND_ICON[example.kind] || '📄'}</span>
- ${escapeHtml(KIND_LABEL[example.kind] || example.kind)}
- </span>
- ${example.owner ? `<span class="ex-card-owner">${escapeHtml(example.owner)}</span>` : ''}
- </div>
- <h3 class="ex-card-title">
- <a href="${escapeAttr(sourceUrl(example))}" target="_blank" rel="noopener noreferrer">${escapeHtml(example.title)}</a>
- </h3>
- ${example.description ? `<p class="ex-card-desc">${escapeHtml(example.description)}</p>` : ''}
- ${
- files.length
- ? `<ul class="ex-card-files">${files
- .slice(0, 5)
- .map((f) => `<li><code>${escapeHtml(f)}</code></li>`)
- .join('')}${files.length > 5 ? `<li class="ex-card-more">+${files.length - 5} more</li>` : ''}</ul>`
- : ''
- }
- ${
- run
- ? `<div class="ex-card-run">
- <code data-role="run" title="${escapeAttr(run)}">${escapeHtml(run)}</code>
- <button type="button" class="ex-copy" data-copy="${escapeAttr(example.run)}" aria-label="Copy the command that runs ${escapeAttr(example.title)}">Copy</button>
- </div>`
- : ''
- }
- <div class="ex-card-actions">
- <a class="ex-btn ex-btn--primary" href="${escapeAttr(sourceUrl(example))}" target="_blank" rel="noopener noreferrer">View source</a>
- ${readme ? `<a class="ex-btn ex-btn--ghost" href="${escapeAttr(readme)}" target="_blank" rel="noopener noreferrer">README</a>` : ''}
- <span class="ex-card-path" title="${escapeAttr(example.path)}">${escapeHtml(example.path)}</span>
- </div>
- </article>`;
-}
-
-function renderChips() {
- if (!els.chips) return;
- const counts = new Map();
- for (const example of state.all) counts.set(example.group, (counts.get(example.group) || 0) + 1);
- const chip = (value, label, count) =>
- `<button type="button" role="tab" class="ex-chip${state.group === value ? ' is-active' : ''}" aria-selected="${state.group === value}" data-group="${escapeAttr(value)}">${escapeHtml(label)} <span class="ex-chip-n">${count}</span></button>`;
- els.chips.innerHTML = [
- chip('', 'All', state.all.length),
- ...state.groups.map((g) => chip(g, g, counts.get(g) || 0)),
- ].join('');
-}
-
-function render() {
- const list = visible();
- show(els.loading, false);
- show(els.error, false);
-
- if (!state.all.length) {
- show(els.grid, false);
- show(els.emptySearch, false);
- show(els.empty, true);
- if (els.count) els.count.textContent = '';
- return;
- }
- show(els.empty, false);
-
- if (!list.length) {
- show(els.grid, false);
- show(els.emptySearch, true);
- if (els.count) els.count.textContent = '0 examples';
- announce('No examples match the current filter.');
- return;
- }
-
- show(els.emptySearch, false);
- els.grid.innerHTML = list.map(card).join('');
- show(els.grid, true);
- if (els.count) els.count.textContent = `${list.length} of ${state.all.length} examples`;
- announce(`${list.length} examples shown.`);
-}
-
-function renderHeroStats(counts) {
- if (!els.heroStats || !counts) return;
- const parts = [`${counts.total} examples`];
- if (counts.html_demos) parts.push(`${counts.html_demos} demos`);
- if (counts.projects) parts.push(`${counts.projects} projects`);
- if (counts.packages) parts.push(`${counts.packages} package sets`);
- els.heroStats.textContent = parts.join(' · ');
-}
-
-async function load() {
- show(els.error, false);
- show(els.empty, false);
- show(els.emptySearch, false);
- show(els.grid, false);
- show(els.loading, true);
- try {
- const res = await fetch('/examples.json', { headers: { accept: 'application/json' } });
- if (!res.ok) throw new Error(`the index returned HTTP ${res.status}`);
- const data = await res.json();
- const examples = Array.isArray(data?.examples) ? data.examples : [];
- state.all = examples.filter((e) => e && e.title && e.path);
- state.groups = [...new Set(state.all.map((e) => e.group).filter(Boolean))].sort();
- renderHeroStats(data?.counts);
- renderChips();
- render();
- } catch (err) {
- show(els.loading, false);
- show(els.grid, false);
- if (els.errorMsg) els.errorMsg.textContent = `Could not load the example index: ${err.message}.`;
- show(els.error, true);
- }
-}
-
-function bind() {
- let debounce;
- els.search?.addEventListener('input', (e) => {
- clearTimeout(debounce);
- const value = e.target.value;
- debounce = setTimeout(() => {
- state.query = value.trim();
- render();
- }, 120);
- });
- els.sort?.addEventListener('change', (e) => {
- state.sort = e.target.value;
- render();
- });
- els.chips?.addEventListener('click', (e) => {
- const button = e.target.closest('[data-group]');
- if (!button) return;
- state.group = button.dataset.group;
- renderChips();
- render();
- });
- els.clearSearch?.addEventListener('click', () => {
- state.query = '';
- state.group = '';
- if (els.search) els.search.value = '';
- renderChips();
- render();
- els.search?.focus();
- });
- els.retry?.addEventListener('click', load);
-
- // Copy-to-clipboard on the run command, with the button reporting its own
- // result: a silent copy leaves the reader unsure whether it worked.
- els.grid?.addEventListener('click', async (e) => {
- const button = e.target.closest('.ex-copy');
- if (!button) return;
- const text = button.dataset.copy || '';
- try {
- await navigator.clipboard.writeText(text);
- button.textContent = 'Copied';
- button.classList.add('is-copied');
- } catch {
- button.textContent = 'Press ⌘C';
- }
- setTimeout(() => {
- button.textContent = 'Copy';
- button.classList.remove('is-copied');
- }, 1600);
- });
-
- // "/" focuses search, the convention the other galleries on this site use.
- document.addEventListener('keydown', (e) => {
- if (e.key !== '/' || e.metaKey || e.ctrlKey || e.altKey) return;
- const tag = document.activeElement?.tagName;
- if (tag === 'INPUT' || tag === 'TEXTAREA' || document.activeElement?.isContentEditable) return;
- e.preventDefault();
- els.search?.focus();
- els.search?.select();
- });
-}
-
-bind();
-load();
diff --git a/src/trading-hub-format.js b/src/trading-hub-format.js
index f2899f4c3..10a18fdab 100644
--- a/src/trading-hub-format.js
+++ b/src/trading-hub-format.js
@@ -150,7 +150,13 @@ export function describeFleet(status, now = Date.now()) {
*/
export function sparkPath(series, w = 120, h = 32) {
if (!Array.isArray(series)) return '';
- const pts = series.map(Number).filter((n) => Number.isFinite(n));
+ // Drop nullish and empty entries BEFORE coercing. Number(null) and Number('')
+ // are both 0, so mapping first would turn a missing datapoint into a real
+ // zero and bend the line toward a value the series never contained.
+ const pts = series
+ .filter((v) => v !== null && v !== undefined && v !== '')
+ .map(Number)
+ .filter((n) => Number.isFinite(n));
if (pts.length < 2) return '';
const min = Math.min(...pts);
const max = Math.max(...pts);
diff --git a/tests/animation-registry.test.js b/tests/animation-registry.test.js
new file mode 100644
index 000000000..a86ef2c9f
--- /dev/null
+++ b/tests/animation-registry.test.js
@@ -0,0 +1,77 @@
+/**
+ * public/animations/registry.json is the developer-facing catalogue of every
+ * animation asset, and its own header tells the reader to consult it first.
+ * A registry that has drifted is worse than none: it drifted to 37 of 112 built
+ * clips, with `source_fbx` paths pointing into a directory that has held no FBX
+ * since the sources moved to animation-sources/, and `agent_slots` recording
+ * slot assignments that had moved to other clips.
+ *
+ * scripts/sync-animation-registry.mjs derives the whole block from the manifest,
+ * the clip config and the live slot map. These tests fail if the committed file
+ * is not what that script would produce, so the catalogue cannot silently rot.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { dirname, resolve } from 'node:path';
+import { DEFAULT_ANIMATION_MAP, SLOTS } from '../src/runtime/animation-slots.js';
+import { buildRows } from '../scripts/sync-animation-registry.mjs';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const readJson = (p) => JSON.parse(readFileSync(resolve(__dirname, p), 'utf8'));
+
+const registry = readJson('../public/animations/registry.json');
+const manifest = readJson('../public/animations/manifest.json');
+const items = registry.collections.clips.items;
+
+describe('animation registry: clips collection', () => {
+ it('lists every clip in the built manifest, exactly once', () => {
+ expect(items.map((r) => r.name)).toEqual(manifest.map((c) => c.name));
+ });
+
+ it('matches what the sync script derives (run npm run sync:animation-registry)', () => {
+ expect(items).toEqual(buildRows());
+ });
+
+ it('records no slot on more than one clip', () => {
+ const seen = new Map();
+ for (const row of items) {
+ for (const slot of row.agent_slots) {
+ expect(seen.has(slot), `slot "${slot}" recorded on both ${seen.get(slot)} and ${row.name}`).toBe(false);
+ seen.set(slot, row.name);
+ }
+ }
+ });
+
+ it('records exactly the slot assignments the runtime map makes', () => {
+ const fromRegistry = new Map();
+ for (const row of items) for (const slot of row.agent_slots) fromRegistry.set(slot, row.name);
+ expect(Object.fromEntries([...fromRegistry].sort())).toEqual(
+ Object.fromEntries(Object.entries(DEFAULT_ANIMATION_MAP).sort()),
+ );
+ });
+
+ it('points every source_fbx at the directory the build actually reads', () => {
+ for (const row of items) {
+ if (row.source_fbx === null) continue;
+ expect(row.source_fbx, `${row.name} has a stale source path`).toMatch(/^animation-sources\//);
+ }
+ });
+});
+
+describe('animation registry: agent_slots section', () => {
+ const slots = registry.agent_slots.slots;
+
+ it('documents every slot in the vocabulary and nothing else', () => {
+ expect(Object.keys(slots)).toEqual(SLOTS);
+ });
+
+ it('documents the same default clip the runtime resolves', () => {
+ for (const [slot, def] of Object.entries(slots)) {
+ expect(def.default_clip, `registry disagrees with the runtime on "${slot}"`).toBe(
+ DEFAULT_ANIMATION_MAP[slot],
+ );
+ }
+ });
+});
diff --git a/tests/docs-world.test.js b/tests/docs-world.test.js
index 053247229..78205724e 100644
--- a/tests/docs-world.test.js
+++ b/tests/docs-world.test.js
@@ -160,4 +160,38 @@ describe('designed states, not blank ones', () => {
const startHere = readFileSync(resolve(root, 'docs/start-here.md'), 'utf8');
expect(startHere).toContain('](./docs-world.md)');
});
+
+ it('offers retry for recoverable boot failures but not for a GPU-less device', () => {
+ // A dropped /docs/nav.json fetch, an exhausted WebGL context budget, and an
+ // unexpected boot throw are all cleared by a reload, so each must hand the
+ // visitor that action. isWebGLAvailable() failing is NOT: reloading cannot
+ // grow the device a GPU, and a button that reproduces the same dead end
+ // reads as a broken product rather than an honest limitation.
+ const shell = readFileSync(resolve(root, 'pages/docs-world.html'), 'utf8');
+ expect(shell).toContain('id="dw-fallback-retry"');
+
+ // Three recoverable branches: manifest fetch, renderer construction, and
+ // the boot catch-all. Each passes an options object, and every such call
+ // opts into retry.
+ // Lookbehind skips the `function showFallback({...})` declaration, which
+ // otherwise counts as a fourth "call".
+ const withOptions = (main.match(/(?<!function )showFallback\(\{/g) || []).length;
+ const withRetry = (main.match(/retry: true/g) || []).length;
+ expect(withOptions).toBe(3);
+ expect(withRetry).toBe(withOptions);
+
+ // The WebGL preflight branch calls showFallback with no argument, so it
+ // defaults to retry:false.
+ expect(main).toMatch(/if \(!isWebGLAvailable\(\)\) \{\s*showFallback\(\);/);
+ expect(main).toContain('retry = false');
+ });
+
+ it('reveals the fallback before focusing it, so the retry is keyboard-reachable', () => {
+ // focus() on a still-hidden element is a no-op, which would strand the
+ // keyboard on <body> with the only recovery action unreachable.
+ const revealIdx = main.indexOf("$('dw-fallback').hidden = false;");
+ const focusIdx = main.indexOf('retryBtn.focus(');
+ expect(revealIdx).toBeGreaterThan(-1);
+ expect(focusIdx).toBeGreaterThan(revealIdx);
+ });
});
diff --git a/tests/trading-hub.test.js b/tests/trading-hub.test.js
new file mode 100644
index 000000000..330a19987
--- /dev/null
+++ b/tests/trading-hub.test.js
@@ -0,0 +1,231 @@
+// /trading, the autonomous-trading hub.
+//
+// Two things are worth pinning here.
+//
+// 1. LINK INTEGRITY. The hub exists because the trading surfaces had no front
+// door; a front door full of dead links is worse than none. The directory is
+// data, so every href is asserted against data/pages.json (for site routes)
+// and the docs tree (for doc routes). A renamed page fails this test instead
+// of silently becoming a dead card.
+//
+// 2. THE PURE FORMATTERS. describeFleet() encodes the judgement that a beating
+// worker with a silent feed is NOT healthy, and sparkPath() refuses to draw a
+// line it cannot honestly draw. Both are easy to regress and neither needs a
+// DOM to test.
+
+import { describe, it, expect } from 'vitest';
+import { readFileSync, existsSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { join } from 'node:path';
+
+import { SURFACES, LEARN } from '../src/trading-hub-data.js';
+import {
+ describeFleet,
+ formatSol,
+ formatPct,
+ formatAgo,
+ formatUptime,
+ sparkPath,
+} from '../src/trading-hub-format.js';
+
+const ROOT = fileURLToPath(new URL('..', import.meta.url));
+
+function sitePaths() {
+ const json = JSON.parse(readFileSync(join(ROOT, 'data', 'pages.json'), 'utf8'));
+ const out = new Set();
+ const walk = (node) => {
+ if (Array.isArray(node)) return node.forEach(walk);
+ if (node && typeof node === 'object') {
+ if (typeof node.path === 'string') out.add(node.path);
+ Object.values(node).forEach(walk);
+ }
+ };
+ walk(json);
+ return out;
+}
+
+const ALL = [...SURFACES, ...LEARN];
+
+describe('trading hub directory', () => {
+ it('lists both product surfaces and docs', () => {
+ expect(SURFACES.length).toBeGreaterThanOrEqual(8);
+ expect(LEARN.length).toBeGreaterThanOrEqual(6);
+ });
+
+ it('gives every entry the fields the card template renders', () => {
+ for (const item of ALL) {
+ expect(typeof item.kicker, `kicker on ${item.href}`).toBe('string');
+ expect(item.kicker.length, `kicker on ${item.href}`).toBeGreaterThan(0);
+ expect(item.title.length, `title on ${item.href}`).toBeGreaterThan(0);
+ expect(item.body.length, `body on ${item.href}`).toBeGreaterThan(0);
+ expect(item.href.startsWith('/'), `href on ${item.title}`).toBe(true);
+ }
+ });
+
+ it('never lists the same destination twice', () => {
+ const hrefs = ALL.map((i) => i.href);
+ expect(new Set(hrefs).size).toBe(hrefs.length);
+ });
+
+ it('points every doc link at a markdown file that exists', () => {
+ const docLinks = ALL.filter((i) => i.href.startsWith('/docs/') || i.href.startsWith('/tutorials/'));
+ expect(docLinks.length).toBeGreaterThan(0);
+ for (const { href } of docLinks) {
+ const rel = href.startsWith('/tutorials/')
+ ? join('docs', 'tutorials', `${href.slice('/tutorials/'.length)}.md`)
+ : join('docs', `${href.slice('/docs/'.length)}.md`);
+ expect(existsSync(join(ROOT, rel)), `${href} -> ${rel}`).toBe(true);
+ }
+ });
+
+ it('declares every destination in data/pages.json so it reaches the sitemap', () => {
+ const known = sitePaths();
+ for (const { href } of ALL) {
+ expect(known.has(href), `${href} missing from data/pages.json`).toBe(true);
+ }
+ });
+
+ it('declares the hub itself', () => {
+ expect(sitePaths().has('/trading')).toBe(true);
+ });
+});
+
+describe('describeFleet', () => {
+ const base = {
+ mode: 'live',
+ strategies: 13,
+ openPositions: 2,
+ feedLive: true,
+ feedSilent: false,
+ lastEventAgeMs: 2000,
+ bootAt: '2026-07-26T22:48:15.757Z',
+ };
+ const NOW = Date.UTC(2026, 6, 30, 22, 48, 15);
+
+ it('reports a healthy live fleet as live', () => {
+ const d = describeFleet(base, NOW);
+ expect(d.tone).toBe('live');
+ expect(d.label).toBe('Trading live');
+ expect(d.feedTone).toBe('live');
+ });
+
+ it('does NOT call a silent feed healthy', () => {
+ // The trap this guards: connected, beating, green everywhere, seeing nothing.
+ const d = describeFleet({ ...base, feedSilent: true }, NOW);
+ expect(d.tone).not.toBe('live');
+ expect(d.feedTone).toBe('warn');
+ expect(d.feedLabel).toBe('Silent');
+ });
+
+ it('reports a disconnected feed as down', () => {
+ const d = describeFleet({ ...base, feedLive: false }, NOW);
+ expect(d.feedTone).toBe('down');
+ expect(d.feedLabel).toBe('Disconnected');
+ });
+
+ it('lets the kill switch override everything else', () => {
+ const d = describeFleet({ ...base, globalKill: true }, NOW);
+ expect(d.tone).toBe('down');
+ expect(d.label).toBe('Fleet halted');
+ });
+
+ it('distinguishes simulate from live', () => {
+ const d = describeFleet({ ...base, mode: 'simulate' }, NOW);
+ expect(d.tone).toBe('muted');
+ expect(d.label).toBe('Simulating');
+ });
+
+ it('degrades to unknown rather than inventing a state', () => {
+ for (const input of [null, undefined, {}, { mode: 'nonsense' }]) {
+ const d = describeFleet(input, NOW);
+ expect(d.tone).toBe('unknown');
+ expect(d.label).toBe('Fleet status unknown');
+ }
+ });
+
+ it('reports uptime in the coarsest honest unit', () => {
+ expect(describeFleet(base, NOW).uptimeLabel).toBe('4d');
+ });
+});
+
+describe('formatters', () => {
+ it('never renders a missing number as zero', () => {
+ for (const bad of [null, undefined, 'abc', NaN]) {
+ expect(formatSol(bad)).toBe('·');
+ expect(formatPct(bad)).toBe('·');
+ }
+ expect(formatUptime(null)).toBe('·');
+ expect(formatUptime('not-a-date')).toBe('·');
+ });
+
+ it('signs positive values and widens precision for dust', () => {
+ expect(formatSol(0.17254)).toBe('+0.173 SOL');
+ expect(formatSol(-0.152)).toBe('-0.152 SOL');
+ expect(formatSol(0.0006)).toBe('+0.0006 SOL');
+ expect(formatSol(0)).toBe('0.000 SOL');
+ expect(formatSol(1.5, { signed: false })).toBe('1.500 SOL');
+ });
+
+ it('formats percentages with a sign only when asked', () => {
+ expect(formatPct(10.2)).toBe('+10.2%');
+ expect(formatPct(-40.3)).toBe('-40.3%');
+ expect(formatPct(50, { signed: false })).toBe('50.0%');
+ });
+
+ it('formats relative time without depending on the clock', () => {
+ const now = Date.UTC(2026, 6, 30, 12, 0, 0);
+ expect(formatAgo(null, now)).toBe('never');
+ expect(formatAgo(new Date(now - 30_000).toISOString(), now)).toBe('just now');
+ expect(formatAgo(new Date(now - 15 * 60_000).toISOString(), now)).toBe('15m ago');
+ expect(formatAgo(new Date(now - 5 * 3_600_000).toISOString(), now)).toBe('5h ago');
+ expect(formatAgo(new Date(now - 3 * 86_400_000).toISOString(), now)).toBe('3d ago');
+ });
+
+ it('treats a future timestamp as now rather than negative time', () => {
+ const now = Date.UTC(2026, 6, 30, 12, 0, 0);
+ expect(formatAgo(new Date(now + 60_000).toISOString(), now)).toBe('just now');
+ });
+});
+
+describe('sparkPath', () => {
+ it('draws nothing when there is nothing honest to draw', () => {
+ // A single point is not a trend; a flat line would imply one.
+ expect(sparkPath([])).toBe('');
+ expect(sparkPath([1])).toBe('');
+ expect(sparkPath(null)).toBe('');
+ expect(sparkPath('nope')).toBe('');
+ });
+
+ it('draws a path across the full width for a real series', () => {
+ const d = sparkPath([0.005, 0.01, 0.015, -0.038, 0.186, 0.172], 120, 32);
+ expect(d.startsWith('M0.00')).toBe(true);
+ expect(d).toContain('L120.00');
+ expect(d.split('L').length).toBe(6);
+ });
+
+ it('centres a flat series instead of dividing by zero', () => {
+ const d = sparkPath([2, 2, 2], 100, 40);
+ expect(d).not.toContain('NaN');
+ expect(d).toContain('20.00');
+ });
+
+ it('ignores non-numeric points rather than emitting NaN', () => {
+ const d = sparkPath([1, 'x', 3, null, 5]);
+ expect(d).not.toContain('NaN');
+ expect(d.split(/[ML]/).filter(Boolean).length).toBe(3);
+ });
+
+ it('keeps every coordinate inside the viewport', () => {
+ const w = 120;
+ const h = 32;
+ const d = sparkPath([-5, 12, 0, 7], w, h);
+ const coords = [...d.matchAll(/[ML]([\d.-]+) ([\d.-]+)/g)].map((m) => [Number(m[1]), Number(m[2])]);
+ expect(coords.length).toBe(4);
+ for (const [x, y] of coords) {
+ expect(x).toBeGreaterThanOrEqual(0);
+ expect(x).toBeLessThanOrEqual(w);
+ expect(y).toBeGreaterThanOrEqual(0);
+ expect(y).toBeLessThanOrEqual(h);
+ }
+ });
+});
diff --git a/tests/tutorials-manifest.test.js b/tests/tutorials-manifest.test.js
new file mode 100644
index 000000000..df917c740
--- /dev/null
+++ b/tests/tutorials-manifest.test.js
@@ -0,0 +1,123 @@
+/**
+ * Tutorial library invariants.
+ *
+ * A tutorial is only real when three things agree: the markdown at
+ * docs/tutorials/<slug>.md (the content), an entry in
+ * public/tutorials-manifest.js (how anyone FINDS it), and a route that
+ * renders it. The manifest is loaded as a classic script by both /tutorials
+ * and /tutorials/<slug>, so a file with no entry is written, shipped, and
+ * unreachable from navigation: it exists only for whoever already knows the
+ * URL. That drift is invisible in review and has happened repeatedly, which is
+ * why it is pinned here rather than left to a periodic sweep.
+ *
+ * The manifest is a browser script (an IIFE assigning window.TUTORIALS), not a
+ * module, so it is evaluated in a tiny window shim instead of imported.
+ */
+
+import { readFileSync, readdirSync, existsSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { describe, it, expect } from 'vitest';
+
+const root = resolve(__dirname, '..');
+
+/** Evaluate the manifest IIFE the way a browser does and return window.TUTORIALS. */
+function loadManifest() {
+ const source = readFileSync(resolve(root, 'public/tutorials-manifest.js'), 'utf8');
+ const win = {};
+ new Function('window', source)(win);
+ return win.TUTORIALS;
+}
+
+const TUTORIALS = loadManifest();
+const TIERS = ['easy', 'middle', 'advanced'];
+
+const markdownSlugs = readdirSync(resolve(root, 'docs/tutorials'))
+ .filter((f) => f.endsWith('.md'))
+ .map((f) => f.replace(/\.md$/, ''));
+
+describe('tutorials manifest', () => {
+ it('parses into a non-trivial list', () => {
+ expect(Array.isArray(TUTORIALS)).toBe(true);
+ expect(TUTORIALS.length).toBeGreaterThanOrEqual(50);
+ });
+
+ it('every entry carries the fields both templates render', () => {
+ for (const t of TUTORIALS) {
+ expect(typeof t.slug, JSON.stringify(t)).toBe('string');
+ expect(t.slug).toMatch(/^[a-z0-9-]+$/);
+ expect(TIERS, `${t.slug} tier`).toContain(t.tier);
+ for (const field of ['title', 'blurb', 'builds', 'time']) {
+ expect(typeof t[field], `${t.slug}.${field}`).toBe('string');
+ expect(t[field].length, `${t.slug}.${field}`).toBeGreaterThan(0);
+ }
+ expect(typeof t.ctaPrimary?.label, `${t.slug}.ctaPrimary.label`).toBe('string');
+ expect(typeof t.ctaPrimary?.href, `${t.slug}.ctaPrimary.href`).toBe('string');
+ }
+ });
+
+ it('has no duplicate slugs', () => {
+ const seen = new Set();
+ const dupes = [];
+ for (const t of TUTORIALS) {
+ if (seen.has(t.slug)) dupes.push(t.slug);
+ seen.add(t.slug);
+ }
+ // A duplicate renders the same card twice and makes the prev/next pager
+ // in /tutorials/<slug> jump backwards.
+ expect(dupes).toEqual([]);
+ });
+});
+
+describe('manifest and markdown agree', () => {
+ it('every manifest entry has the markdown its viewer fetches', () => {
+ const missing = TUTORIALS.filter(
+ (t) => !existsSync(resolve(root, 'docs/tutorials', `${t.slug}.md`)),
+ ).map((t) => t.slug);
+ expect(missing, 'manifest entries with no docs/tutorials/<slug>.md').toEqual([]);
+ });
+
+ it('every tutorial markdown file is listed in the manifest', () => {
+ const listed = new Set(TUTORIALS.map((t) => t.slug));
+ const orphans = markdownSlugs.filter((slug) => !listed.has(slug));
+ // An orphan is written, shipped, and unreachable: /tutorials never links
+ // it and the pager skips it. Add a manifest entry when you add the file.
+ expect(orphans, 'tutorials with no manifest entry (unreachable from /tutorials)').toEqual([]);
+ });
+});
+
+describe('preview models and CTAs resolve', () => {
+ it('every previewModel points at a GLB that ships', () => {
+ const broken = TUTORIALS.filter((t) => t.previewModel).filter(
+ (t) => !existsSync(resolve(root, 'public', t.previewModel.replace(/^\//, ''))),
+ ).map((t) => `${t.slug} -> ${t.previewModel}`);
+ expect(broken, 'previewModel files missing from public/').toEqual([]);
+ });
+
+ it('every internal CTA href is a routable path, not a bare guess', () => {
+ const routes = JSON.parse(readFileSync(resolve(root, 'vercel.json'), 'utf8')).routes;
+ const pages = readFileSync(resolve(root, 'data/pages.json'), 'utf8');
+
+ const routable = (href) => {
+ const path = href.split(/[?#]/)[0].replace(/\/$/, '') || '/';
+ if (pages.includes(`"${path}"`)) return true;
+ // Docs pages are served by the docs SPA, not listed one by one.
+ if (path.startsWith('/docs/')) {
+ return existsSync(resolve(root, 'docs', `${path.slice('/docs/'.length)}.md`));
+ }
+ return routes.some((r) => {
+ if (!r.src) return false;
+ try {
+ return new RegExp(`^${r.src}$`).test(path);
+ } catch {
+ return false;
+ }
+ });
+ };
+
+ const broken = TUTORIALS.map((t) => t.ctaPrimary)
+ .filter((cta) => cta.href.startsWith('/'))
+ .filter((cta) => !routable(cta.href))
+ .map((cta) => cta.href);
+ expect([...new Set(broken)], 'CTA hrefs that match no page or route').toEqual([]);
+ });
+});
diff --git a/vercel.json b/vercel.json
index 25c408b1a..6ddafab17 100644
--- a/vercel.json
+++ b/vercel.json
@@ -1230,6 +1230,10 @@
"src": "/avatar-sdk/?",
"dest": "/avatar-sdk.html"
},
+ {
+ "src": "/avatar-cli/?",
+ "dest": "/avatar-cli.html"
+ },
{
"src": "/avatar-artifact/?",
"dest": "/avatar-artifact.html"
diff --git a/vite.config.js b/vite.config.js
index b9b1ef822..4f978c04e 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -579,6 +579,7 @@ const appConfig = {
'events-build-3d-agents-live': resolve(__dirname, 'pages/events/build-3d-agents-live.html'),
'avatar-page': resolve(__dirname, 'pages/avatar-page.html'),
'avatar-sdk': resolve(__dirname, 'pages/avatar-sdk.html'),
+ 'avatar-cli': resolve(__dirname, 'pages/avatar-cli.html'),
brain: resolve(__dirname, 'pages/brain.html'),
'agent-studio': resolve(__dirname, 'pages/agent-studio.html'),
cosmos: resolve(__dirname, 'pages/cosmos.html'),