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.

docs: refresh 19 docs whose code moved since the 2026-09-17 sweep

nirholas5d7049dede6c
diff --git a/README.md b/README.md
index eed42cd2b..5860af325 100644
--- a/README.md
+++ b/README.md
@@ -8571,7 +8571,7 @@ three.ws is production-ready and serves [three.ws](https://three.ws) live on Goo
- Built-in tools: `wave`, `lookAt`, `play_clip`, `setExpression`, `speak`, `remember`
- Composable skill system — install skills from IPFS, Arweave, or HTTP; each skill is a self-contained bundle with a description, tool definitions, and async handlers
- Weighted emotion blending (celebration, concern, curiosity, empathy, patience) driven by protocol events, not a finite-state machine
-- Web Speech API for STT/TTS out of the box; ElevenLabs integration for production-quality voice
+- Web Speech API for STT/TTS out of the box; on-device speech-to-text when the manifest sets `voice.stt.provider` to `"whisper"` (Moonshine for English, Whisper for 99 languages, run in the browser through transformers.js, with the NVIDIA Riva lane as fallback), so dictation works in Firefox and Safari too; ElevenLabs integration for production-quality voice
- **Talk mode** with audio-driven ARKit-52 lip-sync — TTS audio is analysed in real time and drives 52 standard blendshapes on the avatar
- Anonymous Groq-powered chat for unauthenticated visitors; owner-card gating when an agent has a paying author
@@ -10069,7 +10069,7 @@ GET /.well-known/oauth-authorization-server → RFC 8414 discovery
GET /.well-known/oauth-protected-resource → RFC 9728 resource discovery
```
-Token scopes: `avatars:read`, `avatars:write`, `agents:read`, `agents:write`, `mcp`.
+Token scopes (the full list lives in [api/_lib/oauth-scopes.js](api/_lib/oauth-scopes.js)): `avatars:read`, `avatars:write`, `avatars:delete`, `profile`, `offline_access`, `memory:read`, `memory:write`, `agents:read`, `agents:write`, `feedback:read`, `home:read`, `home:act`, `wallet:read`, `wallet:write`, `services:write`. A bearer token is held to the scopes it was granted: every route that moves an agent's funds requires `wallet:write`, and a bearer can only mint an API key with scopes it holds itself.
Access tokens are short-lived JWTs (1 hour). Refresh tokens are opaque strings stored hashed in Postgres.
@@ -10080,7 +10080,7 @@ Access tokens are short-lived JWTs (1 hour). Refresh tokens are opaque strings s
[`api/mcp.js`](api/mcp.js) is a thin HTTP entrypoint (POST / GET-SSE / DELETE) that implements the [Model Context Protocol](https://modelcontextprotocol.io) 2025-06-18 specification over JSON-RPC 2.0. The protocol logic is split across [`api/_mcp/`](api/_mcp/): `auth.js` (Bearer/OAuth + x402 paywall), `dispatch.js` (JSON-RPC routing), `catalog.js` (dynamic tool catalog), `payments.js` (x402 paid-tool settlement), `render.js`, and `embed-policy.js`. Tools are registered per category under [`api/_mcp/tools/`](api/_mcp/tools/) (14 category modules: `avatars.js`, `models.js`, `solana.js`, `pumpfun.js`, `animations.js`, `agents.js`, `garments.js`, `memory.js`, `oracle.js`, `trader.js`, `embed.js`, `sign.js`, `crypto-data.js`, `tokenize.js`). External AI systems (including Claude Desktop, other agents, or custom integrations) can drive avatars programmatically through this surface.
**Endpoint:** `POST /api/mcp` (tools), `GET /api/mcp` (SSE), `DELETE /api/mcp` (session terminate)
-**Auth:** OAuth 2.1 Bearer token with `mcp` scope; some tools additionally require x402 USDC payment
+**Auth:** OAuth 2.1 Bearer token or API key, with each tool checking its own scope (for example `avatars:read`, or `avatars:delete` for `delete_avatar`); some tools additionally require x402 USDC payment
**Registry:** Listed on the [official MCP Registry](https://registry.modelcontextprotocol.io/?q=io.github.nirholas) as `io.github.nirholas/three.ws`, alongside the other three.ws servers published under the `io.github.nirholas` namespace (`threews-3d-studio`, `threews-avatar`, `threews-pumpfun`, `threews-x402-bazaar`, `three-token-mcp`, and more). Also discoverable on [Smithery](https://smithery.ai/search?q=three.ws), [Glama](https://glama.ai/mcp/servers?query=three.ws), and [PulseMCP](https://www.pulsemcp.com/servers?q=three.ws).
**x402scan:** [view on x402scan](https://www.x402scan.com/server/17cbd874-52ac-4920-a020-b22ff2489a07) — paid MCP tool calls and revenue
@@ -10549,7 +10549,7 @@ Full design and configuration in [docs/solana-pumpfun.md](docs/solana-pumpfun.md
Beyond the Solana reputation signals described above, the platform also ships consumer-facing pump.fun tooling:
-- **Token Launcher** (live at [three.ws/pumpfun](https://three.ws/pumpfun)): UI for creating and launching new tokens, source in [public/pumpfun.html](public/pumpfun.html).
+- **Pump.fun Stream** (live at [three.ws/pumpfun](https://three.ws/pumpfun)): a live feed of every launch, trade, graduation and fee claim with a reacting, optionally narrating 3D agent, source in [public/pumpfun.html](public/pumpfun.html). Its "Launch a coin" button opens the launcher at [three.ws/launch](https://three.ws/launch).
- **Live Dashboard** (live at [three.ws/pump-live](https://three.ws/pump-live)): real-time tracker for new tokens, source in [pages/pump-live.html](pages/pump-live.html).
- **Skills** — the [pump-fun-skills/](pump-fun-skills/) directory contains agent skills for reading and acting on pump.fun.
@@ -11074,14 +11074,14 @@ npm run claude -- <command>
### Production Deployment (Google Cloud Run)
-Production runs on **Google Cloud Run** (`three-ws-api`, region `us-central1`): one Express container ([server/index.mjs](server/index.mjs)) serves the static frontend, the `vercel.json` route table, and every `api/**` handler, fronted by a global HTTPS load balancer + Cloud CDN. Deployment is two steps — build the frontend, then submit the container build:
+Production runs on **Google Cloud Run** (`three-ws-api`, region `us-central1`): one Express container ([server/index.mjs](server/index.mjs)) serves the static frontend, the `vercel.json` route table, and every `api/**` handler, fronted by a global HTTPS load balancer + Cloud CDN. Deployment is two steps, build then submit, from a clean deploy worktree (`npm run prep:worktree -- --apply`):
```bash
-npm run build # frontend build to dist/ (only when frontend changed)
-npm run deploy:gcp # check:dist + db:check, gcloud builds submit, purge CDN
+npm run build:gcp # the full, order-dependent build chain (lib, avatar SDK, chat, frontend, checks)
+npm run deploy:gcp # check:dist + check:pages, then the gated submit, cron sync, CDN purge, smoke test
```
-`npm run deploy:gcp` runs `gcloud builds submit --config server/cloudbuild.yaml`. Routing, cache headers, and cron schedules are defined in `vercel.json`, which the server reads at runtime. The scheduled jobs (110 at time of writing, one per entry in the `crons` array of `vercel.json`) run on **Cloud Scheduler** (provisioned by [scripts/create-gcp-scheduler.mjs](scripts/create-gcp-scheduler.mjs)); the GPU inference workers run as their own Cloud Run services. Full ops runbook (load balancer, DNS/TLS, env, rollback, recovery): **[docs/ops/gcp-production.md](docs/ops/gcp-production.md)**.
+`npm run deploy:gcp` runs `deploy:gcp:submit` (the migration gate `db:check` and the upload and import checks, then `gcloud builds submit --config server/cloudbuild.yaml`), then `deploy:gcp:sync-crons`, which creates a Cloud Scheduler job for any newly declared cron, then a synchronous CDN purge and `smoke:prod`. `npm run deploy:gcp:full` is the build and the deploy in one command. Routing, cache headers, and cron schedules are defined in `vercel.json`, which the server reads at runtime. The scheduled jobs (one per entry in the `crons` array of `vercel.json`) run on **Cloud Scheduler** (provisioned by [scripts/create-gcp-scheduler.mjs](scripts/create-gcp-scheduler.mjs)); the GPU inference workers run as their own Cloud Run services. Full ops runbook (load balancer, DNS/TLS, env, rollback, recovery): **[docs/ops/gcp-production.md](docs/ops/gcp-production.md)**.
**Environment variables** live on the Cloud Run service, not in `.env` files — inspect or update them with `gcloud run services describe/update three-ws-api --region us-central1`. See [Environment Variables](#environment-variables) for the full list.
diff --git a/docs/agent-abilities/chapters/04-the-mind.md b/docs/agent-abilities/chapters/04-the-mind.md
index dda94bcbd..f82d02368 100644
--- a/docs/agent-abilities/chapters/04-the-mind.md
+++ b/docs/agent-abilities/chapters/04-the-mind.md
@@ -16,7 +16,7 @@ The agent reads its own high-salience memories and recent reflections and turns
Nothing is granted by default: the agent can propose but not act until the owner opts in per capability (create_alert, briefing, wallet_transfer). Reversible actions can be flipped to auto-run without asking; SOL transfers are irreversible, always confirmation-gated, and bounded by a daily SOL spend cap. The agent never sells or sends $THREE — it only accumulates and burns it.
-**How it works:** Scopes live on agent_identities.meta.autopilot (AUTOPILOT_DEFAULTS in api/_lib/autopilot.js: all scopes false, daily_spend_sol 0, require_confirm true) and are enforced server-side on every execute, including a live SOL balance read before any transfer (through the shared RPC failover lanes behind SOLANA_RPC_URL, so one provider's outage never blanks the check) that refuses with insufficient_funds when the wallet cannot cover the amount. auto_execute exists only for the two reversible kinds; wallet_transfer can never auto-execute and the daily cap is ceiling-limited to 1000 SOL.
+**How it works:** Scopes live on agent_identities.meta.autopilot (AUTOPILOT_DEFAULTS in api/_lib/autopilot.js: all scopes false, daily_spend_sol 0, require_confirm true) and are enforced server-side on every execute, including a live SOL balance read before any transfer (through the shared RPC failover lanes behind SOLANA_RPC_URL, so one provider's outage never blanks the check) that refuses with insufficient_funds when the wallet cannot cover the amount. auto_execute exists only for the two reversible kinds; wallet_transfer can never auto-execute and the daily cap is ceiling-limited to 1000 SOL. Executing a wallet_transfer also requires the owner's signed real-funds agreements (403 risk_ack_required otherwise), and an API key or OAuth token driving /api/autopilot/proposals (or the other money routes this chapter names: the sniper strategy, the market maker, agent hiring) must hold the wallet:write scope or is refused with 403 insufficient_scope.
**Why it matters:** You decide exactly how much rope the agent gets, capability by capability — and a misconfigured or compromised client can't widen it because enforcement is server-side.
diff --git a/docs/announcement-factory.md b/docs/announcement-factory.md
index ee625f4b7..0cc742045 100644
--- a/docs/announcement-factory.md
+++ b/docs/announcement-factory.md
@@ -13,13 +13,15 @@ that make a post checkable, and writing the thing.
```
announce:rank -> announce:plan -> announce:kit -> announce:media -> x:content review -> approve -> cron posts
- what is when it goes brief, draft, the frame from lint, live facts, owner Cloud Scheduler,
- worth it out, in what pack, queue the live route the AI editor decides every 15 minutes
+ what is when it goes brief, draft, the frame from lint, live facts, owner or Cloud Scheduler,
+ worth it out, in what pack, queue the live route the AI editor policy every 15 minutes
shape
```
-Nothing in this chain posts. Publishing still requires a passing editorial review and the owner
-setting an item's status to `approved`.
+Nothing in this chain posts. Publishing still requires a passing editorial review and an item at
+`approved`, which the owner sets or, for the narrow class the queue's approval policy allows
+(filmed, tags no one, a listed tier, passed on the editor's own verdict), the queue sets itself
+behind a veto window. See [Who approves a post](./x-content-pipeline.md#who-approves-a-post).
---
@@ -39,14 +41,15 @@ publishing rather than chosen here:
| Decision | Where it comes from |
|---|---|
-| How many posts a day, at what times, and which tier owns each one | The `cadence.slots` table of [`data/x-content/queue.json`](../data/x-content/queue.json), which is the same table the publisher fills from: T3 at 04:00 UTC, T2 at 12:00, T1 at 20:00. With no table declared, the times are derived from the daily cap, minimum gap and quiet hours instead, and a slot whose jitter window could land inside quiet hours is dropped rather than promised. |
+| How many posts a day, at what times, and which tier owns each one | The `cadence.slots` table of [`data/x-content/queue.json`](../data/x-content/queue.json), which is the same table the publisher fills from: T2 at 12:00 UTC, T1 at 15:30, T3 at 19:00, plus an X Article slot at 22:30 every second day. With no table declared, the times are derived from the daily cap, minimum gap and quiet hours instead, and a slot whose jitter window could land inside quiet hours is dropped rather than promised. |
| What order, and which shape | The ledger's scores, then rotation: no more than `maximumSameLaneInARow` of one audience, no more than `maximumSamePatternInARow` of one post shape, from the same queue file. |
| Which tier a surface is | What it is: a flagship (T1) is a `token`-lane surface or one that legitimately names a partner, proof of work (T3) is a package, worker or service, whose frame is a typeset card rather than a route, and everything with a page behind it is a feature (T2). The tier travels into the queue item, because the publisher gives each tier a slot of its own and an item with no tier is treated as a T2 feature. |
| Which one jumps the queue | [`data/announce-priority.json`](../data/announce-priority.json), the mirror image of the deferrals. A surface listed there enters the sequencer ahead of the backlog and takes the earliest slot its own tier owns, with the reason recorded beside it. The pin buys position only: the cadence, the tier discipline and the lane and shape rotation are unchanged, and the pack still goes through review and approval like any other. |
| Which ones need owner approval first | Any surface in the `crypto` section of [`data/pages.json`](../data/pages.json) renders live third-party market data, so a frame of it falls under the operating rules' coin gate. Those slots carry `mediaGate: "owner-approval"` and the factory skips them unless asked. |
The plan is a pure function of the ledger and the start date, so it is regenerated rather than
-maintained. A surface already queued, already carrying a pack, or listed in
+maintained. A surface already queued, named in a queued story's `covers` list (see
+[x-story-authoring.md](./x-story-authoring.md)), already carrying a pack, or listed in
[`data/announce-deferred.json`](../data/announce-deferred.json) is dropped from it.
**Gated surfaces are held out of the dated calendar.** `--hold-gated` (which `announce:kit` passes
@@ -150,8 +153,10 @@ image measured 0.875x against the account median, so "this one ships without an
option.
**3. The draft** ([`api/_lib/announce/draft.js`](../api/_lib/announce/draft.js)) is written by the
-model chain (Claude on Vertex AI, then OpenRouter, OpenAI, NVIDIA NIM) from the brief and nothing
-else. It is then held against every gate the queue enforces: the voice lint, the editorial lint,
+model chain (Claude on Vertex AI, then gpt-oss-120b on Groq, Claude through OpenRouter, OpenAI,
+NVIDIA NIM) from the brief and nothing else. The prompt keeps a floor of 100 characters and the
+queue's `maximumLength` as the wall, and tells the model that the first 280 characters are what a
+reader sees rather than steering it into a short band. It is then held against every gate the queue enforces: the voice lint, the editorial lint,
the claims ledger, the evidence list, and the account's own archive. Findings are handed back to
the model verbatim and it writes again, up to three attempts. A draft that still fails is written
to `data/announce-plan/drafts/<id>.rejected.json` instead of into the queue.
@@ -194,11 +199,17 @@ npm run x:content -- run --dry-run --id <id> # the exact calls that would go
npm run x:content -- approve --status review # the owner gate, for the whole batch
```
-`approve` is the only step that is the owner's, and it is a gate rather than a switch: it moves an
-item to `approved` only while a passing review record covers the exact bytes in the queue right
-now, and prints why it is holding anything it refuses. After that the Cloud Scheduler tick
-(`/api/cron/x-content`, every 15 minutes) sends each item at its slot, re-checks every link first,
-and records what it sent.
+`approve` is the owner's step, and it is a gate rather than a switch: it moves an item to
+`approved` only while a passing review record covers the exact bytes in the queue right now, and
+prints why it is holding anything it refuses. The queue's approval policy can also release a post
+itself, but only one that was filmed against the product, tags no one, sits in a listed tier and
+passed on the editor's own verdict, and only after a veto window in which
+`npm run x:content -- pause <id>` takes it back; `npm run x:content -- advance --ship` runs the
+whole line (film, review, policy release, publish) and says what stopped anything it held. After
+that the Cloud Scheduler tick (`/api/cron/x-content`, every 15 minutes) sends each item at its slot,
+re-checks every link first, and records what it sent. An approved post reaches production either
+with the next deploy or, with bundles enabled, straight away
+(see [Publishing without a deploy](./x-content-pipeline.md#publishing-without-a-deploy)).
So a week of announcements is four commands:
@@ -253,7 +264,8 @@ or hold it out of this pipeline entirely.
The factory needs a model for the drafting step and the editorial review. It uses the shared chain
in [`api/_lib/x-content/llm.js`](../api/_lib/x-content/llm.js): Claude on Vertex AI first (the
-standing Google Cloud approval), then `OPENROUTER_API_KEY`, `OPENAI_API_KEY`, `NVIDIA_API_KEY`.
+standing Google Cloud approval), then `GROQ_API_KEY` (text-only, so it drafts but never reviews an
+image), `OPENROUTER_API_KEY`, `OPENAI_API_KEY`, `NVIDIA_API_KEY`.
On a workstation, `gcloud auth application-default login` is enough. Everything else (ranking,
planning, briefs, media capture, packing, the whole gate) runs with no model at all:
`npm run announce:kit -- --brief-only` is the offline half.
diff --git a/docs/configuration.md b/docs/configuration.md
index ee98b2f5c..c4883b08d 100644
--- a/docs/configuration.md
+++ b/docs/configuration.md
@@ -116,7 +116,7 @@ OPENROUTER_API_KEY=sk-or-xxxxx
ANTHROPIC_API_KEY=sk-ant-api03-xxxxx
```
-Get from [console.anthropic.com](https://console.anthropic.com). `OPENAI_API_KEY` fills the same paid-backstop role for OpenAI, and watsonx (`WATSONX_API_KEY` plus a project scope) is served only on explicit request, never as a silent default.
+Get from [console.anthropic.com](https://console.anthropic.com). `OPENAI_API_KEY` fills the same paid-backstop role for OpenAI, and `GROK_API_KEY` (alias `XAI_API_KEY`) adds xAI Grok as the last paid rung; when it is unset the Grok rungs are skipped and only a user's own BYOK Grok key works. watsonx (`WATSONX_API_KEY` plus a project scope) is served only on explicit request, never as a silent default.
#### `CHAT_MODEL`
**Optional.** Pin a default chat model by id. It only applies when the provider that serves that model id (per the model catalog) is the one routed to; every other provider keeps its own default, so an Anthropic-style model id never leaks into a Groq request.
@@ -391,7 +391,7 @@ A **live configuration file** consumed at runtime by the Cloud Run server ([`ser
{
"src": "/agent/([^/]+)/embed",
"headers": {
- "content-security-policy": "frame-ancestors *; base-uri 'self'; object-src 'none'; report-uri /api/client-errors",
+ "content-security-policy": "frame-ancestors *; base-uri 'self'; object-src 'none'; script-src 'self' 'unsafe-inline' 'unsafe-eval' blob: https://cdn.jsdelivr.net https://cdnjs.cloudflare.com https://unpkg.com https://esm.sh https://ajax.googleapis.com https://s3.tradingview.com https://platform.twitter.com https://3d-agent.vercel.app https://three.ws; worker-src 'self' blob:; report-uri /api/client-errors",
"x-content-type-options": "nosniff",
"referrer-policy": "strict-origin-when-cross-origin",
"permissions-policy": "microphone=(self), camera=(self), xr-spatial-tracking=*",
@@ -411,6 +411,8 @@ A **live configuration file** consumed at runtime by the Cloud Run server ([`ser
}
```
+These routes also send `access-control-allow-origin: *` and `cross-origin-resource-policy: cross-origin` so any site can load the bundle. The moving channels (`latest`, a major like `1`, or a minor like `1.5`) get a short cache instead (`max-age=3600, s-maxage=300`). A miss under a version path (one that has not been released yet) answers 404 without the immutable policy, so a CDN edge does not keep serving that 404 after the version is cut. The UMD build (`agent-3d.umd.cjs`) is served as `text/javascript`, so it runs from a plain `<script>` tag.
+
**Cron jobs** are declared here as the source of truth for the schedule. Read the `crons` array itself for the current set rather than trusting a count quoted in prose. In production they are driven by **Google Cloud Scheduler**, each job hitting its `/api/cron/*` handler on the Cloud Run service:
```json
@@ -422,7 +424,7 @@ A **live configuration file** consumed at runtime by the Cloud Run server ([`ser
]
```
-These only run against the production deployment (Cloud Scheduler → Cloud Run), not locally. See [docs/ops/gcp-production.md](ops/gcp-production.md) for how the Scheduler jobs are provisioned.
+These only run against the production deployment (Cloud Scheduler → Cloud Run), not locally. A cron added to this array gets its Scheduler job on the next deploy: `npm run deploy:gcp:sync-crons` (part of `npm run deploy:gcp`) creates a job for every declared cron that has none and never touches existing jobs. See [docs/ops/gcp-production.md](ops/gcp-production.md) for how the Scheduler jobs are provisioned.
---
diff --git a/docs/developer-platform.md b/docs/developer-platform.md
index 401c5b5a2..8e7876d8b 100644
--- a/docs/developer-platform.md
+++ b/docs/developer-platform.md
@@ -8,7 +8,10 @@ discovery endpoints (the MCP tool catalog and the agent skills manifest).
The browser UI for all of this lives in the dashboard:
- **`/dashboard/api`**: create, list, and revoke API keys, and run the MCP
- "Test connection" button (source: `src/dashboard-next/pages/api.js`).
+ "Test connection" button (source: `src/dashboard-next/pages/api.js`). An MCP
+ client with OAuth (Claude, ChatGPT, Cursor, VS Code) needs no key at all:
+ [/connect](https://three.ws/connect) adds three.ws with a browser sign-in.
+ Keys are for scripts, servers, and clients without OAuth.
- **`/dashboard/developers`**: the Developer Hub with webhooks and the usage
overview (source: `src/dashboard-next/pages/developers.js`).
@@ -60,12 +63,20 @@ endpoints that accept `Authorization: Bearer` (see the
[API reference](./api-reference.md)). Each key carries a set of scopes:
`avatars:read`, `avatars:write`, `avatars:delete`, `profile`, `memory:read`,
-`memory:write`, `agents:read`, `agents:write`
-
-One more scope, `herald:announce` (posting through the
-[Herald](./herald.md)), is accepted by `/api/keys`, the dashboard form, and the
-older `POST /api/api-keys` route documented in
-[Authentication](./authentication.md#available-scopes).
+`memory:write`, `agents:read`, `agents:write`, `herald:announce` (posting
+through the [Herald](./herald.md)), `wallet:read`, `wallet:write`,
+`services:write`, and `inference` (model calls on the OpenAI-compatible
+endpoint, billed to the account's credits, and nothing else).
+
+`wallet:write` is the scope every route that moves an agent's funds checks for
+a bearer caller, so a key without it can read balances but never spend. One
+list ([api/_lib/api-keys.js](../api/_lib/api-keys.js)) feeds every surface that
+mints a key: `/api/keys`, the dashboard form, the CLI device link, and the older
+`POST /api/api-keys` route documented in
+[Authentication](./authentication.md#available-scopes). When that older route is
+called with a bearer token rather than a session, it refuses
+(`403 insufficient_scope`) to mint any scope the calling token does not itself
+hold.
Keys are stored as a SHA-256 hash. The plaintext secret is returned **exactly
once**, in the create response. Only the 12-character prefix is kept for
diff --git a/docs/economy-master.md b/docs/economy-master.md
index 53e363dcd..744591599 100644
--- a/docs/economy-master.md
+++ b/docs/economy-master.md
@@ -148,8 +148,8 @@ the return.
## Agent-wallet reclaim: the other half of the fleet's SOL
-Sweepback and `reclaimIdleSol` both walk the **`SOLANA_SIGNERS` registry** — the
-fifteen engine wallets. That is not where most of the platform's SOL lives.
+Sweepback and `reclaimIdleSol` both walk the **`SOLANA_SIGNERS` registry**, the
+sixteen engine wallets. That is not where most of the platform's SOL lives.
`fundAgentForLaunch` ([`api/_lib/launcher-funding.js`](../api/_lib/launcher-funding.js))
moves SOL master → **agent custody wallet** one way, and nothing ever moved it
back: snipes recycle ~97 % of their capital, but the proceeds settle into the
@@ -240,8 +240,19 @@ its next trade, the deficit, and why any arm is not trading:
```bash
node scripts/sniper-fleet-restore.mjs # report only, nothing moves
node scripts/sniper-fleet-restore.mjs --apply --yes # top up the fundable arms
+node scripts/sniper-fleet-restore.mjs --from-platform-bots # plan from idle bots
+node scripts/sniper-fleet-restore.mjs --from-platform-bots --apply --yes
```
+`--from-platform-bots` is for when the funding master itself is dry. It pays the
+deficits out of idle platform-owned agent wallets instead (the house account and
+`*@agents.three.ws` circulation bots that have no sniper strategy and no open
+position), and leaves each source at its idle reclaim floor. A customer's wallet
+is never a source, and only arms that opted into auto-funding and whose one
+blocking stall is `wallet_dry` are targets, so no SOL lands where it cannot trade
+or would be swept straight back. Like the default mode it is dry until
+`--apply --yes`.
+
Sweeps below `ECONOMY_SWEEPBACK_MIN_SOL` (0.01 SOL) are skipped as dust.
### A floor skip says whether the wallet is empty or fenced
@@ -275,6 +286,12 @@ A floor skip now carries both numbers, in the `<have><<need>` shape
}
```
+A wallet that sits ABOVE its keep line but whose excess is smaller than the
+minimum sweep is not fenced at all; it holds dust the sweep declines to move. It
+reports `below_min_sweep:<excess><<min>` (with an `excessSol` field) rather than
+`at_or_below_floor`, and the lever for that SOL is `ECONOMY_SWEEPBACK_MIN_SOL`,
+not a floor.
+
- `keepSol` is the number that actually blocked the sweep. Reporting and sizing
both read `reclaimKeepLineSol()`, so the message can never explain a refusal the
code did not make.
@@ -646,9 +663,9 @@ a third-party-verifiable timestamp of the books.
The 2026-07-02 wiring gaps this section used to track are closed. Current state
of the tree the master feeds:
-- **The registry defines the master plus fifteen engine signers** (relayers,
- launcher master, treasuries, marketplace payer, a2a payer, ring sponsor/payer,
- circulation treasury, NFT collection authority). An engine whose secret env is
+- **The registry defines the master plus sixteen engine signers** (relayers,
+ launcher master, treasuries, marketplace payer, gasless launch sponsor, a2a
+ payer, ring sponsor/payer, circulation treasury, NFT collection authority). An engine whose secret env is
unset simply never resolves and is skipped by the sweep; set each engine's
secret to bring it online, and override floors per signer with
`SIGNER_MIN_SOL_<NAME>` / `SIGNER_REFILL_TO_SOL_<NAME>`.
diff --git a/docs/erc8004.md b/docs/erc8004.md
index c14918766..acad6781d 100644
--- a/docs/erc8004.md
+++ b/docs/erc8004.md
@@ -380,6 +380,8 @@ const agent = await resolveOnchainAgent('/a/8453/42');
The resolver caches results per page session. Pass `{ fresh: true }` to bypass the cache.
+`publicUrl` and the metadata proxy fallback (below) default to the current page's origin. When you call the resolver from a page that is not three.ws, pass `{ origin: 'https://three.ws' }` so `publicUrl` links to the three.ws agent page and the proxy retry goes to three.ws rather than to your own host.
+
### Web component
```html
diff --git a/docs/home-households.md b/docs/home-households.md
index 1f4f5c5d0..460e4afd0 100644
--- a/docs/home-households.md
+++ b/docs/home-households.md
@@ -133,7 +133,7 @@ membership-aware at once rather than each one growing its own check.
|---|---|---|
| Store reads | `api/_lib/home/store.js` | `getConnection`, `listConnections` and `getDecryptedToken` join `home_members`. Each row comes back carrying `role` and `entity_scope`. There is deliberately no `or user_id = ...` beside the join. |
| Bridge runtime | `api/_lib/home/runtime.js` | `acquire` reads the home and its token through those two store functions, so it inherits membership without a check of its own |
-| REST routes | `api/_lib/home/access.js` | `resolveHomeAccess(req, res, homeId, capability)` is the single door. It returns `role` and `scope`, refuses a non-member 404 and a member without the capability 403. A bearer principal is held to the OAuth scope its capability maps to (`read` needs `home:read`, everything that changes the house, the roster, the layout or the allowances needs `home:act`), checked BEFORE the home is read so the refusal names the principal and not a house id |
+| REST routes | `api/_lib/home/access.js` | `resolveHomeAccess(req, res, homeId, capability)` is the single door. It returns `role` and `scope`, refuses a non-member 404 and a member without the capability 403. A bearer principal is held to the OAuth scope its capability maps to (`read` needs `home:read`, everything that changes the house, the roster, the layout or the allowances needs `home:act`), checked BEFORE the home is read so the refusal names the principal and not a house id. The account-level routes that have no single home to resolve (`GET`/`POST /api/home`, `/api/home/pair`, `/api/home/plan`) apply the same table through `homeScopeRefusal(caller, capability)`: listing needs `home:read`, connecting and pairing need `home:act` |
| Room graph | `api/home/[id].js`, `api/home/[id]/stream.js` | `filterGraphForScope` runs before serialization, on the single read and on every streamed frame |
| The gate | `api/home/[id]/call.js` | `confirmed: true` is refused before the socket is acquired, twice over: `canAssertConfirmation` refuses any principal that is not a signed-in browser session (a bearer token holding `home:act` can ask to act and can never say yes), then the role must hold `confirm`. An out-of-scope target is refused against the live graph |
| Scenes | `api/home/[id]/activate.js` | needs `act`; a scoped role is refused outright, because a scene reaches the whole house and a half-run scene is worse than none |
@@ -149,11 +149,11 @@ Route by route:
| `GET /api/home/:id` | `read` |
| `DELETE /api/home/:id` | `disconnect` |
| `GET /api/home/:id/stream` | `read` |
-| `GET /api/home/:id/log`, `/macros` | `read` |
+| `GET /api/home/:id/log`, `/macros` | `read` (the log is session-only, and a scoped member sees only actions on devices inside their scope, without who confirmed them or why) |
| `POST /api/home/:id/call`, `/activate` | `act`, plus `confirm` when the body carries `confirmed: true` |
| `POST /api/home/:id/confirm` | `confirm` |
| `GET /api/home/:id/grants` | `read` |
-| `POST`, `DELETE /api/home/:id/grants` | `grant` |
+| `POST`, `DELETE /api/home/:id/grants` | `grant`, from a signed-in session only (a grant is a standing yes, so a bearer token is refused) |
| `/api/home/pair` on an existing home | `manage` |
| `GET /api/home/:id/members` | `read` |
| `POST`, `PATCH`, `DELETE /api/home/:id/members` | `invite` |
@@ -178,8 +178,10 @@ one home and one role.
`{skipped: true}` and this reports `emailed: false`, which is a fact rather than a failure. A
dead mail provider never costs anybody their invitation: the row is already written and the link
in the response still works.
-- **Single use is enforced in the redeeming UPDATE's own WHERE clause**, not by a read followed by
- a write, so two people opening the same link at the same moment cannot both become members.
+- **Single use is enforced in the redeeming statement itself**, not by a read followed by a write:
+ one statement claims the invite in its UPDATE's WHERE clause and inserts the membership row only
+ from that claim, so two people opening the same link at the same moment cannot both become
+ members, and a burst of concurrent redemptions cannot slip past the seat cap.
- **Accepting requires an account, and this endpoint does not create one.** Registration and
sign-in already exist, they carry the captcha, the password rules and the session handling, and a
second door into account creation is a second door to keep secure. An unauthenticated POST
diff --git a/docs/home-security.md b/docs/home-security.md
index 71666a191..bcb2c3775 100644
--- a/docs/home-security.md
+++ b/docs/home-security.md
@@ -36,7 +36,7 @@ model is never permitted to assert its own confirmation.
|---|---|---|
| A stranger on the internet | Reach our API | Session or bearer auth on every route; ownership resolved in SQL (`WHERE user_id`), never compared in JavaScript; 404 (never 403) across a tenancy boundary; a rate-limit bucket on every route |
| A stranger who obtains a session | Act as the user | The gate. An unlock still needs a fresh, single-use, 90 second confirmation minted server-side and redeemed by a session that also passes CSRF |
-| A compromised or hijacked model | Call any tool with any argument | `confirmed` is absent from every home tool schema on both the MCP and the chat surface. A confirmation is only ever asserted by a browser session: `api/home/:id/confirm.js` refuses a bearer before it authenticates one, and `call.js` and `activate.js` refuse an inline `confirmed: true` from any principal that is not a session ([`canAssertConfirmation`](../api/_lib/home/access.js)). A token holding `home:act` can ask to act and is answered with the same 409 a browser gets |
+| A compromised or hijacked model | Call any tool with any argument | `confirmed` is absent from every home tool schema on both the MCP and the chat surface. A confirmation is only ever asserted by a browser session: `api/home/:id/confirm.js` refuses a bearer before it authenticates one, and `call.js` and `activate.js` refuse an inline `confirmed: true` from any principal that is not a session ([`canAssertConfirmation`](../api/_lib/home/access.js)). A token holding `home:act` can ask to act and is answered with the same 409 a browser gets. A standing allowance is a yes too, so `POST`/`DELETE /api/home/:id/grants` refuse every principal that is not a session for the same reason: otherwise a token could grant itself `lock.front_door` and then unlock it unconfirmed |
| A delegate the user authorised for something else | Hold a valid API key or OAuth token for this account | `resolveHomeAccess` reads the granted scope before it reads the home: `home:read` for a read, `home:act` for anything that changes a house. A token granted only `profile` is refused with `insufficient_scope` and never reaches the tenancy lookup |
| A malicious device or integration in the user's own house | Control entity names, area names, scene names | Those strings reach a model, so they are treated as untrusted input: capped, structured, and never the sole basis of an action. The gate is downstream of all of them and classifies by resolved entity, not by the words in the request |
| Another household member | Hold legitimate partial access | Roles and per-entity scopes ([`api/_lib/home/members.js`](../api/_lib/home/members.js)). A role that is short answers 403 and names the role; a home you are not in answers 404 and names nothing |
@@ -325,8 +325,8 @@ node scripts/home-test-instance.mjs --down --name sec11 --force
**The model half is a real requirement, not a nicety.** Check 4's real arm asks the
[LLM chain](../api/_lib/llm.js) for four turns and executes whatever they ask for. Without a
-credential the chain falls through to its two keyless anonymous rungs, both of which answer 429
-under any load, and the test **fails** with `no model in the chain answered, so this proved
+credential the chain falls through to its keyless anonymous rungs (Kilo's free Nemotron pool,
+OVH, Pollinations and LLM7), which are rate-limited per IP and answer 429 under load, and the test **fails** with `no model in the chain answered, so this proved
nothing`, followed by whatever the chain last said. That is deliberate: a door staying locked
because nothing ever asked to open it is an outage, not a proof, and a security check that passes
during an outage is worse than no check. Production carries the keys; locally, put one keyed rung
diff --git a/docs/labor-market.md b/docs/labor-market.md
index 33a142f4f..1f8ec43e8 100644
--- a/docs/labor-market.md
+++ b/docs/labor-market.md
@@ -29,7 +29,11 @@ agreements: `POST /api/labor/post` (escrowing the reward), `POST /api/labor/awar
signature gets `403 risk_ack_required` and nothing is escrowed, awarded or
released. Sign once at [/legal/agreements](https://three.ws/legal/agreements);
see [risk acknowledgment](./risk-acknowledgment.md). A worker settling a
-delivered job to collect its own payout is not gated.
+delivered job to collect its own payout is not gated. Called with an API key or
+OAuth token instead of a session, `post`, `award` and the autonomy-policy write
+(`PUT /api/labor/policy`, which arms an agent to post and pay on its own) also need
+the `wallet:write` scope; a token without it gets `403 insufficient_scope` before anything is
+escrowed.
The escrow secret lives only on the server (`LABOR_ESCROW_SECRET_BASE58`). The
escrow wallet pays its own SOL fees on release and self-tops-up from the platform
diff --git a/docs/ops/payment-outcomes.md b/docs/ops/payment-outcomes.md
index ff0d14065..61eb5531d 100644
--- a/docs/ops/payment-outcomes.md
+++ b/docs/ops/payment-outcomes.md
@@ -48,7 +48,15 @@ Counts and rates over 1h / 3h / 24h windows for payments arriving at our paid
routes:
- `settled` / `settle_failed`: outcomes of `settlePayment` after a valid
- verify. `settle_success_rate` = settled / (settled + settle_failed).
+ verify. `settle_success_rate` = settled / (settled + settle_failed). A Solana
+ settle that was broadcast but not yet confirmed when the response shipped
+ (the `settlement_pending` path, see
+ [x402-settlement-pending.md](../x402-settlement-pending.md)) is a
+ `payment_settled` row with `settlement_status = 'pending'` until the reconcile
+ cron promotes it, so it counts as settled here.
+- `unsettled_flush`: a handler that ended its own response before settlement
+ ran, so the buyer received the good without paying for it. Any nonzero count
+ is a route bug (it should be `streaming: true`), not buyer behaviour.
- `verify_rejected`: `verifyPayment` refusals, written durably as
`payment_verify_rejected` events (metadata carries `reason` and
`rejected_proof` vs `upstream_fault`). A spike here with flat settles is the
@@ -75,7 +83,8 @@ verify and would otherwise dilute the signal.
### `ring_settle` (from `gatherX402SettleHealth`)
The outbound settle-success sensor over `x402_autonomous_log` (3h window,
-rail-fault allowlist), verbatim: status, human detail, triage hint, and the
+rail-fault allowlist, and excluding unpaid probe pipelines such as the
+`reliability` uptime monitor, whose third-party timeouts never touch a payment), verbatim: status, human detail, triage hint, and the
top fault signatures. This is the same object `/api/healthz` consumes; it is
included here so the board is complete without a second request. Its triage
map lives in [production-log-triage.md](production-log-triage.md).
@@ -84,11 +93,23 @@ The ring log is reason-blind for refusals that arrive over HTTP (they all read
as `http_5xx`), so the sensor reconciles status-only 5xx faults against the
facilitator's own book (`x402_self_facilitator_log.reject_reason`) for the same
window and names the dominant cause in `ring_settle.metrics.cause`:
-`sponsor_floor` (the Solana accept was withdrawn under the SOL floor),
+`sponsor_floor` (the sponsor fee wallet is under its SOL floor),
`fee_governor` (deliberate spend pacing, a budget problem, not a rail fault),
or `rail` (genuine settle faults). `governorSkips` is carried even on a healthy
rate so a wallet sliding toward its budget shows up before the rate does.
+`ring_settle.metrics.mechanism` is what to read second, because one cause can
+point at opposite evidence: `accept_withdrawn` (the Solana accept is gone from
+the challenge, so the facilitator never saw the calls) versus `settle_refused`
+(the accept is still advertised and the facilitator refuses each settle at the
+floor gate, naming the wallet in `fee_wallet_below_floor:<held><<floor>`), plus
+`paced`, `rail`, and `gate_bypass`. `gate_bypass` (counted in
+`metrics.gateBypass`) means a caller outside the ring is signing payments the fee
+governor then refuses at settle without asking the admission gate first; it marks
+the sensor `degraded` even while the ring's own rate looks healthy. The mechanism
+table and where each one's proof lives are in
+[production-log-triage.md](production-log-triage.md).
+
A rent-exemption failure on the fee payer (`InsufficientFundsForRent` on
account index 0, in either spelling the RPCs use) wears a rail-shaped reason
token (`sweep_broadcast_failed`, and `simulation_failed` on any path that has
@@ -201,8 +222,8 @@ the floor, `sponsorKnownBelowFloor()` makes `buildRequirements()` withdraw the
Solana accept from every 402 challenge, so the Solana-only ring never attempts a
payment and there is nothing to reject. Settlements collapse while rail faults
stay flat. The settle sensor reports that as `cause: sponsor_floor` (distinct
-from `fee_governor` and `rail`) in `ring_settle.metrics`; the accepts are
-checkable directly:
+from `fee_governor` and `rail`) with mechanism `accept_withdrawn` in
+`ring_settle.metrics`; the accepts are checkable directly:
```sh
curl -s https://three.ws/api/x402/three-intel | jq '.accepts[].network'
diff --git a/docs/plan-checkout.md b/docs/plan-checkout.md
index f70a9ec23..034a037e4 100644
--- a/docs/plan-checkout.md
+++ b/docs/plan-checkout.md
@@ -102,6 +102,7 @@ On success, one atomic transaction claims the intent, upserts `subscriptions`, a
| 503 | `price_unavailable` | No live price feed for SOL/$THREE right now — retry shortly |
| 503 | `not_configured` | `PAYMENT_RECIPIENT_SOLANA` unset |
| 422 | `tx_not_found` | Not finalized yet — retry in a few seconds |
+| 422 | `tx_failed` | The transaction landed but errored on-chain |
| 422 | `memo_mismatch` | Payment is missing the intent nonce memo |
| 422 | `transfer_not_found` | Right memo, wrong asset/amount/recipient |
| 410 | `intent_expired` | Quote lapsed beyond the grace window — create a new checkout |
@@ -119,4 +120,4 @@ On success, one atomic transaction claims the intent, upserts `subscriptions`, a
| `SOLANA_RPC_URL` / `SOLANA_RPC_URL_DEVNET` | RPC endpoints — set a paid RPC in production |
| `SOLANA_USDC_MINT` | Override the USDC mint (defaults to mainnet USDC) |
-Plan prices live in [api/payments/_config.js](../api/payments/_config.js) (`PLANS`), the single source of truth: both pricing pages and the `plans` action read from it. The EVM (USDC-only) sibling path is [api/payments/evm/[action].js](../api/payments/evm/%5Baction%5D.js). It verifies the same way with two chain-specific differences: it waits for 12 confirmations before granting (EVM reorgs, versus Solana's `finalized` commitment), and because an ERC-20 transfer carries no memo it binds the payment to the account by requiring the payer address to be a wallet linked to that user. It honors the same 1-hour post-expiry grace window, which the confirmation wait makes necessary rather than merely kind.
+Plan prices live in [data/plans.json](../data/plans.json), the single source of truth: [api/payments/_config.js](../api/payments/_config.js) builds `PLANS` from its purchasable rows (and the plan length from its `billing_period_days`), so the `/pricing` page, the quota checks and the `plans` action all quote the same number. The EVM (USDC-only) sibling path is [api/payments/evm/[action].js](../api/payments/evm/%5Baction%5D.js). It verifies the same way with two chain-specific differences: it waits for 12 confirmations before granting (EVM reorgs, versus Solana's `finalized` commitment), and because an ERC-20 transfer carries no memo it binds the payment to the account by requiring the payer address to be a wallet linked to that user. It honors the same 1-hour post-expiry grace window, which the confirmation wait makes necessary rather than merely kind.
diff --git a/docs/smart-home.md b/docs/smart-home.md
index bdc7d9a7b..7ccfe2fb0 100644
--- a/docs/smart-home.md
+++ b/docs/smart-home.md
@@ -299,7 +299,10 @@ page sideways at 320px: the failure it exists to catch is a state nobody ever op
all, connects a real Home Assistant, and is the only one that can prove the summary is the
house's own numbers, that a real long-lived token reaches no browser storage, and that stopping
the container really does produce `degraded` with the summary intact. It runs under
-`npm run test:home:e2e`.
+`npm run test:home:e2e`, which must carry the encryption key bound to the database it writes to
+(`HOME_E2E_ENC_KEY`, else an exported `WALLET_ENCRYPTION_KEY`); a random per-run key is refused at
+the first connect with `secret_box_key_mismatch`, and the global setup checks the binding before
+any browser opens. The exact command is in [tests/e2e/README.md](../tests/e2e/README.md).
Two invariants hold the surface together, and both are asserted in those specs rather than left
as prose.
diff --git a/docs/swarms.md b/docs/swarms.md
index 5332141d3..a3d60a139 100644
--- a/docs/swarms.md
+++ b/docs/swarms.md
@@ -150,6 +150,12 @@ A cookie-session caller must present a single-use CSRF token
is exempt, since the token is itself the proof of intent. Both are metered at
30 mutations per minute per user.
+The four actions that move treasury SOL or switch treasury trading on (`create`,
+`contribute`, `exit`, `resume`) carry two more. On mainnet the account must have
+signed the real-funds agreements first (see the [risk acknowledgment](./risk-acknowledgment.md);
+devnet swarms are exempt), and a bearer/API-key caller must hold the
+`wallet:write` scope. `join`, `pause` and `kill` move nothing and need neither.
+
```bash
# Create. The policy is optional; anything you omit takes the default above.
CSRF=$(curl -s https://three.ws/api/csrf-token -H 'Cookie: <session>' | jq -r .token)
@@ -195,6 +201,8 @@ Every failure returns `{ error, error_description }` with a specific code rather
| 400 | `too_small` | Contribution under the 0.005 SOL floor |
| 401 | `unauthorized` | Mutation or `?mine=1` without a session |
| 402 | `insufficient_funds` | The agent wallet cannot fund the contribution |
+| 403 | `risk_ack_required` | A mainnet `create`, `contribute`, `exit` or `resume` from an account that has not signed the real-funds agreements |
+| 403 | `insufficient_scope` | The same actions from an API key without `wallet:write` |
| 403 | `csrf_missing`, `csrf_invalid` | Session mutation with no (or a spent) `X-CSRF-Token` |
| 403 | `forbidden` | Acting for an agent you do not own, or a creator-only action (`pause`, `resume`) from a member |
| 403 | `invite_only` | `join` by anyone but the creator on a swarm with `join_open: false` |
@@ -208,6 +216,7 @@ Every failure returns `{ error, error_description }` with a specific code rather
| 409 | `killed` | The swarm's kill switch is already pulled |
| 409 | `closed` | `join` or `contribute` on a killed or closed swarm |
| 409 | `share_cap` | The contribution would push one member past `max_member_share_bps` |
+| 409 | `exit_in_progress` | This member already has an exit being paid or settled; a concurrent second `exit` is refused before any SOL moves |
| 409 | `positions_open` | `exit` under `wait_to_close` while positions are still open |
## Related
diff --git a/docs/ux-flows/01-onboarding-creation.md b/docs/ux-flows/01-onboarding-creation.md
index 89f361859..d029d003d 100644
--- a/docs/ux-flows/01-onboarding-creation.md
+++ b/docs/ux-flows/01-onboarding-creation.md
@@ -40,7 +40,7 @@
5. (optional) Upload path: pick a `.glb`; `handleGlbFile` validates the GLB magic bytes, then `stageAndReview` stashes the blob via `guest-avatar.js` (IndexedDB) and navigates to `/create-review`.
6. (optional) Editor/Template path: the in-page `AvatarCreator` produces a GLB blob → `stageAndReview` → `/create-review`.
7. (optional) Remix strip: click a saved avatar thumbnail → `handleFork(av.id)` (same fork path as step 3).
- 8. (optional) Android share-sheet handoff: a file shared into the installed app is POSTed to `/create/share`, parked in the Cache API by `public/share-target-sw.js`, and the visitor lands here with `?shared=glb` (a `.glb`, pulled back out through `src/shared/share-target.js` and fed into the upload path), `?shared=1` (a photo, handed on untouched to `/create/selfie?shared=1`), `?shared=nosw` (the worker was not installed yet; share again) or `?shared=error`. The read is one-shot, so a reload never re-attaches the file.
+ 8. (optional) Share-sheet handoff (Android, and the iOS app): a file shared into the installed app is POSTed to `/create/share`, parked in the Cache API by `public/share-target-sw.js`, and the visitor lands here with `?shared=glb` (a `.glb`, pulled back out through `src/shared/share-target.js` and fed into the upload path), `?shared=1` (a photo, handed on untouched to `/create/selfie?shared=1`), `?shared=nosw` (the worker was not installed yet; share again) or `?shared=error`. The iOS app has no service worker, so its share extension parks the files in the app instead and opens `?shared=glb&inbox=<id>` (or `/create/selfie?shared=1&inbox=<id>` for photos); `takeSharedFiles()` reads them from the app's native bridge before falling back to the Cache API. The read is one-shot, so a reload never re-attaches the file.
- **Decision points / branches:** intent hub (agent wizard / avatar options / Forge / launchpad) vs direct card pick; fork vs fresh; eight creation method cards (base editor / prompt / template / selfie / video / Cosmos / upload / studio); anonymous (stage→review) vs signed-in (direct save/fork); video flag on/off; avatar-quota reached vs not.
- **External calls / dependencies:** `GET /api/config`; `GET /api/avatars`; `GET /api/usage/summary`; `POST /api/avatars/fork`; `GET /api/avatars/:id` + raw GLB fetch (guest fork). External avatar-platform iframes loaded by `AvatarCreator`.
- **Success state:** A staged or owned avatar; the user is forwarded to `/create-review` (anonymous) or `/avatars/<id>` (forked) — onward to agent creation.
diff --git a/docs/ux-flows/04-embed-widget-studio.md b/docs/ux-flows/04-embed-widget-studio.md
index ac03dcbc3..4f377b84e 100644
--- a/docs/ux-flows/04-embed-widget-studio.md
+++ b/docs/ux-flows/04-embed-widget-studio.md
@@ -24,7 +24,7 @@ Routing recap (from `vercel.json`):
### Widget Studio — `/studio`
- **Source:** `public/studio/index.html`, `public/studio/studio.js`, `public/studio/studio.css`, `public/studio/launch-panel.js`, `public/studio/knowledge-panel.js`. Preview iframe loads `/widget` (slim `src/app.js` shell). APIs: `/api/auth/me`, `/api/avatars`, `/api/avatars/public`, `/api/avatars/:id`, `/api/widgets`.
- **Entry point:** Direct nav to `/studio`; "Create yours" / "Open the Studio" CTAs on `/widgets`; "Open Studio →" on `/features/studio`; "Open in Studio" links from gallery cards (`/studio?template=<id>`); the "Configure in wizard" links on avatar/agent pages and the dashboard; deep links `?edit=<id>`, `?type=<type>`, `?model=<url>`, `?avatar=<id>`, plus the inherited embed-editor form `?mode=static|idle|walking|chat` with `?avatar=`, `?controls=`, `?env=`, `?bg=`, `?width=`, `?height=`, `?autoplay=`, `?speed=`, `?ground=`, `?gestures=`, `?badge=`. Those same names are written back into `location.search` as you edit a URL-baked widget, so a configured studio URL is itself a shareable artifact.
-- **Prerequisites / gates:** None to try, and for two widget types, none to finish. A built-in **demo avatar (CZ, `/avatars/cz.glb`)** is preloaded so an anonymous visitor can configure and preview. The **walking-avatar** and **agent-chat** types bake their whole configuration into the embed URL, so a signed-out visitor can configure, generate and copy a working snippet with no account and no database row (the modal hides the `/w/<id>` share URL and the script-tag snippet, which do need one, and says what signing in adds). Every other type stores config server-side, so **saving a draft or embedding with them requires sign-in** (`/login?next=/studio`) and an owned/public avatar. The demo avatar can generate an embed (pointing at a baked demo fixture, e.g. `wdgt_demo_talking`) but cannot save. No $THREE gate. ⚡ Launch tab can optionally launch the agent's coin via `launch-panel.js` (lane toggle: pump.fun or the three.ws curve; oversized token images are downscaled in-browser instead of rejected). The coin-type radio group offers agent / regular / mayhem / USDC / holder-reward / open-source-reward, and a `?reward=` deep link carried in from Launch Studio (`{platform,login}` or `{address}`) pre-fills the creator-fee recipient and is passed through to the Fees & rewards step, so the routing a recipe promised is what the coin ships with. Targets the wizard has no create-time control over are not offered at all.
+- **Prerequisites / gates:** None to try, and for two widget types, none to finish. A built-in **demo avatar (CZ, `/avatars/cz.glb`)** is preloaded so an anonymous visitor can configure and preview. The **walking-avatar** and **agent-chat** types bake their whole configuration into the embed URL, so a signed-out visitor can configure, generate and copy a working snippet with no account and no database row (the modal hides the `/w/<id>` share URL and the script-tag snippet, which do need one, and says what signing in adds). Every other type stores config server-side, so **saving a draft or embedding with them requires sign-in** (`/login?next=/studio`) and an owned/public avatar. The demo avatar can generate an embed (pointing at a baked demo fixture, e.g. `wdgt_demo_talking`) but cannot save. No $THREE gate. ⚡ Launch tab can optionally launch the agent's coin via `launch-panel.js` (lane toggle: pump.fun or the three.ws curve, which is quoted in $THREE, so its first buy is an amount of $THREE capped at 10,000,000 and the panel links to `/three-launchpad`; oversized token images are downscaled in-browser instead of rejected). The coin-type radio group offers agent / regular / mayhem / USDC / holder-reward / open-source-reward, and a `?reward=` deep link carried in from Launch Studio (`{platform,login}` or `{address}`) pre-fills the creator-fee recipient and is passed through to the Fees & rewards step, so the routing a recipe promised is what the coin ships with. Targets the wizard has no create-time control over are not offered at all.
- **Steps (10):**
1. Page boots → `fetchMe()` (`/api/auth/me`) resolves user; user menu renders (signed-out shows "Sign in"); 3-column layout unhides.
2. System renders the **widget-type grid** (11 ready types: turntable, animation-gallery, talking-agent, passport, hotspot-tour, pumpfun-feed, kol-trades, live-trades-canvas, bonding-curve, walking-avatar, agent-chat) and **avatar list** (`loadAvatars()` → demo avatar + `/api/avatars?limit=100` for signed-in users, with skeleton cards while loading).
@@ -65,7 +65,7 @@ Routing recap (from `vercel.json`):
- Customized state (size≠M, custom accent, non-default mint/kind) makes the "Share URL" output the `/widget#…` hash form (preserves overrides) instead of `/w/<id>`.
- Filter chips show/hide cards by type and re-index for the stagger animation.
- Preview iframe uses `reveal=interaction` + a `/api/widgets/<id>/og` poster to keep WebGL slots free on a dense page.
-- **External calls / dependencies:** `/widgets-gallery/showcase.json`, preview iframes at `/widget#widget=<id>…`, `/api/widgets/<id>/og` (poster), model-viewer 4.0.0 (footer avatar, from googleapis CDN with SRI). Mints used in defaults are SOL wrapped-mint and the `$THREE` CA.
+- **External calls / dependencies:** `/widgets-gallery/showcase.json`, preview iframes at `/widget#widget=<id>…`, `/api/widgets/<id>/og` (poster), model-viewer 4.3.1 (footer avatar, from googleapis CDN with SRI, plus the `/model-viewer-meshopt.js` decoder shim so compressed GLBs load). Mints used in defaults are SOL wrapped-mint and the `$THREE` CA.
- **Success state:** Snippet copied to clipboard ("Copied!"); live preview rendered in card.
- **Empty / error states:** Showcase fetch failure → `role=alert` card "The widget showcase could not load. Check your connection and try again." with the detail, a **Try again** button that re-runs the load (replacing the filter bar instead of stacking a second one) and a "Read the widget docs" link (`/docs/widgets`). A manifest with zero widgets → "No showcase widgets yet" empty state with **Open the Studio**. Per-card iframe failure leaves the placeholder/play button. Hero count defaults to 15 in static HTML, overwritten by the real count (and re-written whenever the i18n runtime repaints the badge).
- **Step count:** 6 required (+3 optional)
@@ -162,7 +162,7 @@ Routing recap (from `vercel.json`):
## Cross-flow notes
- **`/widget` shell** is the shared render surface: Studio + gallery previews and the `/embed.js` script-tag embed all point at `/widget#widget=<id>&kiosk=true`.
- **`embed.js`** (`public/embed.js`) is the script-tag loader: reads `data-widget` / `data-widget-url`, `data-width/height/radius/border`, `data-reveal`, `data-poster`, `data-priority`, `data-motion`, mounts a sandboxed iframe at the script position, and supports multiple embeds per page.
-- **Web component `<agent-3d>`** (`/dist-lib/agent-3d.js`, authored in `src/element.js`) is the first-class embedding primitive surfaced by SharePanel and AgentEmbedModal; its observed attributes include `src`, `agent-id`, `avatar-id`, `mode`, `background`, `name-plate`, `avatar-chat`, `avatar-walk` and `sonar`. `sonar` only *permits* acoustic hand control: nothing opens a microphone or emits the ultrasonic carrier until the host page calls `startSonar()` behind a real user gesture, and the sensing modules under `src/sonar/` are imported on that first call, so an embed that never calls it ships none of them. Each recognised gesture fires a cancelable `sonar-gesture` event, so a host page can `preventDefault()` and drive its own surface instead of the default (sweep steps the gesture cast, push dollies the camera, a held lift turns it). Removing the attribute stops a live session.
+- **Web component `<agent-3d>`** (`/dist-lib/agent-3d.js`, authored in `src/element.js`) is the first-class embedding primitive surfaced by SharePanel and AgentEmbedModal; its observed attributes include `src`, `agent-id`, `avatar-id`, `api-base`, `mode`, `background`, `name-plate`, `avatar-chat`, `avatar-walk` and `sonar`. On a third-party page every API call the element makes goes to `api-base` when set, else the origin that served its script (`https://three.ws` when the script came from a package CDN such as unpkg or jsDelivr), never the host page's own origin (`src/shared/embed-api-origin.js`). In chat mode it renders its own composer: a text input, a send button, and a push-to-talk mic where speech input is available. `sonar` only *permits* acoustic hand control: nothing opens a microphone or emits the ultrasonic carrier until the host page calls `startSonar()` behind a real user gesture, and the sensing modules under `src/sonar/` are imported on that first call, so an embed that never calls it ships none of them. Each recognised gesture fires a cancelable `sonar-gesture` event, so a host page can `preventDefault()` and drive its own surface instead of the default (sweep steps the gesture cast, push dollies the camera, a held lift turns it). Removing the attribute stops a live session.
- **avatar-embed runtime** (`src/avatar-embed.js`) backs `/embed/avatar/<handle>` and `/a-embed.html` (the agent embed at `/agents/<id>/embed` is a separate page, see above); exposes the `v1.avatar.*` postMessage bridge (speak, emote, morphs, lookAt, mocap, idle, hotkeys, mic, state) plus third-party-compatible event aliases and a same-origin BroadcastChannel control surface. Three things it does that an embedder feels directly:
- **A stored avatar always renders through the same-origin proxy `/api/avatars/<id>/glb`**, never the `url` the API hands back. That URL is a presigned `r2.cloudflarestorage.com` read for a private avatar and the public `r2.dev` domain for a shared one; the first sends no `access-control-allow-origin` at all and the second allows only the three.ws origin, so GLTFLoader was CORS-blocked on a dev server, a preview host, or any embedding page on another domain. The proxy carries the session cookie through the permission gate and falls back to the public bucket when the signed read is refused. The optimization lane (`?lod=`, `?textureSize=`, `?morphs=`, `?draco=1`) takes the id and only for a public or unlisted avatar; a private one stays on the unoptimized proxy rather than 404ing.
- **A load failure reads as a sentence, not a transport string.** `src/shared/viewer-error-text.js` maps the failures a visitor can hit onto plain language ("This avatar is private. Sign in with the account that owns it.", "The avatar service is unavailable. Refresh to try again.", "Connection lost. Check your network and refresh.", "This avatar's 3D file could not be read."); the raw rejection goes to the console for whoever is debugging the embed.
diff --git a/docs/ux-flows/06-marketplace-skills.md b/docs/ux-flows/06-marketplace-skills.md
index 0fae6dd10..61197ce62 100644
--- a/docs/ux-flows/06-marketplace-skills.md
+++ b/docs/ux-flows/06-marketplace-skills.md
@@ -33,7 +33,7 @@ Routing facts confirmed in `vercel.json` (line numbers shift too often to pin; g
10. (optional) User clicks a tag pill on a card → `navTo(/marketplace?tag=X)` → `render()` re-filters the in-memory grid.
11. User scrolls to the grid bottom → IntersectionObserver fires `loadList(false)` (append) with `?cursor=…`; a manual "Load more" button maps to the same handler.
12. User clicks a card → `navTo()`: agent → `/marketplace/agents/:id` (301 → `/agents/:id`), avatar → `/marketplace/avatars/:id` (301 → `/avatars/:id`), onchain → `/marketplace/onchain/:id` (SPA detail) or external fallback link.
-- **Decision points / branches:** filter type (All / Agents / Avatars / Onchain); price (Any / Free / Paid); 3D model category chips; sort mode; tab via `?tab=` (agents | avatars | onchain | skills | tools | memory | earn | purchases | mine).
+- **Decision points / branches:** filter type (All / Agents / Avatars / Onchain); price (Any / Free / Paid); 3D model category chips; sort mode; tab via `?tab=` (agents | avatars | onchain | skills | animations | tools | memory | earn | purchases | mine). The animations tab lists the platform's generated motion collection from `/api/marketplace/animations` (each clip baked onto the platform rig as a GLB and sold through the x402 `/api/x402/animation-download` route); a fixed-size subset is free for one week at a time, labelled "Free this week" with the date the regular price returns.
- **External calls / dependencies:** `api/marketplace/[action].js` (categories, agents, theme, agents/:id, /versions, /similar), `/api/explore`, `/api/auth/me`, `/api/users/me/purchased-skills`. 3D via model-viewer + Three.js (lobby).
- **Success state:** Populated grid with featured 3D hero, theme strip, and per-section counts; cards navigable to detail.
- **Empty / error states:** `renderEmptyState()` ("No results" + "Browse categories" CTA); `renderCategoriesError()` with retry in sidebar; `renderErrorState('agents'|'avatars'|'skills')` with retry; per-card model-viewer load error message.
@@ -53,11 +53,12 @@ Routing facts confirmed in `vercel.json` (line numbers shift too often to pin; g
5. (optional) User clicks the creator name → `openCreatorModal()` fetches `/api/creators/:id` and shows the creator's agents/avatars.
6. (optional) User starts a trial (see Trial flow), unlocks a skill (see Skill purchase flow), or buys the whole asset (see Asset purchase flow).
7. (optional, owner only) If `currentUserId === agent.owner_id`, a price editor panel appears; save/clear posts to `/api/marketplace/asset-price`.
-- **Decision points / branches:** owner vs buyer view; skill is free / owned / paid / trial-eligible; asset is for-sale vs not.
+ 8. (optional) If the agent offers subscription tiers, **Subscribe** on a tier navigates to `/agents/:id?tier=<plan id>#ad-tiers-card`, where the agent page opens that tier's verified checkout once (quote, wallet signature, `/api/subscriptions/subscribe` then `/verify`). A tier only becomes active after its first payment verifies on-chain; a bare `POST /api/subscriptions` records the row unpaid (`past_due`) and unlocks nothing.
+- **Decision points / branches:** owner vs buyer view; skill is free / owned / paid / trial-eligible; asset is for-sale vs not; tier subscribed vs not.
- **External calls / dependencies:** `/api/marketplace/agents/:id` (+ `/versions`, `/similar`, `/preview`), `/api/creators/:id`, `/api/avatars/:id` (avatar detail), `/api/marketplace/asset-price` (owner price edit).
- **Success state:** Full detail with interactive 3D, skill list, live preview, and the correct action (Unlock / Buy / Try free / owner editor).
- **Empty / error states:** `showDetailState('error'|'notfound')` overlay with retry; avatar detail "Avatar not found"; 3D stage "Couldn't load the 3D model." with a 15s "still loading" hint; preview errors surfaced in the chat footer.
-- **Step count:** 3 required (+4 optional)
+- **Step count:** 3 required (+5 optional)
---
@@ -79,7 +80,7 @@ Routing facts confirmed in `vercel.json` (line numbers shift too often to pin; g
11. **Branch — verification outcomes:** `confirmed` → success; `409 transfer_mismatch` (status `tipped` when a smaller-but-real transfer landed); `410 purchase_expired` for a stale pending row.
12. On confirmed, modal renders a signed receipt (`buildReceiptHTML`) with a Solscan link, then resolves true.
13. Client refreshes ownership: `fetchUserPurchases()` and reloads the detail (`loadDetail`) so the skill now shows "Installed ✓"; the purchase appears under the "My Purchases" tab and in `/collection`.
-- **Decision points / branches:** gasless (wallet connected, sponsored) vs buyer-pays vs mobile QR (Solana Pay); already-owned short-circuit; insufficient funds → Add funds; gift purchase (`recipient`) resolved server-side via `resolveRecipient`; verification mismatch (tipped) vs expired. A separate agent rail exists: `POST /api/marketplace/purchase-as-agent` `{ buyer_agent_id, seller_agent_id, skill }` buys the skill FOR an owned agent from its custodial wallet (owner-authenticated, CSRF-gated, 10 autonomous purchases/hour/agent, same daily spend cap as asset purchases). Because that rail spends from a wallet three.ws custodies, it also calls `requireRealFundsAgreement()` (`api/_lib/real-funds-agreement.js`): an account with no current signature on the Terms of Service, Risk Disclosure and Agent Wallet Agreement gets `403 risk_ack_required` naming `/legal/agreements`, over session and API key alike, and nothing is sent. Devnet is exempt. The buyer-signs-in-their-own-wallet path is not gated there; the embed widget asks for the signature client-side first (`ensureRiskAck({ context: 'skill-purchase' })` in `src/payment-modal.js`).
+- **Decision points / branches:** gasless (wallet connected, sponsored) vs buyer-pays vs mobile QR (Solana Pay); already-owned short-circuit; insufficient funds → Add funds; gift purchase (`recipient`) resolved server-side via `resolveRecipient`; verification mismatch (tipped) vs expired. A separate agent rail exists: `POST /api/marketplace/purchase-as-agent` `{ buyer_agent_id, seller_agent_id, skill }` buys the skill FOR an owned agent from its custodial wallet (owner-authenticated, CSRF-gated, 10 autonomous purchases/hour/agent, same daily spend cap as asset purchases). Because that rail spends from a wallet three.ws custodies, it also calls `requireRealFundsAgreement()` (`api/_lib/real-funds-agreement.js`): an account with no current signature on the Terms of Service, Risk Disclosure and Agent Wallet Agreement gets `403 risk_ack_required` naming `/legal/agreements`, over session and API key alike, and nothing is sent. Devnet is exempt. An API key or OAuth token driving this rail (or `buy-asset` with `agent_id`, or `/api/x402-pay` from an agent wallet) must also hold the `wallet:write` scope, or it gets `403 insufficient_scope` before anything is signed. The buyer-signs-in-their-own-wallet path is not gated there; the embed widget asks for the signature client-side first (`ensureRiskAck({ context: 'skill-purchase' })` in `src/payment-modal.js`).
- **External calls / dependencies:** `POST /api/marketplace/purchase`, `POST /api/marketplace/purchase/:ref/confirm`, `GET /api/marketplace/purchase/:ref` (status), `GET /api/marketplace/check-skill-access`, Solana RPC via `/api/solana-rpc` (rotates lanes; when every lane dies at the wire it re-sweeps once and answers an idempotent read from its last-good body, flagged with an `x-solana-rpc-stale` header, instead of a 502), `@solana/web3.js` + `@solana/spl-token` (lazy-loaded), `@solana/pay` (server `findReference`/`validateTransfer`), gasless tx builder, `/api/users/me/purchased-skills` (post-purchase refresh), `/api/billing/receipts` (receipt download in My Purchases).
- **Success state:** Receipt with tx link; skill flips to owned; appears in My Purchases tab and `/collection`; `check-skill-access` returns `has_access: true`.
- **Empty / error states:** cancelled connect/tx ("try again"), insufficient funds (Add funds button), `verification_failed` (paid but unverified — contact support), network error, expired pending row — all with the confirm button re-enabled for retry. Re-verify (no new tx) supported when a txid exists.
diff --git a/docs/ux-flows/07-crypto-trading-analytics.md b/docs/ux-flows/07-crypto-trading-analytics.md
index 1651e17ce..8ed484fc5 100644
--- a/docs/ux-flows/07-crypto-trading-analytics.md
+++ b/docs/ux-flows/07-crypto-trading-analytics.md
@@ -13,7 +13,7 @@ coin-intel, pump-visualizer and pump-live: adding a coin on any surface shows up
### Oracle — `/oracle`
- **Source:** `pages/oracle.html`, `src/oracle.js` (~2500 lines), lazy `src/oracle-graph.js` (3D force graph), `src/oracle-tape.js` (live trade tape in the coin drawer)
-- **Entry point:** nav link "Oracle"; direct URL; SEO/share links from `coinShareUrl()`. `/oracle/coin/<mint>` is now a standalone full conviction coin page (server-rendered by `api/oracle-share.js` in the markets-hub style: score dial, pillar bars, chart, launch intelligence), reached from the drawer's "Full page ↗" action. The server-rendered hero also carries the score's measured odds (what share of calls in that band won, against the random-launch base rate, read from `conviction-calibration.json` via `hitRateFor`) and a "Since the call" strip (peak multiple, graduated / rugged / still live, market cap now) joined from `pump_coin_outcomes`, so the first paint and the share preview never show an unqualified 100/prime on a coin the market has already resolved; the share description gets a "since:" clause for the same reason. Coin identity falls back to DexScreener when pump.fun does not answer, coin art is proxied through `/api/img`, and the route is GET-only.
+- **Entry point:** nav link "Oracle"; direct URL; SEO/share links from `coinShareUrl()`. `/oracle/coin/<mint>` is now a standalone full conviction coin page (server-rendered by `api/oracle-share.js` in the markets-hub style: score dial, pillar bars, chart, launch intelligence; `public/oracle-coin.js` adds the shared chart-source switcher, so its Line and Agent trades views sit beside DexScreener, Birdeye, GMGN, DEXTools and GeckoTerminal tabs, and the terminal pills carry a `from=oracle-share` tag), reached from the drawer's "Full page ↗" action. The server-rendered hero also carries the score's measured odds (what share of calls in that band won, against the random-launch base rate, read from `conviction-calibration.json` via `hitRateFor`) and a "Since the call" strip (peak multiple, graduated / rugged / still live, market cap now) joined from `pump_coin_outcomes`, so the first paint and the share preview never show an unqualified 100/prime on a coin the market has already resolved; the share description gets a "since:" clause for the same reason. Coin identity falls back to DexScreener when pump.fun does not answer, coin art is proxied through `/api/img`, and the route is GET-only.
- **Prerequisites / gates:** Public dashboard for all read views (feed, movers, wallets, edge, proof, agents, activity, graph). The **Agent** (arm) tab requires sign-in + an existing 3D agent with a custodial Solana wallet; Live mode spends real (capped) SOL.
- **Steps (N):**
1. Arrive on `/oracle` → `boot()` populates category filter, binds tab/seg listeners, reads URL filters (`tier`, `category`, `minScore`, `view`), loads the **feed** view.
@@ -22,7 +22,7 @@ coin-intel, pump-visualizer and pump-live: adding a coin on any surface shows up
4. (optional) Filter: click `#tierSeg` tier buttons / category select / min-score / sort seg / ★-watchlist-only toggle / breadth-bar tier segments → `syncFilterUrl()` + `loadFeed()` (URL is shareable). A hero "Join the live Telegram feed" button appears when `/api/oracle/stats` reports a configured public signals channel.
5. (optional) Switch view tab: `movers`, `wallets` (reputation leaderboard), `edge` (tier backtest win-rate; the hero names the specific bands that invert the ladder instead of claiming calibration, states the fitted event's own hit rate (a 3x run or graduation) beside the stricter clean-win rate, and each calibration row shows "claims N%" next to the realized bar, with "n/a" for an unmeasured band), `proof` (resolved wins), `agents` (agent win-rate ledger), `activity` (live agent actions), `graph` (3D force graph, lazy-imports oracle-graph.js).
6. (optional) Click a coin card → `openDrawer(mint)` → `GET /api/oracle/coin?mint=...` renders the 4-pillar conviction breakdown (who/how/what/move); oracle-tape.js streams that coin's live trades.
- 7. (optional) In the drawer: Full page ↗ (`/oracle/coin/<mint>`), pump.fun ↗, GMGN ↗ (via `src/shared/trading-terminals.js`, referral-tagged), solscan ↗, Details ↗ (`/launches/<mint>`), View in 3D ↗ (`/coin3d?mint=`), ☆/★ Watch (writes `ld_watchlist`), Copy mint, Copy link, Share to X; the live Market panel adds GMGN/DexScreener/GeckoTerminal/Birdeye links when available.
+ 7. (optional) In the drawer: Full page ↗ (`/oracle/coin/<mint>`), pump.fun ↗, GMGN ↗ (via `src/shared/trading-terminals.js`, referral-tagged), solscan ↗, Details ↗ (`/launches/<mint>`), View in 3D ↗ (`/coin3d?mint=`), ☆/★ Watch (writes `ld_watchlist`), Copy mint, Copy link, Share to X; the live Market panel adds GMGN/DEXTools/DexScreener/GeckoTerminal/Birdeye links when available. A DEXTools link that knows only the mint goes through the counted redirect `GET /api/coin/dextools` (it resolves the top pool, redirects to its pair page, and records a per-day, per-surface visit in `dextools_referrals`, since DEXTools Social Boost ranks tokens by pair-page visits); when the pair is already known the link goes straight to its pair page, which is how the Oracle's market panel links the most liquid pair DexScreener names, and $THREE always its Social Boost pair.
8. (optional, agents view) Follow an agent's signals: expand follow-panel → enter Telegram chat ID → `POST /api/oracle/follow`.
9. **Arm payoff (gated):** open **Agent** tab → `loadAgentPanel()` → `GET /api/agents`. Pick agent, set Min conviction (Prime/Strong+/Lean+), Size/trade SOL, Max daily SOL, Max open, category filters, optional Telegram chat ID (Send test → server push), toggle Armed + Live/Simulate switches → **Save configuration** → `POST /api/oracle/watch` `{armed, mode, min_score, per_trade_sol, max_daily_sol, max_open, ...}`. Confirmation: "Armed in simulate/live mode. Your agent is watching the stream." Arming live is judged on the raw request, not the clamped values: a `per_trade_sol` below 0.001 SOL or a `max_daily_sol` below `per_trade_sol` answers 400 before any real-money loop starts (simulate keeps the forgiving clamps), and the GET side rejects a non-uuid `agent_id` with 400. The move INTO live-armed also requires a current signature on the three real-funds agreements (`requireRealFundsAgreement()`, `403 risk_ack_required` pointing at `/legal/agreements`); re-saving a watch that is already live-armed, simulate mode, disarming, and devnet all stay open.
- **Decision points / branches:** view tabs (9); feed warming vs populated vs filtered-empty; drawer coin scored vs "not scored yet"; agent has wallet vs needs creation (`/create/studio`); simulate vs live mode; signed-out → "Sign in and arm an agent".
@@ -77,7 +77,7 @@ coin-intel, pump-visualizer and pump-live: adding a coin on any surface shows up
- **Steps (N):**
1. Arrive → `readUrl()` restores mint/tab/network (network persisted to localStorage `tf_network`); the deep-dive mounts immediately with the URL mint, or $THREE by default (never an empty void).
2. System: left rail loads the active tab: **Launches** (`GET /api/pump/launches?network=&limit=40`, $THREE pinned at the top) or **Exits** (`GET /api/trades/feed?network=&window=7d&min_pnl_pct=10&limit=40`); refreshes every 30s. Header pulse (`GET /api/pump/helius-stats`, 20s) shows network mint rate, graduations/hour, and SOL price ± 24h change.
- 3. System: centre deep-dive (`mountDetail`) paints header + skeleton instantly from the clicked row, then fills progressively from five live endpoints (`/api/pump/launch-detail`, `/api/pump/curve`, `/api/pump/intel`, `/api/pump/smart-money`, `/api/coin/:mint/cohorts`; cohorts only for platform-tracked coins) plus three self-fetching widgets: candlestick chart (`src/mission-control/chart.js`, `GET /api/pump/price-history` over Birdeye, then GeckoTerminal, then pump.fun OHLCV; a single candle is already a chart, so a coin minutes old draws and grows from the live stream, and a coin that has never traded says "No market yet" instead of blaming the interval), bonding-curve ring, live trade tape. A row clicked in the Exits tab carries its trade with it, so an "Agent exit" card (realized PnL, exit multiple, hold time, entry/exit SOL, exit reason, entry/exit tx links, the agent's `/agents/<id>` link and "Copy trader →" to `/trader/<id>`) paints with the shell, no second round-trip. The price strip reads a migrated coin as Graduated even when the curve account is closed, and swaps the SOL cell for a "Price source" cell (Jupiter / pump.fun curve) once there is no curve price to quote.
+ 3. System: centre deep-dive (`mountDetail`) paints header + skeleton instantly from the clicked row, then fills progressively from five live endpoints (`/api/pump/launch-detail`, `/api/pump/curve`, `/api/pump/intel`, `/api/pump/smart-money`, `/api/coin/:mint/cohorts`; cohorts only for platform-tracked coins) plus three self-fetching widgets: a chart with a source switcher (`mountSwitchableChart` from `src/shared/chart-switcher.js`; tabs for the platform's own TradingView-engine candles, DexScreener, Birdeye, GMGN, DEXTools and GeckoTerminal, the pick remembered in `ld_chart_view` and carried to every coin surface, each provider tab with an "Open in <provider>" link, arrow-key navigation, and an explanation plus retry when a provider cannot draw the coin). The default candle view is `src/mission-control/chart.js` (`GET /api/pump/price-history` over Birdeye, then GeckoTerminal, then pump.fun OHLCV, with the TradingView attribution link the chart library's license requires; a single candle is already a chart, so a coin minutes old draws and grows from the live stream, and a coin that has never traded says "No market yet" instead of blaming the interval), bonding-curve ring, live trade tape. A row clicked in the Exits tab carries its trade with it, so an "Agent exit" card (realized PnL, exit multiple, hold time, entry/exit SOL, exit reason, entry/exit tx links, the agent's `/agents/<id>` link and "Copy trader →" to `/trader/<id>`) paints with the shell, no second round-trip. The price strip reads a migrated coin as Graduated even when the curve account is closed, and swaps the SOL cell for a "Price source" cell (Jupiter / pump.fun curve) once there is no curve price to quote.
4. (optional) Switch tab Launches ↔ Exits (`#ttTabs`) → reload rail; URL synced.
5. (optional) Change network mainnet/devnet (`#ttNetwork`, persisted) → reload rail + remount deep-dive.
6. (optional) Paste a mint into `#ttSearch` (base58-validated) → drives the deep-dive for that coin.
@@ -91,22 +91,23 @@ coin-intel, pump-visualizer and pump-live: adding a coin on any surface shows up
---
### Trader Leaderboard — `/leaderboard`
-- **Source:** `pages/leaderboard.html`, `src/leaderboard.js` (imports `src/trader-format.js`, `src/shared/agent-wallet-chip.js`)
+- **Source:** `pages/leaderboard.html`, `src/leaderboard.js` (imports `src/trader-format.js`, `src/shared/agent-wallet-chip.js`, `src/leaderboard-earned.js`)
- **Entry point:** nav "Leaderboard"; footer.
- **Prerequisites / gates:** None — public ranked board.
- **Steps (N):**
- 1. Arrive → `readUrl()` hydrates state (network/window/sort/verified), live-refreshing every 20s.
+ 1. Arrive → `readUrl()` hydrates state (tab/network/window/sort/verified), live-refreshing every 20s. Two boards share the page: **Trading** (default) and **Earned** (`?tab=earned`, picked before first paint so it never flashes the trading view).
2. System: `GET /api/sniper/leaderboard?network=&window=&sort=&verified=` renders ranked rows (agent name + verified badge, wallet chip, unique coins, copiers count); top 3 styled.
3. (optional) Window: 24h/7d/30d/all (`#lb-window`) → URL + reload.
4. (optional) Network: mainnet/devnet (`#lb-network`).
5. (optional) Sort: score/pnl/winrate/roi (`#lb-sort` select).
6. (optional) "Verified only" checkbox (`#lb-verified`).
- 7. (optional) Click a row → trader profile (`src/trader.js`, `/trader/<agent_id>`) with full track record, equity curve, proof tab with on-chain tx, copy-trading panel, shareable PnL card.
-- **Decision points / branches:** 4 windows × sort × network × verified; stale/reconnecting badge when a background refresh fails with a board already on screen.
-- **External calls / dependencies:** `GET /api/sniper/leaderboard`; row payoff `GET /api/sniper/trader` (on trader page).
+ 7. (optional) Click a row → trader profile (`src/trader.js`, `/trader/<agent_id>`) with full track record, equity curve, proof tab with on-chain tx, a "why" drawer on every closed trade (the evidence its gates had at entry, from `GET /api/sniper/receipt?id=`), copy-trading panel, shareable PnL card, a "Watch live room" link to `/trade-rooms/<id>`, and the syndicates and trader duels it appears in.
+ 8. (optional) **Earned** tab → `GET /api/leaderboard/earnings` ranks public agents by what they earned in the window (creator fees from their coins plus service income from x402 skill sales and hires, each beside the total); it opens on 7d, refreshes every 60s (the snapshot behind it updates every 30 minutes), pages 25 rows at a time, and every row links to the agent's page, whose Earned card carries the same figures.
+- **Decision points / branches:** Trading vs Earned tab; 4 windows × sort × network × verified (Trading); stale/reconnecting badge when a background refresh fails with a board already on screen.
+- **External calls / dependencies:** `GET /api/sniper/leaderboard`; `GET /api/leaderboard/earnings` (Earned tab); row payoff `GET /api/sniper/trader` (on trader page).
- **Success state:** shareable ranked board; every number deep-links to its on-chain transaction via the trader profile.
-- **Empty / error states:** "No agent has closed a sniper position in this window…" with guidance (widen window / disable verified); `#lb-retry` button on load failure; stale badge.
-- **Step count:** 2 required (arrive → board) + ~5 optional (filters, sort, drill to trader).
+- **Empty / error states:** "No agent has closed a sniper position in this window…" with guidance (widen window / disable verified); an empty Earned window offers "See all-time earnings"; `#lb-retry` button on load failure; stale badge.
+- **Step count:** 2 required (arrive → board) + ~6 optional (filters, sort, drill to trader, Earned tab).
---
@@ -159,7 +160,7 @@ coin-intel, pump-visualizer and pump-live: adding a coin on any surface shows up
2. System: `connectApi()` polls `GET /api/healthz` (15s) → status dot; `connectWebSocket()` opens `wss://pumpportal.fun/api/data`, subscribes `subscribeNewToken` + `subscribeMigration` (exponential backoff, 8-attempt cap → manual Reconnect banner).
3. System: preloads `GET /api/pump/channel-feed?limit=40`, `GET /api/pump/helius-stats` (30s), `GET /api/agents/featured`, `GET /api/pump/trending?limit=25` ($THREE pinned first), config probes, uptime ticker.
4. (optional) Connect wallet → `wallet:changed` → `POST /api/wallet/balances` renders SOL + top-10 holdings.
- 5. (optional) Default tab: inspect monitor stat cards, featured agent, network health, market chart (`chart:tokenChange` → fetch candles), high-conviction Oracle panel, live-feed preview.
+ 5. (optional) Default tab: inspect monitor stat cards, featured agent, network health, market chart (`chart:tokenChange` → fetch candles; the page's own canvas chart keeps its place and the shared chart-source switcher lines DexScreener, Birdeye, GMGN, DEXTools and GeckoTerminal up beside it), high-conviction Oracle panel, live-feed preview.
6. (optional) **Live Feed** tab: pause + filter (Launches/Trades/Whales/Graduations/Claims) the rAF-batched WS feed.
7. (optional) **Token Scanner**: enter mint → scan for risk/honeypot. Every RPC call is timed out (some providers accept `getTokenLargestAccounts` and never answer), and the button plus a persistent status line carry the busy state so a failed scan cannot read as one that was never run: a timeout is distinguishable from an unreachable endpoint in both the toast and the RPC badge, an address with no account on mainnet says exactly that, and a failure tells the reader to press Scan again.
8. (optional) **Quote Engine**: buy/sell quote forms.
@@ -243,10 +244,10 @@ coin-intel, pump-visualizer and pump-live: adding a coin on any surface shows up
2. System: `GET /api/pump/intel?view=feed&limit=60` renders cards (quality score ring 0–100, verdict pill strong/watch/caution/avoid, organic-vs-bundle bar, risk flags, narrative).
3. (optional) Toolbar filters: search (220ms debounce), category chips, verdict dropdown, quality dropdown → `loadRadar()`.
4. (optional) Watch toggle per coin → `ld_watchlist`.
- 5. (optional) Switch tab: Radar / Leaderboard (`?view=leaderboard`) / Smart-Money Traders (`?view=traders`) / What it learned (`?view=learning`, signal weights + outcome distribution + coverage).
- 6. (optional) Click coin → drawer `GET /api/pump/intel?mint=<mint>` (full signals + outcome + top wallets classified + funder clusters/bubble-map) + async `GET /api/oracle/coin?mint=` conviction enrichment.
-- **Decision points / branches:** 4 tabs; filter combinations; coin observed vs "not observed"; labeled winners vs none; ≥50 labeled coins for trained weights vs baseline; Oracle enrichment present vs absent.
-- **External calls / dependencies:** `GET /api/pump/intel` (`view=feed|leaderboard|traders|learning`, `?mint=`), async `GET /api/oracle/coin`. Data from `pump_coin_intel`, `pump_coin_outcomes`, `pump_coin_wallets`, `pump_intel_weights` (off-browser engine). No direct browser RPC/WS.
+ 5. (optional) Switch tab: Radar / Leaderboard (`?view=leaderboard`) / Smart-Money Traders (`?view=traders`) / What it learned (`?view=learning`, signal weights + outcome distribution + coverage) / **Scout** (`src/coin-intel-scout.js` over `GET /api/pump/sentiment-scout`: the last hour of launches ranked by sourced momentum, every claim carrying its source URL, the time it was true, and for social or paid claims the on-chain facts read in the same run; X posts quoting the exact contract address are counted by distinct voice and one-account shilling is flagged).
+ 6. (optional) Click coin → drawer `GET /api/pump/intel?mint=<mint>` (full signals + outcome + top wallets classified + funder clusters/bubble-map) + async `GET /api/oracle/coin?mint=` conviction enrichment + a Sentiment Scout section injected above the launch signals when the Scout has a read for that coin.
+- **Decision points / branches:** 5 tabs; filter combinations; coin observed vs "not observed"; labeled winners vs none; ≥50 labeled coins for trained weights vs baseline; Oracle enrichment present vs absent.
+- **External calls / dependencies:** `GET /api/pump/intel` (`view=feed|leaderboard|traders|learning`, `?mint=`), `GET /api/pump/sentiment-scout` (Scout tab and drawer section), async `GET /api/oracle/coin`. Data from `pump_coin_intel`, `pump_coin_outcomes`, `pump_coin_wallets`, `pump_intel_weights` (off-browser engine). No direct browser RPC/WS.
- **Success state:** live classified-coin radar with verdicts + risk flags; leaderboard of best coins + confirmed winners (ATH multiple); cross-coin trader board; "what it learned" signal-weight transparency; per-coin bubble-map drawer.
- **Empty / error states:** "The engine is warming up"; "No coins match these filters" + Reset; drawer "Not observed yet"; "No labeled winners yet"; "No traders recorded yet"; "Not enough data to train yet"; degraded badge; retry on network failure. The leaderboard's own empty state reads "Nothing scored in the last 24 hours" (the radar's "loosen your filters" copy no longer appears on a tab with no filters); every failed tab (radar, both leaderboard rails, traders, all three learning panels, the drawer) carries its own Retry, and the header stat tiles fall back to dashes beside the amber degraded pulse rather than disappearing.
- **Step count:** 2 required (arrive → radar feed) + ~6 optional (search/filters, watch, tabs, inspect coin).
@@ -261,7 +262,7 @@ coin-intel, pump-visualizer and pump-live: adding a coin on any surface shows up
- **Steps (N):**
1. Arrive → 3D agent (CZ default) loads into `<model-viewer>` (auto-rotate); params parsed (chain=sol, interval=1h, minSmartBuys=2, narrate, avatar, mood).
2. System: SSE `EventSource('/api/agents/gmgn-feed?chain=sol&interval=1h&minSmartBuys=2')` → `hello` event (status pill "Live · SOL · 1h"), last 10 events replayed (dimmed), then `smart_entry` events stream live.
- 3. System per event: render card (symbol, market cap, smart-buy delta, price change), trigger agent animation by delta/new flag, optional TTS narration, increment stats, "↑ N new" jump button if scrolled.
+ 3. System per event: render card (symbol, market cap, smart-buy delta, price change, and a DEXTools link through the counted `/api/coin/dextools` redirect on chains DEXTools covers), trigger agent animation by delta/new flag, optional TTS narration, increment stats, "↑ N new" jump button if scrolled.
4. (optional) Change chain (sol/eth/base/bsc), interval (1m–24h), minSmartBuys; mood (chill/normal/hype); narration toggle.
5. (optional) Avatar picker modal → `GET /api/avatars/public` + `GET /api/avatars` → "Use this avatar" swaps model.
6. (optional) **Apply** (`#ctl-reconnect`) → `connect()` closes old EventSource, opens new with updated params.
@@ -363,7 +364,7 @@ coin-intel, pump-visualizer and pump-live: adding a coin on any surface shows up
1. Arrive → `renderControls()` paints the window switch (24h / 7 days / 30 days / All time, default `7d`), then `refresh()` runs immediately and every 30s. The timer is cleared on `visibilitychange` when the tab hides and restarted on return.
2. System: `GET /api/sniper/experiments?network=mainnet&window=<key>` fills three regions: summary tiles (`#xp-summary`), the strategy comparison table (`#xp-board`), and the LLM judgment ledger (`#xp-judgment`).
3. System: summary tiles read armed vs paused count, closed trades + open now, fleet realized P&L for the window, fleet SOL on hand across wallets, best arm, moon bags riding (count + SOL at last quote, deliberately excluded from realized P&L), earned-autonomy split (earned / probation / standard), and the master funding wallet with its balance.
- 4. System: one board row per armed strategy: label + autonomy-tier badge, agent link (`/a/<agent_id>`), decision-mode badge (`rules`, or `LLM · <model>`), wallet chip linking to Solscan with a low-balance warning under 0.02 SOL, reasoning-ledger link, entry conditions with per-trade SOL and the exit shape (stop loss, trailing stop, max hold, ladder multiple + moon-bag percentage or "no ladder"), record (`W · L`, open count, moon bags, and a separate paper line for simulate-mode fills), win rate, realized SOL, ROI, average trade, average hold, last trade.
+ 4. System: one board row per armed strategy: label + autonomy-tier badge, agent link (`/a/<agent_id>`), decision-mode badge (`rules`, or `LLM · <model>`, plus `+ Scout` when the judge also reads the Sentiment Scout's sourced evidence), wallet chip linking to Solscan with a low-balance warning under 0.02 SOL, reasoning-ledger link, entry conditions with per-trade SOL and the exit shape (stop loss, trailing stop, max hold, ladder multiple + moon-bag percentage or "no ladder"), record (`W · L`, open count, moon bags, and a separate paper line for simulate-mode fills), win rate, realized SOL, ROI, average trade, average hold, last trade.
5. System: a stalled arm gets a loud explanation instead of a bare zero: `stallLine()` renders "not trading" for a blocking condition and "idle" for an arm that simply has not qualified yet, with every other blocking reason listed beneath the headline so fixing the first does not just reveal the second later.
6. System: the judgment ledger scores each LLM judge on its own verdicts (buy rate, average confidence, buy precision against what the coin did an hour later, missed winners among its skips, average latency).
7. (optional) Click a window button → re-render controls + refetch that window.
diff --git a/docs/ux-flows/12-home-and-content.md b/docs/ux-flows/12-home-and-content.md
index 2b79cf112..51b41177a 100644
--- a/docs/ux-flows/12-home-and-content.md
+++ b/docs/ux-flows/12-home-and-content.md
@@ -220,14 +220,14 @@ Agent/crawler endpoints — not user UX (0 user steps). All resolve via `vercel.
| Endpoint | Route | Served by | Purpose |
|---|---|---|---|
| Sitemap | `/sitemap.xml` | `/api/sitemap` (function) | XML sitemap for crawlers (sub-sitemaps at `/sitemap/{core,agents,avatars,widgets,profiles,news}.xml`) |
-| LLMs index | `/llms.txt` | `public/llms.txt` (static) | LLM site index |
-| LLMs full | `/llms-full.txt` | `public/llms-full.txt` (static) | Full LLM corpus dump |
+| LLMs index | `/llms.txt` | `public/llms.txt` (static, generated by `npm run build:pages`) | Curated guide an agent can read whole: the official-domain and $THREE-mint block, then the pages listed under `site.llms` in `data/pages.json` (the build fails if a curated path stops being a real, indexable page) |
+| LLMs full | `/llms-full.txt` | `public/llms-full.txt` (static, same generator) | The complete page list |
| Robots | `/robots.txt` | `public/robots.txt` (static) | Crawler directives |
| OpenAPI | `/openapi.json` | `/api/openapi-json` (function) | OpenAPI spec for the REST API (domain specs also at `/api/crypto/openapi.json`, `/api/3d/openapi.json`) |
| x402 discovery | `/.well-known/x402` | `/api/wk?name=x402` | x402 micropayment service discovery (`/.well-known/x402.json` → `name=x402-discovery`) |
| Agent attestation schemas | `/.well-known/agent-attestation-schemas` | `/api/wk?name=agent-attestation-schemas` | ERC-8004 attestation schema descriptors |
| OAuth AS metadata | `/.well-known/oauth-authorization-server` | `/api/wk?name=oauth-authorization-server` | OAuth 2.0 Authorization Server metadata |
-| OAuth protected resource | `/.well-known/oauth-protected-resource` (also under `/api/mcp/`) | `/api/wk?name=oauth-protected-resource` | OAuth 2.0 Protected Resource metadata |
+| OAuth protected resource | `/.well-known/oauth-protected-resource` (also under `/api/mcp/`, and per hosted MCP server by RFC 9728 path insertion, e.g. `/.well-known/oauth-protected-resource/api/mcp-agent`) | `/api/wk?name=oauth-protected-resource` (`&path=` for a per-server copy; a path that is not a hosted MCP server 404s) | OAuth 2.0 Protected Resource metadata; each hosted MCP server gets its own `resource` so stock SDK connectors can sign in |
| Chat plugin manifest | `/.well-known/chat-plugin.json` | `/api/wk?name=chat-plugin` | AI chat-plugin manifest (the real LobeChat manifest) |
| Sperax plugin manifest | `/.well-known/sperax-plugin.json` | `/api/wk?name=sperax-plugin` | Sperax plugin manifest |
| Apple app-site association | `/.well-known/apple-app-site-association` | `/api/wk?name=apple-app-site-association` | iOS universal-link association for the App Store shell |