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 17 more docs whose code moved, from wallet and auth scopes to reputation reads

nirholasfc0d16603873
diff --git a/docs/agent-index.md b/docs/agent-index.md
index 8bdb739ca..970a00f63 100644
--- a/docs/agent-index.md
+++ b/docs/agent-index.md
@@ -148,8 +148,13 @@ The monitor reports both legs. Read them differently:
nothing on a tick where every chain is current. The first pass itself walks
chains worst backlog first, with a never-crawled chain ahead of everything
and a caught-up chain ranked by how long its cursor has stood still, so a
- chain that errors on every tick (which keeps reporting the zero backlog its
- last good crawl left) is not sorted to the back of the sweep forever.
+ chain that errors on every tick is not sorted to the back of the sweep
+ forever. A tick that reads the head but fails to advance the cursor still
+ banks the real backlog (`head_block`, `blocks_behind`) without touching the
+ cursor's age, so a chain stuck on a dead lane shows the blocks it is missing
+ instead of the zero its last good crawl left. When a chain's cursor age is
+ stale, the health detail names that stalest chain beside the age, separately
+ from the chain with the worst backlog.
A leg that is reaching every agent and recording nothing counts as `down`, not
as fresh. That shape (every cursor current, zero events) is what a crashing
@@ -161,7 +166,12 @@ Cursor age is blind to a second shape, because the Solana sweep stamps its
account cannot hold the oldest-first queue head forever). A wedged agent then
looks exactly as fresh as a healthy one. So the monitor also scores the **share
of Solana cursors carrying an error**: 5% reads as `degraded`, 25% as `down`
-(`SOLANA_ERROR_RATE_DEGRADED` and `SOLANA_ERROR_RATE_DOWN`).
+(`SOLANA_ERROR_RATE_DEGRADED` and `SOLANA_ERROR_RATE_DOWN`). A provider
+brownout must not read as hundreds of broken agents, so the sweep carries a
+breaker: after `SOLANA_SWEEP_RPC_BREAKER` (5) consecutive RPC-fabric failures it
+stops dispatching for the tick and leaves the rest of the batch untouched at the
+head of the oldest-first queue for the next one. Any success resets the count,
+and errors that are about the agent itself never count toward it.
The failure those thresholds were built for is the retention wall. Each leg
resumes from the last signature or block it recorded; when the RPC answering the
diff --git a/docs/agent-wallet-api.md b/docs/agent-wallet-api.md
index cafdc7402..584664cbe 100644
--- a/docs/agent-wallet-api.md
+++ b/docs/agent-wallet-api.md
@@ -49,11 +49,21 @@ The resolved user id is then compared against `agent_identities.user_id`. The th
Recovery differs: it computes the caller's relationship to the agent (owner, guardian, beneficiary) and authorizes per action. See [Recovery](#recovery-guardians-threshold-and-inheritance).
+#### Bearer scope: `wallet:write`
+
+A session cookie carries every scope. A bearer token carries only what it was granted, and on the capabilities, intents, recovery, and Solana guard surfaces any write (every method other than `GET`, `HEAD`, and `OPTIONS`) from a bearer token needs the `wallet:write` scope. The check is [`assertBearerMaySpend`](../api/_lib/spend-scope.js) and runs while the caller is being resolved, before the owner gate. A bearer without the scope gets:
+
+| Status | `error` | Meaning |
+|---|---|---|
+| `403` | `insufficient_scope` | The token is valid but was not granted `wallet:write` |
+
+Reads still pass with a `wallet:read` token. Orders, Treasury Autopilot, and Portfolio do not run this check today, so any valid bearer token for the owner can call them.
+
### CSRF
Every state-changing request passes through [`api/_lib/csrf.js`](../api/_lib/csrf.js).
-- **Bearer callers are exempt.** The token is itself the proof of intent, and browsers do not attach it automatically.
+- **Bearer callers are exempt** when the bearer is what authenticated them: the request carries no session cookie, or the bearer token resolves to the same account as the cookie. The token is itself the proof of intent, and browsers do not attach it automatically. A request that carries a session cookie plus a bearer header for a different account (or an invalid one) is checked like a cookie caller, because the cookie is what the server authenticates first.
- **Cookie callers must double-submit.** Fetch a token from `GET /api/csrf-token` and echo it in the `X-CSRF-Token` header. Tokens are bound to the user id, expire after one hour, and are consumed on use, so each mutation needs a fresh one.
Failures are `403 csrf_missing` (header absent) and `403 csrf_invalid` (wrong user, expired, or already consumed).
@@ -515,9 +525,11 @@ All writes are owner-gated and CSRF-gated. `:intentId` must be a UUID.
### The intent model
-Triggers: `on_tip_received` (optional `min_sol`), `on_income`, `on_balance_below` (required `threshold_sol`), `on_schedule` (`cadence` of `daily` or `weekly`, `weekday` 0 through 6, `hour` 0 through 23 UTC), `on_launch_matching` (needs a base58 `creator` and/or a `max_mcap_usd`, optional `min_mcap_usd`), and `on_stream_started`.
+Triggers: `on_tip_received` (optional `min_sol`), `on_income`, `on_balance_below` (required `threshold_sol`), `on_schedule` (`cadence` of `daily` or `weekly`, `weekday` 0 through 6, `hour` 0 through 23 UTC), `on_launch_matching` (needs a base58 `creator` and/or a `max_mcap_usd`, optional `min_mcap_usd`), `on_stream_started`, `credits_below` (required `threshold_usd`, the owner's account credits), and `on_mail_received` (optional `from_contains` and `subject_contains` filters, matched case-insensitively). A further trigger, `on_automation`, is fired only by the v1 automation engine, never by the sweep.
-Actions: `tip`, `transfer`, `withdraw`, `split_income` (move SOL: take `pct` with an `of` basis of `tip`, `income`, or `balance`, or a fixed `amount_sol`, or for a withdraw an `above_sol` floor, plus a `destination`), `buy` and `snipe` (need `amount_sol`, plus a `mint` unless the trigger is `on_launch_matching`, with an optional `slippage_pct` clamped to 0 through 50 and defaulting to 5), `freeze` (no parameters, the kill switch), and `notify` (optional `message`, `channel` of `email` or `log`).
+Actions: `tip`, `transfer`, `withdraw`, `split_income` (move SOL: take `pct` with an `of` basis of `tip`, `income`, or `balance`, or a fixed `amount_sol`, or for a withdraw an `above_sol` floor, plus a `destination`), `buy` and `snipe` (need `amount_sol`, plus a `mint` unless the trigger is `on_launch_matching`, with an optional `slippage_pct` clamped to 0 through 50 and defaulting to 5), `freeze` (no parameters, the kill switch), `notify` (optional `message`, `channel` of `email` or `log`), and `fund_inference` (top up the owner's account credits from the agent's USDC: `amount_usdc` from 0.1 to 1000, at most once per rule per UTC day).
+
+Some pairings are refused: `fund_inference` runs only on `credits_below` or `on_schedule`, a `credits_below` rule can only `fund_inference` or `notify`, and an `on_mail_received` rule can only `notify` or `freeze`, because an inbound email is untrusted input and must never move funds.
A tip-back to whoever just tipped needs no destination: with `on_tip_received` plus a `tip` action the engine fills in the tipper at fire time and marks `to_tipper`.
@@ -525,7 +537,9 @@ Owner caps live in `limits`: `per_action_usd`, `daily_usd`, `total_usd`. They ar
Every rolling ceiling a fire answers to (the rule's `daily_usd` and `total_usd`, and the wallet policy's own `daily_usd`) is reserved in the same statement that claims the execution row, under a per-agent lock, counting in-flight spends as spent. Two intents firing in the same sweep, or two overlapping sweeps, therefore cannot both spend headroom only one of them had.
-Validation failures are `422` with a precise code: `bad_trigger`, `bad_action`, `needs_threshold`, `needs_filter`, `needs_amount`, `needs_pct`, `needs_mint`, or `needs_destination`.
+Validation failures are `422` with a precise code: `bad_trigger`, `bad_action`, `bad_pairing`, `needs_threshold`, `needs_filter`, `needs_amount`, `needs_pct`, `needs_mint`, or `needs_destination`.
+
+A `buy` or `snipe` swaps through Jupiter, and the quote request is built from validated parts: the mint must be a real Solana address and the slippage a bounded integer, so a malformed mint ends the fire with `status: "error"` and the reason in its note instead of reaching the quote.
### GET /intents
@@ -808,7 +822,7 @@ Refusal reasons: `not_found`, `kill_switch`, `disarmed`, `no_rules`, `no_wallet`
A cycle that ran returns `{ "ran": true, "trigger": "manual", "dryRun": false, "results": [ … ] }`, one entry per due rule, each stamped with its `last_status` and `last_note`. A rule whose weekday does not match today is reported as skipped rather than silently omitted. An unexpected failure is `500 run_failed`.
-The `dca` and `buyback` rules swap through Jupiter, and the engine treats the two halves of that call differently. The quote is an idempotent read, so a 429, a 5xx, or a network failure is retried up to three times with jittered backoff inside a 15 second per-attempt deadline, while a 4xx (no route for this pair) is taken as the answer and the rule pauses with `no_route` and the reason in its `last_note`. Building the swap returns an unsigned transaction, so it is retried once, and only on a 5xx or network failure (`swap_failed` otherwise). Signing and broadcasting are never retried.
+The `dca` and `buyback` rules swap through Jupiter, and the engine treats the two halves of that call differently. The quote query is built from validated parts (the output mint must be a real Solana address, slippage an integer from 0 to 10000 bps, every value URL-encoded), so no field can rewrite another. The quote is an idempotent read, so a 429, a 5xx, or a network failure is retried up to three times with jittered backoff inside a 15 second per-attempt deadline, while a 4xx (no route for this pair) is taken as the answer and the rule pauses with `no_route` and the reason in its `last_note`. Building the swap returns an unsigned transaction, so it is retried once, and only on a 5xx or network failure (`swap_failed` otherwise). Signing and broadcasting are never retried.
## Portfolio: valuation, P&L, and risk
diff --git a/docs/authentication.md b/docs/authentication.md
index d2cc7accd..de760c2ed 100644
--- a/docs/authentication.md
+++ b/docs/authentication.md
@@ -247,7 +247,9 @@ Every auth endpoint accepts an optional `tosAccepted: true` body field. Send it
- `POST /api/auth/register` **requires** `tosAccepted: true`; account creation without it fails with `400 tos_required`. Registration UIs must show a real agreement control.
- Wallet and Privy verifies (`/api/auth/siwe/verify`, `/api/auth/siws/verify`, `/api/auth/privy/verify`) and `POST /api/auth/login` treat it as an affirmation: acceptance is recorded on every sign-in, so users converge onto the current Terms version over time.
-An already-signed-in user can also record acceptance directly with `POST /api/legal/tos-ack { version?, context? }`, which mirrors the risk-acknowledgment endpoint (`/api/legal/risk-ack`).
+An already-signed-in user can also record acceptance directly with `POST /api/legal/tos-ack { version?, context? }`.
+
+Terms acceptance alone does not unlock real funds. Every custodial money endpoint (withdraw, trade, pay, launch) also requires a typed-name signature of the Terms, the Risk Disclosure, and the Agent Wallet Agreement, recorded by `POST /api/legal/risk-ack` (review them at [/legal/agreements](https://three.ws/legal/agreements)). An unsigned account gets `403 risk_ack_required` over a session and an API key alike; devnet actions are exempt.
---
@@ -267,7 +269,7 @@ The three.ws login and register pages run Privy **headless**: our own UI drives
2. **Email**: `privy.auth.email.sendCode(email, captchaToken)` sends a 6-digit code; `privy.auth.email.loginWithCode(email, code)` exchanges it for an identity token (a JWT signed with Privy's ES256 key).
3. **EVM wallet**: the page runs Privy's SIWE ceremony (`siwe/init` for a nonce and message, `personal_sign` in the wallet, `loginWithSiwe` to finish) and gets the same kind of identity token.
4. The frontend posts that token to `POST /api/auth/privy/verify`.
-5. The backend fetches Privy's JWKS, verifies the token signature and audience, and finds-or-creates the user record (keyed on the Privy DID).
+5. The backend fetches Privy's JWKS, verifies the token signature and audience, and finds-or-creates the user record (keyed on the Privy DID). A first Privy sign-in carrying an email links to an existing account with that email only when three.ws has verified the address; an account registered with an unverified email is left alone and the Privy identity gets its own account, so nobody can pre-register a stranger's address and catch their sign-in. SAML and wallet sign-ins follow the same rule.
6. Linked wallets are synced best-effort from Privy's server API into the user's wallet list; a login with no wallet still succeeds.
7. A session cookie is issued; from this point the user is authenticated identically to a SIWS or SIWE user.
@@ -378,6 +380,10 @@ await fetch('/api/auth/logout-everywhere', {
});
```
+### Resetting a password
+
+Password accounts recover through `POST /api/auth/forgot-password { email }`, which always answers `200 { success: true }` (so it never reveals whether an address has an account) and emails a `/reset-password?token=...` link valid for 60 minutes. The reset page posts `POST /api/auth/reset-password { token, password }`. The token is checked and consumed in a single statement, so one link resets the password exactly once even under concurrent submits; a used or expired link answers `400 invalid_token`. A successful reset revokes every browser session and every OAuth refresh token on the account, the same sweep `logout-everywhere` performs, because a reset is how an owner takes back a compromised account.
+
### Deleting the account
`DELETE /api/auth/me` closes an account for good. It is the endpoint behind the
@@ -443,16 +449,17 @@ API keys are for server-to-server access where session cookies don't apply — C
### Key format
-Keys are prefixed `sk_live_` and are shown exactly once at creation. They are stored as a SHA-256 hash; if you lose the key, create a new one.
+Keys are prefixed `sk_live_` (the dashboard can also mint `sk_test_` keys) and are shown exactly once at creation. They are stored as a SHA-256 hash; if you lose the key, create a new one.
### Creating a key
-Via the dashboard at `/dashboard` → **API Keys** → **Create Key**, or via the API while authenticated:
+Via the dashboard at [/dashboard/api](https://three.ws/dashboard/api), or via the API while signed in. A cookie-authenticated create needs a CSRF token, which `apiFetch` attaches for you:
```js
-const res = await fetch('/api/api-keys', {
+import { apiFetch } from '/src/api.js'; // attaches the x-csrf-token for you
+
+const res = await apiFetch('/api/api-keys', {
method: 'POST',
- credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: 'My Integration',
@@ -461,9 +468,15 @@ const res = await fetch('/api/api-keys', {
}),
});
const { data } = await res.json();
-// data.token = "sk_live_xxxxx" — store this; it won't be shown again
+// data.token = "sk_live_xxxxx": store this; it won't be shown again
```
+A bearer caller (an API key or OAuth token holding `profile`) can create keys too, but only at or below its own grant: requesting any scope the caller does not hold answers `403 insufficient_scope`.
+
+### Signing in from a terminal (device link)
+
+The `three-ws` CLI ([docs](cli.md)) gets an API key without a pasted secret through an RFC 8628-style device link: `POST /api/cli/link { client_name, hostname, scope }` returns a `user_code` and a `verification_uri` (`/cli/authorize`); the person opens it signed in, can narrow the scopes (money-moving ones are flagged), and approves; the CLI polls `POST /api/cli/token { device_code }` every 3 seconds and receives the minted key exactly once. Poll errors use the RFC 8628 codes (`authorization_pending`, `slow_down`, `access_denied`, `expired_token`), and a link expires after 10 minutes. Approval refuses every bearer principal, so a credential can never widen itself into a new one without a person pressing the button. `GET /api/cli/whoami` with the key as a Bearer returns the account, plan, credential, and agent wallet.
+
### Using a key
Pass it as a Bearer token:
@@ -487,21 +500,26 @@ const res = await fetch('/api/agents', {
| `memory:write` | Write agent memory |
| `profile` | Read/write profile data; required to manage API keys themselves |
| `herald:announce` | Post announcements through the [Herald](herald.md) (`POST /api/herald/announce`); the scope the `herald-mcp` package's `THREE_WS_API_KEY` needs |
+| `wallet:read` | See the agent wallet balance, history, and spending caps |
+| `wallet:write` | Move, commit, or redirect funds from a custodial wallet (withdraw, trade, pay, hire, launch), within its caps |
+| `services:write` | Publish paid services that earn USDC to the agent wallet |
+| `inference` | Model calls on the OpenAI-compatible endpoint (`/api/v1/chat/completions`), billed to the account's credits; keys from `/api/me/inference/provision` carry this scope alone |
Scopes are space-separated in the `scope` field. Default when unspecified: `avatars:read avatars:write`.
+A signed-in browser session carries every scope. An API key or OAuth access token carries only what it was granted, and each route checks the scope its action needs, answering `403 insufficient_scope` otherwise. Notable gates: any state-changing request to a route that spends from or redirects a custodial wallet needs `wallet:write` (reads pass with `wallet:read`); pairing or editing a chat-gateway connection needs `agents:write wallet:write` (listing needs `agents:read`); the companion inbox and Knock settings need `profile`, plus `wallet:write` to move the Knock payout address; and granting a home entity standing permission refuses every bearer with `403 confirmation_requires_session`, because only a person in a session can say yes.
+
> **Security:** Treat API keys as passwords. Never commit them to source control. Set the minimum scope your integration actually needs. Set an `expires_at` on keys that don't need to be permanent. Rotate keys after personnel changes.
### Revoking a key
```js
-await fetch(`/api/api-keys/${keyId}`, {
- method: 'DELETE',
- credentials: 'include',
-});
+import { apiFetch } from '/src/api.js'; // a cookie-authenticated revoke needs the CSRF token
+
+await apiFetch(`/api/api-keys/${keyId}`, { method: 'DELETE' });
```
-Or revoke via the dashboard. Revocation takes effect immediately — the key will start returning `401`.
+Or revoke via the dashboard. Revocation takes effect immediately: the key will start returning `401`.
---
@@ -520,6 +538,8 @@ If you're building a third-party app that users authorize to access their three.
PKCE (S256) is mandatory. The authorization server metadata is at `/.well-known/oauth-authorization-server`.
+Native clients may register a loopback redirect on `http://127.0.0.1` or `http://[::1]`; at authorize time any port on that address matches (RFC 8252 section 7.3), so a CLI or desktop app registers once and binds whatever port the OS hands it. `localhost` redirects still match their exact port.
+
### Client authentication
Public clients (`token_endpoint_auth_method: "none"`, the default from dynamic registration) get no secret and identify themselves with a `client_id` form field.
diff --git a/docs/generation-watch.md b/docs/generation-watch.md
index 6710b9214..5858dce85 100644
--- a/docs/generation-watch.md
+++ b/docs/generation-watch.md
@@ -57,7 +57,7 @@ The page polls `GET /api/3d/studio?job=<id>` and moves through five states:
from `glbUrl`). A manual link is rendered in case the redirect is blocked.
- **Error.** An upstream failure (`status: "error"`), a stale or malformed
link (HTTP 400), or a job that produces no viewer link shows an honest error
- with a one-click "Forge it again" path. Generation is free, so retrying
+ with a one-click "Forge it again, free" path. Generation is free, so retrying
costs nothing.
- **Offline.** Four consecutive failed polls (a dropped connection, a captive
portal, a tab woken on a dead network) stop the countdown and say so, rather
diff --git a/docs/media-api.md b/docs/media-api.md
index 7d7abdd04..51fe5ff59 100644
--- a/docs/media-api.md
+++ b/docs/media-api.md
@@ -318,8 +318,10 @@ the exact cost.
|-----------|----------|
| Missing `src` and `id`, or invalid `lod`/`textureSize`/`morphs` | `400 invalid_request` |
| `src` not on a three.ws origin | `400 untrusted_source` |
+| Source redirected off a three.ws origin, to plain `http`, or more than 3 times (every hop is re-checked, never followed blindly) | `400 untrusted_src` |
| Avatar/upstream not found | `404 source_not_found` |
| Source over 50 MB | `413 too_large` |
+| Source did not answer, or stalled mid-download, within 30 s | `504 source_timeout` |
| Upstream fetch failed | `502 upstream_unreachable` |
| Transcode pipeline threw | `500 transcode_failed` |
diff --git a/docs/notifications.md b/docs/notifications.md
index 2a76805c4..30dc70e68 100644
--- a/docs/notifications.md
+++ b/docs/notifications.md
@@ -73,7 +73,8 @@ category; the mapping (`TYPE_CATEGORY`) lives in
| Creations | `creations` | `forge_complete`, `forge_failed` |
| Companion | `companion` | `companion_delivery` |
| (no tab yet) | `knock` | `knock_received` |
-| Account | `account` | `withdrawal_completed`, `withdrawal_failed`, `payment_mismatch`, `asset_payment_mismatch`, `skill_payment_mismatch`, `security_alert`, `wallet_anomaly_frozen`, plus any type not in the map |
+| (no tab yet) | `mail` | `mail_received` |
+| Account | `account` | `withdrawal_completed`, `withdrawal_failed`, `payment_mismatch`, `asset_payment_mismatch`, `skill_payment_mismatch`, `security_alert`, `wallet_anomaly_frozen`, plus any type not in the map (the agent-inference `inference_topup` and `inference_budget_exhausted` land here this way) |
`print_update` is the single type Materialize uses for a physical order's whole
lifecycle, quoted through delivered, and it sits with purchases because the
@@ -86,11 +87,12 @@ Three details worth knowing:
- **Tab filtering is client-side** over the pages already fetched. The API's
own `?type=` parameter filters server-side by a single exact type (e.g.
`?type=pump_alert`), not by category.
-- **`knock` is a preference category without a tab.** The preference center
- lists it ("Knocks at your door") and the server gates delivery on it, but
- the page's own copy of the map has no entry for `knock_received`, so on
- `/notifications` a knock is filtered under **Account** rather than a tab of
- its own.
+- **`knock` and `mail` are preference categories without a tab.** The
+ preference center lists them ("Knocks at your door", "Agent mail") and the
+ server gates delivery on them, but the page's own copy of the map has no
+ entry for `knock_received` or `mail_received`, so on `/notifications` both
+ are filtered under **Account** rather than a tab of their own. Mail the spam
+ filter holds back never notifies at all.
## The avatar channel: delivered in person
@@ -99,8 +101,8 @@ of those lands while you are on the site, the corner companion (the avatar
that already walks your pages) turns to you, plays a gesture, and says it out
loud, with a link straight to the thing that happened.
-`avatar` is a real delivery channel next to `in_app`, `push`, `email`, and
-`telegram`. It is gated by the same per-category matrix, edited in the same
+`avatar` is a real delivery channel next to `in_app`, `push`, `email`,
+`telegram`, and `discord`. It is gated by the same per-category matrix, edited in the same
place (`/dashboard/settings`), and measured in the same funnel.
**What gets announced.** By default: **Sales & earnings**, **Creations**,
@@ -108,7 +110,8 @@ place (`/dashboard/settings`), and measured in the same funnel.
landing, a generation finishing while you waited, a message your companion
triaged as worth hearing, someone who paid your price to reach you, and
anything touching your account are worth an interruption. Purchases, social,
-in person, and market alerts are off by default because they are frequent.
+in person, market alerts, and agent mail are off by default because they are
+frequent.
Every one of them is a toggle, so an inbox that should speak up more (or not
at all) is two clicks away. The defaults live in `DEFAULTS` in
[api/_lib/notify-prefs.js](../api/_lib/notify-prefs.js).
@@ -183,7 +186,10 @@ shared nav on every page and is deliberately cheap:
load), a one-time banner offers Web Push if it is supported, configured,
not yet subscribed, and not previously declined. Push plumbing lives in
[src/push-notifications.js](../src/push-notifications.js) and
- [public/push-sw.js](../public/push-sw.js).
+ [public/push-sw.js](../public/push-sw.js). Inside the three.ws iOS app the
+ same calls register with Apple Push Notification service instead (the
+ WebView runs no service worker), and the bell also fires a `threews:unread`
+ window event with the count so the app can keep its icon badge in step.
## The notification center: /notifications
@@ -317,14 +323,18 @@ curl -s -X PUT 'https://three.ws/api/notifications/preferences' \
```
GET returns
-`{ categories, channels, type_categories, prefs, push: { subscribed_devices } }`:
+`{ categories, channels, type_categories, prefs, push: { subscribed_devices, ios_devices }, gateways: { telegram, discord } }`:
the categories from the table above, the channels (`in_app`, `push`, `email`,
-`telegram`, `avatar`), the type-to-category map (so a browser client can
-resolve a category without a round trip per notification), and the caller's
-resolved matrix. PUT stores a
-sparse override; unknown categories, channels, and keys are dropped, and the
-response echoes the re-resolved matrix. The body also accepts
-`telegram_chat_id` (digits, settable and clearable) for the Telegram channel.
+`telegram`, `discord`, `avatar`), the type-to-category map (so a browser client
+can resolve a category without a round trip per notification), the caller's
+resolved matrix, the push device count (browsers plus iPhones enrolled through
+the iOS app, with the iPhones also counted alone), and how many chats paired
+through the Telegram and Discord chat gateways have notifications on. The
+`telegram` and `discord` channels deliver to those paired chats. PUT returns
+`{ ok: true, prefs }`: it stores a sparse override, unknown categories,
+channels, and keys are dropped, and `prefs` is the re-resolved matrix. The
+body also accepts `telegram_chat_id` (digits, settable and clearable) for the
+Telegram channel.
Delivery gating notes, all enforced in
[api/_lib/notify-prefs.js](../api/_lib/notify-prefs.js):
diff --git a/docs/ops/gcp-credits.md b/docs/ops/gcp-credits.md
index e780b436a..e9590c98c 100644
--- a/docs/ops/gcp-credits.md
+++ b/docs/ops/gcp-credits.md
@@ -363,6 +363,7 @@ Vertex speaks the Anthropic Messages API with four differences, all handled in
- Body gains `"anthropic_version": "vertex-2023-10-16"` and drops `model` (+ `stream`).
- Auth: `Authorization: Bearer <oauth>` (via `api/_lib/gcp-auth.js`, shared with Imagen): no `x-api-key`, no `anthropic-version` header. The token is cached per process and refreshed five minutes ahead of expiry; if a refresh fails, the cached token is served until its hard expiry margin so a metadata-server blip does not fail a request.
- Model id: bare aliases pass through (`claude-sonnet-4-6`); a dated first-party id converts to the `@` form (`claude-haiku-4-5-20251001` → `claude-haiku-4-5@20251001`) via `toVertexModelId()`.
+- Model id validation: the id is spliced into an authenticated URL path and can be caller-supplied (the x402 LLM proxy forwards any non-alias model string), so `vertexMessagesUrl()` refuses anything outside the model-id alphabet (`/`, `..`, `?`, `#`) with a 400 `invalid_model`. `providerChain()` checks `isVertexModelId()` first and simply leaves the Vertex rung out for such an id, so the rest of the chain still serves the request.
SSE event shapes are identical to first-party, so every existing stream parser works unchanged.
@@ -407,8 +408,8 @@ behavior is intact.
### Deploy & rollback
- **Preview first:** set `VERTEX_CLAUDE_ENABLED=1` (and optionally `VERTEX_CLAUDE_PRIMARY=1`) in Vercel **preview** only. Production flags stay unset — flipping production changes the billing lane and is the owner's call.
-- **Production flip (owner):** `printf '1' | vercel env add VERTEX_CLAUDE_ENABLED production` (+ `VERTEX_CLAUDE_PRIMARY` for chain inversion), then redeploy.
-- **Rollback (instant, no code deploy):** unset `VERTEX_CLAUDE_ENABLED` / `VERTEX_CLAUDE_PRIMARY`. Every lane falls through to the free lanes (Groq → OpenRouter → NVIDIA → SambaNova → Mistral → Z.AI, each present only when its key is) → paid backstop exactly as before.
+- **Production flip (owner):** `gcloud run services update three-ws-api --region us-central1 --update-env-vars VERTEX_CLAUDE_ENABLED=1` (add `VERTEX_CLAUDE_PRIMARY=1` for chain inversion). Never `--set-env-vars`, which replaces the whole set.
+- **Rollback (instant, no code deploy):** `--remove-env-vars VERTEX_CLAUDE_ENABLED,VERTEX_CLAUDE_PRIMARY`. Every lane falls through to the free-first chain in `providerChain()` (keyed rungs such as Groq, Cerebras, OpenRouter `:free`, NVIDIA NIM, SambaNova, Mistral and Z.AI when their keys exist; the keyless Kilo, OVH, Pollinations and LLM7 rungs always; the Vertex Gemini anchor whenever `GOOGLE_CLOUD_PROJECT` is set) → paid backstop exactly as before. The full rung order lives in [llm-lanes.md](llm-lanes.md) and is pinned by `tests/vertex-claude.test.js`.
---
@@ -455,7 +456,10 @@ rung runs under one shared budget (`TEXT_TO_IMAGE_BUDGET_MS`, default 60 s): a
lane with a fallback behind it is capped at max(25% of the budget, 60% of what
is left), a lane with under 10% left is skipped, and an exhausted ladder answers
a retryable `rate_limited` that the forge boundary maps to a 429. Any Vertex
-error degrades cleanly to the next rung, and because Pollinations needs no key,
+error degrades cleanly to the next rung. A NIM FLUX answer whose `finishReason`
+is not `SUCCESS`, or whose frame is blank (a content filter's solid fill,
+`isBlankFrame()`), is treated as `safety_blocked` and handed to the next rung
+rather than persisted as a subjectless reference. Because Pollinations needs no key,
no single provider's failure is ever the terminal error. Which provider served
each image is logged (`[text-to-image] served by <model>`) and persisted on the
forge job as `text_to_image_model`.
@@ -989,7 +993,10 @@ Prompt 04 adds one flag that makes the fleet *primary* across every tier/path:
`selfHostPrimary()`.
- The **fallback ladder is unchanged**: self-host error → hosted NIM / HuggingFace
/ Replicate exactly as today. The flag only reorders *preference*, never removes
- a safety net.
+ a safety net. Since 2026-09-30 a photo job that fails on every textured lane
+ falls through, at poll time, to the TripoSG worker's photo pipeline
+ (`api/_lib/forge-failover.js`, gcp provider mode `triposg`): geometry only, so
+ it is the last rung and the forge tells the user the result has no textures.
- **Revert:** unset `FORGE_SELFHOST_PRIMARY` (and/or the worker URLs) → today's
ordering, no redeploy.
@@ -1000,7 +1007,7 @@ Env vars the router reads for the fleet (all bearer-authed with
|---|---|---|
| `MODEL_TRELLIS_URL` | `trellis_selfhost` | free/paid image + text→3D (primary) |
| `GCP_HUNYUAN3D_URL` | `hunyuan3d` | image→3D failover |
-| `GCP_TRIPOSG_URL` | `triposg` | sketch→3D |
+| `GCP_TRIPOSG_URL` | `triposg` | sketch→3D, and the last poll-time photo→3D failover (untextured) |
| `GCP_RECONSTRUCTION_URL` | controller `/reconstruct`, `/rig` | avatar scan + UniRig rigging |
| `GCP_TEXT2MOTION_URL` | text2motion | text→animation clip |
| `GCP_RECONSTRUCTION_KEY` | shared bearer | all of the above |
diff --git a/docs/ops/materialize-fulfillment.md b/docs/ops/materialize-fulfillment.md
index f5c41d39b..3e07c0a85 100644
--- a/docs/ops/materialize-fulfillment.md
+++ b/docs/ops/materialize-fulfillment.md
@@ -85,7 +85,7 @@ configured() false hides the adapter from the registry entirely
submit(order, assets) → { providerOrderId, status, leadTimeDays, note, state }
status(providerOrderId) → { status | null, trackingNumber, carrier, note, state }
cancel(order, reason) → { ok, note, state }
-verifyWebhook(raw, headers) → { ok, deliveryId, reason }
+verifyWebhook(raw, headers) → { ok, deliveryId, bodyDeliveryId?, reason }
parseWebhook(payload) → { providerOrderId, status, trackingNumber, carrier, note, state }
```
@@ -168,7 +168,10 @@ Three properties, enforced in this order:
`print_webhook_deliveries` is a unique-key insert and happens *before* the
payload is interpreted, so even a delivery we end up not applying is
recorded and cannot be replayed. A duplicate answers `200 {duplicate:true}`;
- a 4xx would make the provider retry forever.
+ a 4xx would make the provider retry forever. A provider's delivery-id header
+ is not covered by the signature, so an adapter also returns
+ `bodyDeliveryId`, derived from the signed bytes, and the route claims that
+ too: a captured body replayed under a fresh header id is still a duplicate.
3. **Ordering.** A report the state machine refuses is written to the timeline
as a provider event carrying the refusal, and answered `200
{applied:false}`.
@@ -178,16 +181,17 @@ hash, so "the same event twice" is still one row.
## The reconciliation sweep
-[api/cron/print-orders-sync.js](../../api/cron/print-orders-sync.js), hourly at
-`:17` (registered in `vercel.json`; Cloud Scheduler is synced by
-`scripts/create-gcp-scheduler.mjs` at deploy time).
+[api/cron/print-orders-sync.js](../../api/cron/print-orders-sync.js), every 15
+minutes (registered in `vercel.json`; every deploy creates the missing Cloud
+Scheduler job through `npm run deploy:gcp:sync-crons`, which runs
+`scripts/create-gcp-scheduler.mjs --missing-only`).
Webhooks are the fast path and are not sufficient: a delivery gets lost, a
callback queue backs up, and the manual lane has no webhook at all. Without the
sweep, the worst failure a physical product has goes unnoticed, which is a
finished order sitting in `printing` until the buyer asks.
-Two passes, deliberately separate:
+Four passes, deliberately separate:
- **Reconcile.** Poll every order a configured adapter still owns and apply the
answer through the state machine. A provider with no news moves nothing, so
@@ -196,10 +200,20 @@ Two passes, deliberately separate:
sitting on.
- **Stall.** Page the operator once for any order more than `lead_time_days + 2`
old, then stamp `stall_alerted_at` so the next sweep stays quiet for 24 hours.
-
-Read the response: `{ open, polled, applied, stalled, alerted, failures }`. A
-non-empty `failures` array names the orders whose lane could not be reached and
-why.
+- **Screen.** Run the fabrication gate on every paid order sitting in
+ `screening`: clear it for submission, or move it to `rejected` and tell the
+ operators. It runs here rather than in the payment request because it makes a
+ model call.
+- **Attest.** Backfill the QR and retry the Solana memo for every certificate
+ whose proof never landed, `PRINT_CERT_RETRY_BATCH` (default 10) per tick and
+ up to `PRINT_CERT_MAX_ATTEMPTS` (default 8) per certificate. A mainnet
+ certificate still waiting on the owner approval counts as `refused`, not
+ `failed`.
+
+Read the response: `{ open, polled, applied, stalled, alerted,
+screening_pending, screened, cluster, certificates, failures }`. A non-empty
+`failures` array names the orders whose lane could not be reached (or whose
+screening or attestation pass threw) and why.
## The operator channel
diff --git a/docs/ops/search-indexing.md b/docs/ops/search-indexing.md
index 7a6eb50f3..1ad1e9fd4 100644
--- a/docs/ops/search-indexing.md
+++ b/docs/ops/search-indexing.md
@@ -29,6 +29,14 @@ Every public URL falls into one of these, and the failure modes are different:
works, but only if the controller sets the head tags. `src/seo-meta.js`
exists for exactly that (`setCanonical`, `markNoindex`).
+ `/m/:id` is the exception that no longer starts empty:
+ `server/creation-head.mjs` rewrites the shell's head per creation for every
+ User-Agent (title, description, canonical, a `summary_large_image` card whose
+ image is the PNG render of the model, and `3DModel` JSON-LD), so a reader that
+ never runs the page script still gets the creation's own head. Any lookup miss
+ or timeout serves the untouched shell, and `src/model-page.js` fills it in as
+ before. [seo.md](../seo.md) covers that render path in full.
+
`/avatars/:id` and `/agents/:id` are the interesting case: a browser gets the
SPA shell, and a crawler UA is rewritten by `vercel.json` to a server-rendered
page instead (`api/avatar-detail-og.js`, `api/agent-detail-og.js`). Those two
@@ -80,8 +88,9 @@ differs has no preferred version to point at.
`<img>`, a definition list of facts (creator, category, rig state, fork count,
publication date for an avatar; skills, ERC-8004 identity, home URL for an
agent), tag chips linking into `/gallery` or `/agents`, and a footer of
- related surfaces. Plus `3DModel` / `SoftwareApplication` JSON-LD and a
- `BreadcrumbList`. No `<noscript>`, because nothing hides in it any more.
+ related surfaces. Plus `3DModel` / `SoftwareApplication` JSON-LD (built by
+ [`api/_lib/creation-jsonld.js`](../../api/_lib/creation-jsonld.js), the same
+ builder `/m/:id` and `/forge/share/:id` use) and a `BreadcrumbList`. No `<noscript>`, because nothing hides in it any more.
- **The self-redirect is emitted only for crawlers that never index.**
`isSearchCrawler()` splits indexing crawlers (Googlebot, bingbot, Applebot,
GPTBot, ClaudeBot, PerplexityBot, and the rest) from link unfurlers
diff --git a/docs/reputation.md b/docs/reputation.md
index aad6dda1e..55225d31a 100644
--- a/docs/reputation.md
+++ b/docs/reputation.md
@@ -12,16 +12,19 @@ On-chain reputation addresses all three:
- **Permanent.** The blockchain is append-only. A submitted score exists as long as the chain does.
- **Publicly verifiable.** Anyone can read the `ReputationRegistry` contract directly — no API key, no account required.
-- **Sybil-resistant.** One wallet address gets one review per agent. Creating fake identities costs real gas.
+- **Sybil-resistant.** Every review is tied to the wallet that signed it, and creating fake identities costs real gas.
- **Composable.** Other applications can read the same reputation data. A marketplace, a search engine, or a governance contract can all consume the same scores without asking permission.
---
## How scores work
-The `ReputationRegistry` contract stores scores as signed integers in the range **−100 to +100** (an `int8`). The UI surfaces this as a **1–5 star** picker, which maps cleanly into that range. Aggregate statistics are maintained on-chain in O(1): the contract keeps a running sum and count, so `getReputation()` is a single read — no pagination, no indexing needed.
+Two registry dialects exist, and every three.ws reader and writer speaks both. [src/erc8004/reputation-read.js](../src/erc8004/reputation-read.js) detects which one is deployed by behaviour (does the registry answer `getIdentityRegistry()`?), never by address, because the canonical registry is an upgradeable proxy whose interface can move.
-One review per wallet address per agent is enforced by the contract. Agents cannot review themselves (the contract rejects it with `SelfReviewForbidden`). Once submitted, a review cannot be updated or deleted.
+- **Reference dialect (the canonical `0x8004…` addresses).** The ERC-8004 reference implementation. Feedback is `giveFeedback(agentId, value, valueDecimals, tag1, tag2, endpoint, feedbackURI, feedbackHash)` on a 0 to 100 scale by convention, so three.ws writes a star as 20 points (5 stars is 100, and an on-chain average of 82 reads as 4.1 stars). The aggregate is `getSummary` over the reviewers `getClients` returns (it reverts on an empty list), read in chunks of 100 reviewers so an agent with thousands stays under node gas caps. Self-feedback is rejected by the contract. There is no staking.
+- **Legacy dialect (`contracts/src`).** The three.ws source in [contracts/src/ReputationRegistry.sol](../contracts/src/ReputationRegistry.sol), for an instance you deploy yourself. Scores are signed integers in the range **−100 to +100** (an `int8`), the contract keeps a running sum and count so `getReputation()` is a single read, one review per wallet address per agent is enforced, self-review reverts with `SelfReviewForbidden`, and a review cannot be updated or deleted once submitted.
+
+Every three.ws surface shows a **1 to 5 star** picker and a star average, whichever dialect sits underneath.
---
@@ -36,7 +39,7 @@ One review per wallet address per agent is enforced by the contract. Agents cann
5. Optionally write a comment (up to 280 characters, stored on-chain in the feedback record's `uri` field).
6. Click **Sign & submit** and confirm the transaction in your wallet.
-Gas cost is minimal on L2 networks like Base (typically under $0.10). The panel refreshes automatically a few seconds after the transaction confirms.
+Gas cost is minimal on L2 networks like Base (typically under $0.10). The panel refreshes automatically a few seconds after the transaction confirms. The option to back a vouch with staked ETH only appears where the registry supports staking (the legacy dialect); the canonical registries do not.
**Owners cannot vouch for their own agents.** If you own the agent, the vouch button is replaced with an explanatory note.
@@ -52,13 +55,13 @@ import { submitReputation } from './src/erc8004/reputation.js';
const txHash = await submitReputation({
chainId: 8453, // Base mainnet
agentId: 42,
- score: 5, // Any int8 in -100..+100; the star UI submits 1-5
+ score: 5, // 1-5 stars (a legacy-dialect registry also accepts any int8 in -100..+100)
comment: 'Incredible avatar and fast responses.',
signer: connectedSigner // ethers.js Signer
});
```
-`submitReputation` is a back-compat alias for `submitFeedback` (the contract's own method name). Both work identically.
+`submitReputation` is a back-compat alias for `submitFeedback`. Both work identically: on the reference dialect they call `giveFeedback` with the stars converted to points and the comment as the feedback URI, and they turn the contract's self-feedback revert into "You can't review an agent you own or operate."; on the legacy dialect they call the contract's own `submitFeedback`.
---
@@ -72,7 +75,7 @@ The `ReputationPanel` class ([src/erc8004/reputation-panel.js](../src/erc8004/re
- Total vouch count
- Up to 8 recent vouches with reviewer address, score, optional comment, and a link to the transaction on the chain's block explorer
-Recent vouches are loaded by querying `FeedbackSubmitted` event logs for the last ~50,000 blocks (~7 days on most L2s). If the RPC rejects the log query (common on free-tier endpoints), the panel degrades gracefully — it still shows the aggregate stats but omits the individual review list.
+On the canonical (reference) registries, recent vouches are read straight from registry state with no log scan: the latest feedback of each of the 20 most recent reviewers from `getClients`, fetched through Multicall3 so the whole list costs three `eth_call`s on a keyless public RPC. Those entries carry no transaction hash, so they render without an explorer link, and revoked feedback is skipped. On a legacy-dialect registry they come from `FeedbackSubmitted` event logs for the last ~50,000 blocks (~7 days on most L2s). If the RPC rejects that read (common on free-tier endpoints), the panel degrades gracefully: it still shows the aggregate stats but omits the individual review list.
Reads go through `readProvider(chainId)` from [src/erc8004/chain-meta.js](../src/erc8004/chain-meta.js): every keyless public node listed for the chain becomes a pinned provider and they are combined in an ethers `FallbackProvider` with quorum 1, so the first healthy node answers and a stalled or rate-limited one is passed over after four seconds instead of blanking the panel. The USD figure printed beside a stake amount comes from `getEthPriceUsd()` ([src/shared/usd-price.js](../src/shared/usd-price.js)), which walks four price feeds with per-provider cooldowns; a throttled feed leaves the ETH amount in place and only drops the USD hint.
@@ -127,7 +130,7 @@ reviews.forEach(r => {
});
```
-`getReputation` returns `{ count, average }` where `average` is already computed from the contract's `avgX100` (0 if no reviews). `getRecentReviews` returns an array of objects with `agentId`, `from` (reviewer address), `score`, `comment`, `blockNumber`, and `txHash`.
+`getReputation` returns `{ count, average, reviewers, rawAverage, dialect }`: `average` is in stars (0 to 5, 0 if no reviews), `rawAverage` is the on-chain figure in the registry's own unit, and `dialect` is `'reference'` or `'legacy'`. `getRecentReviews` returns an array, oldest first, of objects with `agentId`, `from` (reviewer address), `score` (in stars on the reference dialect), `comment`, `blockNumber`, and `txHash`. On the reference dialect it reads registry state rather than logs, so `fromBlock` is ignored, `blockNumber` and `txHash` are `null`, and `comment` carries the feedback's primary tag. `supportsStaking({ chainId, runner })` tells you whether the staking helpers below can work on that chain.
### Via the Passport widget
@@ -141,7 +144,7 @@ The **ERC-8004 Passport** widget type ([src/widgets/passport.js](../src/widgets/
## Smart contract reference
-The `ReputationRegistry` contract ([contracts/src/ReputationRegistry.sol](../contracts/src/ReputationRegistry.sol)) exposes the following interface:
+This section documents the legacy-dialect source, `ReputationRegistry` ([contracts/src/ReputationRegistry.sol](../contracts/src/ReputationRegistry.sol)). The canonical addresses run the reference implementation instead; its interface is `REPUTATION_REFERENCE_ABI` in [src/erc8004/abi.js](../src/erc8004/abi.js) (`giveFeedback`, `revokeFeedback`, `getSummary`, `getClients`, `getLastIndex`, `readFeedback`). The legacy source exposes:
### Write
@@ -170,7 +173,9 @@ enforces the same one-review-per-wallet, no-self-review rules, and emits
`withdrawStake` refunds only your own deposit and leaves the review on-chain, so
a staker can reclaim their ETH at any time without erasing what they said. The
SDK wraps both as `stakeReputation({ agentId, score, comment, stakeWei, signer,
-chainId })` and reads the pool with `getTotalStake({ agentId, runner, chainId })`.
+chainId })` and reads the pool with `getTotalStake({ agentId, runner, chainId })`;
+`stakeReputation` refuses on a reference-dialect registry and `getTotalStake`
+returns 0 there.
### Read
@@ -203,7 +208,7 @@ Contract addresses are the same on every supported EVM chain (CREATE2 determinis
| Mainnet (Base, Arbitrum, Optimism, Ethereum, Polygon, and more) | `0x8004BAa17C55a88189AE136b182e5fdA19dE9b63` |
| Testnet (Base Sepolia, Arbitrum Sepolia, Optimism Sepolia, and more) | `0x8004B663056A597Dffe9eCcC1965A193B7388713` |
-One caveat, recorded in the comments of `abi.js`: the canonical addresses run the ERC-8004 reference implementation, not the three.ws source above. An `eth_call` sweep on 2026-08-15 found that deployment answering `readFeedback` / `getClients` on Base and Base Sepolia and reverting on every selector in `contracts/src/ReputationRegistry.sol` (`submitFeedback`, `getReputation`, `getFeedbackRange`, and the stake functions). The ABI and SDK helpers on this page match the three.ws source, so use them against an instance you deploy from `contracts/src` yourself; against the canonical addresses those calls revert.
+One caveat, recorded in the comments of `abi.js`: the canonical addresses run the ERC-8004 reference implementation, not the three.ws source above, and revert on every selector in `contracts/src/ReputationRegistry.sol` (`submitFeedback`, `getReputation`, `getFeedbackRange`, and the stake functions). Calling the legacy ABI directly therefore only works against an instance you deploy from `contracts/src` yourself. The SDK helpers in `src/erc8004/reputation.js`, the reputation panel, the passport widget, and the server-side trust readers all go through the dialect-aware reader, so they work against both.
---
diff --git a/docs/social-layer.md b/docs/social-layer.md
index 1ec989193..9e38bb2d6 100644
--- a/docs/social-layer.md
+++ b/docs/social-layer.md
@@ -17,7 +17,7 @@ the platform already writes (`forge_creations`, `dioramas`, `material_restyles`,
| Activity feed | [/feed](https://three.ws/feed), [/community](https://three.ws/community) | `GET /api/users/me/feed` |
| Follow graph | Follow buttons on `/u/:username` | `GET|POST|DELETE /api/users/:username/follow` |
| Notification bell | Bell in the header, preferences in `/dashboard/settings` | `GET /api/notifications` + `/preferences` |
-| Leaderboard, streaks, badges | [/rankings](https://three.ws/rankings) | `GET /api/leaderboard/unified` |
+| Leaderboard, streaks, badges | [/rankings](https://three.ws/rankings), [/leaderboard?tab=earned](https://three.ws/leaderboard?tab=earned) | `GET /api/leaderboard/unified`, `GET /api/leaderboard/earnings` |
| Creator portfolio | `/u/:username` | `GET /api/users/:username/creations` |
| Cross-entity search | [/search](https://three.ws/search) | `GET /api/search` |
| Onboarding tour | [/start](https://three.ws/start) | `GET /api/me` (`show_onboarding_tour`) |
@@ -131,14 +131,24 @@ PUT /api/notifications/preferences → update it
Preferences are a category × channel matrix
([api/_lib/notify-prefs.js](../api/_lib/notify-prefs.js)): categories are
sales, purchases, social, IRL, market alerts, creations, companion
-deliveries, knocks at your door, and account & security; channels are
-`in_app`, `push`, `email`, `telegram`, and `avatar`. Every channel is a
+deliveries, knocks at your door, agent mail, and account & security; channels
+are `in_app`, `push`, `email`, `telegram`, `discord`, and `avatar`. Every channel is a
per-category toggle (`in_app` defaults on everywhere, and is locked on for
account & security so the bell record of security events never goes silent),
edited from the Notifications panel in `/dashboard/settings`
([src/dashboard-next/pages/settings.js](../src/dashboard-next/pages/settings.js)).
Bell client: [src/notifications.js](../src/notifications.js).
+`telegram` and `discord` deliver to chats paired with an agent through the
+chat gateways (`/api/gateway/connections`), so `GET /preferences` reports a
+`gateways: { telegram, discord }` count of paired chats with notifications on,
+and the panel keeps a column disabled until one exists (Telegram also accepts
+a legacy `telegram_chat_id`). Both default off except for market alerts.
+`push.subscribed_devices` counts Web Push browsers plus iPhones enrolled
+through the iOS app (APNs), with the iPhones also reported alone as
+`push.ios_devices`. The `mail` category (an email arriving in one of your
+agents' inboxes; spam never notifies) defaults to the bell and push only.
+
The `avatar` channel is the corner companion walking on screen and saying the
notification out loud. It is delivered client-side: the bell hands its unread
inbox to [src/notification-herald.js](../src/notification-herald.js), which
@@ -162,7 +172,11 @@ GET /api/leaderboard/unified?metric=creations&limit=50&offset=0
```
`metric` is one of `creations`, `remixes_received`, `launches`, `followers`,
-`walk_distance` (limit 1..100, default 50). Sending the request with a session
+`walk_distance` (limit 1..100, default 50). `launches` counts distinct mainnet
+mints from the platform's own launch records (`pump_agent_mints`, including
+coins signed by an agent's custodial wallet, plus `fixed_supply_launches`),
+through [api/_lib/launch-counts.js](../api/_lib/launch-counts.js), the same
+count the daily top-10 badge sweep uses. Sending the request with a session
or Bearer token pins your own row into the response even when you are outside
the page window. `remixes_received` counts only finished derivatives made by
someone else: both the parent and the child must be `status = 'done'`, and a
@@ -178,7 +192,13 @@ streak can never delay or fail the trade that earned it), and writes
`user_streaks` / `user_badges`. The upsert is idempotent per UTC day, so a
busy session still counts once: the streak measures showing up, not volume. A daily rollup
cron ([api/cron/leaderboard-rollup.js](../api/cron/leaderboard-rollup.js))
-sweeps badge awards. Badges and streaks also render on profile pages.
+sweeps the `top10_<metric>` badge awards. The rest of the catalog
+(`BADGE_META` in the same file) is awarded where it is earned: first creation,
+first remix received, a 7-day streak, completing the copy-trade path,
+founding or joining a syndicate, daily trading quests (first quest, a daily
+clear, a 7-day quest streak), and trader duels (first call, a correct call,
+three correct in a row, and 70% or better over ten or more decided duels).
+Badges and streaks also render on profile pages.
An authenticated request gets `streak` and `badges` back in the same response
as the board, keyed on the session's user id, so the `/rankings` streak card
@@ -186,8 +206,17 @@ works for accounts that have never picked a username. Those three per-viewer
blocks (`me`, `streak`, `badges`) make an authenticated response
`cache-control: private`; anonymous responses stay edge-cacheable.
+Agents also have an earnings board:
+`GET /api/leaderboard/earnings?window=24h|7d|30d|all&limit=25&offset=0` ranks
+public agents by creator fees plus service income for the window, with each
+row's movement against the previous window of the same length. It is public,
+edge-cached for a minute, and computed the same way as each agent's Earned
+card; the full contract is in the
+[API reference](./api-reference.md#earnings-leaderboard).
+
> Page: [pages/rankings.html](../pages/rankings.html).
-> Source: [api/leaderboard/unified.js](../api/leaderboard/unified.js).
+> Source: [api/leaderboard/unified.js](../api/leaderboard/unified.js),
+> [api/leaderboard/earnings.js](../api/leaderboard/earnings.js).
## Creator portfolio: `/u/:username`
diff --git a/docs/trade-rooms.md b/docs/trade-rooms.md
index 173844b58..1bb1200bf 100644
--- a/docs/trade-rooms.md
+++ b/docs/trade-rooms.md
@@ -52,6 +52,10 @@ Code: page [pages/trade-room.html](../pages/trade-room.html), controller
| Ghost-copy | Side column | [Ghost-copy](./ghost-copy.md) this trader with a paper budget. |
| Copy trades | Side column | The copy panel on the trader's profile. See [Copy trading](./copy-trading.md). |
| Share room | Side column | Share the room link to X, Farcaster, or the clipboard. |
+| Call a duel | Side column | Opens [/duels](https://three.ws/duels) filtered to the duels this trader is in, where you call the winner. See [Trader duels](./trader-duels.md). |
+
+The lobby links to [Trader duels](https://three.ws/duels) and the
+[leaderboard](https://three.ws/leaderboard) beside its room grid.
Nothing in a room holds funds, asks for a key, or signs on your behalf.
diff --git a/docs/trading-copilot.md b/docs/trading-copilot.md
index 46163724f..015106dbb 100644
--- a/docs/trading-copilot.md
+++ b/docs/trading-copilot.md
@@ -62,6 +62,11 @@ Arrow keys move through the menu, `Enter`/`Tab` selects, `Esc` closes.
saved per wallet + network in `localStorage` and restored when you return. Live trade
proposals are intentionally **not** persisted, so a reload never resurrects a
confirmable card grounded on a stale quote.
+- **One thread across chats**: every finished web turn is also appended to the agent's
+ cross-channel thread (channel `web`), the same thread the paired Telegram, Discord,
+ and other chat gateways ([`api/_lib/gateway/`](../api/_lib/gateway/)) read and write.
+ Each time the tab is opened or shown again it pulls what was said in those chats since
+ it last looked and shows those messages tagged "via Telegram", "via Discord", and so on.
---
@@ -95,14 +100,32 @@ If the firewall verdict is **block**, the buy card cannot be confirmed at all.
## The endpoint
```
-POST /api/agents/:id/copilot Owner-only. Body: { messages:[{role,content}], network }
+POST /api/agents/:id/copilot Owner-only. Body: { messages:[{role,content}], network, model? }
→ text/event-stream
+GET /api/agents/:id/copilot?after=<message id>&limit=<1-100>
+ Owner-only. → { messages:[{id,role,content,channel,signatures,createdAt}], latest_id }
```
+`POST` keeps the last 24 user and assistant turns, each cut to 4000 characters, and
+refuses a request whose final message is not from the user (`422 no_message`). `GET`
+returns the agent's cross-channel thread oldest first (30 messages by default), so a
+client can merge what the owner said in a paired chat; pass the returned `latest_id` as
+`after` next time to fetch only newer messages.
+
+`model` overrides the agent's default model for this one message (resolved by
+[`api/_lib/agent-model.js`](../api/_lib/agent-model.js)). Because the copilot is a tool
+loop, an override without tool calling is refused (`400 model_lacks_tools`), as is an
+unknown id (`400 unknown_model`); an agent *default* without tool calling is skipped and
+the turn runs on the platform chain instead. A free open model draws on the owner's
+daily free-tier allowance and answers `429 free_tier_exhausted` with a `Retry-After`
+header once it is spent. Every model round is metered to the owner's usage ledger at the
+price of the lane that served it (free lanes cost nothing).
+
SSE events:
| Event | Payload | Meaning |
| --- | --- | --- |
+| `model` | `{ model, source, served?, lane? }` | the model chosen for the turn; re-sent each round with the model and provider lane that actually answered |
| `status` | `{ phase }` | thinking / continuing / finalizing |
| `tool` | `{ name, summary, data }` | a read-only tool ran; `data` is the card payload |
| `proposal` | trade/limits proposal | a confirm-before-execute card |
@@ -110,14 +133,16 @@ SSE events:
| `done` | `{ reply, proposals, citations }` | final reply |
| `error` | `{ code, message }` | turn failed |
-The provider chain is free-first and OpenAI-compatible, shared with the built-in chat
+With no `model` override, the provider chain is free-first and OpenAI-compatible, shared with the built-in chat
agent loop in [`api/_lib/llm-tool-chain.js`](../api/_lib/llm-tool-chain.js): Groq →
Cerebras → OpenRouter (including any `OPENROUTER_FALLBACK_KEYS`) → NVIDIA → SambaNova →
Mistral → Z.ai → Gemini (API key), with paid OpenAI as the backstop, each rung present
only when its key is set, so the copilot works without any paid key. Whenever the GCP
project is configured, a keyless, credits-billed **Vertex Gemini** rung is appended
unconditionally as the final anchor, so the chain always ends on a provider that cannot
-be evicted by a dead key. Each round has a 45s deadline and fails over to the next rung on
+be evicted by a dead key. A named model's own lanes are tried first and the platform
+chain follows behind them. With no rung configured at all, the request is
+`503 llm_unavailable` before the stream opens. Each round has a 45s deadline and fails over to the next rung on
any transport or non-2xx error. A 15s heartbeat keeps the stream alive across slow tool
rounds; the client aborts a genuinely dead stream and offers Retry rather than hanging.
@@ -135,7 +160,9 @@ plumbing — and never suggests, shills, or names another token on its own initi
| --- | --- |
| Client mount (chat UI, cards, slash, persistence, voice) | [`src/agent-copilot.js`](../src/agent-copilot.js) |
| Wallet-hub tab wrapper | [`src/agent-wallet-hub/tabs/copilot.js`](../src/agent-wallet-hub/tabs/copilot.js) |
-| Server (tool loop, SSE, proposals) | [`api/agents/copilot.js`](../api/agents/copilot.js) |
+| Server route (auth, model choice, SSE, thread read) | [`api/agents/copilot.js`](../api/agents/copilot.js) |
+| Copilot engine (tools, prompt, loop; shared with the chat gateways) | [`api/_lib/copilot-engine.js`](../api/_lib/copilot-engine.js) |
+| Cross-channel thread store | [`api/_lib/agent-thread.js`](../api/_lib/agent-thread.js) |
| Provider chain + streamed tool-call reader (shared with the chat agent loop) | [`api/_lib/llm-tool-chain.js`](../api/_lib/llm-tool-chain.js) |
| Markdown renderer | [`src/md.js`](../src/md.js) |
| UI contract tests | [`tests/agent-copilot-ui.test.js`](../tests/agent-copilot-ui.test.js) |
diff --git a/docs/ux-flows/09-x402-agent-commerce.md b/docs/ux-flows/09-x402-agent-commerce.md
index 9ab1388cc..c75735fcf 100644
--- a/docs/ux-flows/09-x402-agent-commerce.md
+++ b/docs/ux-flows/09-x402-agent-commerce.md
@@ -19,7 +19,7 @@ choreographed two-agent narrative driven by Server-Sent Events.
### Pay-per-call (x402) — `/pay`
- **Source:** `public/pay/index.html` (route → `public/pay/index.html`; inline module scripts hold all app logic), backend `api/x402-pay.js`, `api/mcp`, `api/x402-checkout`, `api/_lib/x402-bsc-direct.js`; agent wallet via `api/agents/[id]/solana`.
- **Entry point:** Chat-style page. Left = conversation + quick-tool chips + prompt input ("Pay & Run"); right = "x402 settlement timeline"; footer = live "recent paid calls" ticker. First visit shows a 3-step walkthrough overlay (dismissed → `localStorage x402:seen-walk`).
-- **Prerequisites / gates:** No signup to use the **shared demo wallet** (platform-funded). Three payer modes: (a) **platform/agent server-payer** (default) — optional sign-in loads the user's own agents via `/api/x402-pay?agents=1` (401 → "Sign in" CTA, falls back to demo wallet); selecting an agent with no wallet opens the **generate-wallet overlay** (`POST /api/agents/{id}/solana`, or grind a vanity address at `/vanity-wallet`). (b) **Phantom** (Solana USDC, user signs). (c) **MetaMask/EVM** on the "BNB Chain" tab (user signs `approve` + `pay(bytes32)`). Wallet must hold ≥ $0.001 USDC for the chosen mode.
+- **Prerequisites / gates:** No signup to use the **shared demo wallet** (platform-funded). Three payer modes: (a) **platform/agent server-payer** (default): optional sign-in loads the user's own agents via `/api/x402-pay?agents=1` (401 → "Sign in" CTA, falls back to demo wallet); selecting an agent with no wallet opens the **generate-wallet overlay** (`POST /api/agents/{id}/solana`, or grind a vanity address at `/vanity-wallet`). Paying from your own agent is a real-funds action: the account must first have signed the real-funds agreements (Terms of Service, Risk Disclosure, Agent Wallet Agreement) at `/legal/agreements`, else `403 risk_ack_required` with the sign link and nothing sent, and an API-key or OAuth bearer caller additionally needs the `wallet:write` scope (`403 insufficient_scope` otherwise; `api/_lib/spend-scope.js`). (b) **Phantom** (Solana USDC, user signs). (c) **MetaMask/EVM** on the "BNB Chain" tab (user signs `approve` + `pay(bytes32)`). Wallet must hold ≥ $0.001 USDC for the chosen mode.
- **Steps (4 required + several optional):**
1. (optional) Read/dismiss the "How this works" walkthrough overlay.
2. (optional) Pick a payer: sign in and select an agent, generate/import its wallet, or select Phantom / MetaMask card; otherwise the shared demo wallet is used.
@@ -29,7 +29,7 @@ choreographed two-agent narrative driven by Server-Sent Events.
- **Decision points / branches:** payer mode (server agent vs Phantom vs EVM — `run()` dispatches to `runPhantomPayment` / `runEvmPayment` / SSE path); agent has wallet vs not (gen overlay); prompt parse (`parsePrompt`) into a tool call; stream error vs `result` vs "stream ended without result".
- **External calls / dependencies:** `/api/x402-pay` (SSE payer + `?agents=1`, `?balance=1`, `?feed=1`, `/og`), `/api/mcp` (402 probe + dispatch), `/api/x402-checkout?action=prepare|encode`, `/api/agents/{id}/solana`, Solana mainnet RPC (`api.mainnet-beta.solana.com`), x402 facilitator (verify/settle), Solscan for tx links; BSC path uses `ThreeWSPayments` contract `0x…1B72Cc`. The Phantom path imports `@solana/web3.js` through `/load-module.js`, which tries the pinned version on esm.sh, then jsdelivr, then unpkg, each under a deadline, so one blocked CDN no longer stalls the run at the signing step.
- **Success state:** receipt card + rendered MCP result (incl. live 3D model), Solscan tx link, balance ticks down, feed prepends the call, page title shows elapsed ms.
-- **Empty / error states:** not-signed-in → demo-wallet note; no agents → "Create your first agent"; agent has no wallet → gen overlay; `402`/network failure → timeline stage flips to error + `x402 call failed` / `Network error` message; stream ends without result → explicit error; wallet underfunded surfaces from server error; Solana RPC unreadable while the server builds the transfer (every read on that path is guarded and cache-backed first) → `503 rpc_unavailable` with a `Retry-After` header and the copy "No funds were transferred; retry shortly" (the same guard answers `/api/x402-checkout?action=prepare`); a wallet component that fails to load on all three CDN mirrors → the failed step names the hosts it tried.
+- **Empty / error states:** not-signed-in → demo-wallet note; no agents → "Create your first agent"; agent has no wallet → gen overlay; `402`/network failure → timeline stage flips to error + `x402 call failed` / `Network error` message; stream ends without result → explicit error; wallet underfunded surfaces from server error; unsigned real-funds agreements surface the server's "Sign the real-funds agreements … Nothing was sent" copy; Solana RPC unreadable while the server builds the transfer (every read on that path is guarded and cache-backed first) → `503 rpc_unavailable` with a `Retry-After` header and the copy "No funds were transferred; retry shortly" (the same guard answers `/api/x402-checkout?action=prepare`); a wallet component that fails to load on all three CDN mirrors → the failed step names the hosts it tried.
- **Step count:** 4 required (+ ~4 optional).
### Paid-call permalink — `/pay/calls`
@@ -306,7 +306,7 @@ choreographed two-agent narrative driven by Server-Sent Events.
4. **[user, optional]** **Choose your avatar** → modal → select → spawn player (saved to localStorage).
5. **[user, optional]** Move with WASD / drag look / scroll zoom / touch joystick.
6. **[user, optional]** Click an agent label → camera focus + right drawer profile (equity sparkline, stats grid, recent closed trades with on-chain proof, Oracle conviction section) → **Full proof & copy ↗** → `/trader/<agent_id>` new tab.
-- **Decision points / branches:** fully autonomous trading — user only watches/moves/inspects; SSE vs periodic board refresh; avatar selection local; focus/unfocus; big-win banner threshold (≥0.4◎ or ≥100%).
+- **Decision points / branches:** fully autonomous trading, so the user only watches/moves/inspects; header links out to `/duels` (call which trader books more, free to play), `/syndicates` (copy the winners as a team), and `/quests` (today's trading quests); SSE vs periodic board refresh; avatar selection local; focus/unfocus; big-win banner threshold (≥0.4◎ or ≥100%).
- **External calls / dependencies:** `/api/sniper/leaderboard`, `/api/sniper/rivalries`, `/api/sniper/stream` (SSE), `/api/sniper/trader`, `/api/oracle/agent-stats`, `/animations/manifest.json`, avatar GLBs, Solscan, `/trader/<id>`. Solana mainnet (real pump.fun trades).
- **Success state:** agents render + leaderboard + live tape; user can move + inspect; real trades animate in real time.
- **Empty / error states:** no live agents → "No agents are live yet… arm a trader and enter"; SSE drop → "Reconnecting…" (retry 2.5s); board never read → "Can't reach the leaderboard." + **Retry now** (KPI strip hidden); refresh fail after a good read → "Standings are stale." keeping the last good board and its KPI strip; rivalries → skeleton, an empty note when fewer than two traders have 3+ closed round-trips, or "Can't reach the rivalry feed." + Retry; drawer fail → "Couldn't load this trader"; avatar load fail → mono-initial tile.
@@ -330,7 +330,7 @@ choreographed two-agent narrative driven by Server-Sent Events.
## Notes
- **Routing:** all clean URLs resolve through the `vercel.json` route table — read directly by the Cloud Run server (`server/index.mjs`) in production and mirrored by the `vite.config.js` `historyApiFallback` map in dev. `/pay`, `/bazaar`, `/arbitrage`, `/providers`, `/forever`, `/tutor` live under `public/`; the rest under `pages/`.
-- **Shared payment modal:** `/x402.js` (`public/x402.js`, ~2.4k LOC) is the drop-in `window.X402.pay()` modal used by `/pay/c`, `/bazaar`, `/arbitrage`, `/ibm/x402-demo`, `/shopper` (paywall), `/fact-checker`, `/unstoppable`, `/tutor`. It handles wallet connect (Phantom/Solana, MetaMask/Base via EIP-3009), the 402→sign→retry loop, and SIWX re-entry. Its Solana web3.js and SIWX hashing imports go through `/load-module.js` (the pinned version on esm.sh, then jsdelivr, then unpkg, each under a deadline); only when all three fail does the modal steer the buyer to MetaMask on Base, which needs no third-party code. A cross-origin endpoint whose response carries no CORS headers is reported as "<host> does not allow browser requests" with a pointer to a server, an agent, or the x402 CLI, and no Try-again button.
+- **Shared payment modal:** `/x402.js` (`public/x402.js`, ~2.7k LOC) is the drop-in `window.X402.pay()` modal used by `/pay/c`, `/bazaar`, `/arbitrage`, `/ibm/x402-demo`, `/shopper` (paywall), `/fact-checker`, `/unstoppable`, `/tutor`. It handles wallet connect (Phantom/Solana, MetaMask/Base via EIP-3009), the 402→sign→retry loop, and SIWX re-entry. Before the first payment it collects the real-funds agreements (Terms of Service, Risk Disclosure, Agent Wallet Agreement) through the lazily loaded `risk-ack.js`, degrading to a native `confirm()` with the same wording if that module cannot load. A resource that prices itself in several Solana tokens (USDC and $THREE, a Token-2022 mint the Solana rail now settles) gets a token chooser. Solana transactions are signed through the wallet's Wallet Standard `solana:signTransaction` feature when it offers one, falling back to the injected provider; Phantom's Lighthouse guard instructions (up to 3) are accepted rather than vetoed, unless one names the sponsor's fee-payer account. Only a wallet's own refusal (EIP-1193 code 4001, ethers' `ACTION_REJECTED`) reads as a cancel; a server-side refusal keeps its real reason. Its Solana web3.js and SIWX hashing imports go through `/load-module.js` (the pinned version on esm.sh, then jsdelivr, then unpkg, each under a deadline); only when all three fail does the modal steer the buyer to MetaMask on Base, which needs no third-party code. A cross-origin endpoint whose response carries no CORS headers is reported as "<host> does not allow browser requests" with a pointer to a server, an agent, or the x402 CLI, and no Try-again button.
- **Chain order in the 402:** every `paidEndpoint` route in this cluster (`/api/x402/fact-check`, `/api/x402/tutor`, `/api/x402/symbol-availability`, and the rest) inherits the platform default of Solana first, then Base, so the live challenge lists networks in the same order the discovery catalog advertises and a client that takes the first accept settles on Solana. `tests/x402-solana-first-ordering.test.js` fails the suite if a route pins Base first again.
- **Server-payer vs user-payer:** the "agent economy" narratives (`/agent-exchange`, `/agent-trade`, `/agent-economy`, `/demo`, `/live`) pay from **server-held agent wallets** and stream the choreography over SSE — the user only triggers/selects, then watches. The "showcase" apps (`/shopper`, `/fact-checker`, `/tutor`, `/bazaar`, `/arbitrage`, `/ibm`) make the **user** pay via the `/x402.js` modal.
- **Auto-play demos:** `/agent-exchange`, `/agent-trade`, `/agent-economy`, `/demo` need one user click to start, then auto-play. `/live` adds an auth gate for real settlement. `/play/arena` is fully autonomous (agents trade themselves; user only watches/moves/inspects) and uses **no x402** — real pre-funded Solana trades.
diff --git a/docs/ux-flows/10-chat-brain-labs.md b/docs/ux-flows/10-chat-brain-labs.md
index 7649ea85c..98f80f5fb 100644
--- a/docs/ux-flows/10-chat-brain-labs.md
+++ b/docs/ux-flows/10-chat-brain-labs.md
@@ -35,7 +35,7 @@ modules. Routes resolved via `vercel.json` rewrites.
2. Click an agent card → `/agents/:id` loads `agent-detail.js`.
3. Profile renders: a live Three.js hero avatar (`mountIdleAvatar` retargets the canonical idle clip onto the rig with a procedural idle-life loop; no static `<model-viewer>`), identity, voice metadata (cloned provider or browser TTS pill), live $THREE/pump token chip (streamed via `/api/pump/by-agent`), skills (with dynamic price/promo state from `/api/marketplace/skill-promo?agent_id=…&skill=…`), history.
4. Click "See in world" → routes to `/play?avatar=<glb>&coin=<THREE_MINT>` (the 3D world payoff); or "Edit" / wallet chip / coin-launch actions for owners.
-- **Decision points / branches:** view vs edit (owner); "See in world" (→ /play) vs embed (`/agents/:id/embed`) vs wallet (`/agents/:id/wallet`); token chip present (launched coin) vs not; a `/agents/:id?skill=<name>#pricing` deep link (what the Buy CTA on `/conversions` sends) scrolls the pricing card to that skill row once it renders (`focusRequestedSkill` in `agent-detail-market.js`, honoured once per page load).
+- **Decision points / branches:** view vs edit (owner); "See in world" (→ /play) vs embed (`/agents/:id/embed`) vs wallet (`/agents/:id/wallet`); token chip present (launched coin) vs not; a `/agents/:id?skill=<name>#pricing` deep link (what the Buy CTA on `/conversions` sends) scrolls the pricing card to that skill row once it renders (`focusRequestedSkill` in `agent-detail-market.js`, honoured once per page load); likewise `/agents/:id?tier=<plan id>` (what the marketplace's Subscribe button sends, since a tier activates only through this page's verified checkout) scrolls to the subscription tiers and opens that tier's checkout once, unless the viewer already holds it (`openRequestedTier`).
- **External calls / dependencies:** `/api/agents/:id`, `/api/marketplace/agents/:id`, `/api/pump/by-agent` (live market-cap stream), `/api/marketplace/skill-promo` (skill pricing/promo), `/api/agent-share` (share). Three.js idle-avatar mount for the 3D preview (falls back to a flat image when WebGL/GLB fails).
- **Success state:** Agent profile with interactive 3D avatar, live token data, and working navigation to world/embed/edit.
- **Empty / error states:** Avatar mount failure → flat-image fallback; enrich failure logged non-fatally; save errors surface inline in the edit flow.
@@ -47,7 +47,7 @@ modules. Routes resolved via `vercel.json` rewrites.
### Brain — Persona Builder + Multi-LLM Playground — `/brain`
- **Source:** `/workspaces/three.ws/pages/brain.html` → `/workspaces/three.ws/src/brain.js`.
- **Entry point:** `/brain` → `brain.html` (H1 "Pick a vibe", sub-copy "One tap gives your agent a personality. No extra steps."; "Build Persona" is a sidebar button), two tabs: Persona + Playground.
-- **Prerequisites / gates:** None to open the playground, but signed-out callers are limited to the free-model set (`ANON_BRAIN_PROVIDERS` in `api/brain/chat.js`: gpt-oss-120b plus the NVIDIA NIM family); every paid first-party model returns `401 "sign in to use this model"`, and anonymous traffic is rate limited. `GET /api/brain/chat` reports `requiresAuth` per model alongside `available`, so the page suffixes those chips "(sign in)" for a signed-out visitor and answers a click with the notice "<model> needs an account." plus a Sign in link (`/login?redirect=/brain`) instead of failing after Send. Freeform persona extraction (`POST /api/persona/extract`) also requires sign-in (`401 "Sign in to build your persona."`; the Persona tab shows a "Sign in to build your persona" gate that clears once you sign in and return) and is metered at 5 extractions per user per day. Saving a persona as a deployed agent requires sign-in (auth-hint check + `/api/agents` with credentials). No $THREE gate.
+- **Prerequisites / gates:** None to open the playground, but signed-out callers are limited to the free-model set (`ANON_BRAIN_PROVIDERS` in `api/brain/chat.js`: the platform default under the historical key `gpt-oss-120b`, today labelled "Gemma 4 31B", the three NVIDIA Nemotron models, and every open-model roster row marked `free` in `api/_lib/model-roster.js`); every paid first-party model returns `401 "sign in to use this model"`, and anonymous traffic is rate limited. Each message on a free roster model draws one unit from a daily free-tier allowance (`api/_lib/free-tier.js`, stored in `app_settings['free_tier']`, defaults 100 a day signed in and 20 a day anonymous, reset at 00:00 UTC); a spent allowance answers `429 free_tier_exhausted` with `Retry-After`, and successful turns carry `x-free-tier-remaining`. `GET /api/brain/chat` reports `requiresAuth` per model alongside `available`, so the page suffixes those chips "(sign in)" for a signed-out visitor and answers a click with the notice "<model> needs an account." plus a Sign in link (`/login?redirect=/brain`) instead of failing after Send. Freeform persona extraction (`POST /api/persona/extract`) also requires sign-in (`401 "Sign in to build your persona."`; the Persona tab shows a "Sign in to build your persona" gate that clears once you sign in and return) and is metered at 5 extractions per user per day. Saving a persona as a deployed agent requires sign-in (auth-hint check + `/api/agents` with credentials). No $THREE gate.
- **Steps (6):**
1. Open `/brain`; Persona tab active, archetype presets rendered.
2. (optional) Apply an archetype preset or type freeform persona text → `/api/persona/extract` structures it into a persona object (tone, vocabulary, interests, communication_style, dont_say, sample_greeting); the body is validated before the daily limiter is charged, and an empty model reply comes back as a retryable `502` rather than a blank card.
@@ -56,9 +56,9 @@ modules. Routes resolved via `vercel.json` rewrites.
5. Type a prompt and run; `streamProvider()` POSTs to `/api/brain/chat` per model and streams responses side-by-side, each prefixed with the effective persona system prompt.
6. (optional) Save the persona as an agent → POST `/api/agents` (or PATCH `/api/agents/:id`) with the built `system_prompt`.
- **Decision points / branches:** Compare (multi-model fan-out) vs Focus (single model); persona enabled/disabled (`personaEnabled` toggle injects/omits the system prompt); archetype preset vs freeform extraction; model availability (unavailable models disabled in selector); save-as-agent (gated by auth).
-- **External calls / dependencies:** `GET /api/brain/chat` (provider availability), `POST /api/brain/chat` (per-model streaming completions), `/api/persona/extract` (structure persona), `/api/agents` + `/api/agents/:id` (load/save agent). Models span Anthropic (via Google Vertex), OpenAI (via OpenRouter), xAI Grok, DeepSeek, Qwen/DashScope, IBM watsonx, NVIDIA NIM, and Google Vertex Gemini tiers.
+- **External calls / dependencies:** `GET /api/brain/chat` (provider availability), `POST /api/brain/chat` (per-model streaming completions), `/api/persona/extract` (structure persona), `/api/agents` + `/api/agents/:id` (load/save agent). Models span Anthropic (via Google Vertex), OpenAI (via OpenRouter), xAI Grok, DeepSeek, Qwen/DashScope, IBM watsonx, NVIDIA NIM, and Google Vertex Gemini tiers, plus the open-model roster (`api/_lib/model-roster.js`: Meta Llama, DeepSeek, Moonshot Kimi, Mistral, Qwen, Google Gemini), whose rows stream through their own ordered routes (free lanes, then Vertex AI Model Garden) before the free safety net.
- **Success state:** Multiple model responses stream into the compare grid (or one in focus); persona optionally persisted locally and/or saved as a deployable agent.
-- **Empty / error states:** "Select at least one model" notice; provider-availability fetch failure is non-fatal (all models treated available); upstream stream error surfaces per-model, and when every rung of a model's fallback chain fails the column shows a plain-language verdict (rate limited: try again or pick another model; no working route on this deployment; no longer served upstream; took too long) with the precise upstream reason alongside as `reason`; signed-out use of a paid model errors with a sign-in prompt; auth gate shown when saving while signed out; sessions/persona persisted to localStorage.
+- **Empty / error states:** "Select at least one model" notice; provider-availability fetch failure is non-fatal (all models treated available); upstream stream error surfaces per-model, and when every rung of a model's fallback chain fails the column shows a plain-language verdict (rate limited: try again or pick another model; no working route on this deployment; no longer served upstream; took too long) with the precise upstream reason alongside as `reason`; signed-out use of a paid model errors with a sign-in prompt; a spent free-tier allowance errors with the reset time and a suggestion to sign in or pick a paid model; auth gate shown when saving while signed out; sessions/persona persisted to localStorage.
- **Step count:** 6 required (+2 optional)
---
@@ -156,7 +156,7 @@ modules. Routes resolved via `vercel.json` rewrites.
---
### Club — 3D Pole-Stage Venue (x402) — `/club`
-- **Source:** `/workspaces/three.ws/pages/club.html` → scripts: `/x402.js` (wallet/payment modal), `/workspaces/three.ws/src/club-entrance.js` (walk-in alley scene), `/workspaces/three.ws/src/club-gate.js` (cover-charge bouncer), `/workspaces/three.ws/src/club.js` (main pole stage). Supporting modules in `src/`: `club-venue.js`, `club-audio.js`, `club-camera.js`, `club-crowd.js`, `club-queue.js`, `club-bouncer.js`, `club-perf.js`, `club-sequence.js`, `animation-manager.js`.
+- **Source:** `/workspaces/three.ws/pages/club.html` → scripts: `/x402.js` (wallet/payment modal), `/workspaces/three.ws/src/club-entrance.js` (walk-in alley scene), `/workspaces/three.ws/src/club-gate.js` (cover-charge bouncer), `/workspaces/three.ws/src/club.js` (main pole stage). Supporting modules in `src/`: `club-venue.js`, `club-audio.js`, `club-camera.js`, `club-crowd.js`, `club-queue.js`, `club-bouncer.js`, `club-floor-crowd.js` (the crowd standing around the stages), `club-money.js` (the bills on each stage), `club-tip-hud.js` (the in-room tip picker), `club-perf.js`, `club-sequence.js`, `animation-manager.js`.
- **Entry point:** `/club` → `club.html`; entrance scene + door gate + pole stage boot in parallel behind a loading screen.
- **Entrances:** the same page is served at more than one path, and the path picks the walk-in (`src/club-variant.js`). `/club` opens on the neon alley; `/stripclub` opens on a brick back alley (a CC BY 4.0 Sketchfab model by anthonydpc, credited on screen while it is visible and in `public/club/venue/LICENSES.md`). The cover charge, the pass, the gallery and clubhouse that follow, and the pole stage are shared, so a cover paid at one door is good at the other. An "Entrance" switcher under the agent picker links between them. If an entrance's own alley model cannot be loaded, the walk-in opens on the neon alley instead of failing.
- **Prerequisites / gates:** **x402 wallet payment**: a cover charge settled on-chain via `/api/x402/club-cover`; wallet (Phantom / EVM) connected through `x402.js`. The one door's 402 quotes both USDC and $THREE on Solana (while `X402_ACCEPT_THREE_SOLANA` is on, the default), so the checkout shows a token chooser with each token's real price and either token issues the same pass. Paying in $THREE is optional, not a gate. WebGL required.
@@ -166,8 +166,8 @@ modules. Routes resolved via `vercel.json` rewrites.
3. Spawn in the entrance scene; move with WASD / touch joystick, look via drag. The alley is dressed as the outside of a club: a line of platform avatars waits along the wall behind a velvet rope, neighbours trade scripted exchanges in speech bubbles, and a few drunks sway, stagger and slide down the wall (`src/club-queue.js`; bodies come from `src/club-crowd.js`). The line reacts to you: walk past it to the door, crowd it, or get let in, and someone has something to say.
4. Walk to the neon door → "Enter the club" prompt; activate it.
5. Door reveals the x402 cover screen; connect wallet, pick USDC or $THREE in the token chooser, and pay the cover → a paid `GET /api/x402/club-cover` (x402, `club-gate.js`) settles on-chain and checks the gate.
- 6. On approval the rope drops; walk through to the pole stage — entrance fades, main `club.js` stage becomes active (dancers at poles, leaderboard, live tip feed).
- 7. Select a pole + dance style and tip → `POST /api/x402/dance-tip`; on settlement the dancer performs the routine, leaderboard + live feed update, reactions float up.
+ 6. On approval the rope drops; walk through to the pole stage. The entrance fades and the main `club.js` stage becomes active: dancers at poles with a name tag over each, a crowd around the three stages, a pile of $0.001 bills on each stage sized from that dancer's real tips today, the leaderboard, and the live tip feed.
+ 7. Click a dancer or her pole to open the in-room picker, choose her routine, and tip → `POST /api/x402/dance-tip`; on settlement a clump of bills flies from where you stand onto her stage, she performs the routine, the crowd at her stage cheers, and the leaderboard + live feed update. A tip from another visitor plays the routine they paid for on your screen too, with bills dropping from the lights. Tips paid from a registered platform wallet are labelled agent tips in the feed, drop a single violet bill, and never start a routine; each dancer's card splits today's tips into people vs agents (`agent_tip_count` on `/api/club/leaderboard`, `agent` on each `/api/club/tips` row).
- **Decision points / branches:** avatar choice; cover approved vs "not tonight"; wallet not connected / insufficient balance; tip per pole + dance style; back-out to alley while paying; entrance-GLB failure → drop straight to stage.
- **External calls / dependencies:** `GET /api/x402/club-cover` (the door; a `POST` to the same path is a separate paid read for agents, `mode: "snapshot"` for membership growth/churn or `mode: "revenue"` for the door + floor take over a `period` of 24h/7d/14d/30d/all, not part of the visitor flow), `POST /api/x402/dance-tip`, `GET /api/club/tips`, SSE `/api/club/tips/stream`, `GET /api/club/leaderboard`, `/api/avatars/`, `/api/explore`; club venue/prop GLBs under `/club/...`, `/avatars/default.glb`, animation manifest/clips; `x402.js` wallet modal (Solana web3 / EVM). Three.js + post-processing.
- **Success state:** User is inside the 3D club after paying cover; tipping plays dance routines and updates the live leaderboard/feed in real time.