Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
docs: refresh feature docs and UX flows against current code
nirholas3302d4073e6a
diff --git a/docs/agent-abilities/ABILITIES.md b/docs/agent-abilities/ABILITIES.mdindex 8eb73a228..edd5259b5 100644--- a/docs/agent-abilities/ABILITIES.md+++ b/docs/agent-abilities/ABILITIES.md@@ -18,7 +18,7 @@ three.ws runs a complete prompt-to-world 3D pipeline in production: text or imagType a prompt at /forge (or call the forge_free MCP tool) and get a downloadable textured 3D model (GLB) plus a browser viewer link. The default lane is completely free — no account, no key, no wallet — with paid quality tiers (draft $0.05 / standard $0.15 / high $0.50 USDC) when more geometric budget is needed.-One ordered free-lane walk lives in the backend registry (api/_lib/forge-tiers.js), and both the env-only default and the health-aware resolver read it, so they can never disagree. It starts at the tier's named free engine (FREE_DEFAULT_FOR_TIERS: our self-hosted TRELLIS worker at draft and standard, our self-hosted Hunyuan3D worker at high), falls through the remaining self-hosted GCP GPU workers, then the free Hugging Face Spaces (Hunyuan3D/TRELLIS/TripoSR with automatic failover), and ends at the free NVIDIA NIM/NVCF TRELLIS lane, which is the fallback that still answers a text prompt when every worker and Space is cold. Only configured, capable lanes survive the walk. The NIM lane is async submit + poll and pinned to a 15-step sampling budget below the high tier, since higher budgets overrun its gateway window; prompts are clamped to 77 chars with an auto 'studio lighting' suffix; output bytes are persisted to R2 for a durable first-party URL. The registry also routes to Replicate and BYOK Meshy/Tripo native-geometry engines; paid calls settle over x402 (/api/x402/forge, text_to_3d MCP).+One ordered free-lane walk lives in the backend registry (api/_lib/forge-tiers.js), and both the env-only default and the health-aware resolver read it, so they can never disagree. It starts at the tier's named free engine (FREE_DEFAULT_FOR_TIERS: our self-hosted TRELLIS worker at draft and standard, our self-hosted Hunyuan3D worker at high), falls through the remaining self-hosted GCP GPU workers, then the free Hugging Face Spaces (Hunyuan3D/TRELLIS/TripoSR with automatic failover; one chain-wide Spaces failure pauses that lane for five minutes, so the walk skips it at once and an explicit pick of it answers 503 with Retry-After and a list of working engines to hop to), and ends at the free NVIDIA NIM/NVCF TRELLIS lane, which is the fallback that still answers a text prompt when every worker and Space is cold. Only configured, capable lanes survive the walk. The NIM lane is async submit + poll and pinned to a 15-step sampling budget below the high tier, since higher budgets overrun its gateway window; prompts are clamped to 77 chars with an auto 'studio lighting' suffix; output bytes are persisted to R2 for a durable first-party URL. The registry also routes to Replicate and BYOK Meshy/Tripo native-geometry engines; paid calls settle over x402 (/api/x402/forge, text_to_3d MCP).Zero-cost text→3D that any human or AI agent can use instantly, with a transparent pay-per-call ladder — identical pricing across REST and MCP — when quality matters.@@ -1220,7 +1220,7 @@ Your agent's body can never 404. The exact GLB — manifest baked inside it —Skills are the agent’s installed abilities: trading rails, launch tooling, NFTs, blinks, sentiment, scenes, all wired to real APIs. Owners switch them on and off in the Agent Studio's Skills room (three.ws/agent-studio), and MCP-exposed skills are callable by other agents through /api/mcp. The enabled skill list also travels in the agent's signed manifest, pinned to IPFS whenever a public agent's persona is saved (private agents publish on request), so anyone can verify which skills an agent carries without an account ([agent manifest](/docs/agent-manifest)).-The in-world agent skills system (src/agent-skills.js plus 13 family modules) is what a three.ws agent can DO — and what you can watch it doing. Each skill bundles an instruction, an animation hint, a voice template, and a real handler, so execution flows through the agent protocol bus and the avatar physically performs the action (gestures, speech, mood shifts) instead of silently returning JSON. Skill families span 3D work (present/validate models, build the scene), the full Solana economy (pump.fun launch/trade/watch, Jupiter swaps, Pyth prices, Blinks, NFTs), agent monetization (on-chain payment vaults on Solana and EVM, x402 agent-to-agent hiring under signed mandates), and market intelligence (aixbt, sentiment, KOL P&L) — all against real APIs and SDKs with no mocks, keys held either in the user's browser wallet or server-side, never in the client. MCP-exposed skills double as tools on /api/mcp, so the same registry powers both the living avatar and the developer API.+The in-world agent skills system (src/agent-skills.js plus 15 family modules) is what a three.ws agent can DO, and what you can watch it doing. Each skill bundles an instruction, an animation hint, a voice template, and a real handler, so execution flows through the agent protocol bus and the avatar physically performs the action (gestures, speech, mood shifts) instead of silently returning JSON. Skill families span 3D work (present/validate models, build the scene), the full Solana economy (pump.fun launch/trade/watch, Jupiter swaps, Pyth prices, Blinks, NFTs), agent monetization (on-chain payment vaults on Solana and EVM, x402 agent-to-agent hiring under signed mandates), an EVM launch leg (Robinhood Chain coins through Pons, and paired-quote coin launches and markets), and market intelligence (aixbt, sentiment, KOL P&L), all against real APIs and SDKs with no mocks, keys held either in the user's browser wallet or server-side, never in the client. MCP-exposed skills double as tools on /api/mcp, so the same registry powers both the living avatar and the developer API.## Skill registry and performed execution (core)@@ -1874,7 +1874,7 @@ The Withdraw tab is the owner's exit door and control room for an agent's custodThe agent's private key lives encrypted on the server and never touches the browser — a withdrawal is a server-signed request, and each time the key is decrypted, that access is itself recorded as a custody event. Before signing, the server runs the withdrawal through the shared spend policy: the freeze switch, the withdraw allowlist, the owner's plain-English safety rules (compiled by an LLM into deterministic rules, then enforced by code), per-transaction and rolling 24-hour USD ceilings, and a behavioral anomaly guard. Each request carries a unique idempotency key claimed as a row in the custody ledger, so a retry replays the original result instead of double-sending, and an ambiguous network timeout leaves the withdrawal marked pending with an explorer link rather than risking a duplicate. On a SOL "Max" the server reserves rent plus fee headroom so a full sweep can never brick the wallet, and token withdrawals automatically open the recipient's token account when needed. The asset picker, spend totals, and activity feed all read live on-chain and ledger data — nothing is cached guesswork.-Owner-only end to end: every endpoint verifies the signed-in user owns the agent. Withdrawals are capped at 5 per day per user with an additional per-IP burst guard. Every state-changing request requires a single-use CSRF token, and mainnet withdrawals require an explicit risk acknowledgment. The server enforces the shared spend policy before signing: withdraw allowlist (if set, funds can only go to approved addresses), per-transaction and rolling 24-hour USD ceilings, the owner's plain-English safety rules enforced deterministically, and a behavioral anomaly guard that can auto-freeze the wallet. The freeze switch halts all autonomous spending but deliberately never blocks the owner's withdrawals — a freeze can never trap funds. Destinations must be valid, on-curve addresses and cannot be the wallet itself. SOL sweeps always reserve rent plus fees so the account survives. Idempotency keys make retries safe against double-sends, ambiguous confirmations return a pending state with an explorer link instead of guessing, and every withdrawal, key decryption, limit change, and policy block lands in an owner-visible audit ledger.+Owner-only end to end: every endpoint verifies the signed-in user owns the agent. Withdrawals are capped at 5 per day per user with an additional per-IP burst guard. Every state-changing request requires a single-use CSRF token, and mainnet withdrawals require an explicit risk acknowledgment. The server enforces the shared spend policy before signing: withdraw allowlist (if set, funds can only go to approved addresses), per-transaction and rolling 24-hour USD ceilings, the owner's plain-English safety rules enforced deterministically, and a behavioral anomaly guard that can auto-freeze the wallet. The freeze switch halts all autonomous spending but deliberately never blocks the owner's withdrawals: a freeze can never trap funds. An API key or OAuth token (a bearer, as opposed to the owner's signed-in session) can withdraw only when it carries the wallet:write scope; the no-funds withdraw preview and every read still answer with a lesser grant, and the same gate (api/_lib/spend-scope.js) guards every REST route that trades, pays, hires, launches, or arms an autonomous spender. Destinations must be valid, on-curve addresses and cannot be the wallet itself. SOL sweeps always reserve rent plus fees so the account survives. Idempotency keys make retries safe against double-sends, ambiguous confirmations return a pending state with an explorer link instead of guessing, and every withdrawal, key decryption, limit change, and policy block lands in an owner-visible audit ledger.## 19 · Give@@ -1944,7 +1944,7 @@ Real-time and nine-years-deep crypto news in one place, readable without visitinA CoinGecko-style /coins index (global stats bar, sortable top-coins table with 7d sparklines, debounced full-catalog search, load-more paging) and a shareable /coin/:id detail page per coin: interactive 24H-1Y chart with crosshair (switchable between the native CoinGecko chart and TradingView, DexScreener, Birdeye, GMGN, and GeckoTerminal views where the coin qualifies, the embed URLs living once in src/shared/chart-embeds.js so /coin/:id and /launches/<mint> build identical charts and a provider that does not index the coin's chain is never offered; a third-party embed that is blocked or never renders is replaced within a deadline by a designed panel with a Try again button and a link to the provider, never a blank frame), market stats, related news, official links, and per-chain contract addresses. Also a live perpetual-futures view (price, funding rate, open interest per contract).-pages/coins.html + src/coins-index.js and pages/coin.html + src/coin-page.js over api/coin/* (detail, ohlc, markets, news, global, derivatives) proxying CoinGecko via api/_lib/coingecko.js. :id accepts a CoinGecko slug OR a Solana mint; mint-shaped ids cross-link into Alpha Copilot, the live trade feed, /launches, and Coin Intelligence.+pages/coins.html + src/coins-index.js and pages/coin.html + src/coin-page.js over api/coin/* (detail, ohlc, markets, tickers, news, global, derivatives) proxying CoinGecko via api/_lib/coingecko.js. The coin page's Markets table (api/coin/tickers) falls back to CoinPaprika when CoinGecko is throttled, and then to the coin's own DEX pairs read by its contract addresses, so a young DEX-only token still lists where it trades. :id accepts a CoinGecko slug OR a Solana mint; mint-shaped ids cross-link into Alpha Copilot, the live trade feed, /launches, and Coin Intelligence.Full-market price coverage that plugs directly into the platform's Solana/pump.fun surfaces — a coin page is never a dead end.@@ -1984,7 +1984,7 @@ Rug/bundle detection and launch quality signals for any pump.fun coin, free andA public directory of every coin launched through three.ws by its agents: registry rows render instantly, then live pump.fun market data (price, art, graduation status) streams in per card, with an agent filter, generative per-mint identicons, and a 60s live refresh. The feed is deliberately neutral: no score, tier, or grade is painted on a user's coin. Judgment is replaced by facts on each mint's own addressable profile at /launches/<mint>, a trader sheet over /api/pump/token-stats (5m/1h/6h/24h volume, buys, sells, net buy, unique traders, price change; holder count, top-10 share, dev share, early-buyer share; mint and freeze authority; bonding-curve progress and graduation state; liquidity) beside a live price chart and trade tape, where a field that could not be read renders as a dash and never as 0. Launching itself is built in: a 'Launch Pump.fun' modal on every agent profile (client-signed, so user keys never leave the browser via launch-prep/launch-confirm), autonomous server-signed agent launches under spend caps, the Memetic Launcher (per-user autonomous launcher with trend sources and daily SOL caps), and Launch Studio's 50 declarative launch recipes.-src/launches.js reads the platform's own pump_agent_mints launch records via GET /api/pump/launches and enriches per-coin from pump.fun via /api/pump/coin; the launch path is documented in docs/coin-launches.md and docs/pump-launcher.md over api/pump/[action].js.+src/launches.js reads the platform's own launch records via GET /api/pump/launches (pump_agent_mints bonding-curve coins plus fixed_supply_launches, one query in api/_lib/pump-agent-launches.js) and enriches per-coin from pump.fun via /api/pump/coin; a coin an agent launched on Robinhood Chain through Pons renders with its venue, a chain explorer link and its /markets/robinhood/coin/<address> page instead of pump.fun data; the launch path is documented in docs/coin-launches.md and docs/pump-launcher.md over api/pump/[action].js.Launch a real on-chain pump.fun coin from an agent's profile in one flow, and every launch gets a live, shareable home in the platform's public feed plus its own /launches/<mint> profile that shows the numbers and leaves the verdict to the reader.diff --git a/docs/agent-economy-volume.md b/docs/agent-economy-volume.mdindex d2768887d..13cf2bf72 100644--- a/docs/agent-economy-volume.md+++ b/docs/agent-economy-volume.md@@ -40,7 +40,9 @@ signature on file".A hire is also refused outright, before a row is inserted or any spend isreserved, when the hiring account has not signed the real-funds agreements: theendpoint answers `403 risk_ack_required` and nothing reaches the ledger (see-[the real-funds agreements](risk-acknowledgment.md)).+[the real-funds agreements](risk-acknowledgment.md)). The same holds for a bearer+token that lacks the `wallet:write` scope, which gets `403 insufficient_scope`+(see [the agent wallet API](agent-wallet-api.md)).The one place pending work appears is `totals.pending_hires`, a plain count shownas the sub-label under "Settled hires". It never enters a money figure.@@ -104,10 +106,14 @@ canvas on resize and on a theme change.The alert strip is built from a static translated sentence plus a dynamic detailclause in a separate element (`#an-error-detail`). That split is load-bearing:-`src/i18n.js` rewrites annotated elements after first paint, so anything JS writes-must live outside an annotated node or the catalog overwrites it. The same rule is-why the leaderboard and feed counts sit next to their translated headings rather-than inside them.+`src/i18n.js` rewrites annotated elements after first paint. Its runtime now+infers when a page script has rewritten an annotated element and leaves it alone+(`primeOwnership`, see [i18n.md](i18n.md)), but an element the page wrote also+stops translating, and a `data-i18n-html` pass still replaces the whole block's+innerHTML. Keeping the live text in a sibling of the annotated node is what lets+the static sentence translate while the detail stays live. The same rule is why+the leaderboard and feed counts sit next to their translated headings rather than+inside them.---diff --git a/docs/agent-shell.md b/docs/agent-shell.mdindex a1cee113b..ebe0255ec 100644--- a/docs/agent-shell.md+++ b/docs/agent-shell.md@@ -31,9 +31,11 @@ claims it.- The agent reacts to work done through the ⌘K palette — it waves and commentswhen a forge finishes or a digest arrives (`tws:palette-action` DOM events,mirrored onto the agent bus as `action:taken`).-- Auto-summon is polite: it waits for `load` + idle, skips visitors with- `prefers-reduced-motion` or `Save-Data`, skips full-screen 3D/camera routes- (`/play`, `/tour`, `/scan`, …), and never re-summons after the visitor closes+- Auto-summon is polite: it waits for `load`, then for the main thread to go+ 1.2 seconds without a long task (giving up after 20 seconds rather than+ landing on a busy page), skips visitors with `prefers-reduced-motion` or+ `Save-Data`, skips full-screen 3D/camera routes (`/play`, `/tour`, `/scan`,+ `/create/selfie`, …), and never re-summons after the visitor closesthe companion. A page opts out with `data-walk-auto="off"` on its `html`element. The existing nav "Walk" toggle keeps working exactly as before.@@ -51,7 +53,7 @@ verbs and runs them in place against the real public APIs — no account needed:| --- | --- | --- || `forge <prompt>` (also `make`, `generate`, `imagine`) | `forge a bronze dragon statue` | `POST /api/forge` on the free text→3D lane, polls to completion, returns open/download/refine links for the real GLB || `digest` (also `briefing`, `what happened today`) | `digest` | `GET /api/news/digest` — the last 24h clustered into narratives, rendered as rows |-| `price <coin>` or `$ticker` | `price btc`, `$sol` | `GET /api/coin/markets` + `/detail`, falling back to pump.fun token search |+| `price <coin>` (also `quote`) or `$ticker` | `price btc`, `$sol` | `GET /api/coin/markets` + `/detail`, falling back to pump.fun token search || `ask <question>` (or any query of ten or more characters ending in `?`) | `ask what is x402?` | `POST /api/chat`: the site agent's answer streamed into the panel; honors the free lane's `retry_after` backoff when it's at capacity |Grammar rules: commands are strict verb-first parses — a bare verb (`forge`)diff --git a/docs/agent-system.md b/docs/agent-system.mdindex d1efd16f3..216e35cd5 100644--- a/docs/agent-system.md+++ b/docs/agent-system.md@@ -12,7 +12,7 @@ A plain 3D viewer loads a GLB file and renders it. An agent is a viewer plus a b- **Avatar** — a Three.js 3D model with the Empathy Layer on top: continuous emotion blending, morph target control, gaze direction, and one-shot gestures all run per-frame.- **Memory** — a typed, ranked store of what the agent knows and has experienced, backed by `localStorage` and optionally synced to `/api/agent-memory`.- **Skills** — modular capabilities, each with a handler function, animation hint, and voice template. Skills are what the agent can *do*: wave, validate a model, remember something, sign an action with a wallet.-- **Runtime** — an LLM-driven tool-loop (`runtime/index.js`) that reads user input, calls Claude with a set of tools, executes the tool calls through `SceneController`, and emits the result as speech.+- **Runtime**: an LLM-driven tool-loop (`runtime/index.js`) that reads user input, sends it to the model with a set of tools, executes the tool calls through `SceneController`, and emits the result as speech.The viewer layer (`viewer.js`) knows nothing about agents. The agent layer wraps the viewer through `SceneController` (`runtime/scene.js`), which provides the clean surface area the runtime and skills need: `playClipByName`, `lookAt`, `setExpression`, `loadGLB`.@@ -90,13 +90,13 @@ protocol.recent('speak', 5); // last 5 speak actions- `manifest.instructions` (the agent's persona and rules)- A `<memory>` block with relevant entries from the memory store, up to `manifest.memory.maxTokens` (default 8192) tokens- A skill context block listing available skills and their descriptions-4. The provider (`AnthropicProvider`) calls `POST /v1/messages` (or a proxy URL) with the system prompt, conversation history, and available tools.+4. The provider (`AnthropicProvider`) streams an Anthropic-shape Messages request with the system prompt, conversation history, and available tools. It posts to `proxyURL` when one is set; otherwise, when the config carries an `agentId` and `apiOrigin` and no key, to `<apiOrigin>/api/llm/anthropic?agent=<id>`, the hosted proxy that routes free and paid models server-side (the default model is the free `google/gemma-4-31b-it:free`); and only with an explicit Anthropic `apiKey` does it call `https://api.anthropic.com/v1/messages` directly.5. If Claude returns **tool calls**, each one is dispatched through `_dispatchTool()`. Skill-provided tools take priority over built-ins; unknown tool names throw.6. Tool results are appended to the conversation as a `user`-role `tool_result` message, and the loop iterates again.7. The loop runs for at most `MAX_TOOL_ITERATIONS = 8` iterations. If the model returns a plain text response with no tool calls, the loop ends.8. The final text is returned from `send()`. If `voice: true` was passed, TTS speaks it before resolving.-**NullProvider:** When `brain.provider` is `"none"` in the manifest (or no API key is configured), `NullProvider` is used instead. It always returns `{ text: '', toolCalls: [] }`. The agent still loads, the avatar still emotes, and skills still execute — but the LLM never generates responses. This is useful for testing avatar behavior without an API key.+**NullProvider:** When `brain.provider` is `"none"` in the manifest, `NullProvider` is used instead (any other value except `anthropic` throws). It always returns `{ text: '', toolCalls: [] }`. The agent still loads, the avatar still emotes, and skills still execute, but the LLM never generates responses. This is useful for testing avatar behavior without an API key.```jsconst runtime = new Runtime({@@ -273,7 +273,7 @@ Beyond single gestures, an agent can carry named **routines**: sequences of gest## 6. Agent Memory-`agent-memory.js` implements a typed, ranked key-value store. It persists to `localStorage` immediately and optionally syncs to `/api/agent-memory` asynchronously (localStorage is always authoritative).+`agent-memory.js` implements a typed, ranked key-value store. It persists to `localStorage` immediately and optionally syncs to `/api/agent-memory` asynchronously (localStorage is always authoritative). Every sync and search call is prefixed with the store's `apiOrigin` option: empty (relative) on three.ws's own pages, and the three.ws origin when an `<agent-3d>` embed runs on another site, so those calls never land on the host page's origin. The file-based `Memory.load({ apiOrigin })` in `src/memory/index.js` and the runtime's `providerConfig.apiOrigin` follow the same rule.### Memory types@@ -318,7 +318,7 @@ When `localStorage` quota is exceeded, the store prunes expired entries first, t## 8. Skills-Skills extend what an agent can do. Every built-in capability is itself a skill: `greet`, `present-model`, `validate-model`, `remember`, `think`, `sign-action`, `help`.+Skills extend what an agent can do. Every built-in capability is itself a skill: `greet`, `present-model`, `validate-model`, `remember`, `think`, `sign-action`, `help`. On top of those seven, the `AgentSkills` constructor registers the domain skill families that live in the `src/agent-skills-*.js` modules (token trading, launching and watching, swaps, Blinks, NFTs, scene control, sentiment and market intel, and agent and agent-to-agent payments).Each skill definition (`SkillDef`) has:- `name` — unique identifier@@ -337,7 +337,9 @@ When a skill executes, `AgentSkills.perform()` emits `perform-skill` (so the avaSkills loaded from a manifest bundle go through `SkillRegistry` (`skills/index.js`), which enforces trust modes:- `any` — any skill installs without restriction- `owned-only` — `manifest.author` must match the `ownerAddress` element attribute or backend record-- `whitelist` — only explicitly approved skill URIs load+- `whitelist`: accepted as a mode, but the allowlist check is not wired yet, so today it installs like `any`++A bundle's `sandboxPolicy: "trusted-main-thread"` is only a request. Handlers run in the worker sandbox unless `SkillRegistry.mayRunOnMainThread()` grants the main thread, which it does only for a bundle served from a trusted origin (by default the page's own; `<agent-3d>` passes `mainThreadOrigins` with the page's origin and the origin that served its script) and never under `any` trust. A refused request logs a warning and the skill still runs, sandboxed.Skill dependencies are resolved recursively. A skill can declare `dependencies: ['wave', 'look-at']` and the registry will install them in order before registering the dependent skill.@@ -354,6 +356,7 @@ For the full skill bundle format, see [SKILL_SPEC.md](../specs/SKILL_SPEC.md).| Provider | Class | Key requirement | Notes ||---------|-------|----------------|-------|| `browser` (default) | `BrowserTTS` | None | Uses `window.speechSynthesis`. Free, offline-capable, voice quality varies by OS. |+| `neural` | `NeuralTTS` | None | In-browser Kokoro 82M via HeadTTS (WebGPU, WASM fallback), loaded lazily on first speak. Free, no audio leaves the device, and its phoneme timings drive lip-sync. || `elevenlabs` | `ElevenLabsTTS` | `voiceId` required; `apiKey` or `proxyURL` | Streaming MP3 via MediaSource (with Safari buffered fallback). Higher quality, requires server-side key management via proxy. || `none` | — | — | TTS disabled. |@@ -366,9 +369,10 @@ An ElevenLabs config also carries `agentId`, the agent the voice belongs to. `Ru| Provider | Notes ||---------|-------|| `browser` (default) | Uses `window.SpeechRecognition` or `window.webkitSpeechRecognition`. Chrome/Edge only. Silently fails if unavailable. |+| `whisper` | `WhisperSTT` (`runtime/whisper-stt.js`): on-device recognition in any browser with WebAssembly, Firefox and Safari included. A voice-activity detector cuts one utterance, then transformers.js transcribes it (Moonshine for English, Whisper base for other languages; models cached by the browser after the first download). If on-device decoding fails it posts the audio to `/api/asr`; where the browser cannot capture audio or run WebAssembly, the factory returns `BrowserSTT` instead. || `none` | STT disabled. |-STT starts listening when `runtime.listen()` is called, which the UI typically triggers on mic button press. Interim results fire `voice:transcript` events with `final: false`; the final transcript fires with `final: true` and the runtime feeds it into `send()`.+STT starts listening when `runtime.listen()` is called, which the UI typically triggers on mic button press. Interim results fire `voice:transcript` events with `final: false`; the final transcript fires with `final: true` and the runtime feeds it into `send()`. Recognizers that do work before any text exists (the `whisper` model downloading, an utterance decoding) report it as `voice:stt-status` events and through the `onStatus` callback of `listen()`, so the UI can say what is happening on a slow first load.---@@ -484,7 +488,7 @@ These are debug-only globals. Do not rely on them in production code — use depconst hasSpeech = !!(window.SpeechRecognition || window.webkitSpeechRecognition);```-STT silently no-ops on unsupported browsers (Firefox, Safari). Check this before relying on voice input.+The `browser` STT provider silently no-ops on unsupported browsers (Firefox, Safari). Check this before relying on voice input, or set `voice.stt.provider` to `whisper`, which recognizes on-device in those browsers.**Inspecting memory:**@@ -512,7 +516,7 @@ Quick reference for where each piece of the system lives:| `src/runtime/providers.js` | `AnthropicProvider`, `NullProvider` || `src/runtime/scene.js` | `SceneController` — wraps Viewer with agent-facing API || `src/runtime/tools.js` | `BUILTIN_TOOLS` definitions and handlers |-| `src/runtime/speech.js` | `BrowserTTS`, `ElevenLabsTTS`, `BrowserSTT` |+| `src/runtime/speech.js` | `BrowserTTS`, `ElevenLabsTTS`, `BrowserSTT`, and the `createTTS` / `createSTT` factories (`NeuralTTS` lives in `neural-tts.js`, `WhisperSTT` in `whisper-stt.js`) || `src/manifest.js` | Manifest loading and normalization || `src/skills/index.js` | `SkillRegistry` with trust modes and dep resolution || `src/memory/index.js` | File-based memory backend (frontmatter `.md` files) |diff --git a/docs/announcements/forged.md b/docs/announcements/forged.mdindex 1c8dfab4b..73834c08c 100644--- a/docs/announcements/forged.md+++ b/docs/announcements/forged.md@@ -14,24 +14,27 @@ against [the announcement voice](../announce-voice.md).> paid the Forge $0.15 in USDC over x402, the payment settled on Solana, and the card carries the> receipt (price, paying wallet, settlement transaction).-Verified by reading the code and by querying the live feed on 2026-09-17:+Verified by reading the code and by querying the live feed on 2026-09-17, and re-verified on+2026-10-09 (`GET /api/forged?limit=100`: 100 of 100 props at `price_usdc: 0.15`, tier `standard`,+every one carrying a `tx_sig`):| Part of the claim | Where it is real ||---|---|-| Every prop was bought by an autonomous agent | The only writer of `forge_autonomous_props` is the `forge` pipeline in the autonomous x402 loop, [`api/_lib/x402/pipelines/forge-content.js`](../../api/_lib/x402/pipelines/forge-content.js) ("Each call is a real on-chain USDC payment from the seed wallet via the shared payX402 client"). The feed, [`api/forged.js`](../../api/forged.js), reads only that table and states "There are no synthetic entries". The live page says "Every asset here was purchased by one of the platform's autonomous agents". |+| Every prop was bought by an autonomous agent | The only writer of `forge_autonomous_props` is `persistProp` in [`api/_lib/x402/pipelines/forge-content.js`](../../api/_lib/x402/pipelines/forge-content.js), called by two autonomous buyers: the `forge` pipeline in the autonomous x402 loop ("Each call is a real on-chain USDC payment from the seed wallet via the shared payX402 client"), and since 2026-09-22 the [fresh-wallet workers](../x402-fresh-workers.md) lane, which pays the same standard-tier `/api/x402/forge` call from a brand-new wallet per job (the feed marks those `payer_kind: "fresh"` and the card adds a "fresh wallet" badge). The feed, [`api/forged.js`](../../api/forged.js), reads only that table and states "There are no synthetic entries". The live page says "Every asset here was purchased by one of the platform's autonomous agents". || $0.15 in USDC per prop | The pipeline pays `POST /api/x402/forge` at the standard tier ([`docs/forged.md`](../forged.md), priced in [`api/_lib/forge-tiers.js`](../../api/_lib/forge-tiers.js)). `GET /api/forged?limit=100` on 2026-09-17 returned 100 of 100 props at `price_usdc: 0.15`, tier `standard`. Each card renders it as "$0.15 USDC" ([`src/forged-gallery.js`](../../src/forged-gallery.js), `formatUsdc`). || Over x402 | `payX402` in [`api/_lib/x402/pay.js`](../../api/_lib/x402/pay.js) selects the `solana` accept entry and settles through the self-hosted facilitator. The page hero: "real USDC over the x402 payment protocol". || The card links the Solana settlement | `toProp()` in [`api/forged.js`](../../api/forged.js) builds `explorer_url` from the stored `tx_sig`; the card renders it as a `receipt` link titled "View the settlement transaction on Solscan". All 100 props returned carried a `tx_sig`. The newest one (`28gNXzZjZSAQ...`) was checked with `getSignatureStatuses` against Solana mainnet: `finalized`, `err: null`. |-Full mechanism: [docs/forged.md](../forged.md). Live totals at time of writing, from the same feed-the hero reads: 129 renderable props, $21.15 USDC settled, across 8 prop families.+Full mechanism: [docs/forged.md](../forged.md). Live totals from the same feed the hero reads: 129+renderable props and $21.15 USDC settled on 2026-09-17; 276 renderable props and $46.50 settled+on 2026-10-09, across 8 prop families.## Media-Captured from the live route with `scripts/capture-doc-media.mjs`. Provenance (route, commit,-time, sha256) goes in [`public/announce/media-manifest.json`](../../public/announce/media-manifest.json)-when the recipe is merged into [`data/announce-media.json`](../../data/announce-media.json) and-`npm run announce:media` runs.+Captured from the live route with `scripts/capture-doc-media.mjs`. The `forged-hero` recipe lives in+[`data/announce-media.json`](../../data/announce-media.json), and `npm run announce:media` records its+provenance (route, commit, time, sha256) in+[`public/announce/media-manifest.json`](../../public/announce/media-manifest.json).| Shot | File | Notes ||---|---|---|@@ -68,9 +71,9 @@ the card. So the post opens on "bought by an autonomous agent", gives the exactthe frame and every receipt confirm), and ends on the receipt link, which is the reader's reasonto click.-The prop count (129) and the settled total ($21.15) were left out on purpose. They are true today-and read live off the feed, but the autonomous loop can resume buying at any time, and a count in-a queued post goes stale the moment it does. The per-prop price is fixed by the tier and does not+The prop count and the settled total were left out on purpose. They read live off the feed, and+they grow whenever the autonomous buyers run (129 props on 2026-09-17, 276 by 2026-10-09), so a+count in a queued post goes stale the moment it ships. The per-prop price is fixed by the tier and does notdrift.## Telegram variant@@ -102,11 +105,11 @@ nothing new.## Notes-- **Freshness.** The newest prop in the feed is from 2026-08-13; the autonomous loop has not bought- a prop since. Nothing in the post claims an ongoing cadence ("every hour" appears in the docs- but not in the copy), so the post stays true whether or not the loop resumes. Worth checking- the loop before scheduling: a live gallery that is growing on the day of the post is a better- demo than one that is a month old.+- **Freshness.** On 2026-09-17 the newest prop was from 2026-08-13. Buying resumed after that:+ on 2026-10-09 the newest prop was from 2026-10-03. Nothing in the post claims an ongoing cadence,+ so the post stays true whether or not the buyers are running on the day. Still worth checking+ `latest_ts` on `/api/forged` before scheduling: a gallery that is growing on the day of the post+ is a better demo than one that has gone quiet.- **Queue item:** status `review`, lane `agent-economy`, pattern `mechanism`, `notBefore` to be setby the owner.diff --git a/docs/aws-marketplace-listing-kit.md b/docs/aws-marketplace-listing-kit.mdindex 20f3eeb8c..173090ba2 100644--- a/docs/aws-marketplace-listing-kit.md+++ b/docs/aws-marketplace-listing-kit.md@@ -218,7 +218,12 @@ The free AWS subscription only grants the x402 access key.Lifecycle events land on `POST /api/aws-marketplace/subscription`, which isdeployed and accepts both transports: EventBridge agreement/license eventsrelayed through the API destination (the path a new listing uses), and legacy-signed SNS notifications with the SubscriptionConfirmation handshake.+signed SNS notifications with the SubscriptionConfirmation handshake. On the SNS+leg, both the signing certificate URL and the `SubscribeURL` must be HTTPS on the+SNS service endpoint itself (`sns.<region>.amazonaws.com`, certificate at+`/SimpleNotificationService-<id>.pem`), and neither is followed through a+redirect. Any other `*.amazonaws.com` host is refused, because S3 buckets and API+Gateway stages under that suffix can be created by anyone.---@@ -267,7 +272,8 @@ Done (in repo, deployed):- EULA HTML, S3 publish script, IAM + EventBridge provision script.- Welcome onboarding page.- Test coverage for the event mapping, the relay secret, the ambiguity guard, the- metering call shape, and SNS SignatureVersion 1 and 2.+ metering call shape, SNS SignatureVersion 1 and 2, and the SNS-endpoint-only+ certificate host check.Not done (requires AWS console / seller creds — cannot be done from this repo):- Running the provision + EULA-publish scripts (no AWS CLI/creds in codespace).@@ -326,7 +332,7 @@ Seven independent confirmations:| 4 | [saas-code-examples](https://docs.aws.amazon.com/marketplace/latest/userguide/saas-code-examples.html) | GetEntitlement example marks the `CUSTOMER_IDENTIFIER` filter "existing integrations only, not supported for new integrations" and prefers `CUSTOMER_AWS_ACCOUNT_ID`; a dedicated "BatchMeterUsage with License ARN" example exists for new products. || 5 | [AWS Marketplace blog: Concurrent Agreements upgrade guide](https://aws.amazon.com/blogs/awsmarketplace/complete-guide-to-upgrading-your-saas-product-to-aws-marketplace-concurrent-agreements/) | "replace any existing primary keys based on `CustomerIdentifier` or `ProductCode` with `LicenseArn`" and restructure tables accordingly. || 6 | [What's New, 2026-02-26](https://aws.amazon.com/about-aws/whats-new/2026/02/concurrent-agreements-february) | Concurrent Agreements launched; SaaS sellers must update entitlement + metering APIs and move notifications to EventBridge; mandatory for new products from June 1 2026. |-| 7 | Installed SDK, `@aws-sdk/client-marketplace-metering` 3.1066.0 | `ResolveCustomerResult` and `UsageRecord` typings both carry `LicenseArn` and `CustomerAWSAccountId`, so the re-key is implementable with the SDK version already pinned in this repo; no upgrade needed. |+| 7 | Installed SDK, `@aws-sdk/client-marketplace-metering` (3.1066.0 when verified; the repo now pins `^3.1131.0`) | `ResolveCustomerResult` and `UsageRecord` typings both carry `LicenseArn` and `CustomerAWSAccountId`, so the re-key is implementable with the SDK version already pinned in this repo; no upgrade needed. |We have never created a product, so our listing is a *new* integration by definition.diff --git a/docs/chatgpt-ar.md b/docs/chatgpt-ar.mdindex d0fb8dd02..7ec4b3271 100644--- a/docs/chatgpt-ar.md+++ b/docs/chatgpt-ar.md@@ -31,9 +31,11 @@ The same free lane ships into ChatGPT twice, because ChatGPT has two integration### 1. The ChatGPT app (Apps SDK / MCP connector)-Two front doors serve the same free tools over one handler, both with no authentication. `https://three.ws/api/mcp-chatgpt` is the one ChatGPT lists: the eight 3D tools and the model viewer, with no persona tools and no `frameDomains`, because OpenAI's app guidelines reserve frame domains for embedding an essential third-party experience. `https://three.ws/api/mcp-studio` is the full surface for Claude and every other MCP host and adds the three persona tools. `SURFACES` in [api/_mcp-studio/dispatch.js](../api/_mcp-studio/dispatch.js) is the single definition of what each door advertises. Across the two, eleven free tools: six generation tools (`forge_free`, `text_to_avatar`, `mesh_forge`, `rig_mesh`, `forge_avatar`, `refine_model`), the `check_job` collector that picks up a generation which outran the tool call (a pending result now names its `stage`, `mesh` or `rig`, so the collector knows which leg it is waiting on), the read-only `look_at_model` tool that renders any public GLB from several angles and returns the frames as images plus a plain reading of its geometry, so the assistant can judge its own output before printing a link, and, on `/api/mcp-studio` only, three persona/embodiment tools (`create_agent_persona`, `get_agent_persona`, `persona_say`, in [api/_mcp-studio/persona-tools.js](../api/_mcp-studio/persona-tools.js)). Full server documentation: [3D Studio MCP](./mcp-studio.md).+Three front doors serve the same free tools over one handler, all with no authentication. `https://three.ws/api/mcp-chatgpt` is the one ChatGPT lists: the eight 3D tools and the model viewer, with no catalog or persona tools and no `frameDomains`, because OpenAI's app guidelines reserve frame domains for embedding an essential third-party experience. `https://three.ws/api/mcp-studio` is the full surface for Claude and every other MCP host, and `https://three.ws/api/mcp-grok` serves the same full set to Grok and the xAI Responses API. `SURFACES` in [api/_mcp-studio/dispatch.js](../api/_mcp-studio/dispatch.js) is the single definition of what each door advertises. The full surface carries fourteen free tools: six generation tools (`forge_free`, `text_to_avatar`, `mesh_forge`, `rig_mesh`, `forge_avatar`, `refine_model`), the `check_job` collector that picks up a generation which outran the tool call (a pending result names its `stage`, `mesh` or `rig`, so the collector knows which leg it is waiting on), the read-only `look_at_model` tool that renders any public GLB from several angles and returns the frames as images plus a plain reading of its geometry, so the assistant can judge its own output before printing a link, three read-only asset catalog tools (`search_catalog`, `get_catalog_item`, `get_item_source`, in [api/_mcp-studio/catalog-tools.js](../api/_mcp-studio/catalog-tools.js)), and three persona/embodiment tools (`create_agent_persona`, `get_agent_persona`, `persona_say`, in [api/_mcp-studio/persona-tools.js](../api/_mcp-studio/persona-tools.js)). The first eight are the ChatGPT listing. Full server documentation: [3D Studio MCP](./mcp-studio.md).-Every successful tool result carries `arUrl` in its `structuredContent`, and the inline 3D widget renders it as a **View in your space** button next to the rotatable model. When the result is a rigged avatar the response additionally carries `irlUrl` and the button becomes **Bring it to life**. Refined versions (`refine_model`) each carry their own `arUrl`, so any point in the version lineage can be placed in the room.+ChatGPT drops a tool call still open at 60 seconds, while a generation takes one to four minutes. So on `/api/mcp-chatgpt` every call answers inside a 40 second budget (`CHATGPT_CALL_BUDGET_MS`) with either the finished model or a pending job, and the inline viewer widget collects that job itself (running the rig leg when an avatar's mesh lands first) and shows the model when it is ready. The assistant does not have to loop on `check_job`. Generation quotas on this door are keyed per ChatGPT user rather than on OpenAI's shared egress IP.++Every successful tool result carries `arUrl` in its `structuredContent` (next to the four plain links every model result now leads with for clients that render no widget: `viewer_url`, `glb_url`, `poster_png_url`, and `embed_html`), and the inline 3D widget renders it as a **View in your space** button next to the rotatable model. When the result is a rigged avatar the response additionally carries `irlUrl` and the button becomes **Bring it to life**. Refined versions (`refine_model`) each carry their own `arUrl`, so any point in the version lineage can be placed in the room.### 2. The "three.ws 3D Studio" custom GPT (Actions)@@ -120,7 +122,7 @@ Everything above is public plumbing:- **Any MCP client:** the full connector at `/api/mcp-studio` works in Claude and every other MCP host, not just ChatGPT. Every generation it returns already carries `arUrl` (and `irlUrl` for rigged avatars) plus a [Spatial MCP](./spatial-mcp.md) artifact, so no extra tool call is needed to get the AR link. To build that link set for a GLB the connector did **not** generate, use the read-only `export_ar` tool on the separate [`/api/mcp-3d` server](./mcp-3d-studio.md), which returns `arLaunchUrl`, `sceneViewerUrl`, `viewerUrl`, and `irlUrl`. That server is account- or payment-gated and is not part of the free connector.- **By hand:** the `arUrl` format is stable. If you have a public GLB, you can construct `https://three.ws/api/ar?src=<encoded GLB>&title=<name>` yourself and it will route correctly on every device.-The generation lane is operator-funded, so the end user pays nothing and needs no account. No backend is pinned: the health-aware router in [api/gpt-forge.js](../api/gpt-forge.js) walks the free lanes first (the self-hosted TRELLIS worker, the free NVIDIA NIM text→3D lane, the Hugging Face Spaces image→3D lane) and keeps the platform-keyed Replicate lane as a failover rung, so a cold or throttled free worker degrades to the next healthy engine instead of failing the request. Either way the cost lands on the platform. Real per-IP rate limits apply and are documented per endpoint (see [Funding & limits](./mcp-studio.md#funding--limits)).+The generation lane is operator-funded, so the end user pays nothing and needs no account. No backend is pinned: the health-aware router in [api/gpt-forge.js](../api/gpt-forge.js) walks the free lanes first (the self-hosted TRELLIS and Hunyuan3D GPU workers, then the Hugging Face Spaces image→3D lane and the free NVIDIA NIM text→3D lane; `freeLaneCandidates` in [api/_lib/forge-tiers.js](../api/_lib/forge-tiers.js) is the ordering) and keeps the platform-keyed Replicate lane as a failover rung, so a cold or throttled free worker degrades to the next healthy engine instead of failing the request. Either way the cost lands on the platform. Real per-IP rate limits apply and are documented per endpoint (see [Funding & limits](./mcp-studio.md#funding--limits)).---diff --git a/docs/coin-pages.md b/docs/coin-pages.mdindex 8bb80cb93..0f9110e74 100644--- a/docs/coin-pages.md+++ b/docs/coin-pages.md@@ -176,12 +176,20 @@ through the shared [`failover-fetch`](../src/shared/failover-fetch.js) primitivepublished either, but market cap ÷ price recovers it exactly. The lookup bySolana mint (`?contract=`) has no fallback: CoinPaprika is addressed by coinid, not by mint.-- **Exchange listings** (`/api/coin/tickers`) — CoinGecko `/coins/{id}/tickers`- → CoinPaprika `/coins/{id}/markets`. Derivatives venues are filtered out (the- CoinGecko endpoint it stands in for is spot-only, and perps would otherwise- head the table by volume). Spread and ±2% order-book depth don't exist in this- feed, so the client drops those three columns rather than render a wall of- em-dashes.+- **Exchange listings** (`/api/coin/tickers`): CoinGecko `/coins/{id}/tickers`+ → CoinPaprika `/coins/{id}/markets` → the coin's DEX pairs from DexScreener's+ keyless token index. Derivatives venues are filtered out of the CoinPaprika+ rung (the CoinGecko endpoint it stands in for is spot-only, and perps would+ otherwise head the table by volume). The DEX rung covers coins CoinPaprika+ does not list (young DEX-only tokens above all): the page passes the contract+ addresses it already holds from `/api/coin/detail` as `?contracts=` (up to 8,+ EVM or base58), and the handler keeps only pairs where the coin is the base+ token, ranked by 24h volume, cached and single-flighted like the CoinPaprika+ rung. DexScreener has no pagination, so page 1 is the whole answer. Without+ contracts, or with nothing trading, the 502 stands. The response's `source`+ names the rung that answered (`coingecko`, `coinpaprika`, `dexscreener`).+ Spread and ±2% order-book depth don't exist in either backup feed, so the+ client drops those three columns rather than render a wall of empty cells.- **Price chart** (`/api/coin/ohlc`) — CoinGecko `market_chart`, backed up forBTC/ETH/SOL by exchange candles (Kraken OHLC → Coinbase Exchange) — real tradeprints, so they lead — and for **every other coin** by DefiLlama's coins@@ -608,7 +616,7 @@ All data is real and fetched at runtime — nothing is hardcoded or sampled:| Endpoint | Upstream | Cache || ----------------------- | ---------------------------------------------------------- | ------------ || `/api/coin/detail` | CoinGecko `/coins/{id}` or `/coins/solana/contract/{mint}` (with community + developer blocks) | 60 s |-| `/api/coin/tickers` | CoinGecko `/coins/{id}/tickers` (exchange listings, ±2% depth) | 120 s |+| `/api/coin/tickers` | CoinGecko `/coins/{id}/tickers` (exchange listings, ±2% depth), CoinPaprika markets, then DexScreener pairs when `contracts=` is passed | 120 s || `/api/coin/ohlc` | CoinGecko `/coins/{id}/market_chart` | 120 s || `/api/coin/pool` | Top-pool lookup by token address (feeds the pool-keyed chart embeds: DEXTools, GeckoTerminal) | 60 s + 300 s CDN || `/api/coin/markets` | CoinGecko `/coins/markets` (optional `category=`), `/search` | 60 s / 300 s |diff --git a/docs/copy-coach.md b/docs/copy-coach.mdindex 61b9f9ca4..31a07a9a2 100644--- a/docs/copy-coach.md+++ b/docs/copy-coach.md@@ -79,19 +79,21 @@ curl -X POST "https://three.ws/api/copy/coach" \-d '{"message":"Can I lose money?","step":"ghost_copy","leader_id":"<agent uuid>","window":"30d","budget_sol":1}'```-`GET` returns `{ network, win, leaders[], starter_caps, eligibility_bar, generated_at }`.+`GET` takes an optional `?network=mainnet|devnet` (default `mainnet`) and returns+`{ network, win, leaders[], starter_caps, eligibility_bar, generated_at }`.`win` is null when no public agent closed a signed 25%+ win in the last 14days, and the page says so rather than reaching further back. Each leadercarries `copyable` and, when not, `unmet` in words.`POST` takes `message` (required, up to 500 characters), `history` (the lastturns as `{ role: 'user'|'coach', text }`), `step` (`see_a_win`, `ghost_copy`,-`starter_copy`, `full_copy`), `leader_id`, `window` and `budget_sol`, and+`starter_copy`, `full_copy`), `leader_id`, `window` (`24h`, `7d`, `30d`, `all`;+default `30d`), `budget_sol` (default 1) and `network`, andreturns `{ reply, source: 'llm'|'guide', model, facts_used }`.Both are public and need no account. `GET` shares the public IP limit;`POST` has its own bucket (30 questions per 10 minutes per IP). Errors use the-platform shape `{ error, error_description }`: `invalid_message`,+platform shape `{ error, error_description }`: `invalid_json`, `invalid_message`,`message_too_long`, `invalid_leader`, `invalid_network`.## Relateddiff --git a/docs/demo-routes.md b/docs/demo-routes.mdindex 9e0836d9f..a594fb20d 100644--- a/docs/demo-routes.md+++ b/docs/demo-routes.md@@ -119,7 +119,7 @@ live at their own top-level URLs:| Route | Page file | What it does ||---|---|---|-| `/coin3d` | `pages/coin3d.html` | Token-in-3D visualizer. |+| `/coin3d` | `pages/coin3d.html` | Token-in-3D visualizer. Keyed by `?mint=` or by `?pair=` (a pool address, resolved through `/api/coin/pair`); `?embed=1` drops the site chrome, and the route serves `frame-ancestors *` so it frames anywhere. See [coin3d-embed.md](coin3d-embed.md). || `/embed-demo` | `pages/embed-demo.html` | Avatar embed demo. || `/hero-demo` | `pages/hero-demo.html` | Cinematic 3D hero stage: a lit avatar over glowing rings and a starfield, with pointer parallax. || `/lipsync` | `public/demos/lipsync-tts.html` | Alias into the lab: TTS-driven lipsync. |diff --git a/docs/economy-solver.md b/docs/economy-solver.mdindex 7b161a023..c9d6046e2 100644--- a/docs/economy-solver.md+++ b/docs/economy-solver.md@@ -117,7 +117,7 @@ quoted without its assumptions is a lie:The game's XP award wraps `Math.round` around a uniform integer roll:```js-const xp = Math.round((9 + Math.floor(Math.random() * 5) + lvl * 0.3) * difficulty) * got;+let xp = Math.round((9 + Math.floor(Math.random() * 5) + lvl * 0.3) * difficulty) * got;```Rounding is not linear, so `E[round(X)] ≠ round(E[X])`. Substituting the mean of thediff --git a/docs/embody.md b/docs/embody.mdindex ed5e413d5..123cec7ee 100644--- a/docs/embody.md+++ b/docs/embody.md@@ -37,8 +37,8 @@ Response (`200`):"agent_id": "persona_8f2a1c9d4be6f70a1b2c","glb_url": "https://…/personas/persona_8f2a1c9d4be6f70a1b2c.glb","viewer_url": "https://three.ws/viewer?src=…",- "profile_url": "https://three.ws/embodiment/embed?persona=persona_8f2a1c9d4be6f70a1b2c",- "embed_html": "<iframe src=\"https://three.ws/embodiment/embed?persona=persona_8f2a1c9d4be6f70a1b2c\" width=\"480\" height=\"640\" …></iframe>",+ "profile_url": "https://three.ws/embodiment/embed?persona=persona_8f2a1c9d4be6f70a1b2c&glb=…&name=Nova+Scout&state=idle",+ "embed_html": "<iframe src=\"https://three.ws/embodiment/embed?persona=persona_8f2a1c9d4be6f70a1b2c&glb=…&name=Nova+Scout&state=idle\" width=\"480\" height=\"640\" …></iframe>","reload_url": "https://three.ws/api/mcp3d/persona?id=persona_8f2a1c9d4be6f70a1b2c","voice": "nova","rigged": true,@@ -51,7 +51,9 @@ Response (`200`):- **`embed_html`** is the real one-tag embed — drop it into any page and the bodyrenders, idles, lip-syncs, and emotes (the same embodiment component the 3DStudio uses).-- **`profile_url`** is the hosted presence page the iframe frames.+- **`profile_url`** is the hosted presence page the iframe frames. It carries the+ persona id plus the persisted GLB URL, the display name and `state=idle`, so the+ page renders the body without a second lookup.- **`rigged`** is `true` when the auto-rig succeeded. A model that can't beskeleton-rigged (e.g. a non-humanoid prop) falls back to the un-rigged mesh and`rigged` is `false` — never a broken T-pose.diff --git a/docs/event-readiness/16-invite-flow.md b/docs/event-readiness/16-invite-flow.mdindex 10416e998..96909f094 100644--- a/docs/event-readiness/16-invite-flow.md+++ b/docs/event-readiness/16-invite-flow.md@@ -4,8 +4,8 @@ Everyone at the event arrives through one link, and everyone who has fun should## Where the code lives-- Deep-link contract: `coinWorldUrl()` in `src/fits-lib.js` (tested in `tests/fits-lib.test.js`); canonical URL emission in `src/game/coincommunities.js` (`history.replaceState` in `enter()`, which keeps exactly `coin`, `name`, `symbol`, `image`, `tier` for a holders world, and `ui`; a bare `coin` link now resolves its name, symbol and image through `_fetchCoinIdentity` before the rewrite, so the canonical link is always complete)-- OG image for /play links: `api/play-og.js` (GET-only since the fleet hardening pass; any other verb is refused before the satori render); house OG patterns: `api/page-og.js`, `api/og-leaderboard.js`+- Deep-link contract: `coinWorldUrl()` in `src/fits-lib.js` (tested in `tests/fits-lib.test.js`); canonical URL emission in `src/game/coincommunities.js` (`history.replaceState` in `enter()`, which keeps exactly `coin`, `name`, `symbol`, `image`, `tier` for a holders world, and `ui`; any link that arrives short of a full identity, including a complete share link since it carries no market cap, resolves name, symbol, image and market cap through `_fetchCoinIdentity` before the rewrite, so the canonical link is always complete)+- OG image for /play links: `api/play-og.js` (GET-only since the fleet hardening pass; any other verb is refused before the satori render). Its coin lookup is a self-call on the configured origin from `api/_lib/self-origin.js`, never the request's `host` or `x-forwarded-host`; outside production a loopback host is honored, so hitting the endpoint on `npm run dev` renders against the local server. House OG patterns: `api/page-og.js`, `api/og-leaderboard.js`- HUD mount + share precedent: `src/game/coincommunities-ui.js` and the build-share sheet. Do not confuse this with the friend invites in `src/game/friends-panel.js`, which are a social-graph request, not a world link- QR: `qrcode` is already a dependency (`src/wallet-deposit.js` and `src/marketplace.js` render with it); use it, no new encoderdiff --git a/docs/ghost-copy.md b/docs/ghost-copy.mdindex 31f8cb010..2b4b68f2e 100644--- a/docs/ghost-copy.md+++ b/docs/ghost-copy.md@@ -51,7 +51,8 @@ costs the headline number something:- **Open positions stay out of the headline.** Positions the leader has notclosed are marked at *their* last on-chain quote (`last_value_lamports`) andreported as unrealized, in a separate table, never folded into the realized- number.+ number. A position with no quote yet is held at cost and labelled+ `marked: "cost"` rather than given a guessed mark.- **Slippage is not modelled, and the page says so.** Your fills would land afterthe leader's, not at the same price. The result is stated as a ceiling on theoutcome, not the outcome.@@ -160,6 +161,14 @@ renders the summary without it is misrepresenting the result.copies with real money, under segregated custody and hard spend limits. See[docs/copy-trading.md](copy-trading.md) for that engine.- A leader's underlying record: `/trader/<agent_id>`, one click from every result.+- First-timers: [/copy-coach](https://three.ws/copy-coach), linked from the top of+ the page, walks a newcomer from a real win through a ghost copy like this one to+ one small capped copy they sign themselves. See [docs/copy-coach.md](copy-coach.md).+- Quests: for a signed-in visitor, the page reports each finished replay to+ `POST /api/quests/event` (`kind: "ghost_copy"`), which counts toward the daily+ "ghost-copy a new agent" quest on [/quests](https://three.ws/quests). Only the+ first ghost of a given leader counts. The replay endpoint itself stays public and+ anonymous; signed-out visitors send nothing.## Sourcediff --git a/docs/github-memory-seeding.md b/docs/github-memory-seeding.mdindex f9747b7cd..6d783b990 100644--- a/docs/github-memory-seeding.md+++ b/docs/github-memory-seeding.md@@ -177,6 +177,13 @@ variables on the API service:| `GITHUB_OAUTH_CLIENT_ID` | The OAuth app's client ID, sent on the authorize redirect || `GITHUB_OAUTH_CLIENT_SECRET` | The client secret, used for the code exchange and for revoking the grant on disconnect |+The OAuth callback only completes in the signed-in browser that started the+connect: a callback that arrives with no session is sent back to+`/settings?tab=connected-accounts&github=error`, and one whose session is a+different account than the signed state answers `403 session_mismatch`. That+stops a connect link started on one account from binding someone else's GitHub+to it.+The app requests `read:user` and `public_repo`, both read-only, and the accesstoken is encrypted with a key derived from `JWT_SECRET` before it is stored, sorotating `JWT_SECRET` invalidates stored tokens (users reconnect) rather than@@ -195,7 +202,11 @@ unaffected: no other feature depends on these variables.## APIAll three calls are owner-only: the session (or bearer) user must own the-agent. The two mutations (POST and DELETE) additionally require the standard+agent. A bearer caller (API key or OAuth token) also needs the memory scope that+matches the verb: `memory:read` for the GET, `memory:write` for the POST and+DELETE, the same scopes the memory MCP tools require. A bearer without it+answers `403 insufficient_scope` before GitHub is read or any memory is+touched. The two mutations (POST and DELETE) additionally require the standardCSRF token in `x-csrf-token` when the caller authenticates with a sessioncookie: without it they answer `403 csrf_missing` and change nothing. Bearercallers are exempt, because a bearer token is not attached automatically by a@@ -276,6 +287,7 @@ because no API can delete a personal access token using that token.| Code | HTTP | Meaning ||---|---|---|| `unauthorized` | 401 | Sign-in required |+| `insufficient_scope` | 403 | A bearer caller lacks `memory:read` (GET) or `memory:write` (POST, DELETE) || `csrf_missing` / `csrf_invalid` | 403 | A cookie-authenticated POST or DELETE arrived without a valid `x-csrf-token` || `not_found` | 404 | No such agent, or it is not yours (a malformed id also answers 404, never a 500) || `not_connected` | 412 | Connect GitHub first; the response carries `connect_url` |diff --git a/docs/globe.md b/docs/globe.mdindex 31fc0c6fb..dd105d950 100644--- a/docs/globe.md+++ b/docs/globe.md@@ -213,6 +213,12 @@ per-point size, which `PointsMaterial` cannot express. Area layers (hotspots,outages, chokepoints) render as annuli instead of filled dots so a region neverreads as a single incident.+The detail card treats every feed value as untrusted. Titles and fields are+escaped before they reach the DOM, and the "Open source" link is only drawn when+`safeUrl()` ([`src/safe-url.js`](../src/safe-url.js)) accepts the event's `url`+as http(s) or site-relative; anything else (a `javascript:` URL from a poisoned+feed, say) simply gets no link.+## Sources and their terms| Source | Access | Notes |diff --git a/docs/home-plans.md b/docs/home-plans.mdindex 6c69045a3..a13899ca1 100644--- a/docs/home-plans.md+++ b/docs/home-plans.md@@ -198,6 +198,8 @@ curl -X POST https://three.ws/api/home/plan \```Admin session only. Sending `"limits": {}` clears the override and returns the account to its plan.+(For a bearer token rather than a session, `GET /api/home/plan` needs the `home:read` scope and+every `POST` needs `home:act`, the same capability-to-scope rule the per-home routes apply.)An unknown dimension is dropped rather than stored, so a typo in a form cannot install a limitnothing reads. A dimension the deal did not mention keeps its plan value.@@ -347,10 +349,16 @@ connected home and proves on screen that the row stays, is labelled paused, keepand can be made live again.```bash-HOME_E2E_API_PORT=8171 HOME_E2E_WEB_PORT=3031 HOME_LIVE=1 HOME_LIVE_NAME=plan19 \+HOME_E2E_ENC_KEY="$(node scripts/read-service-env.mjs '^WALLET_ENCRYPTION_KEY$' --raw)" \+ HOME_E2E_API_PORT=8171 HOME_E2E_WEB_PORT=3031 HOME_LIVE=1 HOME_LIVE_NAME=plan19 \npx playwright test --config playwright.home.config.js tests/e2e/home-plan.spec.js```+`HOME_E2E_ENC_KEY` (or an exported `WALLET_ENCRYPTION_KEY`) has to be the key bound to the+database in `.env.local`: [`api/_lib/secret-box.js`](../api/_lib/secret-box.js) refuses any other+writer with `secret_box_key_mismatch`, and the global setup checks the binding before the first+browser opens. [`tests/e2e/README.md`](../tests/e2e/README.md) has the details.+The journeys pause by clicking the button, never by posting to `/api/home/plan` directly: thatroute is CSRF-guarded like every other state change, so a raw request would have to mint a tokenthe product mints for itself, and the test would then be exercising a path no user takes.diff --git a/docs/internal/fable-playbook.md b/docs/internal/fable-playbook.mdindex dce20ff39..74a44c364 100644--- a/docs/internal/fable-playbook.md+++ b/docs/internal/fable-playbook.md@@ -58,6 +58,14 @@ The open work orders now live in `prompts/finish/` with a `roadmap-` prefix, andare open and what each owns. Feed one file to one fresh session. Do not inventnew work while those sit unexecuted; they were sequenced deliberately.+The queue is also worked unattended. Evolve (`npm run evolve:start`, runbook+[docs/ops/evolve.md](../ops/evolve.md)) runs headless Claude Code sessions+around the clock in its own worktree: it runs the lowest runnable order, writes+new scouted orders into the `400` band when the queue runs thin, and sweeps+production every few hours. It leaves an order alone for 6 hours after a human+last touched it, and `npm run evolve:pause` frees the subscription for+interactive work.+### Session patterns that fit Fable- **One work order, one session.** Each assumes a fresh context. Do not chain.@@ -79,8 +87,8 @@ new work while those sit unexecuted; they were sequenced deliberately.| OSS scout | weekly | Scan npm and GitHub for movement in our dependency frontier (three.js releases, gltf-transform, meshoptimizer, gsplat, model-viewer, TalkingHead). Diff against the REUSE-MAP; open a dated addendum with license verdicts. | Manual. No script yet; this is the next routine worth automating. || Docs drift | weekly | Cross-check `STRUCTURE.md`, `docs/`, and `data/pages.json` against the tree; fix stale rows in place. | `.claude/workflows/docs-drift.js`, `npm run audit:docs` || Gate health | daily | Run the regression gate; on red, bisect and report. Never let the baseline rot. | `npm run gate` |-| Production sweep | daily | Health, logs, TLS, fleet readiness, live pages, crons, migrations. | the `gcp-triage` skill, `npm run smoke:prod` |-| Changelog to community | on deploy | Nothing to run. `/api/cron/changelog-push` reads the feed baked into the running image and posts new entries to the community Telegram channel on its own. **Do not run `npm run changelog:push`**: its file-based state is separate from the cron's DB state, so a manual push double-posts. The script survives for `--dry-run` previews and owner-directed backfills only. X delivery is retired. | Cloud Scheduler |+| Production sweep | daily | Health, logs, TLS, fleet readiness, live pages, crons, migrations. | the `gcp-triage` skill, `npm run smoke:prod`; Evolve's `triage` lane also runs it unattended |+| Changelog to community | on deploy | Nothing to run. `/api/cron/changelog-push` reads the feed baked into the running image and posts new entries on its own: every entry to the community Telegram channel, and every entry that passes `data/changelog-x-filter.json` as a reply in the @trythreews X thread (X was retired on 2026-07-18 and turned back on by the owner on 2026-09-24). **Do not run `npm run changelog:push`**: its file-based state is separate from the cron's DB state, so a manual push double-posts. The script survives for `--dry-run` previews and owner-directed backfills only. | Cloud Scheduler || Revenue readout | weekly | Split settled x402 volume into external, internal ring, and synthetic; report the external number. That is the only number that counts toward §4. | `npm run readout:revenue` |---@@ -112,8 +120,10 @@ noted per item so nobody rebuilds what already exists.4. **Embed, oEmbed and OG thumbnails.** *Shipped.* `api/agent-oembed.js`,`api/play-oembed.js`, the `/embed/*` route family in `vercel.json`, and OGimage endpoints (`api/avatar-og.js`, `api/avatar-detail-og.js`,- `api/og/`). Remaining upside is the same as 3: distribution is wired but not- yet defaulted into every share path.+ `api/og/`). Shared `/m/:id` creation links now unfurl as a render card with+ `3DModel` JSON-LD (`server/creation-head.mjs`, `api/_lib/creation-jsonld.js`,+ [docs/seo.md](../seo.md)). Remaining upside is the same as 3: distribution is+ wired but not yet defaulted into every share path.The honest reading of 2 through 4: the capability is built, the funnel is notmeasured. A generation that produces an AR link nobody clicks converts nothing.@@ -167,21 +177,24 @@ $50M to $100M ARR. The ladder:### The measured position-Run `npm run readout:revenue -- --window all`. As of 3 September 2026 that+Run `npm run readout:revenue -- --window all`. As of 9 October 2026 thatreturns:-- **38,620 settled x402 payments, $972.098 gross.**-- **38,614 of them (99.98%, $972.092) are the internal ring**: platform-controlled+- **61,767 settled x402 payments, $10,303.60 gross.**+- **61,748 of them (99.97%, $10,163.51) are the internal ring**: platform-controlledwallets paying platform endpoints on a cron. Real money on a real chain, andentirely our own.-- **2 calls, $0.002, are synthetic**: a literal `PAYER` string from a- replay-test path. Not a buyer, not money.-- **External, all time: 4 calls from 3 addresses, $0.004**, across- `/api/x402/skill-marketplace` and `/api/x402/solana-register-health`, the most- recent in August 2026.+- **0 calls are synthetic** (the classifier's bucket for test payers such as a+ literal `PAYER` string from a replay-test path).+- **External, all time: 19 calls from 4 addresses, $140.09.** $140.00 of it is+ two routes, nine `/api/x402/dance-tip` payments ($90) and five+ `/api/x402/club-cover` payments ($50); the rest is cents across+ `/api/x402/skill-marketplace`, `/api/x402/pump-agent-audit` and+ `/api/x402/mint-to-mesh-batch`. Four addresses is few enough to check by hand+ that they are strangers before any of it is cited as rung-1 proof.So we are not on rung 1. We are below it, and the gross ledger hides that by a-factor of roughly 240,000. This is the single most important fact in this+factor of roughly 74. This is the single most important fact in thisdocument, and until this readout existed it was not visible to anyone readingthe numbers the platform reported about itself.@@ -235,13 +248,15 @@ of the map is already a dependency.1. **Distribution beats features from here.** The platform out-builds itsawareness. `llms.txt`, the sitemap and the changelog rails exist; the missingpiece is the loop that turns every artifact into a share. Wire sharing into- artifacts (§3.3, §3.4) rather than adding surfaces. Note that the changelog's automatic X delivery- stays retired and the toolkit that drove it is no longer vendored here: it- lives at `nirholas/XActions` and on npm (see `STRUCTURE.md`). The X surface- that does exist is the reviewed @trythreews content queue- (`/api/cron/x-content` every 15 minutes, [docs/x-content-pipeline.md](../x-content-pipeline.md)),- and it only previews: nothing is sent until an item is `approved` and- `X_CONTENT_AUTO_PUBLISH=true` is set on the service, which it is not today.+ artifacts (§3.3, §3.4) rather than adding surfaces. X has two live lanes on+ @trythreews. The changelog cron replies filtered release entries into one+ thread (back on since 2026-09-24). The reviewed content queue+ (`/api/cron/x-content` every 15 minutes, [docs/x-content-pipeline.md](../x-content-pipeline.md))+ publishes only `approved` items, and it is live: `X_CONTENT_AUTO_PUBLISH=true`+ is set on the service, and `X_CONTENT_REMOTE_QUEUE=true` lets a post approved+ after the last deploy ship as a signed bundle from object storage without+ another deploy. The old automation toolkit is no longer vendored here: it+ lives at `nirholas/XActions` and on npm (see `STRUCTURE.md`).2. **Trust is a sellable feature.** We run a hash-chained economy ledger, breachmonitoring, risk-acknowledgment gating, spend guards, and fail-closed tradingrules. "Agents that touch real money, auditable by design" is positioningdiff --git a/docs/knock.md b/docs/knock.mdindex 4713a430d..ba02d51a7 100644--- a/docs/knock.md+++ b/docs/knock.md@@ -256,10 +256,16 @@ a 404, not a 403: an id on its own should not confirm that a knock exists.| `POST /api/knock/escrowed` | on-chain escrow | Knock on a door that takes escrowed knocks, where the money only moves if you get an answer. || `POST /api/knock/escrow-sync` | none | Re-read one escrow on-chain and update the cached state on its delivered knock. Open to anybody: it can only write back what the program already recorded. || `GET /api/knock/reply?id=&token=` | receipt token | What became of a knock you sent. |-| `GET /api/knock/settings` | session | Your door, your totals, your block list. |-| `PATCH /api/knock/settings` | session | Change any of it. |-| `GET /api/knock/inbox` | session | The knocks your door has taken. |-| `PATCH /api/knock/inbox/<id>` | session | Reply, mark read, dismiss, block. |+| `GET /api/knock/settings` | session, or a bearer with `profile` | Your door, your totals, your block list. |+| `PATCH /api/knock/settings` | session, or a bearer with `profile` (plus `wallet:write` to change a payout wallet) | Change any of it. |+| `GET /api/knock/inbox` | session or bearer | The knocks your door has taken. |+| `PATCH /api/knock/inbox/<id>` | session or bearer | Reply, mark read, dismiss, block. |++A bearer is an API key or OAuth access token. A cookie session carries every+scope; a bearer holds only what it was granted, and `/api/knock/settings`+answers `403 insufficient_scope` when it lacks `profile`. Moving the payout+(`pay_to_solana` or `pay_to_base`) needs `wallet:write` as well, because it+redirects every future paid knock.Error codes are stable and mean what they say: `no_door`, `door_closed`,`door_full` (429, retryable tomorrow), `message_too_long`, `message_too_short`,diff --git a/docs/materialize.md b/docs/materialize.mdindex 2d5dbbcbf..15aca257e 100644--- a/docs/materialize.md+++ b/docs/materialize.md@@ -240,6 +240,14 @@ free with a `422` and a caller never pays for something that was going to berejected. The 402 then quotes that token's own total, because every print is itsown object with its own price.+An agent has no session, so to get the `$THREE` holder discount it names the+wallet it will pay from as `payerWallet` in the quote request, and the tier is+read from that wallet's own on-chain holdings. A discounted quote is then bound+to that wallet: the token carries it, and checkout refuses a payment from any+other wallet with `403 quote_wallet_mismatch` before anything settles, so naming+a large holder's wallet buys nothing. Leave `payerWallet` out to quote at list+price and pay from any wallet.+```bash# 1. Quote (free, keyless). Keep `token` from the response.curl -s https://three.ws/api/print/quote \diff --git a/docs/mcp-3d-studio.md b/docs/mcp-3d-studio.mdindex 841ec9d80..0152fdae7 100644--- a/docs/mcp-3d-studio.md+++ b/docs/mcp-3d-studio.md@@ -7,8 +7,8 @@ MCP server, registered separately as **`io.github.nirholas/threews-3d-studio`**.- **Endpoint:** `https://three.ws/api/mcp-3d`- **Transport:** Streamable HTTP (MCP `2025-06-18`, JSON-RPC 2.0)-- **Auth:** OAuth 2.1 (same three.ws authorization server as `/api/mcp`) or x402-- **Backends:** Microsoft TRELLIS image→3D + FLUX text→image (Replicate, platform-keyed); Meshy / Tripo native geometry (BYOK); Make-It-Animatable auto-rig (self-hosted GPU worker); IBM Granite (watsonx.ai) for prompt direction + material generation+- **Auth:** OAuth 2.1 (same three.ws authorization server as `/api/mcp`) or x402. The server is its own OAuth resource, `https://three.ws/api/mcp-3d`, described at `https://three.ws/.well-known/oauth-protected-resource/api/mcp-3d`, so stock MCP SDK connectors can sign in; tokens minted for `/api/mcp` are accepted here too+- **Backends:** image→3D on the self-hosted GCP reconstruction worker when configured, else Microsoft TRELLIS on Replicate; text→image on the free lanes first (FLUX on NVIDIA NIM, Vertex AI Imagen) with Replicate FLUX as the paid backstop; Meshy / Tripo / Rodin / Stability native geometry (BYOK); Make-It-Animatable auto-rig (self-hosted GPU worker); IBM Granite (watsonx.ai) for prompt direction + material generation## The pipeline@@ -75,6 +75,7 @@ analyze: inspect_model · optimize_model preview: preview_3d| `grade_sim_readiness(glb_url, hash?)` | Free: can this GLB be dropped into a physics simulator (MuJoCo, Isaac, Bullet, a game engine) and behave? Returns `simulation_ready`, `needs_scale`, `needs_repair`, or `unusable`, plus the measurements behind the verdict. || `anchor_provenance(glb_url, creator?, prompt?, …)` | Issue a signed content credential for a generated GLB and anchor its hash on Solana, so anyone can later check authenticity for free. || `verify_provenance(glb_url, hash?)` | Free: recompute the model’s content hash, check the signed credential and its on-chain anchor, and answer `verified`, `tampered`, or `unknown`. |+| `read_resource(uri?, format?)` | Free: read a live `three://` resource (`three://me`, `three://agents`, `three://agents/<id>`, `three://models`, `three://assets/<id>`) for clients that render tools but not MCP resources. Omit `uri` to list what you can read. || `validate_spatial_response(artifact)` | Free: check a structured-content payload against the open [Spatial MCP](./spatial-mcp.md) artifact shape before you ship it. || `x402_preflight(origin, network?)` | Read-only, free: fetch an x402 seller's signed payability attestation from `<origin>/.well-known/x402-preflight`, verify its ed25519 signature, expiry, and subject, and answer whether that seller can actually settle before you pay it. An attestation that does not verify is reported as unverified, never as health. Spec: [`specs/x402-preflight.md`](../specs/x402-preflight.md). |@@ -98,6 +99,7 @@ derivation scheme).| Tool | What it does || -------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- || `persona_identity(persona_id, network?)` | Read-only: wallet address, live SOL/USDC balance, ERC-8004-style reputation, token holdings, a resolved SNS nameplate, and the visual tiers below. |+| `persona_payment_preview(persona_id, to, usdc, session_id?, network?)` | Read-only: the paying wallet and its live USDC balance, the recipient, the balance afterwards, session spend against the cap, and every rule that would refuse the transfer (`would_execute` plus `blockers`). Moves nothing; show it, get a yes, then call `persona_tip` or `persona_send`. || `persona_tip(persona_id, to, usdc, session_id?, memo?, network?, confirm?)` | Send a small USDC tip from the persona's own wallet. Real, irreversible on-chain settlement. || `persona_send(persona_id, to, usdc, session_id?, memo?, network?, confirm?)` | The general-purpose USDC send from the persona's own wallet. Same guardrails as `persona_tip`. |@@ -110,6 +112,10 @@ derivation scheme).`session_id` (or a persona+UTC-day bucket when omitted).- **Confirmation threshold** — $0.25 USDC by default. Above it, the call mustcarry `confirm: true` or it returns `confirmation_required`.+- **Owner only.** A persona created by a signed-in three.ws account moves funds+ only for that account: any other caller gets `not_owner`, because the+ `persona_id` travels in every shared embodiment URL. A persona minted with no+ account keeps the `persona_id`-as-capability model it was created under.Settlement rides the same MEV-aware execution engine every other outboundtransfer on the platform uses — no mocked transfer, ever. USDC is the only@@ -138,22 +144,33 @@ timestamp.`text_to_3d` / `image_to_3d` take three optional axes (see[`api/_lib/forge-tiers.js`](../api/_lib/forge-tiers.js)):-- **`tier`** — `draft` (~12k poly, fast), `standard` (~30k, default), `high`- (~200k + PBR, slower). Honoured by poly-aware backends; on the TRELLIS default- it's recorded as provenance.-- **`path`** — `image` (FLUX→TRELLIS reference-image reconstruction, the- platform-keyed default) or `geometry` (native text/image→mesh, cleaner- topology).-- **`backend`** — force a specific engine; defaults to the best for the path.--| Backend | Path(s) | Key | Notes |-| ----------- | --------------- | --------- | ------------------------------------ |-| `trellis` | image | platform | Fast default. No poly target. |-| `meshy` | geometry, image | **BYOK** | Native text→geometry, quad topology. |-| `tripo` | geometry, image | **BYOK** | Cleanest quad topology. |-| `hunyuan3d` | image | self-host | High-poly, image-conditioned (GCP). |--When no `backend` is named, the resolver walks the free lanes first: the tier's named free engine (the self-hosted TRELLIS worker at `draft` and `standard`, the self-hosted Hunyuan3D worker at `high`), then the per-path fallback chain (self-host TRELLIS, self-host Hunyuan3D, the free HuggingFace Spaces lane, and last the free NVIDIA NIM TRELLIS lane, which is text-only). The paid Replicate `trellis` lane is the standing default only when no free lane is live on the deployment. Lane health is consulted, so a cold or down free worker is skipped for the next healthy one before submit.+- **`tier`**: `draft` (~12k poly, fast), `standard` (~30k, default), `high`+ (~200k + PBR, slower). Honoured by poly-aware engines; on the default image+ engine it's recorded as provenance.+- **`path`**: `image` (reference-image reconstruction, the platform-keyed+ default) or `geometry` (native text/image→mesh, cleaner topology, BYOK).+- **`backend`**: a three.ws engine name; `auto` (the default) picks the best+ engine for the path. Responses report the engine under the same branded+ name. Legacy vendor ids are still accepted as hidden aliases, and an engine+ that does not serve the chosen path is ignored.++| Engine | Runs on | Path(s) | Key | Notes |+| -------------------- | --------- | --------------- | -------- | --------------------------------------------- |+| `three-image` | platform | image | platform | The default. No poly target. |+| `three-geometry` | Meshy | geometry, image | **BYOK** | Native text→geometry, quad topology. |+| `three-geometry-pro` | Tripo | geometry, image | **BYOK** | Cleanest quad topology. |+| `three-sculpt` | Rodin | geometry, image | **BYOK** | High-poly detail. |+| `three-instant` | Stability | image | **BYOK** | Fast single-image. |+| `three-detail` | platform | image | platform | Poly-aware; reconstructs on the platform lane. |++The image path on this server always reconstructs on the platform provider: the+self-hosted GCP reconstruction worker when `GCP_RECONSTRUCTION_KEY` and+`GCP_RECONSTRUCTION_URL` are set, otherwise TRELLIS on Replicate. The free-lane+walk of `/api/forge` (self-host TRELLIS and Hunyuan3D, the HuggingFace Spaces+lane, NVIDIA NIM, with failover between them) is not wired into this server, so+the HuggingFace engine is deliberately not selectable here. Free text→3D over+MCP is the `forge_free` tool on the [free 3D Studio](./mcp-studio.md)+(`/api/mcp-studio`).**BYOK note:** the geometry backends (Meshy/Tripo) have no platform key. Supplyyour own via the `x-forge-provider-key` request header (or a key stored on your@@ -201,7 +218,7 @@ For tool calls there are two lanes:| `stylize_model`, `remesh_model`, `segment_model` | $0.02 || `capture_scene`, `anchor_provenance` | $0.05 || `remove_background`, `pose_model`, `apply_animation`, `direct_prompt`, `generate_material` | $0.01 |-| `generation_status`, `preview_3d`, `list_animations`, `animation_signature`, `find_similar_animations`, `text_to_animation`, `inspect_model`, `optimize_model`, `save_avatar`, `export_ar`, `verify_provenance`, `grade_sim_readiness`, `x402_preflight`, the persona tools, `validate_spatial_response`, `getting_started` | free |+| `generation_status`, `preview_3d`, `list_animations`, `animation_signature`, `find_similar_animations`, `text_to_animation`, `inspect_model`, `optimize_model`, `save_avatar`, `export_ar`, `verify_provenance`, `grade_sim_readiness`, `x402_preflight`, the persona tools (including `persona_payment_preview`), `read_resource`, `validate_spatial_response`, `getting_started` | free |Payment settles only after the work succeeds — a wholesale failure costsnothing, and the same signed payment cannot be replayed.@@ -229,11 +246,11 @@ as a live orbitable artifact, then `auto_rig_model` → `apply_animation(animati| Env | Purpose | Default || --------------------------------------------------- | ------------------------------------------------------------------------------------- | -------------------------------- |-| `REPLICATE_API_TOKEN` | Required. Powers reconstruction, rigging, remesh, retexture. | — |+| `REPLICATE_API_TOKEN` | Replicate lane for reconstruction, rigging, remesh, retexture, and the paid text→image backstop. Required for any mode with no GCP worker configured. | unset || `REPLICATE_RECONSTRUCT_MODEL` | image→3D model. | `firtoz/trellis` |-| `REPLICATE_TXT2IMG_MODEL` | text→image model for `text_to_3d`. | `black-forest-labs/flux-schnell` |-| `REPLICATE_RERIG_MODEL` | Auto-rig model. Without it, `auto_rig_model` reports "not configured". | — |-| `GCP_RECONSTRUCTION_URL` / `GCP_RECONSTRUCTION_KEY` | Optional self-host backend (Hunyuan3D, masked region retexture). | — |+| `REPLICATE_TXT2IMG_MODEL` | Replicate text→image model for `text_to_3d`, used only after the free lanes (`NVIDIA_API_KEY` for NIM FLUX, `GOOGLE_CLOUD_PROJECT` for Vertex Imagen). | `black-forest-labs/flux-schnell` |+| `REPLICATE_RERIG_MODEL` | Replicate auto-rig model, used when no GCP rig worker is configured. Without either, `auto_rig_model` reports "not configured". | unset |+| `GCP_RECONSTRUCTION_KEY` + per-mode worker URLs | Self-hosted GCP workers, preferred over Replicate for every mode whose URL is set: `GCP_RECONSTRUCTION_URL` (reconstruct), `GCP_UNIRIG_URL` (rig), `GCP_REMESH_URL`, `GCP_STYLIZE_URL`, `GCP_SEGMENT_URL`, `GCP_TEXTURE_URL` (retexture; required for `retexture_region`), `GCP_REMBG_URL`, `GCP_VIDEO2SCENE_URL` (`capture_scene`). | unset || `WATSONX_API_KEY` / `WATSONX_PROJECT_ID` | Enable `direct_prompt` + `generate_material`. | — || `APP_ORIGIN` | Origin used to load the animation manifest for `list_animations` / `apply_animation`. | request host || `MCP_POSE_PREVIEW_BASE` | Base URL for `pose_model` preview links. | `https://three.ws/pose` |@@ -256,6 +273,10 @@ mcp-publisher login githubmcp-publisher publish --file server-3d.json```+Or let the repo's publisher do it alongside the other servers, under the+`remote-3d` key: `npm run publish:mcp:dry`, then+`npm run publish:mcp -- --only remote-3d`.+## Local development```bashdiff --git a/docs/mcp-x402-bazaar.md b/docs/mcp-x402-bazaar.mdindex 0170fa1fc..dd6d2d99f 100644--- a/docs/mcp-x402-bazaar.md+++ b/docs/mcp-x402-bazaar.md@@ -8,7 +8,7 @@ client. Registered with the MCP Registry as- **Endpoint:** `https://three.ws/api/mcp-bazaar`- **Transport:** Streamable HTTP (MCP `2025-06-18`)- **Auth:** OAuth 2.1 (same three.ws authorization server as `/api/mcp`) or x402-- **Data:** live `/discovery/resources` from the configured x402 facilitators — no cached or synthetic listings+- **Data:** live `/discovery/resources` from the configured x402 facilitators, never synthetic listings. `search_services` scores against an in-process copy of the merged catalog that is refreshed at most every 60 seconds (`BAZAAR_CATALOG_TTL_MS`); `browse_services`, `get_service` and `bazaar_service_details` query the facilitators on every call## Tools@@ -18,6 +18,7 @@ client. Registered with the MCP Registry as| `browse_services(type?, network?, max_price_usdc?, limit?)` | List services without a query — "what can I pay for?". || `get_service(resource_url, tool_name?)` | Full payment requirements (price, asset, network, recipient), input/output schema, and a ready pay link. || `bazaar_service_details(resource_url, tool_name?)` | Live price only: cheapest across networks plus a per-network breakdown. Built for price tracking on a schedule. |+| `read_resource(uri?, format?)` | Reads a `three://` resource (see below) for clients that show tools but not resources. Omit `uri` to list what you can read; `format: "markdown"` returns a readable rendering. || `getting_started(section?)` | Free, no auth or payment. An overview of the server, its tools, and how to connect. Call this first. |`type` is `http` (paid HTTP APIs) or `mcp` (paid MCP tools). `network` is a@@ -59,6 +60,21 @@ missing label and a missing sample stay distinguishable.Use `get_service` instead when you also need the input/output schema and a paylink. `bazaar_service_details` deliberately omits both to stay cheap to poll.+## Resources and prompts++The server also publishes the shared three.ws MCP resources and guided prompts+(full reference: [Resources](./mcp.md#resources) and+[Guided prompts](./mcp.md#guided-prompts)). On this server that is:++- **Resources:** `three://me` (your credential, scopes and daily quota),+ `three://x402/services` (the live x402 service catalog) and+ `three://marketplace` (paid agent skills and agent services). The last two are+ public.+- **Prompts:** `get-started`, `hire-agent(task)`, `explore-marketplace` and+ `explore-x402(capability)`.++`resources/list` and `prompts/list` on the endpoint are the authoritative lists.+## Use on claude.aiAdd the connector with URL `https://three.ws/api/mcp-bazaar` and complete OAuth.diff --git a/docs/ops/cron-auth.md b/docs/ops/cron-auth.mdindex 768f61bf8..de94704eb 100644--- a/docs/ops/cron-auth.md+++ b/docs/ops/cron-auth.md@@ -34,6 +34,13 @@ the line is directly internet-invokable. The edge gate makes that omissionsurvivable: mounted ahead of the route table in `server/index.mjs`, it refusesthe request before any handler is imported.+It decides what counts as a cron path on the same view of the URL the API+dispatcher routes on (`apiSegments` in `server/route-resolve.mjs`): empty+segments dropped and each segment percent-decoded. Matching the raw string let+`/api//cron/x` and `/api/%63ron/x` slip past this gate while still dispatching+to `api/cron/x.js`; both are gated now, and a path that will not decode is+treated as gated rather than waved through.+It accepts two credentials, permanently. This is defense in depth, not amigration with a cutover:@@ -68,7 +75,8 @@ itself is a 401, not a pass.Covered by `tests/server-cron-edge-auth.test.js`, which verifies real RS256signatures against a locally generated key set: a forged token, a wrongaudience, a wrong issuer, a wrong service account, an unverified email, and an-expired token are each refused, and a genuine one is accepted.+expired token are each refused, and a genuine one is accepted. It also pins the+path spellings above (doubled slashes, a percent-encoded `cron`) as gated.## Attaching the OIDC token (the fleet-wide step)@@ -113,6 +121,12 @@ gcloud logging read \The sync reads `CRON_SECRET` from `--env-file`, then `process.env`, then thelive Cloud Run service, so on an authenticated machine step 2 needs no argument.+Every deploy also runs `npm run deploy:gcp:sync-crons`+(`create-gcp-scheduler.mjs --missing-only`), which creates a job for each newly+declared cron and never touches an existing one. It does not pass `--oidc`, so+after the migration a cron added later starts on the Bearer secret, which the+edge still accepts. Re-run step 3 to move it onto the token.+**Rollback** is one command and needs nothing else: `nodescripts/create-gcp-scheduler.mjs` (no `--oidc`) puts the Bearer secret back onevery job. The edge keeps accepting it, because it never stopped.diff --git a/docs/oracle-trading-mcp-plan.md b/docs/oracle-trading-mcp-plan.mdindex e749fd7da..08e10badd 100644--- a/docs/oracle-trading-mcp-plan.md+++ b/docs/oracle-trading-mcp-plan.md@@ -1,6 +1,6 @@# Plan: ship Oracle and the autonomous trading agents as MCP servers-**Status:** planned, not started. Written 2026-08-19; still unstarted at 2026-09-17 (no `packages/oracle-mcp`, no `api/mcp-oracle.js` in the tree). Facts below re-verified 2026-09-17.+**Status:** planned, not started. Written 2026-08-19; still unstarted at 2026-10-09 (no `packages/oracle-mcp`, no `api/mcp-oracle.js` in the tree; `packages/oracle-model` is the local scorer library, not an MCP server). Facts below re-verified 2026-10-09.**Goal:** make [Oracle](https://three.ws/oracle) and the autonomous trading agents first-class,discoverable MCP servers, publish them to the official MCP registry(`registry.modelcontextprotocol.io`), document them, and announce them in one plain-language X post.@@ -15,15 +15,15 @@ tree and the live registry on 2026-08-19, so the plan starts from facts, not assOracle is the best thing we run and almost nobody can find it from an agent client.Its four MCP tools (`oracle_top_plays`, `oracle_coin`, `oracle_arm_watch`, `oracle_watch_status`)-live inside the main `https://three.ws/api/mcp` server, buried among 50+ avatar, model, animation,-sign-language, memory, and market tools (55 in `public/mcp-catalog.json` today). In the registry that server is listed as+live inside the main `https://three.ws/api/mcp` server, buried among 80+ avatar, model, animation,+sign-language, memory, and market tools (87 in `public/mcp-catalog.json` today). In the registry that server is listed as"3D avatars, embeds, glTF tools, agent memory, and on-chain agent identity". An agent looking fora conviction signal on a new launch has no way to find it, and a human browsing the registry hasno reason to click.The same is true of the autonomous side. `oracle_arm_watch` is the single most interesting writetool on the platform (it arms an agent to trade a live conviction stream inside a spend leash), and-it is discoverable only by reading a 55-tool list on an avatar server.+it is discoverable only by reading an 87-tool list on an avatar server.The fix is not new capability. It is **packaging**: two focused servers, named for what they do,listed under their own registry entries.@@ -36,7 +36,7 @@ listed under their own registry entries.| Layer | Location | State ||---|---|---|-| Conviction engine | `api/_lib/oracle/` + `conviction-model.json` | Live, fitted model, AUC 0.879 on holdout |+| Conviction engine | `api/_lib/oracle/` + `conviction-model.json` | Live, fitted model with three heads; holdout AUC 0.840 win, 0.918 rug, 0.893 moon || Public API | `api/oracle/*.js` (26 endpoints) | Live: `feed`, `coin`, `signal`, `stats`, `backtest`, `calibration`, `leaderboard`, `wins`, `movers`, `categories`, `search`, `history`, `market`, `social`, `trades`, `wallet`, `watch`, `agent-stats`, `action-stream`, `activity`, `follow`, `batch`, `stream`, and more || Pages | `/oracle`, `/oracle/docs`, `/oracle/arm` (in `data/pages.json`) | Live || Reference doc | `docs/oracle.md` | Complete, long-form |@@ -47,16 +47,16 @@ listed under their own registry entries.| Surface | Location | Registry state ||---|---|---|-| Sniper engine (library + CLI + MCP + x402 API) | `packages/agent-sniper`, `workers/agent-sniper` | `io.github.nirholas/agent-sniper` @ 0.1.6 in the registry; the tree and npm are both at 0.1.7, so a registry bump is still pending |-| Autopilot control plane | `packages/autopilot-mcp` | `io.github.nirholas/autopilot-mcp` @ 0.2.0 published |-| Copy-trade follows | `packages/copy-mcp` | published @ 0.1.1 |-| Signal marketplace | `packages/signals-mcp` | published @ 0.1.1 |-| Portfolio + PnL | `packages/portfolio-mcp` | published @ 0.1.1 |+| Sniper engine (library + CLI + MCP + x402 API) | `packages/agent-sniper`, `workers/agent-sniper` | `io.github.nirholas/agent-sniper` @ 0.1.7 in the registry, matching the tree |+| Autopilot control plane | `packages/autopilot-mcp` | `io.github.nirholas/autopilot-mcp` @ 0.2.1 in the registry; the tree is at 0.2.2 |+| Copy-trade follows | `packages/copy-mcp` | registry @ 0.1.2; the tree is at 0.1.4 |+| Signal marketplace | `packages/signals-mcp` | registry @ 0.1.2; the tree is at 0.1.3 |+| Portfolio + PnL | `packages/portfolio-mcp` | registry @ 0.1.1; the tree is at 0.1.2 || Market intel | `packages/intel-mcp`, `packages/kol-mcp` | published || Oracle-armed agent loop | `api/oracle/watch.js`, `api/oracle/action-stream.js`, `api/oracle/agent-stats.js` | **No dedicated server. Only the two tools inside `/api/mcp`.** |-72 distinct servers are already published under the `io.github.nirholas` namespace (counted against-the live registry on 2026-09-17), so the publishing path is proven and boring. `scripts/publish-mcp-servers.mjs` (`npm run publish:mcp`)+77 distinct servers are already published under the `io.github.nirholas` namespace (counted against+the live registry on 2026-10-09), so the publishing path is proven and boring. `scripts/publish-mcp-servers.mjs` (`npm run publish:mcp`)handles npm plus registry, idempotently, and skips anything already at the target version.### The publishing machinery (already built, do not rebuild)@@ -66,7 +66,9 @@ handles npm plus registry, idempotently, and skips anything already at the targe`GITHUB_TOKEN`.- `npm run audit:mcp` / `audit:mcp-golden` / `audit:mcp-safety` / `audit:mcp-catalog`: manifest,golden-transcript, safety-annotation, and catalog checks. All four are in `npm run gate`.-- `npm run smoke:mcp`: hits the hosted remotes for real.+- `npm run smoke:mcp`: hits the hosted remotes for real. `npm run probe:mcp-clients`+ (`scripts/mcp-client-probe.mjs`) drives every hosted server the way a cloud connector does,+ OAuth discovery included.- `public/.well-known/mcp.json`: the hand-maintained hosted-server directory (7 entries today).- `public/mcp-catalog.json` + `/mcp-tools` page: the human-facing catalog, built by`scripts/build-mcp-catalog.mjs`.@@ -89,10 +91,14 @@ Copy the structure of `api/mcp-3d.js` exactly: Streamable HTTP, shared OAuth/x40`api/_mcp/auth.js` and `api/_mcp/payments.js`, per-IP rate limits, SSE on GET, terminate on DELETE.Registry name `io.github.nirholas/threews-oracle`, URL `https://three.ws/api/mcp-oracle`.-Route it in `vercel.json` (both the handler entry and the-`/api/mcp-oracle/.well-known/oauth-protected-resource` route, matching the existing-`/api/mcp/.well-known/oauth-protected-resource` → `/api/wk?name=oauth-protected-resource` entry),-and add the entry to `public/.well-known/mcp.json`.+Route the handler in `vercel.json` and add the entry to `public/.well-known/mcp.json`. Since+2026-10-08 every hosted MCP server is its own OAuth resource (RFC 8707): add `/api/mcp-oracle` to+`OAUTH_MCP_PATHS` in `api/_lib/mcp-resources.js`, and pass `resourcePath` through the `api/_mcp/auth.js`+helpers as `api/mcp-3d.js` does. That alone makes its 401 point at+`/.well-known/oauth-protected-resource/api/mcp-oracle` (already routed generically to `api/wk.js`, so+no new `vercel.json` metadata route) with `resource` set to the server's own URL, which is what stock+MCP SDK connectors check before they will sign in. `tests/mcp-resources.test.js` fails when that list+and `public/.well-known/mcp.json` drift.**1b. stdio package: `packages/oracle-mcp`**@@ -193,7 +199,8 @@ npm run smoke:mcp # hit the hosted remotes for realAlso in this phase, because they are one-line fixes that are currently drifted:-- Bump `packages/agent-sniper` in the registry to 0.1.7 (the registry has 0.1.6, the tree and npm have 0.1.7).+- Publish the version bumps the registry is missing: `autopilot-mcp` 0.2.2, `copy-mcp` 0.1.4,+ `signals-mcp` 0.1.3, `portfolio-mcp` 0.1.2 (the registry has 0.2.1, 0.1.2, 0.1.2, 0.1.1).- Add both new remotes to `public/.well-known/mcp.json` (7 entries today, 8 after Phase 1).- Add both new server keys to the `SERVERS` array in `scripts/publish-mcp-servers.mjs`. A serverthat is not in that array is invisible to the publisher, which is the single easiest way for@@ -226,7 +233,7 @@ Per the documentation rules in `CLAUDE.md`, all of these apply and none are opti### Phase 5: the X post-Draft lives at [`docs/oracle-trading-mcp-x-post.md`](x-posts/oracle-trading-mcp-x-post.md). Written before+Draft lives at [`docs/x-posts/oracle-trading-mcp-x-post.md`](x-posts/oracle-trading-mcp-x-post.md). Written beforethe work ships so the announcement shapes the scope rather than the reverse: if a claim in thatpost is not true when the phases are done, the phases are not done.diff --git a/docs/oracle.md b/docs/oracle.mdindex 340506ea4..9658f0d26 100644--- a/docs/oracle.md+++ b/docs/oracle.md@@ -228,7 +228,7 @@ This is where the engine earns its keep. One score, many consumers.**The Telegram channel feed.** The whole Oracle also runs as a public Telegram channel, so you can hold the feed in your pocket without keeping a tab open. Three kinds of posts flow into it. Live signals: the scoring cron sweeps every two minutes and posts each coin the first time it crosses the feed floor, either by tier (`ORACLE_ALERT_MIN_TIER`, prime and strong by default) or by raw score (`ORACLE_FEED_MIN_SCORE`, default 56, the Lean boundary tracking the top slice of the live distribution). Agent activity: live entries and profitable exits post as they happen, with the agent's track-record link. A daily digest at 08:00 UTC anchors the channel with the day's scored count, top conviction, and platform-wide agent results. Every post carries the coin's mint, score, tier, and pillar breakdown, plus links back to the pump.fun page and the Oracle coin page. The channel is set by `TELEGRAM_ORACLE_CHAT_ID`; when it is a public @handle, `/api/oracle/stats` exposes the join URL and the /oracle hero renders a "Join the live Telegram feed" button. Each coin posts exactly once, deduplicated in-process and durably via `oracle_conviction.alerted_at`.-**The coin pages.** Every Oracle coin page (`/oracle/coin/<mint>`) renders in the markets-hub design, the same editorial system as `/coin/bitcoin`: breadcrumbs, a coin header with the live price and 24h/7d change chips, a conviction card with the score dial and four pillar bars, and stacked full-width sections. It fuses conviction with a live market intel aggregator that fans out to six real sources in parallel: DexScreener, the pump.fun API, GeckoTerminal, GoPlus, Birdeye, and CoinGecko. Price, liquidity, FDV, bonding curve progress, holder count, top ten concentration, mint and freeze authority, all in one view, every number traced to a live upstream. Each source is isolated, so one being down degrades that slice to null instead of failing the page. A Launch Intelligence section brings the Coin Radar engine's first-90-seconds read onto the same page: quality score, organic versus bundle, risk flags, the full signal breakdown, smart-money buyers, and the top-trader ledger. It also shows the who-is-in breakdown: every early wallet labeled by archetype and track record. That trader-classification surface is what the product is built around. The price chart keeps the TradingView-grade DexScreener candles embed alongside a native line view and an agent-trades view that plots every three.ws agent buy and sell on the series.+**The coin pages.** Every Oracle coin page (`/oracle/coin/<mint>`) renders in the markets-hub design, the same editorial system as `/coin/bitcoin`: breadcrumbs, a coin header with the live price and 24h/7d change chips, a conviction card with the score dial and four pillar bars, and stacked full-width sections. It fuses conviction with a live market intel aggregator that fans out to six real sources in parallel: DexScreener, the pump.fun API, GeckoTerminal, GoPlus, Birdeye, and CoinGecko. Price, liquidity, FDV, bonding curve progress, holder count, top ten concentration, mint and freeze authority, all in one view, every number traced to a live upstream. Each source is isolated, so one being down degrades that slice to null instead of failing the page. A Launch Intelligence section brings the Coin Radar engine's first-90-seconds read onto the same page: quality score, organic versus bundle, risk flags, the full signal breakdown, smart-money buyers, and the top-trader ledger. It also shows the who-is-in breakdown: every early wallet labeled by archetype and track record. That trader-classification surface is what the product is built around. The price chart is the platform's shared chart switcher (`src/shared/chart-switcher.js`): the page's own native line view and agent-trades view (every three.ws agent buy and sell plotted on the series) come first, and every chart terminal in the shared provider list (`src/shared/chart-embeds.js`, DexScreener candles among them) is one tab away. A coin agents have traded opens on the agent-trades view, a coin still on its bonding curve opens on the native line, and anything else opens on DexScreener candles unless the viewer last chose another view; if the switcher cannot load, the native chart still renders from our own API.**What the verdict card says out loud.** A big dial reading 100 next to a chart that already collapsed is not a wrong score, it is an unlabelled one, so the conviction card carries two lines the dial cannot say by itself. Directly under the score, the odds line quotes the measured rate behind the score instead of the score itself, from `hitRateFor()`: "48% of calls in the 0.45-1 band have won (n=267), 15.0x the 3% a random launch wins" (the band is the probability band the score claims, and the rate is what the active model's holdout observed there), followed by when the call was made relative to the coin first surfacing ("Scored 54s after this coin surfaced") and the one sentence that resolves the whole confusion, that the score ranks the odds of a 3x run or graduation and not the odds of a safe hold. Below it, once the market has resolved the coin, a **Since the call** strip states the ground truth in the order a holder reads it: peak multiple, whether it graduated or rugged, and what it is worth now ("peak 6.7x · rugged · now $2.2K"). Both lines are rendered server-side in `api/oracle-share.js` (a GET-only surface; when pump.fun does not answer, the coin's identity, symbol, name, image, market cap and graduation state, comes from DexScreener's pair listing so the card still names the coin) and refilled by `public/oracle-coin.js`, so a link pasted into a chat shows them in the preview rather than a bare triumphant number; the share description carries the same clause ("since: ran 6.7x, then rugged"). The drawer's one-line take leads with the result for the same reason: "It ran to 6.7x and then rugged." before it repeats what Oracle called. On the feed at `/oracle`, each card carries the compact version of that strip as an outcome chip next to its odds chip, so a resolved coin never sits in the board looking like a live call.@@ -316,7 +316,7 @@ GET https://three.ws/api/oracle/trades?mint=<mint>- Realized calibration per conviction band at `/api/oracle/calibration`: the fleet's actual win rate from real fills, next to what the band predicted, plus the bounded correction factor the scorer applies.- A dynamic 1200x630 OpenGraph conviction card (SVG) for sharing a coin at `/api/oracle/og`. Its live market cap reads pump.fun first (with one retry, honouring `Retry-After`) and falls through to the shared multi-source market reader (Birdeye, DexScreener, GeckoTerminal) when pump.fun does not answer.-The write endpoints. Two are auth-scoped to the agent's owner: `GET·POST /api/oracle/watch` reads or arms an agent's watch config with server-side validation clamping every limit, and `POST /api/oracle/test-alert` sends a test alert. The clamps only ever move a number toward safety: a size above the ceiling is lowered, but arming `mode: "live"` with a `per_trade_sol` under the 0.001 SOL floor, or a `max_daily_sol` smaller than one trade, is a 400 rather than a silent round-up into real spending. Simulate runs keep the forgiving clamps. Two are public and IP rate-limited instead: `POST·DELETE /api/oracle/follow` subscribes a Telegram chat to an agent's signals (the chat id the caller supplies is the identity, so there is no session to scope to), and `POST /api/oracle/social` ingests tweets to additively boost virality (never downgrades an LLM read).+The write endpoints. Two are auth-scoped to the agent's owner: `GET·POST /api/oracle/watch` reads or arms an agent's watch config with server-side validation clamping every limit, and `POST /api/oracle/test-alert` sends a test alert. The clamps only ever move a number toward safety: a size above the ceiling is lowered, but arming `mode: "live"` with a `per_trade_sol` under the 0.001 SOL floor, or a `max_daily_sol` smaller than one trade, is a 400 rather than a silent round-up into real spending. Moving a mainnet watch into live-armed also requires the account's signed real-funds agreements (Terms of Service, Risk Disclosure, Agent Wallet Agreement); without them the arm is refused with a 403 that links to `/legal/agreements` (see [Risk acknowledgment](risk-acknowledgment.md)). Re-saving an already live-armed watch, simulate mode, devnet, and disarming are not gated. Simulate runs keep the forgiving clamps. Two are public and IP rate-limited instead: `POST·DELETE /api/oracle/follow` subscribes a Telegram chat to an agent's signals (the chat id the caller supplies is the identity, so there is no session to scope to), and `POST /api/oracle/social` ingests tweets to additively boost virality (never downgrades an LLM read).### Through MCP@@ -326,7 +326,7 @@ The read API is plain HTTP, so any MCP-capable assistant can call it with a gene**Read the market in sixty seconds.** Open three.ws/oracle. The board is live, newest first. Click any coin: the drawer shows the score, the four pillars, the plain-language reasons ordered by what mattered most, the conviction sparkline, who is in, and the full live market picture. Prime and strong are the only tiers that mean act.-**Arm your agent, risk free.** Create or pick an agent, open three.ws/oracle/arm, set minimum tier to strong, pick your categories, set a per-trade size and a daily budget, require smart money if you want the strictest gate, and leave mode on simulate. Add your Telegram chat and send the test alert. Watch your agent's simulated entries appear on three.ws/activity and its graded results accumulate. Flip to live only when the simulated ledger has earned it.+**Arm your agent, risk free.** Create or pick an agent, open three.ws/oracle/arm, set minimum tier to strong, pick your categories, set a per-trade size and a daily budget, require smart money if you want the strictest gate, and leave mode on simulate. Add your Telegram chat and send the test alert. Watch your agent's simulated entries appear on three.ws/activity and its graded results accumulate. Flip to live only when the simulated ledger has earned it; the first live arm asks you to sign the real-funds agreements.**Buy intel like an agent.** Walk into any coin town in /play, find the kiosk by the plaza, press E, and pay one cent USDC. Or skip the world and do it from code: point `@three-ws/x402-mcp` at the crypto intel endpoint and ask your assistant for the pump.fun trending board. Either way you just did what the sniper does on every pass: paid the machine economy for a real market read.diff --git a/docs/seeker-publishing.md b/docs/seeker-publishing.mdindex e4fbde5be..e74975e20 100644--- a/docs/seeker-publishing.md+++ b/docs/seeker-publishing.md@@ -25,7 +25,7 @@ Everything scriptable is in [solana-mobile/scripts/](../solana-mobile/scripts/).4. **Add a dApp**, filling every field from the repo rather than from memory, so the portal and git never drift:- identity and URLs: [solana-mobile/publish/config.yaml](../solana-mobile/publish/config.yaml)- listing text: [solana-mobile/publish/listing/](../solana-mobile/publish/listing/) (long description, short description, what's-new, Seeker features)- - media: [solana-mobile/publish/media/](../solana-mobile/publish/media/) (icon, banner, and feature graphic are committed; screenshots are not, see below)+ - media: [solana-mobile/publish/media/](../solana-mobile/publish/media/) (icon, banner, feature graphic, Editor's Choice card, and the five carousel screenshots are all committed, see [Listing media](#listing-media))Completing this mints the **App NFT**. The portal matches later uploads to this app by Android package name, `ws.three.app`.5. Settings → API keys → create one. Store it in the owner's password manager; it never goes in the repo.@@ -68,7 +68,7 @@ DAPP_STORE_API_KEY='<portal API key>' \[scripts/publish.sh](../solana-mobile/scripts/publish.sh) checks that assetlinks is reachable, refuses a `versionCode` it already shipped from this machine, passes the API key over stdin so it never appears in a process listing, uploads the APK, mints the release NFT, and submits for review. If the upload dies part way through, resume it with `npx --no-install dapp-store resume --release-id <id>` rather than starting over.-For a later release, bump `appVersionCode` and `appVersion` in [solana-mobile/twa/twa-manifest.json](../solana-mobile/twa/twa-manifest.json) (or pass `VERSION_CODE` / `VERSION_NAME`), then repeat steps 3 and 5. The store rejects a reused `versionCode`.+For a later release, bump `appVersionCode` and `appVersion` in [solana-mobile/twa/twa-manifest.json](../solana-mobile/twa/twa-manifest.json) (or pass `VERSION_CODE` / `VERSION_NAME`), then repeat steps 3 and 5. The store rejects a reused `versionCode`. The manifest already reads `1.1.0` / versionCode 2 for the next release, which adds the Agent glance home screen widget ([native widgets](./native-widgets.md)); its status is tracked at the top of [solana-mobile/README.md](../solana-mobile/README.md).Releases are run locally by the owner. This repo does not use GitHub Actions.diff --git a/docs/selfie-to-avatar.md b/docs/selfie-to-avatar.mdindex 9f008e2ea..828fe5cdf 100644--- a/docs/selfie-to-avatar.md+++ b/docs/selfie-to-avatar.md@@ -17,7 +17,7 @@ The client half lives in three modules the page imports on demand: [`src/selfie-Two of those numbers are measured rather than reasoned about. The blur floor (`BLUR_STDDEV_MIN`) is calibrated against six real portrait photographs framed as 720x1280 phone selfies and scored through the module's own math, sharp versus the reconstruction worker's exact `robustness.py` degradations: sharp faces read 22.8 to 39.4, a Gaussian blur of radius `longestEdge/220` reads 10.6 to 15.7, and a radius-10 smear reads 6.3 to 9.4. The floor sits at 12, in the empty band between the blurred and sharp populations. And because a blown-out face *raises* Laplacian response instead of lowering it, and averages back into the accepted band, neither the blur nor the mean-luma gate can see window glare on its own: `grayFaceStats` also reports `clippedFrac`, the share of the face crop pinned to near-white, gated separately by `CLIPPED_FRAC_MAX`.-1. **Capture, in the browser.** `getUserMedia({ video: { facingMode: 'user', width: { ideal: 1280 }, height: { ideal: 1706 } } })` opens the front camera. A real-time wireframe overlay tracks head pose, yaw, centering, blur, luminance, and highlight clipping, and only unlocks the shutter when a face is found; the hint line names the single most actionable fix ("Face the camera straight on.", "Hold steady. The image is blurry.", "Too dark. Find better light.", "Too bright. Move out of direct light or turn away from the window.") until every gate passes. A 3-2-1 countdown fires, then `shoot()` draws the current video frame to a canvas and calls `canvas.toBlob(blob, 'image/jpeg', 0.92)`. This is a **single still**, not a video scan. Camera support is feature-detected; if none exists, the shutter is disabled and an "Upload instead" path takes any image file. A photo shared into three.ws from the Android share sheet (the Seeker app or any installed PWA) is POSTed to `/create/share`, parked by `public/share-target-sw.js`, and lands here with `?shared=1`; the capture page reads those files once (`src/shared/share-target.js`), fills the frontal slot and then left and right, and strips the param so a reload does not look like a fresh share.+1. **Capture, in the browser.** `getUserMedia({ video: { facingMode: 'user', width: { ideal: 1280 }, height: { ideal: 1706 } } })` opens the front camera. A real-time wireframe overlay tracks head pose, yaw, centering, blur, luminance, and highlight clipping, and only unlocks the shutter when a face is found; the hint line names the single most actionable fix ("Face the camera straight on.", "Hold steady. The image is blurry.", "Too dark. Find better light.", "Too bright. Move out of direct light or turn away from the window.") until every gate passes. A 3-2-1 countdown fires, then `shoot()` draws the current video frame to a canvas and calls `canvas.toBlob(blob, 'image/jpeg', 0.92)`. This is a **single still**, not a video scan. Camera support is feature-detected; if none exists, the shutter is disabled and an "Upload instead" path takes any image file. A photo shared into three.ws from the Android share sheet (the Seeker app or any installed PWA) is POSTed to `/create/share`, parked by `public/share-target-sw.js`, and lands here with `?shared=1`. The iOS app has no service worker, so its share extension parks the photos in the app instead and opens the page with `?shared=1&inbox=<id>`, and the `ThreeWsApp` native plugin hands them over once. Either way the capture page reads those files once (`src/shared/share-target.js`), fills the frontal slot and then left and right, and strips both params so a reload does not look like a fresh share.2. **Review the still.** The countdown leaves ~3 seconds for motion blur, a head turn, or a lighting change to land in the actual capture, so the frozen still is re-scored (`checkImageQuality`) against the same gates before you accept it. The review screen shows per-gate chips plus a verdict line; only a missing face disables "Use this" (mirroring the worker's one hard input rejection), everything else is a warning you can accept.3. **Optional side angles.** Under an "Add side angles" disclosure you can capture two extra stills (`left`, `right`, turned ~45 degrees). They raise fidelity and the ETA, but only the frontal is required. Confirmed shots (and the style choice) are mirrored to `sessionStorage`, so a refresh or accidental back-swipe mid-capture restores every slot instead of starting over; the build phase has its own resume rail (`selfie:pendingJobId`).4. **Refine, in the browser.** `assessPhoto` gates the frontal (no face is the only hard block; blur, illustration, or a distant subject are non-fatal warnings). `refineSelfie` isolates the subject from its background and reframes to a clean head-and-shoulders square, rendered at 1024x1024 with JPEG quality 0.92 ([`src/selfie-refine.js`](../src/selfie-refine.js)). The refined frontal is previewed so you see exactly what the engine sees.@@ -30,7 +30,13 @@ Two of those numbers are measured rather than reasoned about. The blur floor (`B### The text-to-avatar variant-The same `/api/avatars/reconstruct` endpoint accepts a `prompt` instead of `photos`. It runs a Flux text-to-image step (with a suffix that forces a head-and-shoulders portrait), then feeds that image into the identical reconstruct and auto-rig pipeline. One endpoint, two front doors.+The same `/api/avatars/reconstruct` endpoint accepts a `prompt` instead of `photos`, but a prompt never touches the face pipeline: face-texture transfer keeps only the face and pastes it onto the template body, so a described character came back in the template's own clothes. Instead ([`api/_lib/prompt-avatar.js`](../api/_lib/prompt-avatar.js)):++1. The prompt is painted as one square (1:1) full-body reference image on the forge reference-image lane (`generateReferenceImage`: Vertex first, then the shared text-to-image ladder), with framing cues appended (single figure, neutral A-pose, head to feet in frame, plain background) that say nothing about style.+2. That image is reconstructed on a full-figure image-to-3D engine, in plan order: the self-hosted Hunyuan3D worker (high tier), self-hosted TRELLIS, the Replicate and HuggingFace lanes, then the caller's own Meshy or Tripo key. A self-hosted lane whose health probe reads hard down is moved to the back of the plan rather than accepting a job it would fail.+3. The unchanged finalize tail auto-rigs the bare mesh and materializes the avatar and its agent, exactly as for a selfie. The job records `source: 'prompt'`, the reference image, and the engine that ran.++One endpoint, two front doors.## Walkthroughdiff --git a/docs/shipfeed.md b/docs/shipfeed.mdindex 85ba44cfb..c9f28c49d 100644--- a/docs/shipfeed.md+++ b/docs/shipfeed.md@@ -156,6 +156,8 @@ three.ws/changelog/2026-08-27-text-to-3d-... · 2026-08-27 · #fix #infraThe footer is best-effort by design: if GitHub cannot be read at that moment, the announcement goes out without it rather than not going out. Entries are keyed by date and title, and repeats of one key within a batch are collapsed before sending, so a duplicated line in `data/changelog.json` never reaches the channel twice.+The same cron also replies to the @trythreews X thread with every entry that passes `data/changelog-x-filter.json` (no wallet, payment, key, outage or security internals, and nothing that is only a fix). That lane is isolated from Telegram, so one failing never blocks the other, and its tweets carry no provenance footer: just the title, summary and changelog link inside the 280-character budget.+**The raw commit feed** (`/api/cron/commit-feed-push`, every 5 minutes) reads its headline from the same parser, so a scoped commit now says "Feature · resilience" rather than "feat(resilience)", and it skips commits the classifier calls noise: merges, `chore(deps):` bumps, and lockfile-only changes. A skipped commit still advances the lane's state, so nothing is ever re-read, and the tick reports `{ posted, skipped }` so the drop is visible in the logs rather than silent.---diff --git a/docs/site-performance.md b/docs/site-performance.mdindex 05d1e598c..26af26647 100644--- a/docs/site-performance.md+++ b/docs/site-performance.md@@ -1,4 +1,4 @@-# What the site's load numbers are, and the four rules that keep them there+# What the site's load numbers are, and the rules that keep them there`/play` has [its own boot-cost document](./play-boot-performance.md) because a coin world is a special case: a WebGL renderer, a physics solver and a multiplayer room all have to start before anything is playable. This document covers everything else. Every ordinary page on three.ws is a static HTML document plus a module graph, and the cost of opening one is almost entirely decided by four questions:@@ -127,7 +127,7 @@ Our lib output is not an npm dependency. It is the file a browser downloads fromA `renderChunk` pass that runs esbuild with `minifyWhitespace: true` (and identifiers and syntax left alone, since Vite's own pass already handled those) took the shipped bundle from **4,244,387 bytes to 3,433,103** raw, and from **1,031,741 to 853,007** gzipped at `gzip -9`. That is 811,284 fewer bytes, 19.1%. On the homepage, `agent-3d.js` was 2,293ms of script evaluation and two long tasks of 1,299ms and 526ms.-Measure the right file. `dist-lib/` also holds `agent-3d.umd.cjs`, which is naturally smaller (2,761,457 bytes) because it is a different format, and quoting it makes the win look better than it is. [scripts/publish-lib.mjs](../scripts/publish-lib.mjs) mirrors the **ES** build, `dist-lib/agent-3d.js`, to `/agent-3d/<version>/`, so that is the file a browser downloads.+Measure the right file. `dist-lib/` also holds `agent-3d.umd.cjs`, which is naturally smaller (2,761,457 bytes) because it is a different format, and quoting it makes the win look better than it is. [scripts/publish-lib.mjs](../scripts/publish-lib.mjs) mirrors the **ES** build, `dist-lib/agent-3d.js`, to the moving channels (`/agent-3d/latest/`, `/agent-3d/<major>/`, `/agent-3d/<major>.<minor>/`), so that is the file a browser downloads. A pinned `/agent-3d/<version>/` directory is never rebuilt: its bytes come from the write-once release archive recorded in `data/agent-3d-releases.json`, so a minifier change reaches pinned embedders only when a new version is cut with `npm run release:lib`.**Do not "simplify" this away by trusting `build.minify`.** Check the byte count of `dist-lib/agent-3d.js` after any change to the lib config; a jump back over 4 MB means the plugin stopped running.@@ -219,6 +219,8 @@ function setChipPrompt(chip, text) {**Any node whose text becomes dynamic loses its `data-i18n` at the point it becomes dynamic.** Not later, not in a cleanup pass. `src/i18n.js` uses the same guard for `data-auth-name` in the nav.+Since 2026-09-30 `applyCatalog` also backs this up on its own: `primeOwnership()` records what each annotated element held when the runtime first saw it, and a pass skips any element whose content now matches neither that, nor the runtime's own last write, nor the English source string, because the page wrote it. That catches writers that never opted out, but it is a safety net, not the contract. Removing the attribute at the write is still the rule, because it is explicit and does not depend on the boot order of the page's scripts.+### That fixed the revert. It did not fix the growth.The 2026-08-15 sweep ran against a build that already contained the fix above, and `/forge` still measured **CLS 0.256 desktop, 0.263 mobile, with `<div class="chips" id="examples">` still named as the largest single shift at 0.190**. Removing the revert removed one direction of a shift that had two.diff --git a/docs/skill-bundles.md b/docs/skill-bundles.mdindex 639740a3c..f7a1080ca 100644--- a/docs/skill-bundles.md+++ b/docs/skill-bundles.md@@ -57,9 +57,12 @@ All four live under the agent. `:id` is the agent's UUID.| `PATCH` | `/api/agents/:id/bundles/:bundleId` | owner | Rename, reprice, or change its skills || `DELETE` | `/api/agents/:id/bundles/:bundleId` | owner | Deactivate it (nothing is deleted) |-Owner calls need a session cookie (plus the `x-csrf-token` header that-[`src/api.js`](../src/api.js) attaches automatically in the browser) or a bearer-token. The two `GET`s are public on purpose: they read only aggregate counts and+Owner calls need a signed-in session cookie plus the `x-csrf-token` header that+[`src/api.js`](../src/api.js) attaches automatically in the browser (outside the+browser, mint one from `GET /api/csrf-token` with the same cookie). Bearer tokens+and API keys are not accepted on these owner calls: without a session they answer+`401 unauthorized`, and a session that does not own the agent gets+`403 forbidden`. The two `GET`s are public on purpose: they read only aggregate counts andthe agent's own list prices, both of which the marketplace already publishes perskill. No buyer identity and no row-level history ever leaves the handler.@@ -116,8 +119,8 @@ produces a number that means nothing.### Publish```bash-curl -s -X POST "https://three.ws/api/agents/$AGENT_ID/bundles" \- -H "authorization: Bearer $THREE_WS_TOKEN" \+curl -s -X POST "https://three.ws/api/agents/$AGENT_ID/bundles" --cookie "$JAR" \+ -H "x-csrf-token: $CSRF" \-H "content-type: application/json" \-d '{"name": "Research starter pack",@@ -164,7 +167,9 @@ trusted), EVM by the submitted tx hash. On a confirmed verdict the handler writeone `skill_purchases` row per skill with `kind = 'bundle'` and `amount = 0`, whichis what [`hasSkillAccess()`](../api/_lib/skill-access.js) reads, and records asingle bundle-level revenue event so one bundle sale is never counted as N skill-sales in GMV.+sales in GMV. That event is marked `settled_to_wallet`: the buyer paid the+creator's payout wallet directly, so the sale counts as income already held and+never as a balance withdrawable from the platform treasury.**Reach today:** the builder, the two public `GET`s, and this checkout are live.The buyer-facing *browser* surface is not: no marketplace or agent-profile viewdiff --git a/docs/solana-pumpfun.md b/docs/solana-pumpfun.mdindex 27c6c160e..84bc51634 100644--- a/docs/solana-pumpfun.md+++ b/docs/solana-pumpfun.md@@ -51,7 +51,7 @@ This document covers what was added, how it composes with what was already there|---|---|---|| MCP client | [api/_lib/pumpfun-mcp.js](../api/_lib/pumpfun-mcp.js) | Cached JSON-RPC client to upstream bot || Read API | [api/agents/pumpfun.js](../api/agents/pumpfun.js) | `?op=claims|graduations|token|creator` |-| SSE feed | [api/agents/pumpfun.js](../api/agents/pumpfun.js) (`?_handler=feed`) | Live event stream, 90s window, auto-reconnects |+| SSE feed | [api/agents/pumpfun.js](../api/agents/pumpfun.js) (`/api/agents/pumpfun-feed`, rewritten to `?_handler=feed`) | Live event stream, 90s window, auto-reconnects. An anonymous `GET` answers any origin, so an `<agent-3d tracked-mint>` embed on another site can open it || Cron crawler | [api/cron/\[name\].js](../api/cron/%5Bname%5D.js) (`name=pumpfun-signals`) | 15-min sweep → `pumpfun_signals` || Schema | [api/_lib/schema.sql](../api/_lib/schema.sql) | New `pumpfun_signals` table || Skills | [src/agent-skills-pumpfun-watch.js](../src/agent-skills-pumpfun-watch.js) | 4 skills: recent-claims, token-intel, watch-start, watch-stop |@@ -147,7 +147,7 @@ These are **off-chain** signals — flagged as such, not on-chain attestations.## Widget-The `pumpfun-feed` widget renders a stack of cards (claim or graduation) as an absolutely-positioned overlay on top of the 3D viewer. With `autoNarrate: true`, the avatar narrates each event through the protocol bus. Each card's trading-terminal links come from the shared builder in [src/shared/trading-terminals.js](../src/shared/trading-terminals.js) (`terminalLinks(mint)` and `referralOffers()`), the same one the copy pages use, so adding or re-pointing a terminal is one change. The overlay carries no inline event handlers (a broken token image hides through the `data-fallback="hide"` hook), which is what keeps it inside the site's CSP.+The `pumpfun-feed` widget renders a stack of cards (claim or graduation) as an absolutely-positioned overlay on top of the 3D viewer. With `autoNarrate: true`, the avatar narrates each event through the protocol bus. Each card's trading-terminal links come from the shared builder in [src/shared/trading-terminals.js](../src/shared/trading-terminals.js) (`terminalLinks(mint, { from })` and `referralOffers()`), the same one the copy pages use, so adding or re-pointing a terminal is one change. DEXTools leads the list and its link goes through the counted `/api/coin/dextools` redirect, attributed to the `pumpfun-feed` surface. The overlay carries no inline event handlers (a broken token image hides through the `data-fallback="hide"` hook), which is what keeps it inside the site's CSP.Studio config schema (validated in `widget-types.js`):diff --git a/docs/solana.md b/docs/solana.mdindex 4d0a5dc4e..235ab293e 100644--- a/docs/solana.md+++ b/docs/solana.md@@ -84,9 +84,10 @@ Failing over is only half the contract. The other half is *how long* a lane stay| Dead or misrouted URL (404, 410) | 30 min | Persistent misconfiguration, not a blip. || One refused *call shape* (403 + `Request blocked`) | none for the lane | The lane is healthy; only this request is unwelcome, so the *method* is demoted on that endpoint (`markMethodDemotion`) and every other call shape keeps flowing. A caller that reaches `markEndpointCooldown` directly still gets the cheapest window, 30 s. || Provider 5xx | 2 min | Server-side wobble. |+| TLS handshake refused by the lane (`ERR_SSL_*`, `ERR_TLS_*`, certificate errors) | 30 min | The provider's own TLS terminator rejected us, and every retry gets the same answer until the endpoint is fixed (a disabled or suspended QuickNode endpoint answers every handshake with `tlsv1 alert internal error`). The verdict is shared with the fleet, and it does not arm the whole-chain re-sweep that other transport failures trigger. || Fetch threw (DNS, connection) | 30 s | Network blip. |-The second-to-last row is the subtle one, and it cost us a primary. Each provider draws its own line between "you may not do this" and "your key is bad", and they answer both with the same status code. PublicNode returns **HTTP 403** for `getTokenAccountsByOwner` filtered by `programId` while serving every other method perfectly:+The refused-call-shape row is the subtle one, and it cost us a primary. Each provider draws its own line between "you may not do this" and "your key is bad", and they answer both with the same status code. PublicNode returns **HTTP 403** for `getTokenAccountsByOwner` filtered by `programId` while serving every other method perfectly:```jsonc// HTTP 403, but the key is fine and getBalance still works@@ -308,7 +309,7 @@ There is no global Solana registry to query — discovery happens via the platfo## What's on Solana instead of a registry contract- **Reputation**: there is no single `ReputationRegistry` contract like ERC-8004's. Instead, permissionless SPL Memo attestations (feedback, stakes, tasks, disputes) are written on-chain against the agent's asset pubkey, crawled into `solana_attestations`, and aggregated by `/api/agents/solana-reputation`. Off-chain pump.fun behavior signals land in `pumpfun_signals` and feed the same score. See [Solana reputation](solana-reputation.md) and [solana-pumpfun.md](solana-pumpfun.md).-- **Validation**: no registry contract either; validations are `threews.validation.v1` SPL Memo attestations (including the automatic glb-schema attestation at register-confirm), plus SAS credentialed validations signed by the platform authority ([SAS attestations](sas-attestations.md)).+- **Validation**: no registry contract either; validations are `threews.validation.v1` SPL Memo attestations (including the automatic glb-schema attestation at register-confirm), plus SAS credentialed validations signed by the platform authority ([SAS attestations](sas-attestations.md)). The Memo program accepts a memo from any wallet, so a glb-schema validation counts as the model-verified badge (in `/api/agents/solana-validation` and the agent card) only when the platform attester signed it; with no attester key configured there is no badge at all.## What's intentionally not on Solana yetdiff --git a/docs/spotlight.md b/docs/spotlight.mdindex a5e966631..909eae0e7 100644--- a/docs/spotlight.md+++ b/docs/spotlight.md@@ -36,9 +36,13 @@ Every entry has its own page at `/spotlight/<entry id>`. That is where thewrite-up is actually readable (the index can only show three clamped lines ofit), and it is the one place an entry is edited after it is created:-- the agent standing in 3D, live from its own GLB, with its still image held- underneath until the viewer has painted so a model that fails to load degrades- to the avatar rather than an empty stage,+- the agent standing in 3D, live from its own GLB. Its still image holds the+ stage until `<agent-3d>` fires `agent:ready` (the body is already standing in+ its idle by then), and the two swap in the same frame, so exactly one avatar+ is ever on screen. If the viewer fails to boot (`agent:error`) it is removed+ and the still stays, so a model that fails to load degrades to the avatar+ picture rather than an empty stage+ ([`revealWhenReady()` in `src/spotlight-shared.js`](../src/spotlight-shared.js)),- the full write-up as real paragraphs,- a facts panel read live off the agent on every request: skills, conversations,on-chain actions, network, upvotes, views,diff --git a/docs/tutorials/pay-for-x402-service.md b/docs/tutorials/pay-for-x402-service.mdindex 1a14328f9..8e598f870 100644--- a/docs/tutorials/pay-for-x402-service.md+++ b/docs/tutorials/pay-for-x402-service.md@@ -38,7 +38,7 @@ There are two distinct problems: **finding** an endpoint and **paying** it.- For **Solana**, the wallet can only sign serialized transactions, so the module posts the challenge's `accept` to `/api/x402-checkout?action=prepare` (`api/x402-checkout.js`), gets back a partially-signed SPL `transferChecked`, has Phantom add the buyer's signature, then `?action=encode`s it into the `X-PAYMENT` header.- For **Base / EVM**, the wallet signs an EIP-3009 `transferWithAuthorization` typed-data message locally — no server prep needed.-- For an **agent wallet** (signed-in three.ws users only), no browser wallet is involved at all. The modal lists your agents with their live USDC balances (from `/api/x402-pay?agents=1`), and picking one sends the payment through `POST /api/x402-pay`: the server decrypts the agent's custodial key (audit-logged), enforces the agent's per-call/daily spend policy *before* signing, builds and settles the SPL transfer, and streams progress back. Underfunded agents render disabled with their exact balance; the option pays Solana USDC only, and never appears on third-party merchant embeds (the session cookie doesn't travel cross-origin).+- For an **agent wallet** (signed-in three.ws users only), no browser wallet is involved at all. The modal lists your agents with their live USDC balances (from `/api/x402-pay?agents=1`), and picking one sends the payment through `POST /api/x402-pay`: the server decrypts the agent's custodial key (audit-logged), enforces the agent's per-call/daily spend policy *before* signing, builds and settles the SPL transfer, and streams progress back. Underfunded agents render disabled with their exact balance; the option pays Solana USDC only, and never appears on third-party merchant embeds (the session cookie doesn't travel cross-origin). Called with a bearer API key or OAuth token instead of a session, `POST /api/x402-pay` requires the `wallet:write` scope and answers `403 insufficient_scope` without it; a `wallet:read` credential can still list balances.Either way the signed payload is base64-encoded into `X-PAYMENT`, the gated request is retried once, and the unlocked result plus the decoded `X-PAYMENT-RESPONSE` receipt come back.@@ -103,12 +103,12 @@ You get back a `402 Payment Required` whose JSON body (and a base64 mirror in th```jsonc{"scheme": "exact",- "network": "solana", // or "eip155:8453" for Base+ "network": "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp", // Solana mainnet; "eip155:8453" for Base"amount": "1000", // 6-decimal atomic USDC → $0.001"asset": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", // USDC mint"payTo": "<recipient address>","maxTimeoutSeconds": 60,- "extra": { "name": "USD Coin", "decimals": 6, "feePayer": "<sponsor>" }+ "extra": { "name": "USDC", "decimals": 6, "feePayer": "<sponsor>" }}```@@ -120,7 +120,7 @@ Read it like a receipt-in-advance:- **`extra.feePayer`** is the sponsor that co-signs the Solana transaction so your SOL is untouched. It is optional: an accept with no `feePayer` is the **self-pay** contract, where you cover the network fee yourself. The modal says so on the approve step ("you cover the network fee on this one") rather than letting the wallet popup be the first you hear of it.- **`maxTimeoutSeconds`** bounds how long your signed authorization is valid — your one safety net against a stale payment lingering.-A single endpoint can list several `accepts` (e.g. Base *and* Solana). You — or your wallet — pick whichever network you hold funds on.+A single endpoint can list several `accepts` (e.g. Base *and* Solana). You, or your wallet, pick whichever network you hold funds on. A Base entry may also appear twice: the plain EIP-3009 one, and a sibling marked `extra.assetTransferMethod: "permit2"` for SDK clients that use the gas-sponsored Permit2 path. The browser modal always signs the EIP-3009 entry and skips the Permit2 sibling.---@@ -222,7 +222,9 @@ If the result looks wrong but you were charged, note: x402 has **single-shot, no- **"Payment module failed to load (x402.js)"** on a Bazaar card — the drop-in script 404'd or didn't evaluate, so `window.X402` is undefined. Reload the page; check the network tab for the `/x402.js` request.- **Wallet button is disabled** — that wallet isn't detected, or no `accept` matches its network. Install the extension (Phantom for Solana, MetaMask/Coinbase for Base) and reload, or pick the other rail.- **"Not enough USDC — you need X but your wallet holds Y"** — the balance pre-check caught a shortfall before you signed. Top up the wallet on the shown network (the error links your address on the explorer) and retry. The check is fail-open: if your balance can't be read, payment still proceeds.-- **"Payments are temporarily paused while we top up the wallet that settles them"**: a `503 settlement_unavailable`, the sponsor wallet is under its SOL reserve or the fee budget is spent. Nothing was charged and the error is marked retryable; try again shortly.+- **"Payments are temporarily paused while we top up the wallet that settles them"**: a `503 settlement_unavailable`, the sponsor wallet that pays network fees is under its SOL reserve. (The daily fee budget only paces the platform's own autonomous traffic; a paying customer's settle is admitted past it.) Nothing was charged and the error is marked retryable; try again shortly.+- **"... rewrote the payment transaction before signing ..."**: your Solana wallet changed the prepared transaction (a different transfer, a swapped fee payer, or an unknown program), so it can no longer settle and nothing was sent. Phantom's default transaction protection is not the cause: its Lighthouse guard instructions are accepted. Turn off transaction modification in the wallet, or pay with a different Solana wallet.+- **"Your wallet could not display this payment request"**: the wallet refused to open its approval window. Nothing was signed or charged; unlock or update the wallet and retry, or pay with the other token.- **"Endpoint did not return 402 (got 200/404…)"** — you pointed `pay()` at a free or non-x402 URL. Confirm the endpoint actually challenges with `curl -i <url>` (Step 3).- **402 but "no `accepts` array could be found"** — a proxy stripped the body *and* the `payment-required` header, or the seller's challenge is malformed. Try the endpoint's own canonical URL; if it's third-party, the seller's 402 is non-compliant.- **Signature rejected at settle on Base** — almost always a wrong EIP-712 domain. Base USDC's domain name is `"USD Coin"` at version `"2"`; a seller advertising anything else produces a payload the facilitator rejects. Nothing you can fix as a buyer — report it to the provider.diff --git a/docs/ux-flows/02-forge-text-to-3d.md b/docs/ux-flows/02-forge-text-to-3d.mdindex bd16e5e73..d357cf8dd 100644--- a/docs/ux-flows/02-forge-text-to-3d.md+++ b/docs/ux-flows/02-forge-text-to-3d.md@@ -6,7 +6,7 @@ Routing facts (from `vercel.json`):- `/forge` → `pages/forge.html` (loads `src/forge.js` + 25 sibling `forge-*` modules).- `/image-to-3d` → `pages/forge.html` (same app; lands with the photos tab preselected and its own document title; `?mode=image` on any forge URL does the same).- `/forge-max` → `pages/forge.html` (same app; lands with the High tier pinned and "Forge Max" header copy; `?tier=draft|standard|high` presets the selector on any forge URL).-- `/forge/share/<id>` → `api/forge-share.js` (SSR page that bakes OG/Twitter/Farcaster preview meta for crawlers, then JS-redirects browsers to `/forge?share=<id>`, which opens the creation in the viewer).+- `/forge/share/<id>` → `api/forge-share.js` (SSR page that bakes OG/Twitter/Farcaster preview meta plus a schema.org `3DModel` JSON-LD node for crawlers (built by `api/_lib/creation-jsonld.js`: the GLB, a poster rendered by `/api/render/glb`, the creator, the date), then JS-redirects browsers to `/forge?share=<id>`, which opens the creation in the viewer; a private or unknown id redirects to `/forge` instead).- `/features/forge` → `pages/features/forge.html` (static marketing landing, no app module).- `/create/prompt` → `pages/create-prompt.html` → `src/create-prompt.js` (text → **rigged avatar**, a different backend from Forge).- `/tutorials/text-to-3d` and `/tutorials/image-to-3d` → `pages/tutorial.html` (one shared template) which `fetch`es `/docs/tutorials/<slug>.md` and renders it with marked.js. Read-only content pages.@@ -41,9 +41,9 @@ Routing facts (from `vercel.json`):8. User clicks **Generate** (or ⌘/Ctrl+Enter). `collectComposerCfg()` validates (text ≥ 3 chars). If High is locked and submitted via keyboard, the gate/upsell opens instead of firing.9. `startJob()` `POST`s to `/api/forge` with `{ prompt, aspect_ratio, path, tier, backend }` plus headers (client id, BYOK key if any, $THREE tier pass if eligible/needed — minted/awaited before the request when `highTierNeedsPass()`). Stage switches to `#state-generating`.10. **Generating state**: a named stage timeline (`#gen-stages`, rendered by `forge-timeline.js`) animates; every row and state change is driven by a real `/api/forge` signal, so the lane decides which stages exist (a no-reference-image engine never shows one). Below it: an honest elapsed-vs-typical progress bar (asymptotic, never fakes 100%, recolors amber past the catalog ETA), a "feel free to leave this page" hint, and a **Cancel** button. When the API reports `cold_start` for a scale-to-zero self-hosted GPU lane, a "Waking up a GPU" warming card appears and is dismissed by the first real running poll, never by a timer (a keep-warm cron, `/api/cron/gpu-keepwarm`, holds allowlisted GPU workers open during peak hours; every routed scale-to-zero lane is registered there, including `hunyuan3d`, the High image tier's default engine and the fleet's longest spin-up at 75 s, though it stays off by default because the region's L4 grant is already spoken for). While waiting, `forge-wait.js` rotates curated craft tips. The reference image no longer waits for the job id: the page mints a trace id, sends it with the submit, and polls `GET /api/forge?progress=<traceId>` while its own POST is still open, so the director's rewrite, the reference view and the extra view count paint as the server passes each real milestone (`api/_lib/forge-progress.js` writes the crumbs). It is fail-open, with no timers and no guessed crumbs: without a trace id, or on a deployment that does not serve the channel, the submit response's own `preview_image_url` still paints the reference pane a moment later.- 11. If the engine is the synchronous free draft lane, the POST returns the finished `glb_url` directly; otherwise `forge.js` polls `GET /api/forge?job=<id>` every interval until `status:"done"` (with `glb_url`), `failed`, or timeout. The loop is built on `src/shared/resilient-poll.js`, so a backgrounded phone tab, a dropped radio, or the odd edge `502` is retried and woken on visibility rather than read as a dead job, with the give-up budget counted in attempts.+ 11. If the engine is the synchronous free draft lane, the POST returns the finished `glb_url` directly; otherwise `forge.js` polls `GET /api/forge?job=<id>` every interval until `status:"done"` (with `glb_url`), `failed`, or timeout. The loop is built on `src/shared/resilient-poll.js`, so a backgrounded phone tab, a dropped radio, or the odd edge `502` is retried and woken on visibility rather than read as a dead job, with the give-up budget counted in attempts. When an async lane fails after accepting the job, the server's poll-time failover (`api/_lib/forge-failover.js`) continues it on the next configured lane under the same id and the generating panel says so ("<engine> hit a snag. Continuing on <engine>, no action needed."); TripoSG is the last photo rung, after every textured lane, and the note adds that it returns the shape without textures.12. On done: `showResult()` sets the `<model-viewer src>`, plays the WebGL **materialize** reveal (`forge-reveal.js`, skipped under reduced-motion), shows the result bar, wires the **Download GLB** anchor, and (if `creation_id`) shows a "Saved ✓" auto-save chip. Under `prefers-reduced-motion` the result viewer drops `auto-rotate` (camera controls stay, so the model is still fully inspectable by drag, pinch and arrow key), and the "Nice model. What now?" handoff card retracts on its own instead of sitting over the result bar's own next-step buttons. The result action row carries seventeen tools and wraps, so every one of them stays clickable at 320px. Geometry-first/sketch results with no reference image get a captured **poster** frame (`POST /api/forge-poster`).- 13. (optional) User rates the model: **👍 Keep / 👎 Discard** (verdict) → `POST /api/forge-feedback`; or tags a category (Avatar/Creature/Item/Accessory/Scene/Vehicle) → `POST /api/forge-categorize`. (Data flywheel.)+ 13. (optional) User rates the model: **👍 Keep / 👎 Discard** (verdict) → `POST /api/forge-feedback`; or tags a category (Avatar/Creature/Item/Accessory/Scene/Vehicle) → `POST /api/forge-categorize`. A **Making this for:** chip row (Game / Web / Avatar / Simulation / Print / AR / Just playing, from `src/shared/forge-destinations.js`) asks once what the model is for: the answer is written onto the model on screen via `POST /api/forge-feedback` and remembered per browser, so every later generation sends it as `destination`. (Data flywheel.)14. (optional) **Refine → <next tier>**: re-runs the exact same prompt/views one quality tier higher (re-enters step 9). Shown only when a higher tier exists and the job is re-runnable. Every user-initiated generation is stamped with a random seed that rides on the stored job, and Refine, Retry, "Generate anyway" and an automatic lane hop all replay it, so Refine returns *this* model at higher quality instead of a different object; only a fresh submit (and "Make another") mints a new seed.15. (optional) **Refine** panel (`forge-refine.js`) — instant in-browser geometry passes (weld/smooth/relax/decimate/subdivide), non-destructive, no API call, no rate limit. Download the refined GLB.16. (optional) **Iterate** (`forge-conversational-refine.js`): a free-text instruction against the model on screen ("make the helmet red", "add a cape") via `POST /api/forge-iterate` (polled). The only post-result action that changes the model's shape from natural language; same core as the MCP `refine_model` tool.@@ -82,7 +82,7 @@ Routing facts (from `vercel.json`):- **Photoreal reference-image path (the realism lever):** the final mesh reads as real only if the reference image the reconstructor sees is a photoreal, single-subject, plain-seamless-background, evenly-lit photograph. Two pieces drive that:- `POST /api/forge-enhance` (director): rewrites the raw prompt into one centered real-world subject with material + surface micro-detail + neutral studio-lighting cues. It classifies the subject (person / animal / vehicle / food / object) and returns a `subject`-aware `negative_prompt` targeting that class's failure modes (hands/faces for people, wheel-count/panel symmetry for vehicles, plastic-replica sheen for food). It prefers a Vertex Gemini rewrite (GCP credits) and falls through to the free-first LLM chain automatically, so it never hard-depends on Vertex. Response schema is unchanged apart from the additive `subject` field.- `api/_lib/forge-reference-image.js` → `generateReferenceImage(directedPrompt, { aspectRatio, negativePrompt?, seed, skipNim })`: generates the reconstruction reference image on the Vertex Gemini 2.5 Flash Image lane (`imageConfig.imageSize:"2K"`), tuned as a plain-background studio photo, with the director's negatives folded in as natural-language avoidance. Automatic fallthrough to the existing provider chain (`textToImage`: NIM FLUX free → Vertex Imagen → Replicate), returning `{ imageUrl, model, lane }` (generated base64 output is persisted through the shared `image-persist` lib). The same directed prompt + aspect + negatives within 24h reuses its cached reference set instead of re-spending a Vertex generation. When `negativePrompt` is omitted it derives subject-aware negatives from the prompt itself, so a caller gets them for free. `api/forge.js` imports it on the text→3D path (dynamic import with `textToImage` as the fallback). The whole reference step (the Vertex lane, its QA score and corrective retry, and the fallthrough ladder) runs under one shared budget, `TEXT_TO_IMAGE_BUDGET_MS` (default 60 s), so a stalled image provider can no longer hold a submit open for minutes before a job exists. Separately from the client-side Enhance button, `api/forge.js` runs its own art-director rewrite on every text prompt by default (send `director: false` to skip it; it fails soft to the raw prompt).- - 3rd-party viewer: model-viewer 4.0.0 (googleapis CDN).+ - 3rd-party viewer: model-viewer 4.3.1, loaded by `src/shared/model-viewer-loader.js` from the googleapis CDN with jsDelivr and unpkg as fallbacks.- **Success state:** A textured **GLB** standing in the in-page `<model-viewer>` (orbit/AR), auto-saved to "Your creations", with a downloadable file and all post-processing/export/embed/share actions enabled. Optional converted formats (OBJ/STL/PLY/USDZ/FBX) and a community showcase entry.- **Empty / error states:**- **Empty/idle** (`#state-empty`): isometric wireframe art + "Enter a prompt to generate", with a live sample/community model in the viewer.@@ -90,6 +90,7 @@ Routing facts (from `vercel.json`):- **Generation failed** (`#state-error`): generic failure with "Try again", plus contextual recovery buttons: "Refine current model instead" (rate-limited fallback), "Generate anyway" (vision override).- BYOK errors: `needs_key` / `invalid_key` reveal + focus the key field; `insufficient_credits` explains provider is out of credits.- `429`/limiter-unavailable, and any other `503` (`generation_unavailable`: a worker still warming or a free lane that shed the request): the recoverable countdown state carrying the server's own message and `retry_after` (20 s when absent) + local-refine escape hatch.+ - Explicitly picked free engine unavailable (`503 provider_busy`, e.g. the Hugging Face lane, which pauses for 300 s after a chain-wide Space failure and reads as down in `?health=1` so the picker disables it): when the response names `retry_backends`, the page hops once automatically to the first one (the picker flips and the panel says "<engine> hit a snag. Retrying on <engine>"), and if that hop fails too it shows one-click engine switches; without suggestions it falls back to the recoverable countdown.- High gate `402 three_hold_required`: designed upsell (held vs required, Get $THREE, Pay-per-use).- Payment errors: `payment_invalid` / `payment_expired` re-offer Pay; `payment_already_used` clears the stale proof; a settle call that cannot be reached after the $THREE transfer already confirmed surfaces `settle_unreachable` with the transaction signature, so the payment is reconciled rather than sent twice.- Upload errors: per-slot states (503 uploads unavailable, 429 rate-limited, too-large/empty/wrong-type, network). `POST /api/forge-upload` now asks whether storage will *accept* the bytes (`objectStorageUsable()`, a cached signed one-key list) rather than whether the credential vars merely exist, so a rotated or whitespace-only R2 token answers `503 storage_unavailable` (or `503 unconfigured`, which falls the page back to accepting a public image URL) instead of handing out a signed URL whose CORS-less `403 SignatureDoesNotMatch` the browser could only report as "Network error during upload".diff --git a/docs/ux-flows/03-3d-editing-viewer.md b/docs/ux-flows/03-3d-editing-viewer.mdindex d80508454..eaa6b9151 100644--- a/docs/ux-flows/03-3d-editing-viewer.md+++ b/docs/ux-flows/03-3d-editing-viewer.md@@ -19,27 +19,27 @@ Routing summary (from `vite.config.js`):### Scene Studio — `/scene`- **Source:** `pages/scene.html`, `src/scene-studio/main.js`, vendored editor under `src/scene-studio/vendor/js/` (`Editor.js`, `Viewport.js`, `Menubar.*.js`, `Sidebar.*.js`, commands), `src/scene-studio/studio.css`, plus the sibling modules that layer three.ws behavior over the vendored editor without editing `vendor/**`: `src/scene-studio/loader.js` (the decoder-wired GLB add), `actions.js` (Import from Forge / Export presets / Share), `empty-state.js` (first-run overlay), `toolbar-a11y.js` (accessible names for the transform and animation transport buttons), and `src/shared/scene-handoff.js`.-- **Entry point:** `pages/scene.html` loads the CodeMirror/Draco vendor `<script>` chain, then `<script type="module" src="/src/scene-studio/main.js">` (scene.html:88). `main.js` constructs the vendored `Editor` (main.js:41), mounts Viewport/Toolbar/Script/Player/Sidebar/Menubar/Resizer/Animation panels into `#studio-app`, mounts the three.ws action bar, a11y labels and empty state over them (main.js:77-87), exposes `window.editor`/`window.THREE`, and inits IndexedDB-backed autosave/storage (`editor.storage.init`, main.js:108-163). The surface is dark-locked (`data-theme='dark'` re-pinned, main.js:11).-- **Prerequisites / gates:** None. No auth, no wallet, no $THREE gate. Works fully anonymously; an empty default scene loads immediately. State persists locally via `editor.storage` (autosave to IndexedDB, debounced ~1s, main.js:132-162).+- **Entry point:** `pages/scene.html` loads the CodeMirror/Draco vendor `<script>` chain, then `<script type="module" src="/src/scene-studio/main.js">` (scene.html:88). `main.js` constructs the vendored `Editor` (main.js:42), mounts Viewport/Toolbar/Script/Player/Sidebar/Menubar/Resizer/Animation panels into `#studio-app`, mounts the three.ws action bar, a11y labels and empty state over them (main.js:78-88), exposes `window.editor`/`window.THREE`, and inits IndexedDB-backed autosave/storage (`editor.storage.init`, main.js:109-164). The surface is dark-locked (`data-theme='dark'` re-pinned, main.js:11).+- **Prerequisites / gates:** None. No auth, no wallet, no $THREE gate. Works fully anonymously; an empty default scene loads immediately. State persists locally via `editor.storage` (autosave to IndexedDB, debounced ~1s, main.js:133-163).- **Steps (N):**- 1. Arrive at `/scene`. Editor mounts; prior autosaved scene restored from IndexedDB, or `sceneEnvironmentChanged('Default')` fires for a fresh scene (main.js:110-115). A fresh scene is no longer a silent black grid: the first-run overlay (`empty-state.js`) names the three ways to start (drag a `.glb`/`.gltf`, pick a primitive from **Add**, or pull in a model you already generated) and retires itself the moment the scene holds anything, a restored autosave included. The transform toolbar is lifted above that card in `studio.css`, because the vendored `#toolbar` leaves `z-index` at `auto` and on a phone-height viewport it parks inside the band the overlay covers.- 2. (optional, deep-link) Arrive via `/scene?model=<glb_url>&name=<label>` (hand-off from Forge/Parts). `importModelFromQuery()` validates the URL is `https://` or same-origin relative, fetches the GLB, parses it with the Draco/KTX2/Meshopt-wired GLTFLoader (`loader.js`), adds it via `AddObjectCommand`, selects it, and strips the query from the address bar (main.js:178-202).- 3. (optional, deep-link) Arrive via `/scene?handoff=1` (hand-off from Animation Studio `/pose`). `importHandoffAnimation()` reads the baked GLB from IndexedDB via `takeSceneHandoff()`, adds it, and attaches a `Play Animation` player script so the embedded clip plays live and records to video (main.js:225-251).- 4. Import a model: drag a GLB/glTF (or a folder of glTF+textures) anywhere on the page → `drop` handler routes to `editor.loader.loadItemList`/`loadFiles` (main.js:260-273); or use **File ▸ Import** file picker (`Menubar.File.js`); or **Import from Forge** on the three.ws action bar, which takes a GLB URL in a shared `<dialog>` that validates the link inline rather than a native `prompt()` (`actions.js`).+ 1. Arrive at `/scene`. Editor mounts; prior autosaved scene restored from IndexedDB, or `sceneEnvironmentChanged('Default')` fires for a fresh scene (main.js:111-116). A fresh scene is no longer a silent black grid: the first-run overlay (`empty-state.js`) names the three ways to start (drag a `.glb`/`.gltf`, pick a primitive from **Add**, or pull in a model you already generated) and retires itself the moment the scene holds anything, a restored autosave included. The transform toolbar is lifted above that card in `studio.css`, because the vendored `#toolbar` leaves `z-index` at `auto` and on a phone-height viewport it parks inside the band the overlay covers.+ 2. (optional, deep-link) Arrive via `/scene?model=<glb_url>&name=<label>` (hand-off from Forge/Parts). `importModelFromQuery()` validates the URL is `https://` or same-origin relative, fetches the GLB, parses it with the Draco/KTX2/Meshopt-wired GLTFLoader (`loader.js`), adds it via `AddObjectCommand`, selects it, and strips the query from the address bar (main.js:179-203).+ 3. (optional, deep-link) Arrive via `/scene?handoff=1` (hand-off from Animation Studio `/pose`). `importHandoffAnimation()` reads the baked GLB from IndexedDB via `takeSceneHandoff()`, adds it, and attaches a `Play Animation` player script so the embedded clip plays live and records to video (main.js:226-252).+ 4. Import a model: drag a GLB/glTF (or a folder of glTF+textures) anywhere on the page → `drop` handler routes to `editor.loader.loadItemList`/`loadFiles` (main.js:261-274); or use **File ▸ Import** file picker (`Menubar.File.js`); or **Import from Forge** on the three.ws action bar, which takes a GLB URL in a shared `<dialog>` that validates the link inline rather than a native `prompt()` (`actions.js`).5. Add primitives/lights/cameras via the **Add** menu (`Menubar.Add.js`); add scripts via **Script** panel (CodeMirror).6. Select an object in the Viewport or the Outliner (Sidebar). The transform gizmo attaches.7. Transform with the gizmo — translate / rotate / scale (Toolbar mode buttons + Viewport `TransformControls`).8. Edit properties in the Sidebar: object transform, **Geometry**, **Material** (color/maps/roughness/metalness/etc.), **Scene** (background, environment, fog), per-light settings.9. (optional) Edit a script in the Script panel; (optional) press **Play** (`Player`) to run scene scripts/animations live.- 10. (optional) Keyframe/inspect animations in the Animation panel (timeline at bottom; `animationPanelChanged` resizes Viewport, main.js:90-104; the play/pause/stop transport is given accessible names and pressed state by `toolbar-a11y.js`).+ 10. (optional) Keyframe/inspect animations in the Animation panel (timeline at bottom; `animationPanelChanged` resizes Viewport, main.js:91-105; the play/pause/stop transport is given accessible names and pressed state by `toolbar-a11y.js`).11. (optional) **File ▸ New** (empty / templates) to reset; undo/redo via the command history.12. Export via **File ▸ Export** submenu: GLB, GLTF, OBJ, PLY (ASCII/binary), STL (ASCII/binary), USDZ, DRC/Draco (`Menubar.File.js`). A download is triggered (e.g. `scene.glb`, `scene.gltf`). The action bar's **Export presets** ("Web GLB", "AR bundle (USDZ)") are one click for the same two exports, and **Share / Embed** uploads the scene as a GLB and opens the platform's embed panel (iframe / web component / `<agent-3d>` snippet). The bar docks beside the sidebar and follows it as it is dragged, instead of sitting on top of the Scene/Project/Settings tabs.13. (optional) **File ▸ Export Project** saves the editor scene as a `.json` project; **File ▸ Open** re-imports a `.json` project (`Menubar.File.js`:91-185).14. (optional) **Render** menu → render an image or video of the scene via `APP.Player` (`Menubar.Render.js`).-- **Decision points / branches:** Fresh scene vs restored autosave (main.js:109-118). Deep-link arrival (`?model=` add, `?handoff=1` animation import) vs plain manual import. `#file=<url>` hash → prompts to open a remote `.json` project, replacing the scene (main.js:285-299). Drag of a folder (`DataTransferItemList`) vs single files.-- **External calls / dependencies:** `fetch(modelUrl)` for `?model=` deep-link GLB (main.js:187); IndexedDB via `editor.storage` (autosave) and `src/shared/scene-handoff.js` (`takeSceneHandoff`, DB `three-ws-scene-handoff`); Draco decoder at `/three/draco/gltf/` (shared with the main app), KTX2 transcoder at `/scene-studio/basis/` (both wired in `loader.js`); local CodeMirror/esprima/acorn/tern vendor libs. Imports: glTF/GLB (+ companion textures), `.json` editor projects. Exports: GLB, GLTF, OBJ, PLY, STL, USDZ, DRC, JSON project, rendered image/video. No platform API calls.+- **Decision points / branches:** Fresh scene vs restored autosave (main.js:110-119). Deep-link arrival (`?model=` add, `?handoff=1` animation import) vs plain manual import. `#file=<url>` hash → prompts to open a remote `.json` project, replacing the scene (main.js:287-307); the linked scene loads with its object scripts and undo history stripped (`remote-scene.js`, since scripts compile with `new Function` on Play) and a toast counts the scripts dropped, while a trusted scene keeps its scripts through **File ▸ Import**. Drag of a folder (`DataTransferItemList`) vs single files.+- **External calls / dependencies:** `fetch(modelUrl)` for `?model=` deep-link GLB (main.js:188); IndexedDB via `editor.storage` (autosave) and `src/shared/scene-handoff.js` (`takeSceneHandoff`, DB `three-ws-scene-handoff`); Draco decoder at `/three/draco/gltf/` (shared with the main app), KTX2 transcoder at `/scene-studio/basis/` (both wired in `loader.js`); local CodeMirror/esprima/acorn/tern vendor libs. Imports: glTF/GLB (+ companion textures), `.json` editor projects. Exports: GLB, GLTF, OBJ, PLY, STL, USDZ, DRC, JSON project, rendered image/video. No platform API calls.- **Success state:** Imported/transformed objects appear in the Viewport + Outliner; autosave indicator (`savingStarted`/`savingFinished`) confirms persistence; export triggers a file download.-- **Empty / error states:** A fresh scene shows the grid, the default environment, and the first-run card telling the visitor how to start (see step 1). Failures report through the shared toast (`src/shared/toast.js`), not a native `alert()`: `?model=` fetch failure → "Could not load the handed-off model: … Download the GLB and drag the file into the editor instead." (main.js:196-200); `?handoff=1` IndexedDB unavailable → silently no-ops, load failure → "Could not load the animation from the Animation Studio: … Try Export GLB on /pose and drag the file in instead." (main.js:245-249). No-GLB-in-drop handled by the vendored loader.+- **Empty / error states:** A fresh scene shows the grid, the default environment, and the first-run card telling the visitor how to start (see step 1). Failures report through the shared toast (`src/shared/toast.js`), not a native `alert()`: `?model=` fetch failure → "Could not load the handed-off model: … Download the GLB and drag the file into the editor instead." (main.js:197-201); `?handoff=1` IndexedDB unavailable → silently no-ops, load failure → "Could not load the animation from the Animation Studio: … Try Export GLB on /pose and drag the file in instead." (main.js:246-250). No-GLB-in-drop handled by the vendored loader.- **Step count:** ~7 required (arrive → import → select → transform → edit material → edit scene → export) + ~7 optional (deep-link arrival, primitives/lights, scripts, Play, animation timeline, project save/open, render).---@@ -81,7 +81,7 @@ Routing summary (from `vite.config.js`):5. Pose with FK (default mode): rotate gizmo on the selected bone + X/Y/Z rotation sliders + "Reset this bone" (`renderControlsPanel`, 640-696).6. (optional) Pose with IK: toggle IK (top bar or **I** key; disabled if the rig exposes no limb chains) and drag a glowing cyan hand/foot handle → `rig.solveIK` (pose-studio.js:585-630). FK and IK are mutually exclusive.7. (optional) Apply a preset pose from the grouped grid (Standing/Action/Sitting/Expressive, `poseFromMannequinPreset`, pose-studio.js:734-758).- 8. (optional, rigged GLB only) Apply a curated motion clip or AI-generate one: `AnimationLibrary` cards from `/animations/manifest.json` retarget+play live; a clip the curated manifest does not carry (an `mx-*` name deep-linked from the `/animations` gallery) is resolved one at a time through `GET /api/animations/library?name=<name>` rather than by downloading the whole multi-megabyte catalog (`_lookupFullLibrary`, animation-library.js:163-172); the text box POSTs `/api/forge-motion` and polls for the clip. That endpoint has exactly one backend, the self-hosted text2motion GPU worker behind `GCP_TEXT2MOTION_URL` (no vendor fallback, so an unset URL is an honest `503`), and it meters against the free-lane rate bucket rather than the paid one.+ 8. (optional, rigged GLB only) Apply a curated motion clip or AI-generate one: `AnimationLibrary` cards from `/animations/manifest.json` retarget+play live; a clip the curated manifest does not carry (an `mx-*` name deep-linked from the `/animations` gallery) is resolved one at a time through `GET /api/animations/library?name=<name>` rather than by downloading the whole multi-megabyte catalog (`_lookupFullLibrary`, animation-library.js:164-173); the text box POSTs `/api/forge-motion` and polls for the clip, which the finished poll returns already converted from HumanML3D's rest shape to the library's canonical basis (so it plays upright, head up and arms hanging), with the raw worker URL only as a fallback. That endpoint has exactly one backend, the self-hosted text2motion GPU worker behind `GCP_TEXT2MOTION_URL` (no vendor fallback, so an unset URL is an honest `503`), and it meters against the free-lane rate bucket rather than the paid one.9. Keyframe the timeline: pose, then **Add keyframe** / **K** (`captureKeyframe`, 1262-1273); drag diamonds to retime, set per-key easing, set name/duration/FPS/loop (pose-studio.js:1275-1394).10. Scrub / play: drag the track or arrow keys; transport play/pause (Space), stop, jump start/end (Home/End), loop toggle. Playback slerp-interpolates poses via `sampleAtTime` (pose-animation.js:136).11. (optional) Import a pose JSON (`#pose-import-json`) → applies a single static pose (pose-studio.js:917-934).@@ -118,27 +118,27 @@ Routing summary (from `vite.config.js`):### 3D Viewer / Editor (main app) — `/app`- **Source:** `pages/app-next.html` (the Next shell served at `/app`), `pages/app.html` (the classic shell at `/app-classic`, `/deploy`, `/showcase`), `src/app.js`, `src/app-next-overlay.js`, `src/viewer.js`, `src/editor/index.js`, `src/validator.js`, `src/account.js`, `src/wallet.js`, `src/erc8004/*`, widget mounts under `src/widgets/*`, `src/components/screenshot-modal.js`, `src/next-layout.js`.-- **Entry point:** `<script defer type="module" src="/src/app.js">` (app-next.html:59, followed by `/src/app-next-overlay.js`, which re-skins the same app with the Next chrome; app.html:57 loads the identical module for the classic shell). `_bootApp()` constructs `new App(document.body, location)` and exposes `window.VIEWER.app` (app.js:2583-2596). The `App` constructor (app.js:162-401) parses hash + query into `this.options`, conditionally builds dropzone/avatar-creator/layout/nav, dispatches on route mode, then inits the agent system + widget bridge.+- **Entry point:** `<script defer type="module" src="/src/app.js">` (app-next.html:59, followed by `/src/app-next-overlay.js`, which re-skins the same app with the Next chrome; app.html:57 loads the identical module for the classic shell). `_bootApp()` constructs `new App(document.body, location)` and exposes `window.VIEWER.app` (app.js:2713-2717). The `App` constructor (app.js:183-424) parses hash + query into `this.options`, conditionally builds dropzone/avatar-creator/layout/nav, dispatches on route mode, then inits the agent system + widget bridge.- **Prerequisites / gates:** No hard gate blocks the viewer: the default CZ avatar (or `?model=`/`?agent=` target) loads for everyone, anonymous included. The "gate" is presentation-only: in `main` mode `_applyViewerMode` sets `data-authed` (`pending`/`false`, app.js:647-662); on the classic shell that CSS (`public/style.css`) overlays the `.auth-gate` card ("Your agent lives here") and hides the agent sidebar + dat.GUI editor for anonymous/pending users, while the Next shell's overlay header shows a "Sign in to save" primary CTA that routes to `/login?next=/app` (`src/app-next-overlay.js`); `getMe()` (`GET /api/auth/me`) reconciles to the real state. A wallet button exists (`initWalletButton`, eager `eagerConnectWallet`) but connecting is never required. **No $THREE token gate.** "Save to account" and "Save edits" redirect to `/login` when signed out. The dat.GUI editor only exists once a model has loaded (built by the viewer on content load).- **Steps (N):**- 1. Arrive at `/app`. Constructor dispatches by mode; `_maybeResumeOrLoad(options)` runs for the default path (app.js:378, 408-458).- 2. A model auto-loads: `?resume=<token>` restores a stashed editor session (optional), else `options.model || '/avatars/cz.glb'`; the default CZ avatar crossfades into a "taunt" landing clip (app.js:451-486).+ 1. Arrive at `/app`. Constructor dispatches by mode; `_maybeResumeOrLoad(options)` runs for the default path (app.js:401, 431-491).+ 2. A model auto-loads: `?resume=<token>` restores a stashed editor session (optional), else `options.model || '/avatars/cz.glb'`; the default CZ avatar crossfades into a "taunt" landing clip (app.js:474-491).3. Viewer renders via `view()` → WebGL check, `createViewer()`, `viewer.load(url, …)` with a progress callback, then attach avatar, notify editor, configure animations, set AR target, run validator. Framing reads the rig's facing off its canonicalized shoulder, arm or leg bones (`src/viewer/facing.js`) so the camera seats in front of the face whether the rig was authored facing +Z or -Z; a model with no readable rig keeps the legacy +Z seat.- 4. (optional) Load your own model — drag-drop a `.glb`/`.gltf` or folder anywhere on `.wrap` (`SimpleDropzone` → `load(files)`, app.js:1708-1776); or the `#file-input` picker; or `?model=<url>`/`#model=` (host-validated by `isSafeQueryModelUrl` for the deploy path, app.js:25-38); or `?agent=<uuid>`.+ 4. (optional) Load your own model: drag-drop a `.glb`/`.gltf` or folder anywhere on `.wrap` (`SimpleDropzone` → `load(files)`, app.js:1783-1864); or the `#file-input` picker; or `?model=<url>`/`#model=` (host-validated by `isSafeQueryModelUrl` from `src/shared/safe-model-url.js` for the deploy path, app.js:326-330); or `?agent=<uuid>`.5. (optional) Open the editor controls (dat.GUI / Next-layout drawer): **Display** (background, autoRotate, wireframe, skeleton, grid, point size, transparent bg, screenshot, model info, mesh labels), **Lighting** (IBL/envMap, exposure, tone mapping, punctual lights), **Light Probes**, **Animation**, **Morph Targets**, **Cameras**, **Agent** follow mode, **Performance** stats (viewer.js `addGUI`).6. (optional) Play animations: `_configureAnimations` fetches `/animations/manifest.json`, registers clips, honors `?anim=<name|uuid>`; Next-layout dock gives clip picker + play/pause + scrubber + loop. When an agent is loaded, its per-slot gesture overrides (`meta.edits.animations`, written by `PUT /api/agents/:id/animations` with `animationSlots`) are applied via `setAnimationMap`; the `/gestures` page documents the slot vocabulary.7. (optional) Edit environment / lights / camera / display via the GUI (`updateEnvironment`, `updateLights`, `setCamera`, `frameContent`, etc. in viewer.js).8. (optional) Edit materials / textures / scene via the `Editor` (`MaterialEditor`, `TextureInspector`, `SceneExplorer`, `MagicBrush`; rebuilt on each new model, editor/index.js:19-55).- 9. (optional) Take a screenshot → `viewer.captureScreenshot()` → `ScreenshotModal.show(blob)` (app.js:825-837).- 10. (optional) Export GLB → editor export folder → `exportEditedGLB(session)` → `downloadGLB(...)`; also a postMessage `exportGLB` bridge returns base64 GLB to a parent frame (editor/index.js:57-129; app.js:1498-1526).- 11. (optional) Save edits / save model to account: editor `_saveEdits` (R2 presign+upload+PATCH) or header "Save to account" (`_triggerSaveToAccount` → if signed out, stash + `/login?next=/app?pending=1`; if signed in, `_performSave` saves the GLB, creates/links an agent, redirects to `/agents/<id>`, app.js:839-1010).- 12. (automatic) Validate — `validator.validate(...)` runs on every non-kiosk load; surfaces a `.validator-toggle` badge + lightbox (app.js:1872; validator.js).- 13. (optional) Cross-links — "Make this a widget" → `/studio?model=<url>`; "Open in Composer" → `/compose?glb=<url>`; "Deploy on Solana" → guided on-chain deploy agent `/app?agent=67bf6e67-…` (app.js:759-810).- 14. (optional) Chat with the agent — `_initNichAgent` mounts the NichAgent chat/voice UI + thought bubble (skipped in widget/kiosk/deploy/showcase, app.js:1633-1648).-- **Decision points / branches:** Route mode dispatch (app.js:288-394): kiosk/embedChat (chromeless), `/deploy` (RegisterUI wizard), `/showcase` (the ERC-8004 directory: every indexed on-chain agent that carries a 3D glTF body, rendered by `src/erc8004/showcase.js`; like `/deploy` it demotes the shell's wordmark `h1` so the page has one real heading, and upgrades the legacy flex footer to the horizon footer, which is what used to drag the document sideways at 320px), on-chain `/a/<chain>/<id>` (anonymous-safe), legacy `#agent=` embed, chat embed `/a/<uuid>?embed=1`, `#widget=<id>` (slim shell vs full SPA, type-specific mounts), `?agent=<uuid>` authenticated agent-edit, else default `_maybeResumeOrLoad`; `?pending=1` replays a stashed post-login save. Anonymous vs signed-in (auth-gate overlay + save gating only). Classic vs Next layout (localStorage toggle). File-drop vs URL vs agent vs on-chain model source.+ 9. (optional) Take a screenshot → `viewer.captureScreenshot()` → `ScreenshotModal.show(blob)` (app.js:869-881).+ 10. (optional) Export GLB → editor export folder → `exportEditedGLB(session)` → `downloadGLB(...)`; also a postMessage `exportGLB` bridge returns base64 GLB to a parent frame (editor/index.js:57-129; app.js:1535-1602).+ 11. (optional) Save edits / save model to account: editor `_saveEdits` (R2 presign+upload+PATCH) or header "Save to account" (`_triggerSaveToAccount` → if signed out, stash + `/login?next=/app?pending=1`; if signed in, `_performSave` saves the GLB, creates/links an agent, redirects to `/agents/<id>`, app.js:883-1023).+ 12. (automatic) Validate: `validator.validate(...)` runs on every non-kiosk load; surfaces a `.validator-toggle` badge + lightbox (app.js:1965; validator.js).+ 13. (optional) Cross-links: "Make this a widget" → `/studio?model=<url>`; "Open in Composer" → `/compose?glb=<url>`; "Deploy on Solana" → guided on-chain deploy agent `/app?agent=67bf6e67-…` (app.js:803-855).+ 14. (optional) Chat with the agent: `_initNichAgent` mounts the NichAgent chat/voice UI + thought bubble (skipped in widget/kiosk/deploy/showcase, app.js:1708-1723).+- **Decision points / branches:** Route mode dispatch (app.js:311-402): kiosk/embedChat (chromeless), `/deploy` (RegisterUI wizard), `/showcase` (the ERC-8004 directory: every indexed on-chain agent that carries a 3D glTF body, rendered by `src/erc8004/showcase.js`; like `/deploy` it demotes the shell's wordmark `h1` so the page has one real heading, and upgrades the legacy flex footer to the horizon footer, which is what used to drag the document sideways at 320px), on-chain `/a/<chain>/<id>` (anonymous-safe), legacy `#agent=` embed, chat embed `/a/<uuid>?embed=1`, `#widget=<id>` (slim shell vs full SPA, type-specific mounts), `?agent=<uuid>` authenticated agent-edit, else default `_maybeResumeOrLoad`; `?pending=1` replays a stashed post-login save. Anonymous vs signed-in (auth-gate overlay + save gating only). Classic vs Next layout (localStorage toggle). File-drop vs URL vs agent vs on-chain model source.- **External calls / dependencies:** `GET /api/auth/me`, `POST /api/auth/logout`, `GET /api/avatars/<id>`, `GET /api/agents/<id>`, `GET /api/agents/me`, `POST /api/agents`, `PUT /api/agents/<id>`, `POST /api/avatars/thumbnail`, `POST /api/widgets/<id>/view`, `GET /animations/manifest.json` + `HEAD /animations/*.glb`; `saveRemoteGlbToAccount` (R2 presign/upload/commit); editor save (R2); on-chain dynamic imports (`erc8004/queries|abi|register-ui|showcase`) + Solana/ETH RPC; IPFS/Arweave URL resolution (`ipfs.js`). Imports: glTF/GLB (+ textures). Exports: binary GLB; PNG screenshot; AR uses USDZ (iOS) + GLB (Android). Validator: in-browser `gltf-validator`.-- **Success state:** `LOAD_END(success)` fades the poster, hides the status overlay, fires `three-ws:first-frame`, runs first-time onboarding (agent-edit), backfills a missing thumbnail (app.js:2033-2066). Model renders, orbitable; editor + agent sidebar available for signed-in users.-- **Empty / error states:** No true empty void: the CZ default always loads. Anonymous main mode shows the `.auth-gate` card ("Your agent lives here", classic shell) or the "Sign in to save" CTA (Next shell) with sidebar/GUI hidden; the dropzone invites upload/generate. Loading: spinner/determinate progress bar (`_showViewerLoading`/`_updateLoadProgress`) + poster thumbnail for agent-edit. Errors: `_classifyLoadError` → human message + Retry (`_showViewerError`, app.js:2090-2181); a drop or pick with no model file shows the error card "No .gltf or .glb file in that drop. Pick a model file to view it." with a "Choose a file" action that reopens the picker (app.js:1840-1857); `_showWebglUnavailable` reload card; `_showWidgetError`; on-chain `_showOnChainError`/`_updateOnChainCard`.+- **Success state:** `LOAD_END(success)` fades the poster, hides the status overlay, fires `three-ws:first-frame`, runs first-time onboarding (agent-edit), backfills a missing thumbnail (`_captureAndUploadThumbnail`, app.js:2163-2168 and 2369+: the GLB is re-rendered offscreen by `glbFileToThumbnail`, with a humanoid stood in a natural rest pose rather than its T-pose bind pose, never read back from the live canvas, then posted to `/api/avatars/thumbnail`). Model renders, orbitable; editor + agent sidebar available for signed-in users.+- **Empty / error states:** No true empty void: the CZ default always loads. Anonymous main mode shows the `.auth-gate` card ("Your agent lives here", classic shell) or the "Sign in to save" CTA (Next shell) with sidebar/GUI hidden; the dropzone invites upload/generate. Loading: spinner/determinate progress bar (`_showViewerLoading`/`_updateLoadProgress`) + poster thumbnail for agent-edit. Errors: `_classifyLoadError` → human message + Retry (`_showViewerError`, app.js:2122-2295); a drop or pick with no model file shows the error card "No .gltf or .glb file in that drop. Pick a model file to view it." with a "Choose a file" action that reopens the picker (app.js:1854-1858); `_showWebglUnavailable` reload card; `_showWidgetError`; on-chain `_showOnChainError`/`_updateOnChainCard`.- **Step count:** ~3 required (arrive → model auto-loads → view/orbit) + ~11 optional (load own model, GUI controls, animations, env/lights/camera, material/texture editing, screenshot, export GLB, save to account, validate review, cross-links, agent chat).---diff --git a/docs/ux-flows/05-discovery-social.md b/docs/ux-flows/05-discovery-social.mdindex 5ced31e65..9527b6eac 100644--- a/docs/ux-flows/05-discovery-social.md+++ b/docs/ux-flows/05-discovery-social.md@@ -11,7 +11,8 @@ Routing recap (from `vercel.json`):| `/animations` | `pages/animations.html` | `src/animations-gallery.js` || `/characters` | `public/characters.html` | `src/characters.js` || `/community` | `pages/community.html` | inline live-activity module in page |-| `/walk` | `pages/walk.html` | `src/walk.js` (+ `src/community/coin-world-boot.js`) |+| `/walk` | `pages/walk-landing.html` | landing page; its "Try it now" opens `/walk/app` (`pages/walk-embed.html` → `src/walk-embed.js`) |+| `/temporary` | `pages/temporary.html` | `src/walk.js` (+ `src/community/coin-world-boot.js`) || `/irl` | `pages/irl.html` | `src/irl.js` (+ `src/irl/*`, `src/irl-net.js`) || `/irl/sign` | `pages/irl-sign.html` | `src/irl-sign.js` || `/irl-privacy` | `pages/irl-privacy.html` | (static content) |@@ -117,8 +118,8 @@ Routing recap (from `vercel.json`):----### Walk — `/walk`-- **Source:** `pages/walk.html` (inline boot), `src/walk.js`, `src/community/coin-world-boot.js`+### Walk: `/temporary` (the full world)+- **Source:** `pages/temporary.html` (inline boot, titled "Drive Your Avatar"), `src/walk.js`, `src/community/coin-world-boot.js`. `/walk` itself is a marketing landing (`pages/walk-landing.html`) whose "Try it now" and "Start walking" buttons open `/walk/app`, the chrome-less embed build (`pages/walk-embed.html` → `src/walk-embed.js`) that has no multiplayer, no AR passthrough and no HUD; the flow below is the full `src/walk.js` world.- **Entry point:** `/src/walk.js` loaded as module. Splash overlay "Loading avatar…" shows while the scene boots. URL params: `?avatar=`, `?avatarUrl=`, `?name=`, `?coin=`, `?ui=hidden`, `?handle=`, `?agent=`.- **Prerequisites / gates:** None to play (solo mode works offline). **Camera permission** requested only on AR-button tap (`navigator.mediaDevices.getUserMedia`, not on load). Auth only needed to list personal avatars in the picker. No motion/geolocation. WebGL required for full render.- **Steps (6 required + many optional):**diff --git a/docs/ux-flows/11-account-dashboard.md b/docs/ux-flows/11-account-dashboard.mdindex 72e5ec557..93bf51f96 100644--- a/docs/ux-flows/11-account-dashboard.md+++ b/docs/ux-flows/11-account-dashboard.md@@ -21,7 +21,8 @@ Resolved from `vercel.json` (`routes`) and `vite.config.js` (`vercel-rewrites` dShared auth concepts:- **Session:** a `__Host-sid` cookie minted server-side by `createSession()`, identical across email/password, SIWE (EVM), SIWS (Solana), Privy, and SAML.-- **Post-auth redirect:** `?next=` query param → `sessionStorage.login_redirect` → default (`/dashboard` for login, `/create` for register). On `/login`, an already-authenticated visitor is bounced to `next` via a `GET /api/auth/me` probe on load. The value is sanitized by a shared `safeNext` helper: anything that is not a single-leading-slash same-site path (protocol-relative `//host`, backslashes, control characters) is silently discarded and the default is used, so a crafted external `?next=` can no longer navigate off-site.+- **Account linking by email:** a Privy or SAML sign-in that carries an email joins the existing account with that address only when the platform has itself verified it (`users.email_verified`). An unverified match is left alone and the identity gets its own new account (Privy falls back to a `privy-<did>@privy.local` address), so pre-registering someone else's email cannot capture their later sign-in.+- **Post-auth redirect:** `?next=` query param → `sessionStorage.login_redirect` → default (`/dashboard` for login, `/create` for register). On `/login`, an already-authenticated visitor is bounced to `next` via a `GET /api/auth/me` probe on load. The value is sanitized by a shared `safeNext` helper: anything that is not a single-leading-slash same-site path (protocol-relative `//host`, backslashes, control characters) is silently discarded and the default is used, so a crafted external `?next=` can no longer navigate off-site. The Privy email and wallet paths (`src/privy-login.js`) run their `next` through the same helper.- **Auth hint:** every successful auth writes `localStorage['3dagent:auth-hint']` so other surfaces render a logged-in chrome optimistically.- **Terms clickwrap (ToS v3):** every auth surface asserts Terms acceptance. `/register` has a required checkbox; `/login` and the Privy/wallet paths use notice-style clickwrap ("By signing in... you agree to the Terms of Service and Privacy Policy") and send `tosAccepted: true`; the Privy SIWE message statement itself carries the agreement text. The server records `users.tos_accepted_version`/`tos_accepted_at` plus an append-only `audit_log` row (`api/_lib/legal.js`, `TOS_VERSION = 3`) and re-stamps on login.- **Real-funds agreements (separate from sign-up):** signing up does not unlock money movement. Before a real-funds action (an armed sniper or Oracle watch, a custodial agent purchase, an x402 payment, a withdrawal) and before an agent wallet's deposit address is revealed, the account must separately sign three documents together at `/legal/agreements`: the Terms of Service (`/legal/tos`), the Risk Disclosure (`/legal/risk`), and the Agent Wallet Agreement (`/legal/agent-wallet`). Signatures are typed-name e-signatures recorded append-only in `legal_signatures`; the dialog is `public/risk-ack.js` posting to `/api/legal/risk-ack`, and every money-moving endpoint enforces it server-side through `requireRealFundsAgreement()` (`api/_lib/real-funds-agreement.js`), answering `403 risk_ack_required` over session and API key alike. Devnet is exempt. See [risk-acknowledgment.md](../risk-acknowledgment.md).@@ -91,7 +92,7 @@ Shared auth concepts:4. `POST /api/auth/forgot-password` with `{ email }`.5. Server always answers 200 with a privacy-preserving body. On status `< 500` → show success notice: "If an account exists for that email, a reset link has been sent."; on `>= 500` → error notice "Something went wrong on our end…"; on fetch rejection → "Couldn't reach the server…".6. Button re-enabled ("Send reset link") regardless, so the user can retry.- 7. **(completion, separate route) `/reset-password?token=…`:** user clicks the emailed link → `public/reset-password.html` reads `?token`. If no token → error + disabled submit. Enter new password + confirm (both min 10, must match) → **Reset password** → `POST /api/auth/reset-password` with `{ token, password }` → on success swap to "Password reset. You can now log in." with a link back to `/login`; on error show message and re-enable.+ 7. **(completion, separate route) `/reset-password?token=…`:** user clicks the emailed link → `public/reset-password.html` reads `?token`. If no token → error + disabled submit. Enter new password + confirm (both min 10, must match) → **Reset password** → `POST /api/auth/reset-password` with `{ token, password }` → on success swap to "Password reset. You can now log in." with a link back to `/login`; on error show message and re-enable. The server consumes the token in the same statement that checks it, so one link can win only once even under concurrent submits, and a successful reset revokes every session and OAuth refresh token on the account.- **Decision points / branches:** Single path (email). The reset-completion step is a distinct page reached from email, not a branch within `/forgot-password`.- **External calls / dependencies:** `POST /api/auth/forgot-password`; (completion) `POST /api/auth/reset-password`; model-viewer CDN.- **Success state:** Privacy-preserving "reset link sent" notice (request side); on the completion page, "Password reset" confirmation with a sign-in link.@@ -153,19 +154,20 @@ Shared auth concepts:- **Prerequisites / gates:** Signed-in required (`requireUser()`; 401 → `/login?return=…`).- **Steps (N):**1. Boot: `mountShell()` → `requireUser()`; 4 skeletons while data loads.- 2. Parallel fetch: `GET /api/auth/sessions`, `GET /api/notifications?limit=20`, `GET /api/notifications/preferences`, `GET /api/avatars/mine?limit=24` (per-avatar storage mode), `GET /api/billing/summary` (storage), `GET /api/usage/summary` (LLM usage), `GET /api/dashboard/prefs`, `GET /api/version` (About).- 3. Render sections: **Appearance/theme**, **Active sessions**, **Notifications**, **Notification preferences**, **Default payment network**, **Avatar storage**, **Storage usage**, **LLM usage**, **Vanity wallet tools**, **Preferences**, **Data export**, **About**.+ 2. Parallel fetch: `GET /api/auth/sessions`, `GET /api/oauth/grants`, `GET /api/notifications?limit=20`, `GET /api/notifications/preferences`, `GET /api/avatars/mine?limit=24` (per-avatar storage mode), `GET /api/billing/summary` (storage), `GET /api/usage/summary` (LLM usage), `GET /api/dashboard/prefs`, `GET /api/version` (About).+ 3. Render sections: **Appearance/theme**, **Active sessions**, **Connected apps**, **Notifications**, **Notification preferences**, **Default payment network**, **Avatar storage**, **Storage usage**, **LLM usage**, **Vanity wallet tools**, **Preferences**, **Data export**, **About**.4. **(optional) Theme:** click Dark/Light/Auto → `localStorage['twx_theme']` (+ `window.threeTheme.set`) → toast "Theme applied" (no API).5. **(optional) Sessions:** "Revoke" → `DELETE /api/auth/sessions/{id}` → toast + row removed; "Revoke all other" → `DELETE /api/auth/sessions` (revokes every other session **and rotates the current session cookie**) → toast.+ 5b. **(optional) Connected apps** (`#connected-apps`, deep-linked from the OAuth consent screen and three.ws Desktop): one row per app holding a live refresh token (the desktop app, the CLI, MCP clients) with its scopes in plain words, last used and authorized times. **Revoke** → confirm → `DELETE /api/oauth/grants?client_id=` → toast and the row drops; the app loses access when its current token expires (within an hour). Empty state: "No connected apps".6. **(optional) Notifications:** "Mark all read" → `POST /api/notifications/read-all` → toast. The inbox covers the full bell vocabulary (sales, purchases, follows, remixes, DMs, coin-launch graduations, IRL, market, account).- 6b. **(optional) Notification preferences:** a category × channel matrix driven by the server response (`categories` + `channels`, default channels in-app / push / email / Telegram / avatar). The **Avatar** column routes a category to the corner companion, which walks on screen and says the message out loud while the user is on the site; a hint line under the table explains it, and it can be muted per browser from the bubble's "Turn off" control. The response also carries `type_categories` (notification type → category), so the client-side herald (`src/notification-herald.js`) gates the avatar channel with the same mapping the server uses for push and email. Toggles flip locally; a single **Save notification preferences** button sends the whole matrix via `PUT /api/notifications/preferences` `{ categories }` → toast "Notification preferences saved". Per-category `lockedChannels` render disabled (in-app is typically locked on); the Telegram column stays disabled ("Link a Telegram chat id to enable") until `telegram_chat_id` is set; a footer reports subscribed push devices.+ 6b. **(optional) Notification preferences:** a category × channel matrix driven by the server response (`categories` + `channels`, default channels in-app / push / email / Telegram / Discord / avatar). The **Avatar** column routes a category to the corner companion, which walks on screen and says the message out loud while the user is on the site; a hint line under the table explains it, and it can be muted per browser from the bubble's "Turn off" control. The response also carries `type_categories` (notification type → category), so the client-side herald (`src/notification-herald.js`) gates the avatar channel with the same mapping the server uses for push and email. Toggles flip locally; a single **Save notification preferences** button sends the whole matrix via `PUT /api/notifications/preferences` `{ categories }` → toast "Notification preferences saved". Per-category `lockedChannels` render disabled (in-app is typically locked on); the Telegram and Discord columns stay disabled until the account has a chat paired with notifications on through the chat gateways (`/api/gateway/connections`; the response's `gateways` block counts them) or, for Telegram only, a legacy `telegram_chat_id`. Their disabled tooltip reads "Pair a Telegram (or Discord) chat at /settings/connections to enable", but no page is served at that path yet, so pairing currently happens through the gateway API and the bot's `/link <code>` command. A footer reports subscribed push devices, counting Web Push subscriptions and iOS (APNs) devices together (`push.subscribed_devices`, with `push.ios_devices` broken out).6c. **(optional) Avatar storage (R2 vs IPFS):** one row per avatar the caller owns, listing its size, its R2 copy, and its IPFS state. `GET /api/avatars/mine` carries a flattened `storage` block (`primary`, `r2_present`, `ipfs_pinned`, `ipfs_cid`, `ipfs_pinned_at`) so the panel needs no per-avatar request. **Pin to IPFS** → `POST /api/avatars/:id/pin-ipfs` reads the object out of R2 and pins it through the provider chain (Pinata, then web3.storage), and the row repaints with the CID linked to a public gateway. A deployment with no pinning provider answers `stub: true` with a `stub:` pseudo-CID: that is a recorded content hash, not a pin, and the row says exactly that ("Content hash only") instead of linking a CID that resolves nowhere. The **R2 / IPFS** segmented control sets which copy a viewer resolves first; it re-reads `GET /api/avatars/:id/storage-mode` and writes the whole record back with `PUT`, because the schema is whole-object and the server owns the attestation block. The IPFS half stays disabled until a real pin exists.7. **(optional) Default network:** Base/Solana/Polygon → `localStorage['twx_default_network']` + best-effort `PATCH /api/dashboard/prefs` `{ prefs: { default_network } }` → toast.8. **(optional) Preferences:** toggle email notifications / show tips / compact sidebar → **Save preferences** → `PATCH /api/dashboard/prefs` `{ prefs }` → toast "Preferences saved".9. **(optional) Data export:** Agents / Avatars / All → fetch `GET /api/agents`, `GET /api/avatars?limit=100`, `GET /api/widgets` → build JSON blob → browser download → toast "Data exported".- **Decision points / branches:** Theme, default network, and privacy-style toggles are local-first (localStorage) with best-effort prefs sync; sessions/notifications/export hit live APIs. Read-only meters for storage/LLM usage.-- **External calls / dependencies:** `GET /api/auth/me`, `GET /api/auth/sessions`, `DELETE /api/auth/sessions/{id}`, `DELETE /api/auth/sessions` (revoke-others + cookie rotation), `GET /api/notifications`, `POST /api/notifications/read-all`, `GET /api/notifications/preferences`, `PUT /api/notifications/preferences`, `GET /api/avatars/mine`, `POST /api/avatars/{id}/pin-ipfs`, `GET`/`PUT /api/avatars/{id}/storage-mode`, `GET /api/billing/summary`, `GET /api/usage/summary`, `GET`/`PATCH /api/dashboard/prefs`, `GET /api/version`, `GET /api/agents`, `GET /api/avatars`, `GET /api/widgets`.-- **Success state:** Toasts on each action (Theme applied / Session revoked / All notifications marked read / Default network set / Preferences saved / Data exported); sections reflect new state.+- **External calls / dependencies:** `GET /api/auth/me`, `GET /api/auth/sessions`, `DELETE /api/auth/sessions/{id}`, `DELETE /api/auth/sessions` (revoke-others + cookie rotation), `GET /api/oauth/grants`, `DELETE /api/oauth/grants?client_id=`, `GET /api/notifications`, `POST /api/notifications/read-all`, `GET /api/notifications/preferences`, `PUT /api/notifications/preferences`, `GET /api/avatars/mine`, `POST /api/avatars/{id}/pin-ipfs`, `GET`/`PUT /api/avatars/{id}/storage-mode`, `GET /api/billing/summary`, `GET /api/usage/summary`, `GET`/`PATCH /api/dashboard/prefs`, `GET /api/version`, `GET /api/agents`, `GET /api/avatars`, `GET /api/widgets`.+- **Success state:** Toasts on each action (Theme applied / Session revoked / <app> revoked / All notifications marked read / Default network set / Preferences saved / Data exported); sections reflect new state.- **Empty / error states:** "No session data", "No notifications" / "You're all caught up", "No avatars yet" (with a **Create an avatar** action to `/create`), "No usage data"; a panel whose fetch failed renders an in-place error state with a working **Retry** that re-fetches every panel; per-action error toasts with button re-enable for retry; skeletons during load.- **Step count:** 3 required (boot + fetch + render) (+7 optional setting flows)@@ -182,7 +184,7 @@ Shared auth concepts:4. **(optional) Account tab:** read-only email with Verified/Unverified badge (`user.email_verified`); password "Reset via email ↗" → `/forgot-password`; connected wallets count from `GET /api/auth/wallets` (→ `/dashboard/account` to manage); plan display (→ `/dashboard#billing`); **Sign out everywhere** → `POST /api/auth/logout-everywhere` → clear localStorage → redirect to `/login`.5. **(optional) Privacy tab:** default avatar visibility select (private/unlisted/public) → **Save** → `localStorage['3dagent:default-vis']` → "Saved preference."6. **(optional) Sessions tab:** list from `GET /api/auth/sessions` (device/IP/date); "Revoke" → `DELETE /api/auth/sessions/{id}` (row removed); **Revoke all other sessions** → `DELETE /api/auth/sessions` → "All other sessions revoked." + reload.- 7. **(optional) Connected Accounts tab:** GitHub status `GET /api/auth/github/status`; connect → `/api/auth/github/connect?agent_id=…`; seed agent memory → `POST /api/agents/{agentId}/memory-seed`. X status `GET /api/agents/{agentId}/memory/seed/x`; connect → `/api/auth/x/connect?agent_id=…`; seed → `POST /api/agents/{agentId}/memory/seed/x`. Supports `?agent_id=` prefill.+ 7. **(optional) Connected Accounts tab:** GitHub status `GET /api/auth/github/status`; connect → `/api/auth/github/connect?agent_id=…` (the callback requires the same signed-in session that started it; a callback with no session or a different one returns to `/settings?tab=connected-accounts&github=error`); seed agent memory → `POST /api/agents/{agentId}/memory-seed`. X status `GET /api/agents/{agentId}/memory/seed/x`; connect → `/api/auth/x/connect?agent_id=…`; seed → `POST /api/agents/{agentId}/memory/seed/x`. Supports `?agent_id=` prefill.8. **(optional) Danger Zone tab:** click "Delete my account…" → type "delete my account" to enable → **Permanently delete** → `DELETE /api/auth/me` with `{ confirm: 'delete my account' }` (the server refuses without the phrase, `400 confirmation_required`) → the account's avatars, agents, and widgets are retired, the `/u/<username>` handle is released, every session is revoked and the cookie cleared → clear localStorage → redirect to `/?deleted=1`. Sign-in is refused afterwards (wallet/SAML paths answer `account_deleted`).- **Decision points / branches:** Six hash-routed tabs; profile is the primary editable surface; privacy is local-only; account/sessions/connections/danger hit live APIs. Distinct from `/dashboard/settings` (which is app preferences, no identity/security fields).- **External calls / dependencies:** `GET /api/auth/me`, `PATCH /api/auth/profile`, `GET /api/auth/wallets`, `POST /api/auth/logout-everywhere`, `GET /api/auth/sessions`, `DELETE /api/auth/sessions/{id}`, `DELETE /api/auth/sessions`, `GET /api/auth/github/status`, `/api/auth/github/connect`, `POST /api/agents/{id}/memory-seed`, `GET`/`POST /api/agents/{id}/memory/seed/x`, `/api/auth/x/connect`, `DELETE /api/auth/me`.diff --git a/docs/vaults.md b/docs/vaults.mdindex 07484cc65..eef1c1d0e 100644--- a/docs/vaults.md+++ b/docs/vaults.md@@ -28,13 +28,13 @@ Two GETs are worth calling out because the pattern is easy to get wrong: `/api/vEvery write accepts either form of credential:- **Session cookie**, as the browser does it. A one-time CSRF token is then required in `X-CSRF-Token`; get one from `GET /api/csrf-token`. A missing or stale token is `403 csrf_missing` / `403 csrf_invalid`.-- **API key** (`Authorization: Bearer sk_live_...`), for scripts and servers. Bearer callers are CSRF-exempt because the token is itself the proof of intent. See [authentication.md](authentication.md) for minting one.+- **API key** (`Authorization: Bearer sk_live_...`), for scripts and servers. Bearer callers are CSRF-exempt because the token is itself the proof of intent. The four routes that move funds (`deposit`, `redeem`, `trade`, `claim-fees`) additionally require the key to hold the `wallet:write` scope; a key without it gets `403 insufficient_scope` and nothing moves (the check is [`assertBearerMaySpend`](../api/_lib/spend-scope.js), the same gate as the [agent wallet API](agent-wallet-api.md)). Opening a vault and the owner's `PATCH` need no extra scope. See [authentication.md](authentication.md) for minting a key.Every write is also rate limited per user at 30 per minute, and the limiter fails closed: if the shared limiter backend is unreachable in production the write is refused rather than silently uncapped.Every write additionally requires the caller's account to have signed the real-funds agreements (Terms of Service, Risk Disclosure, Agent Wallet Agreement). Opening a vault, resuming a paused one, depositing, redeeming, owner-trading and claiming fees each call `requireRealFundsAgreement` before anything is built, so an unsigned account gets `403 risk_ack_required` with a `sign_url`, over a session and an API key alike, and nothing moves. Signing once at [/legal/agreements](https://three.ws/legal/agreements) covers all of them; devnet is exempt, and no `GET` is ever gated. See [risk-acknowledgment.md](risk-acknowledgment.md).-The examples below use an API key in `$API_KEY`.+The examples below use an API key in `$API_KEY`, granted `wallet:write` for the spending calls.## Opening a vaultdiff --git a/docs/voice-lab.md b/docs/voice-lab.mdindex e7c7ad86f..9dc370318 100644--- a/docs/voice-lab.md+++ b/docs/voice-lab.md@@ -28,7 +28,7 @@ The `providers` array from `GET /api/tts/catalog` is the source of truth: it rep### The ElevenLabs Voice Library-The **ElevenLabs Library** tab searches the public catalog ElevenLabs users share (thousands of voices, filterable by accent, age, gender, and use case). A shared voice cannot be synthesized directly: press "Add to my voices" and it is copied into the account behind the request (yours under BYOK, the platform's otherwise), which returns a normal `voice_id` usable everywhere else on the platform.+The **ElevenLabs Library** tab searches the public catalog ElevenLabs users share (thousands of voices, filterable by accent, age, gender, and use case). A shared voice cannot be synthesized directly: press "Add to my voices" and it is copied into the account behind the request (yours under BYOK, the platform's otherwise), which returns a normal `voice_id` usable everywhere else on the platform. An add without your own key takes one of the platform account's finite voice slots, so it draws on the same 3-per-user-per-day budget as a platform-key clone (`429` past it, with a hint to add your own key); an add with `x-eleven-key` is uncapped.## How it works@@ -146,7 +146,7 @@ The agent-voice handler ([`api/agents/_id/voice.js`](../api/agents/_id/voice.js)- **A rejected key reads as a key problem.** When ElevenLabs turns down the key on a request, `/api/tts/eleven/voices` and both `/api/tts/eleven/library` methods answer `401 invalid_key` rather than `502`, so the UI can prompt for a new key instead of retrying. A rejected *platform* key still reads as `503 not_configured`, because that one is ours to fix.- **Voice ids are checked against the lane.** `POST /api/tts/synthesize` rejects a `voiceId` the chosen lane does not publish with `400 validation_error`, naming the id and the catalog URL to pick from, before anything is metered. It is never quietly swapped for the lane default (omit `voiceId` if that is what you want). ElevenLabs, whose catalog grows at runtime, reports an unknown id as a `400` from upstream instead.- **Paid cloning tier.** Instant Voice Cloning is an ElevenLabs paid-tier (Starter and up) feature. On a free upstream tier the API surfaces the upstream `can_not_use_instant_voice_cloning` body verbatim as a `502`.-- **Length rules.** Voice Lab recommends 20 to 30 seconds, auto-stops at 60, and rejects under 3. The separate agent-clone endpoint (`POST /api/agents/:id/voice/clone`) enforces a 30-second floor. Platform-key clones on both endpoints are capped at 3 per user per day (an abuse guard on the shared account's limited clone slots) and each is charged per the billing section; BYOK clones on `/api/tts/eleven-clone` skip the cap.+- **Length rules.** Voice Lab recommends 20 to 30 seconds, auto-stops at 60, and rejects under 3. The separate agent-clone endpoint (`POST /api/agents/:id/voice/clone`) enforces a 30-second floor. Platform-key clones on both endpoints, and Voice Library adds made without your own key, share one cap of 3 per user per day (an abuse guard on the shared account's limited voice slots); each clone is charged per the billing section. BYOK clones on `/api/tts/eleven-clone` and BYOK library adds skip the cap.- **Synthesis limits.** 1,000 characters per `/api/tts/synthesize` request (500 on the older `/api/tts/eleven`); every platform-key request is metered to credits per the billing section (charged before synthesis, refunded on failure). BYOK requests are unmetered by the platform. Clips are cached in R2 and cache hits are not charged.- **Audio size.** Clone uploads are capped at ~10 MB.- **"Add to an agent" on `/voice`** links to the dashboard; the actual assignment happens in the agent editor. The cloned `voice_id` lives in browser `localStorage` until you assign it.diff --git a/docs/x402-endpoints.md b/docs/x402-endpoints.mdindex 95d6e76e9..ab165a476 100644--- a/docs/x402-endpoints.md+++ b/docs/x402-endpoints.md@@ -125,14 +125,14 @@ buyer's USDC settles **directly** to that wallet and the platform never holds it| `/api/x402/agents/:id` | the **agent** sold as an API | Solana payout wallet, else the agent's own Solana wallet (`resolveServicePayTo` in [agent-api-service.js](../api/_lib/agent-api-service.js)) || `/api/x402/asset-download` | 3D-asset **creator** | `creator_payto_*` ([asset-download.js:124](../api/x402/asset-download.js#L124)) || `/api/x402/animation-download` | clip **creator** | `creator_payto_*` ([animation-download.js:115](../api/x402/animation-download.js#L115)) |-| `/api/x402/pay-by-name` | **buyer-named** wallet | resolved name/`.sol`/address, direct SPL transfer ([pay-by-name.js:280](../api/x402/pay-by-name.js#L280)) |+| `/api/x402/pay-by-name` | **buyer-named** wallet | resolved name/`.sol`/address, direct SPL transfer ([pay-by-name.js:273](../api/x402/pay-by-name.js#L273)) |**2. Post-settlement split** — the USDC lands in the **platform receiver**, then a*separate* treasury forwards a share out-of-band (these are NOT `payTo` overrides):| Endpoint | Lands in | Then forwarded to | By || -------- | -------- | ----------------- | -- |-| `/api/x402/cosmetic-purchase` | platform receiver | **creator** 50% (≤90% cap) | `COSMETIC_SPLIT_TREASURY_SECRET_KEY_B64` ([cosmetics-economy.js:203](../api/_lib/cosmetics-economy.js#L203); the 50% default and 90% ceiling are [L31-L32](../api/_lib/cosmetics-economy.js#L31)) |+| `/api/x402/cosmetic-purchase` | platform receiver | **creator** 50% of the USDC list price (≤90% cap) | `COSMETIC_SPLIT_TREASURY_SECRET_KEY_B64` ([cosmetics-economy.js:203](../api/_lib/cosmetics-economy.js#L203); the 50% default and 90% ceiling are [L31-L32](../api/_lib/cosmetics-economy.js#L31)) || `/api/x402/dance-tip` | platform receiver | **dancer** (full tip) | `club-payouts` cron ([club/sweep.js](../api/_lib/club/sweep.js)) paying from `CLUB_SOLANA_TREASURY_SECRET_KEY_B64` ([club/payouts.js:55](../api/_lib/club/payouts.js#L55)) || `/api/x402/club-cover` | platform receiver (kept) | — (funds the club float; issues a door pass) | — |@@ -210,7 +210,7 @@ named in its description:| `/api/x402/market-dex-volumes` | $0.001 | Top 100 DEXes by 24h volume, with 7d volume, WoW change, chains, and market-share. || `/api/x402/market-hacks` | $0.001 | Full DeFiLlama hack history — amount stolen, technique, chains, funds returned; searchable, with all-time/12mo loss stats. || `/api/x402/market-pulse` | $0.005 | Flagship one-call market bundle: global stats, Fear & Greed, top-10 coins, trending, ETH gas, DeFi TVL, stablecoin supply, DEX volume, protocol fees — each section degrades independently. |-| `/api/x402/print-order` | from $12 | **Physical manufacturing.** Pay to have a 3D model printed in resin, nylon or full-colour sandstone and shipped to a street address. Quote free at `POST /api/print/quote`, then post that signed token plus an address: the 402 quotes that order's exact total, because every print is its own object. Settles into a real job with safety screening, tracked shipping and an on-chain certificate. |+| `/api/x402/print-order` | from $12 | **Physical manufacturing.** Pay to have a 3D model printed in resin, nylon or full-colour sandstone and shipped to a street address. Quote free at `POST /api/print/quote`, then post that signed token plus an address: the 402 quotes that order's exact total, because every print is its own object. Settles into a real job with safety screening, tracked shipping and an on-chain certificate. A quote priced at a declared `payerWallet`'s $THREE holder tier is bound to that wallet: paying it from any other wallet is refused before settle with `403 quote_wallet_mismatch`. |Beneath the named endpoints sits the **datapoint fabric**: `/api/x402/d/<family>/…`(one route, `api/x402/d/[...path].js`) serves 1,000,000+ individually priced@@ -254,7 +254,7 @@ datapoints at **$0.0005** USDC each by default, overridable per family with| [`/api/x402/vanity`](vanity.md) | $0.01–$0.50 (≤3) · $2.50–$10 (4–5, inventory-only) | **Vanity Grinder** — get a brand-new Solana address that starts with your ticker/prefix and/or ends with a suffix, for a branded token mint or agent/treasury wallet. Checks the pre-ground warehouse first for **instant delivery** (`source: "inventory"`); falls back to a live grind (`source: "ground"`) up to 3 chars. Keypair or importable BIP-39 mnemonic; nothing stored; optional `sealTo` ECIES. Full doc: [vanity.md](vanity.md). || [`/api/x402/vanity-verifiable`](vanity.md#tier-2--provably-fair-grinder) | $0.02–$0.40 | **Provably-fair grinder** — same grind with a signed commit–reveal receipt proving the key was ground fresh and never kept. Spec: [PROTOCOL-vanity.md](PROTOCOL-vanity.md). || [`/api/x402/vanity-premium`](vanity.md#tier-3--premium-inventory) | $1–$50 by rarity | **Premium inventory** — buy a pre-ground 4–5+ char brandable address from stock. GET lists available patterns + prices (free); `?address=…` buys via x402 and delivers the key **once** (ciphertext destroyed on delivery). Browsable at `/vanity/premium`. |-| `/api/x402/pay-by-name` | $0.001 | Resolve and pay a `@username` / `.sol` name / raw address (see [Agent wallets](agent-wallets.md)); the paid resolve toll is $0.001, the transfer amount itself is buyer-specified. A name that resolves to nothing returns `404 not_found` and the payment is left unsettled, so an unresolvable name is free. A body-less POST lands on this paid resolve lane and gets the 402 challenge (the free prep flow must say `mode: "prep"` or carry its wallet/amount fields). |+| `/api/x402/pay-by-name` | $0.001 | Resolve and pay a `@username` / `.sol` name / raw address (see [Agent wallets](agent-wallets.md)); the paid resolve toll is $0.001, the transfer amount itself is buyer-specified. A name that resolves to nothing returns `404 not_found` and the payment is left unsettled, so an unresolvable name is free. A body-less POST lands on this paid resolve lane and gets the 402 challenge (the free prep flow must say `mode: "prep"` or carry its wallet/amount fields). `mode: "send"` signs from the caller's agent wallet and needs a session or a bearer token holding the `wallet:write` scope; any other bearer gets `403 insufficient_scope`. || `/api/x402/did` | $0.001 | **POST** is the DID verification canary: it resolves three.ws's published W3C DID document over its real public route, structurally validates it, and returns `{ verified, latency_ms, configured, checks }`. `configured: false` means the resolver answered 404 or could not be reached at all. `mode: "sweep"` audits recent agent identities for resolvable key material instead. **GET** is the free publisher for `/.well-known/did.json`; every other verb returns `405`. || `/api/x402/three-buy` | $0.001 | Micro-buy service: one settled toll payment triggers one small, real on-chain USDC to $THREE buy funded by the micro-buy wallet (driven by the `three-buy-loop` cron). || `/api/x402/knock` | set by recipient | **Knock**: pay a person's own price and get exactly one message through to them, in person. The recipient sets what a moment of their attention costs and the USDC settles straight to their wallet, never the platform's, so a priced door cannot be opened without one. The accepted message becomes a companion event whose importance is derived from the amount paid, and their 3D companion walks on screen wherever they are and delivers it out loud. Body is validated against that door's limits before any 402 is issued, so nobody pays for a message that was going to be refused. |