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
feat: add Object Library documentation with API details and usage instructions
nirholas5ed659ddbc02
diff --git a/.gitignore b/.gitignoreindex c0f2a6b74..a3f82a3e3 100644--- a/.gitignore+++ b/.gitignore@@ -248,7 +248,9 @@ scripts/genesis-results.json# local test wallet (never commit).wallet-test.jsondocs/three-ws-feature-article.md-animation-sources/+# Motion sources are build-time inputs, never committed; the README documents the directory.+animation-sources/*+!animation-sources/README.mdscripts/mixamo-dl/demo.htmldemo2.htmldiff --git a/ARCHITECTURE.md b/ARCHITECTURE.mdindex b9765d85b..09b42cc61 100644--- a/ARCHITECTURE.md+++ b/ARCHITECTURE.md@@ -2318,7 +2318,7 @@ sequenceDiagram> `docs/ALL.md` (3.4 MB) is a generated concatenation of the entire docs tree; `docs/llms.txt` / `docs/llms-full.txt` are the LLM-discovery indexes.-> **Prompt / work-order collections** (agent-dispatch task files and campaign runbooks — not product docs) live under the top-level [`prompts/`](prompts) directory, not `docs/`: `store-submissions/`, `agent-briefs/`, and `roadmap/` (moved out of `docs/`), alongside `gcp-credits/` and `okx-ai/`. Completed campaigns (`x402-catalog/`, `x402-overhaul/`, `bnb-chain/` work orders) are deleted once verified shipped and remain readable in git history.+> **Prompt / work-order collections** (agent-dispatch task files and campaign runbooks; not product docs) live under the top-level [`prompts/`](prompts) directory, not `docs/`: `store-submissions/` and `roadmap/` (moved out of `docs/`), alongside `gcp-credits/` and `okx-ai/`. Completed campaigns (`x402-catalog/`, `x402-overhaul/`, `agent-briefs/`, `bnb-chain/` work orders) are deleted once verified shipped and remain readable in git history.---diff --git a/CLAUDE.md b/CLAUDE.mdindex e043cfcfa..ea5fe4e90 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -276,7 +276,7 @@ Remember stop-and-ask gate 2: production deploys need owner approval unless the1. **Prepare a CLEAN worktree.** `git worktree add --detach /workspaces/.deploy-wt HEAD`, then hardlink THREE artifacts with `cp -al` on the same filesystem (not just the first): `node_modules`, `chat/node_modules`, and `character-studio/build`, plus copy `.env`. Omitting either nested one kills the build minutes in: an OOM exit 144 on the avatar-studio rebuild, or `Cannot find package '@sveltejs/vite-plugin-svelte'` on the chat build. See `docs/ops/gcp-production.md`.2. **Build: `npm run build:gcp`.** ORDER IS LOAD-BEARING and `build:gcp` already encodes it. Never hand-run the steps in a different order. The full chain, in order:- `check:conflicts` → `ensure:avatar-studio` → `build:info:snapshot` → `build:chat` → `build` (the frontend `vite build`) → `build:lib:full` (the UMD lib) → `publish:lib` → `build:info` → `check:dist` → `check:pages`+ `check:conflicts` → `check:browser-graph` → `ensure:avatar-studio` → `build:info:snapshot` → `build:chat` → `build` (the frontend `vite build`) → `build:lib:full` (the UMD lib) → `publish:lib` → `build:info` → `check:dist` → `check:pages`Why the order is load-bearing: `check:conflicts` runs first so an unresolved merge-conflict marker fails in seconds instead of after a full build. Then the frontend `vite build` runs with `emptyOutDir`, so it WIPES `dist/` and everything that writes into `dist/` must come after it. `publish:lib` mirrors the UMD lib into `dist/`, so it must follow `build:lib:full`, and `check:dist` fails without that bundle present. The first two steps are exactly why step 1 stages worktree artifacts: `ensure:avatar-studio` consumes `character-studio/build` and `build:chat` consumes `chat/node_modules`. Do NOT hand-run `build:vercel` as the frontend build: it builds the SDK/lib sub-artifacts, NOT the static HTML pages, so `dist/` ends up without `/`, `/create`, etc. and `check:dist` fails.3. **Submit: `gcloud builds submit --config server/cloudbuild.yaml --region us-central1 --project aerial-vehicle-466722-p5`.** EVERY cloudbuild config must pin `serviceAccount: .../three-ws-build@...` (the default compute SA was deleted), and manual submits need `--substitutions=SHORT_SHA=manual$(date +%s)` when the config tags images with `$SHORT_SHA`.diff --git a/README.md b/README.mdindex ba3f31c72..015c8d800 100644--- a/README.md+++ b/README.md@@ -8437,23 +8437,17 @@ endsolid threews_avatar## Table of Contents- [What is three.ws?](#what-is-threews)-- [Vision](#vision)-- [Roadmap](#roadmap)- [Key Features](#key-features)+- [Screenshots](#screenshots)- [Forge — Text & Image to 3D](#forge--text--image-to-3d)- [Platform Pages](#platform-pages)-- [Install in Claude Code](#install-in-claude-code)-- [Cloud Marketplaces](#cloud-marketplaces)-- [Ecosystem Directories](#ecosystem-directories)-- [IBM watsonx & Granite](#ibm-watsonx--granite)-- [Screenshots](#screenshots)+- [Getting Started](#getting-started)+- [Examples](#examples)+- [Tutorials](#tutorials)- [Architecture](#architecture)- [Design Docs & Specs](#design-docs--specs)- [Tech Stack](#tech-stack)- [Browser Support](#browser-support)-- [Getting Started](#getting-started)-- [Examples](#examples)-- [Tutorials](#tutorials)- [Project Structure](#project-structure)- [The Agent System](#the-agent-system)- [Event Bus (Agent Protocol)](#event-bus-agent-protocol)@@ -8461,10 +8455,12 @@ endsolid threews_avatar- [Empathy Layer](#empathy-layer)- [Skills](#skills)- [Memory](#memory)+- [Animation System](#animation-system)- [Web Component & Embedding](#web-component--embedding)- [Widget System](#widget-system)- [Embed Editor](#embed-editor)- [Pose Studio](#pose-studio)+- [Avatar Accessories & Coin Launchpad](#avatar-accessories--coin-launchpad)- [Launchpad](#launchpad)- [The Club](#the-club)- [Walk & Multiplayer](#walk--multiplayer)@@ -8473,28 +8469,32 @@ endsolid threews_avatar- [Friends, Presence & Social](#friends-presence--social)- [In-Game Economy](#in-game-economy)- [Voice Lab & Mocap Studio](#voice-lab--mocap-studio)-- [x402 Payments](#x402-payments)-- [A2A — Agent-to-Agent Protocol](#a2a--agent-to-agent-protocol)- [Talk Mode & Lip-Sync](#talk-mode--lip-sync)-- [Solana Mobile (Seeker)](#solana-mobile-seeker)-- [Selfie Reconstruction Pipeline (Phase 1)](#selfie-reconstruction-pipeline-phase-1)-- [Livepeer Inference Network (Phase 4)](#livepeer-inference-network-phase-4)-- [Voice & Persona Hub (Phase 2)](#voice--persona-hub-phase-2)-- [WASM Vanity Grinder](#wasm-vanity-grinder)-- [News CMS & Syndication](#news-cms--syndication)-- [Security Hardening](#security-hardening)-- [Developer SDKs](#developer-sdks)-- [Claude Code Integration](#claude-code-integration)- [Demos Hub](#demos-hub)- [Skill Library](#skill-library)-- [Animation System](#animation-system)-- [Avatar Accessories & Coin Launchpad](#avatar-accessories--coin-launchpad)-- [Brain Proxy & LLM Routing](#brain-proxy--llm-routing)+- [Developer SDKs](#developer-sdks)- [API Reference](#api-reference)- [Authentication & OAuth 2.1](#authentication--oauth-21)- [MCP Server](#mcp-server)+- [Brain Proxy & LLM Routing](#brain-proxy--llm-routing)+- [Claude Code Integration](#claude-code-integration)+- [Install in Claude Code](#install-in-claude-code)+- [Cloud Marketplaces](#cloud-marketplaces)+- [Ecosystem Directories](#ecosystem-directories)+- [IBM watsonx & Granite](#ibm-watsonx--granite)+- [x402 Payments](#x402-payments)+- [A2A — Agent-to-Agent Protocol](#a2a--agent-to-agent-protocol)- [On-Chain Identity (ERC-8004 + Metaplex Core)](#on-chain-identity-erc-8004--metaplex-core)- [Pump.fun Integration](#pumpfun-integration)+- [WASM Vanity Grinder](#wasm-vanity-grinder)+- [Solana Mobile (Seeker)](#solana-mobile-seeker)+- [Vision](#vision)+- [Roadmap](#roadmap)+- [Selfie Reconstruction Pipeline (Phase 1)](#selfie-reconstruction-pipeline-phase-1)+- [Voice & Persona Hub (Phase 2)](#voice--persona-hub-phase-2)+- [Livepeer Inference Network (Phase 4)](#livepeer-inference-network-phase-4)+- [News CMS & Syndication](#news-cms--syndication)+- [Security Hardening](#security-hardening)- [Database Schema](#database-schema)- [Build & Deployment](#build--deployment)- [Versioning & Compatibility](#versioning--compatibility)@@ -8529,135 +8529,6 @@ three.ws is production-ready and serves [three.ws](https://three.ws) live on Goo----## Vision--One day, creating your agent should be as simple as taking a selfie.--Point your camera at yourself — or anyone — and watch a fully realized 3D avatar emerge: your face, your voice, your personality, alive in the browser. That avatar becomes an agent with memory and skills, registered onchain — as an ERC-8004 token on EVM or a Metaplex Core asset on Solana — permanent and verifiable by anyone forever. No 3D software. No wallet setup. No uploads. Just a photo and a name.--This is the direction three.ws is heading: **photo → avatar → agent → onchain identity**, in a single flow. The infrastructure is already here — the viewer, the runtime, the contracts, the embedding layer. What comes next is closing the gap between a picture of a person and a living, ownable, embeddable piece of them that exists on the internet permanently.-------## Roadmap--three.ws ships in four phases. Each phase closes a specific gap between the current platform and the end-state vision: **anyone can mint a 3D agent of themselves, own it onchain, and embed it anywhere on the internet.**--| Phase | Theme | Status |-| ----- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |-| **0** | Platform foundations (viewer, runtime, ERC-8004 + Metaplex Core identity, embed layer) | ✅ Shipped |-| **1** | Selfie → Avatar engine (3-photo capture, hosted inference) | 🟡 In progress — capture UX + quality gates shipped; GPU reconstruction backend wiring |-| **2** | Agent personalization + voice cloning | 🟡 In progress — voice clone, persona, memory seeds shipped behind `/demos`; main-flow integration next |-| **3** | Onchain economy (agent tokens, reputation markets, royalties) | 🟡 Scaffolding — bonding-curve sim, EAS-reputation viewer, 0xsplits + EAS SDKs landed; contracts + audits next |-| **4** | Open inference network (decentralized GPU layer) | 🔮 Future — livepeer dep landed for early experimentation |-------### Phase 0 — Foundations _(Shipped)_--The full stack is live at [three.ws](https://three.ws): WebGL viewer, LLM agent runtime, ERC-8004 identity contracts (EVM) and Metaplex Core mints (Solana), OAuth 2.1 server, MCP endpoint, and the `<agent-3d>` web component. Anyone can register an agent today — but the avatar still has to come from a 3D artist or a third-party tool.--**What works:** model upload, agent runtime, onchain registration, embedding, signed action history, reputation scores.-**What doesn't:** there is no automated path from a real human face to a usable 3D avatar.-------### Phase 1 — Selfie → Avatar Engine--**Goal:** any user takes 3 selfies (left, center, right) and receives a rigged, animatable 3D avatar in under 60 seconds.--**Deliverables**--- Mobile-first capture UX with realtime quality gates (lighting, framing, blur)-- Multi-view face reconstruction pipeline (FLAME / 3DMM fitting on top of a base body mesh)-- Hosted inference workers (GPU-backed) for sub-minute generation-- Output written directly to R2 and minted as a draft agent token — ERC-8004 on EVM, Metaplex Core asset on Solana--**Compute requirements**--- A100/H100-class GPUs for inference, sized to ~10k avatars/day at launch-- Training budget for fine-tuning a stylized face-fitter on a curated dataset-- CDN egress scaling for high-res GLB delivery--**Verification:** 1,000 test users complete capture and mint an onchain agent of themselves end-to-end with ≥4/5 likeness score.-------### Phase 2 — Agent Personalization--**Goal:** the avatar isn't just _you_ — the agent _acts_ like you.--**Deliverables**--- Voice cloning (3–10 seconds of speech → ElevenLabs custom voice bound to the agent)-- Persona extraction from a short onboarding interview (tone, vocabulary, interests)-- Memory seeding from connected accounts (X, GitHub, Farcaster) with explicit user consent-- Per-agent fine-tuned system prompt stored in the manifest, signed and pinned to IPFS--**Verification:** users return to converse with their own agent; ≥30% week-2 retention on minted agents.-------### Phase 3 — Onchain Economy--**Goal:** agents are real economic objects on EVM and Solana, not just collectibles.--**Deliverables**--- **Agent tokens** — ERC-8004 mints with bonding-curve pricing or fair launch options-- **Reputation markets** — stake on agents, earn from their action history (extends `ReputationRegistry.sol`)-- **Skill royalties** — skill authors earn per-call fees through EIP-7710 delegated permissions-- **Agent-to-agent payments** — agents transact autonomously via their delegated signer wallets-- **Subscriptions & DCA** — recurring onchain payments to creators (cron infra already in place)--**Funding requirements**--- Smart contract audits (multi-firm) for the reputation, royalty, and delegation contracts-- Liquidity for agent token launches-- Indexer infrastructure across Base, Solana, and additional EVM chains--**Verification:** ≥1,000 agents minted with active onchain reputation; ≥$X in cumulative skill royalties paid out.-------### Phase 4 — Open Inference Network--**Goal:** decouple agent inference from any single provider. Anyone can run a node; agents pay nodes onchain for compute.--**Deliverables**--- Open protocol for agent inference (model weights, GPU runtime, signed responses)-- Node operator client (Docker + GPU drivers) with onchain registration-- Onchain settlement for inference jobs — pay-per-token with cryptographic receipts-- Federation with existing decentralized compute networks where appropriate--**Compute requirements**--- Bootstrap GPU credits for early node operators-- Cryptoeconomic security model (slashing, validator set) — research + audit budget--**Verification:** ≥50% of production agent traffic served by independent node operators; latency parity with centralized inference.-------### What we need--| Resource | Used for | Phase |-| -------------------------- | ------------------------------------------ | ----- |-| **Inference GPUs** | Avatar generation, agent conversations | 1, 2 |-| **Training compute** | Fine-tuned face-fitter, voice models | 1, 2 |-| **Smart contract audits** | Reputation, royalty, delegation contracts | 3 |-| **Token launch liquidity** | Agent token markets | 3 |-| **Indexer infrastructure** | Multi-chain crawl + reputation aggregation | 3 |-| **Node operator credits** | Bootstrap the open inference network | 4 |-| **Engineering headcount** | Capture pipeline, contracts, indexer, ops | 1–4 |--Phases 1 and 2 unblock the consumer story — _anyone gets an agent of themselves_. Phases 3 and 4 unblock the onchain story — _those agents are real economic actors that don't depend on any one company to keep running_. Both are required for the vision; neither is funded yet.--If you want to support the project — compute credits, grants, partnerships, or contributions — open an issue or reach out via [three.ws](https://three.ws).------## Key Features**Text → 3D Generation (Forge)**@@ -8752,6 +8623,18 @@ If you want to support the project — compute credits, grants, partnerships, or---+## Screenshots++| Viewer | Widget Studio |+| ---------------------------------------- | ----------------------------------------------- |+|  |  |++| Agent Discovery | Avatar Creation |+| -------------------------------------------- | ---------------------------------------- |+|  |  |++---+## Forge — Text & Image to 3DType a sentence, get a 3D model. [**Forge**](https://three.ws/forge) turns a text prompt, one to four photos, or a rough sketch into a textured, downloadable GLB — in the browser, with a free draft tier and no account required.@@ -8842,243 +8725,52 @@ A map of every user-facing route. [`STRUCTURE.md`](STRUCTURE.md) maps each produ----## Install in Claude Code--three.ws ships an official **Claude Code plugin marketplace** — install wallet, payments, pump.fun trading, agent scaffolding, and the 3D Forge as namespaced skills and MCP tools, in one command. Add the marketplace once:+## Getting Started-```-/plugin marketplace add nirholas/three.ws-```+### Prerequisites-Then install any of the four plugins:+- Node.js 24+ (the project pins `"engines.node": "24.x"` in `package.json`; earlier majors are not tested)+- npm 10++- A Neon Postgres database+- A Cloudflare R2 bucket+- An Anthropic API key-```-/plugin install three-ws-core@three-ws # wallet + x402 — authenticate, fund, send, trade, bazaar, pay, monetize, query onchain-/plugin install three-ws-developer@three-ws # scaffold agents, configure MCP, runnable code examples-/plugin install three-ws-pump-fun@three-ws # create coins, swap, creator fees, tokenize agents, live avatar reactions-/plugin install three-ws-3d@three-ws # text→3D (free), text→avatar, mesh forge, auto-rig + scene/avatar MCP-```+### Installation and Setup-Run `/reload-plugins` and the skills appear under each plugin's namespace (e.g. `/three-ws-3d:forge-3d`). Plugins that expose MCP tools (`three-ws-developer`, `three-ws-3d`) wire the published `@three-ws/*` MCP servers automatically — `forge_free` is free (no wallet); the paid lanes settle over x402 in USDC. The canonical manifest lives at [.claude-plugin/marketplace.json](.claude-plugin/marketplace.json).+1. **Clone the repository**:+ ```bash+ git clone https://github.com/nirholas/three.ws.git+ cd three.ws+ ```+2. **Install dependencies**:+ ```bash+ npm install+ ```+3. **Set up environment variables**:+ Copy the `.env.example` file to `.env.local` and fill in the required values. See the [Environment Variables](#environment-variables) section for more details.+ ```bash+ cp .env.example .env.local+ ```+4. **Initialize the database**:+ The schema is idempotent. Run it against your Postgres instance to create all tables:+ ```bash+ psql $DATABASE_URL < api/_lib/schema.sql+ ```+5. **Run the development server**:+ ```bash+ npm run dev+ ```+ The application will be available at `http://localhost:3000`.----## Cloud Marketplaces--three.ws is available on major cloud marketplaces and open to infrastructure partnerships.--| Cloud | Status |-| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| **AWS** | **AWS Partner** (APN Software Path). AWS Marketplace SaaS listing in review — see [docs/aws-marketplace.md](docs/aws-marketplace.md) and the public partner page at [three.ws/aws](https://three.ws/aws). Part of the stack runs on AWS `us-east-1` — the Forge sculptor Lambda (`three-ws-forge`) and the S3 avatar bucket — registered in AWS MyApplications under account `155407237916` (the main app runs on Google Cloud Run). |-| **Alibaba Cloud** | Live: [product listing →](https://marketplace.alibabacloud.com/products/56724001/sgcmfw00036800.html) · [storefront →](https://marketplace.alibabacloud.com/store/3247293.html) |-| **Google Cloud** | Production runs on **Google Cloud Run** (`three-ws-api`, `us-central1`) fronted by a global HTTPS load balancer + Cloud CDN, with all 100 scheduled jobs on Cloud Scheduler and GPU inference workers on Cloud Run — a natural fit for GCP's AI infrastructure and Vertex AI. Open to co-listing, credits, and joint GTM. |--## Ecosystem Directories+## Examples-three.ws is indexed in chain-ecosystem dApp directories so the community can discover, vet, and rank it.+Copy-paste ready snippets for the most common use cases. Swap in your own GLB URL and go.-| Directory | Status |-| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |-| **BNB Chain · Dappbay** | Live: [dappbay.bnbchain.org/detail/three →](https://dappbay.bnbchain.org/detail/three) — categories: AI Agent Launchpad · AI Data · AI Infra |+### 1. Minimal viewer (no AI)------## IBM watsonx & Granite--three.ws is an **IBM Business Partner**, and the agent runtime runs on **IBM Granite** foundation models served through **IBM watsonx.ai**. One IBM Cloud API key + project unlocks the whole suite; every call is real inference (no mock path — endpoints return `503` when unconfigured). Full docs: **[docs/ibm.md](docs/ibm.md)**. Live showcase: **[three.ws/ibm/galaxy](https://three.ws/ibm/galaxy)**.--> **The public showcase is not the partnership.** The demos under `/ibm/*` are independent tools three.ws built for developers to explore Granite on watsonx.ai and build their own integrations — they are not official IBM partnership deliverables, not IBM products, and not endorsed by IBM. Our formal partnership work with IBM is being built on the IBM platform and is not yet public.--| Granite model | Where it runs |-| ------------- | ------------- |-| `granite-3-8b-instruct` | Selectable avatar **brain** + all narration |-| `granite-guardian-3-8b` | **Trust Layer** — allow/review/block governance gate, inline in `/api/chat` before an avatar moves value |-| `granite-ttm-512/1024/1536-96-r2` | **TimeSeries** forecasting (Oracle, Twin, Proof) |-| `granite-embedding-278m-multilingual` | **Semantic** agent map + `/api/watsonx/embed` |-| `granite-vision-3-2-2b` | **Vision** — reads an avatar into a full agent identity |--Six showcase surfaces put it on screen, cross-linked by an in-page suite switcher: the [Agent Galaxy](https://three.ws/ibm/galaxy) (semantic 3D star-map), the [Granite Oracle](https://three.ws/ibm/oracle) (narrated forecast), the [Digital Twin](https://three.ws/ibm/twin) (back-test + what-if), the [Trust Layer](https://three.ws/ibm/trust-layer) (Guardian + hash-chained audit ledger), [Granite Proof](https://three.ws/ibm/proof) (a Guardian-governed forecast notarized on Solana), and [Granite Vision](https://three.ws/ibm/vision). The standalone connector [`@three-ws/ibm-watsonx-mcp`](packages/ibm-watsonx-mcp/) exposes watsonx.ai to any MCP host — it is community-built and not an IBM product; the hosted platform integration is what runs on IBM watsonx.ai.--### Pay-per-call Granite over MCP (x402)--The world's first **x402-enabled MCP server on IBM Cloud**: [`@three-ws/ibm-x402-mcp`](packages/ibm-x402-mcp/) turns IBM Granite into a metered utility any AI agent can call. The operator holds the IBM credentials and funds inference; the caller pays **a few cents of USDC per call** — no IBM Cloud account, no subscription, no API-key signup. Full guide: **[docs/ibm-x402-mcp.md](docs/ibm-x402-mcp.md)**.--| Tool | What it does | Price |-| ---- | ------------ | ----- |-| `ibm_granite_chat` | Conversational AI — Q&A, drafting, reasoning | $0.02 |-| `ibm_granite_code` | Generate / review / refactor / explain / test / document code | $0.025 |-| `ibm_granite_embed` | Batch text embeddings (1–64) for RAG, search, clustering | $0.005 |-| `ibm_granite_analyze` | Structured doc analysis — entities, sentiment, risk, next steps | $0.04 |-| `ibm_granite_forecast` | Zero-shot time-series forecasting via Granite TTM | $0.05 |--The same five tools ship over two transports: **stdio** (`npx @three-ws/ibm-x402-mcp`, for Claude Desktop / Code / Cursor, paid on Solana) and **Streamable HTTP** (`https://three.ws/api/ibm-mcp`, for hosted clients and watsonx Orchestrate, paid on Base or Solana). An unpaid `tools/call` returns a `402` quoting the exact USDC price; x402-capable clients pay and retry automatically, settling on-chain only after the tool succeeds. Independent project integrating IBM Granite via watsonx.ai — not an IBM product.-------## Screenshots--| Viewer | Widget Studio |-| ---------------------------------------- | ----------------------------------------------- |-|  |  |--| Agent Discovery | Avatar Creation |-| -------------------------------------------- | ---------------------------------------- |-|  |  |-------## Architecture--The platform is organized into four layers. All layers communicate through a single event bus (`agent-protocol`) rather than direct calls.--```-┌────────────────────────────────────────────────────────────┐-│ Layer 4: Embed & Distribution │-│ <agent-3d> web component · CDN library · 5 widget types │-│ Widget Studio · oEmbed · Open Graph cards │-└────────────────────────────────────────────────────────────┘- ↓ protocol events-┌────────────────────────────────────────────────────────────┐-│ Layer 3: Identity & Persistence │-│ Agent passport · ERC-8004 (EVM) + Metaplex Core (Solana) │-│ Signed action log · Memory store · Cross-chain SIWX │-└────────────────────────────────────────────────────────────┘- ↓ protocol events-┌────────────────────────────────────────────────────────────┐-│ Layer 2: Agent Runtime │-│ LLM tool-loop · Built-in tools · Skill registry │-│ Empathy Layer (emotion blending) · TTS/STT │-└────────────────────────────────────────────────────────────┘- ↓ protocol events-┌────────────────────────────────────────────────────────────┐-│ Layer 1: Viewer │-│ three.js r184 · glTF / GLB · Draco / KTX2 / Meshopt │-│ Animations · Morph targets · HDR · Validation │-└────────────────────────────────────────────────────────────┘-```--The event bus decouples every component. The avatar emotion system reacts to `speak` events without knowing the runtime exists. The identity module records actions without knowing the UI exists. This makes the system testable, embeddable in isolation, and composable across pages.--The backend is stateless serverless functions. All persistent state lives in Postgres (Neon), object storage (Cloudflare R2), or on-chain. Cron jobs handle scheduled blockchain operations (ERC-8004 crawl, DCA execution, subscription execution).--### Design Docs & Specs--The architecture above is the bird's-eye view; each load-bearing surface has a dedicated spec that defines its wire format, invariants, and extension points. New contributors should skim the spec for any subsystem they're about to change.--| Spec | What it covers |-| ------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------- |-| [specs/AGENT_MANIFEST.md](specs/AGENT_MANIFEST.md) | Agent manifest JSON schema — body, brain, voice, memory, skills, signing. The contract every `<agent-3d>` reads. |-| [specs/3D_AGENT_CARD.md](specs/3D_AGENT_CARD.md) | The on-chain passport card layout — fields, signing, and rendering rules. |-| [specs/SKILL_SPEC.md](specs/SKILL_SPEC.md) | Skill bundle layout (`SKILL.md`, `tools.json`, `handlers.js`), trust modes, and distribution. |-| [specs/PERMISSIONS_SPEC.md](specs/PERMISSIONS_SPEC.md) | EIP-7710 delegated permissions model — capability scopes, redemption, revocation. |-| [specs/MEMORY_SPEC.md](specs/MEMORY_SPEC.md) | Memory file format, types, salience model, and storage modes. |-| [specs/STAGE_SPEC.md](specs/STAGE_SPEC.md) | Scene/stage configuration: camera presets, lighting, environment maps, hotspots. |-| [specs/EDITOR_SPEC.md](specs/EDITOR_SPEC.md) | Widget Studio + Embed Editor configuration surface and persistence shape. |-| [specs/EMBED_SPEC.md](specs/EMBED_SPEC.md) | The `<agent-3d>` element and chromeless iframe — attributes, JS API, and lifecycle. |-| [specs/EMBED_HOST_PROTOCOL.md](specs/EMBED_HOST_PROTOCOL.md) | `postMessage` wire protocol between the iframe and its host page (origin lock, message kinds, RTT). |-| [specs/CLAUDE_ARTIFACT.md](specs/CLAUDE_ARTIFACT.md) | Claude Artifact viewer integration — snippet loading and sandbox boundaries. |-| [specs/ENS_AGENT_CLAIM.md](specs/ENS_AGENT_CLAIM.md) | ENS-based agent claim flow for verifiable owner ↔ agent binding. |-| [specs/VALIDATORS.md](specs/VALIDATORS.md) | Validator attestation rules — what gets signed, who can sign, how to read attestations. |-| [specs/SECURITY.md](specs/SECURITY.md) | Threat model, trust boundaries, and the hardening checklist for production deployments. |--Longer-form architecture and how-to documentation lives under [docs/](docs/): [docs/architecture.md](docs/architecture.md), [docs/agent-system.md](docs/agent-system.md), [docs/3d-asset-pipeline.md](docs/3d-asset-pipeline.md), [docs/animations.md](docs/animations.md), [docs/web-component.md](docs/web-component.md), [docs/api-reference.md](docs/api-reference.md), [docs/mcp.md](docs/mcp.md), [docs/permissions.md](docs/permissions.md), [docs/security.md](docs/security.md), [docs/smart-contracts.md](docs/smart-contracts.md), and more.--### 3D asset pipeline — FBX, GLB, JSON--Every avatar the site renders is a **GLB** (binary glTF 2.0 — the body, rig, and textures in one file); every shared gesture and dance is a format-light **clip JSON** (a serialized `THREE.AnimationClip` — motion only, retargeted onto any rig at runtime); and both originate as **FBX** source from Mixamo or a DCC tool. Two conversions come off one FBX — `npm run convert:fbx` for a full character GLB, `npm run build:animations` for a reusable library clip — then `npm run optimize:glb` makes it web-ready (~90% smaller). The full explainer, format specs, runtime modules, and the generate→rig→animate→export capability chain are in **[docs/3d-asset-pipeline.md](docs/3d-asset-pipeline.md)**.-------## Tech Stack--**Frontend**--- **Main UI**: The core application, including the 3D viewer, agent creation, and marketplace, is built with vanilla JavaScript modules and Vite.-- **Chat**: The chat interface is a standalone Svelte application located in the `chat/` directory.-- **3D Rendering**: three.js (r184) is used for WebGL 2.0 rendering.--**Backend (Google Cloud Run)**--- **Runtime**: Node.js — serverless-style handlers in `api/` served by one Express container ([server/index.mjs](server/index.mjs)) on Cloud Run (`three-ws-api`, `us-central1`).-- **Database**: Neon Postgres (serverless)-- **Storage**: Cloudflare R2 for model and avatar storage.-- **Rate Limiting**: Upstash Redis.-- **LLM**: The agent's brain is powered by the Anthropic (Claude) SDK.--**Smart Contracts**--- **Language**: Solidity 0.8+-- **Framework**: Foundry for compiling, testing, and deploying the ERC-8004 contracts.-- **Standards**: ERC-721, EIP-712, EIP-7710.--### Browser Support--The viewer targets every browser that ships WebGL 2.0 on a desktop or modern mobile device. Concrete support matrix:--| Browser | Minimum | Notes |-| ------------------------ | --------- | ------------------------------------------------------------------------------------------------------------------ |-| Chrome / Edge (Chromium) | 113+ | Full feature set including WebGPU experiments behind a flag. Recommended for development. |-| Safari (macOS / iOS) | 16.4+ | WebGL 2.0, Web Speech recognition (iOS 16.4 added support behind a permission prompt). Voice input requires HTTPS. |-| Firefox | 115+ | KTX2 / Meshopt decoders all supported. Web Speech recognition is feature-gated by user-locale. |-| Mobile Safari | iOS 16.4+ | Touch controls and gyroscope mapped through `OrbitControls`. |-| Android Chrome | 113+ | Full feature set; AR button surfaces a Scene Viewer intent when present. |--**Capabilities and graceful degradation**--- **WebGL 2.0** is required; the viewer refuses to boot without it and shows a fallback message.-- **WebAssembly** is required for the Draco / KTX2 / Meshopt decoders that are copied into `public/three/draco/` and `public/three/basis/` by `scripts/copy-three-decoders.mjs` on `postinstall` (both paths are generated and gitignored, so they only exist after `npm install`), plus `node_modules/three/examples/jsm/libs/`.-- **`getUserMedia` (microphone)** requires HTTPS — see [Common gotchas](#common-gotchas). Without it the agent falls back to text input.-- **`speechSynthesis`** is detected at runtime; agents fall back to silent text replies when TTS is unavailable.-- **WebGPU** is not required and is not used yet — Phase 4 reserves it for client-side inference experiments.-------## Getting Started--### Prerequisites--- Node.js 24+ (the project pins `"engines.node": "24.x"` in `package.json`; earlier majors are not tested)-- npm 10+-- A Neon Postgres database-- A Cloudflare R2 bucket-- An Anthropic API key--### Installation and Setup--1. **Clone the repository**:- ```bash- git clone https://github.com/nirholas/three.ws.git- cd three.ws- ```-2. **Install dependencies**:- ```bash- npm install- ```-3. **Set up environment variables**:- Copy the `.env.example` file to `.env.local` and fill in the required values. See the [Environment Variables](#environment-variables) section for more details.- ```bash- cp .env.example .env.local- ```-4. **Initialize the database**:- The schema is idempotent. Run it against your Postgres instance to create all tables:- ```bash- psql $DATABASE_URL < api/_lib/schema.sql- ```-5. **Run the development server**:- ```bash- npm run dev- ```- The application will be available at `http://localhost:3000`.-------## Examples--Copy-paste ready snippets for the most common use cases. Swap in your own GLB URL and go.--### 1. Minimal viewer (no AI)--The simplest possible setup — one script tag, one element, zero build step.+The simplest possible setup — one script tag, one element, zero build step.```html<!doctype html>@@ -9340,42 +9032,148 @@ For sandboxed iframes use the widget embed path instead — it runs in its own b----## Project Structure--- `src/`: The core frontend JavaScript for the main application, including the 3D viewer, agent protocol, custom element, and feature modules (`club-*.js`, `walk*.js`, `pose-*.js`, `voice/`, `selfie-*.js`). Social/gameplay surfaces live in `game/` (Coin Communities: `coincommunities*`, `spin-wheel-ui`, `cosmetics-visual`, `avatar-rig`), `city/` (the `/city` world), `social/` (sentiment, X-post impact), `community/` (coin lobby/town), plus `friends.js`, `communities.js`, `marketplace*.js`, and `token-pay.js`.-- `api/`: Serverless-style handlers that form the backend API, served in production by the Cloud Run container ([server/index.mjs](server/index.mjs)) with `vercel.json`-parity routing. Subdirectories include `x402/`, `a2a/`, `club/`, `pump/`, `persona/`, `news/`, `admin/`, `agents/`, `auth/`, `oauth/`, `cron/`, plus the social/game surfaces `play/`, `token/`, `three-token/`, `friends/`, `social/`, `community/`, `marketplace/`, and `mocap/`.-- `public/`: Static assets and various sub-applications (`club/`, `seeker/`, `news/`, `persona/`, `vanity-wallet.html`, `pumpfun.html`).-- `chat/`: A standalone Svelte application for the chat interface.-- `character-studio/`: A sub-project for in-browser character creation; also serves the rebranded **Avatar Studio** marketplace.-- `rider/`: A-Frame WebVR music visualization experiment.-- `contracts/`: Solidity smart contracts for on-chain identity (ERC-8004) and the multichain payment factory.-- `multiplayer/`: Colyseus WebSocket server for `/walk` and `/play` (WalkRoom); deployable on Fly.io. Holds the authoritative world logic and single sources of truth — `items.js`, `playerStore.js`, `game-token.js`, `play-pass.js`, `holder-pass.js`, and the per-account `social-hub.js`.-- `sdk/`: `@three-ws/sdk` (the AgentKit SDK; the legacy avatar helpers live in `sdk/agent-sdk/`).-- `agent-payments-sdk/`: EVM agent payments SDK (Base / BSC / other EVM chains).-- `solana-agent-sdk/`: SDK for Solana blockchain interactions (Metaplex Core mints, SIWS, attestations).-- `pump-fun-skills/`: Skills related to the pump.fun integration.-- `scripts/`: Node.js scripts for development, build, deployment, and pump.fun launch automation.-- `workers/`: Code for background workers — includes the Cloudflare Worker mirror of the pump.fun MCP read API in [`workers/pump-fun-mcp/`](workers/pump-fun-mcp/).-- `docs/`: Public-facing developer docs.-- `docs/internal/`: Working docs (PLAN, STATUS, TODO, NEXT, PROGRESS, RELEASE_CHECKLIST, club venue notes) — not part of the published docs surface.-- `tests/`: Vitest unit tests (`tests/api/`, `tests/src/`, `tests/workers/`) and Playwright end-to-end smokes (`tests/e2e/`).+## Architecture----+The platform is organized into four layers. All layers communicate through a single event bus (`agent-protocol`) rather than direct calls.-## The Agent System+```+┌────────────────────────────────────────────────────────────┐+│ Layer 4: Embed & Distribution │+│ <agent-3d> web component · CDN library · 5 widget types │+│ Widget Studio · oEmbed · Open Graph cards │+└────────────────────────────────────────────────────────────┘+ ↓ protocol events+┌────────────────────────────────────────────────────────────┐+│ Layer 3: Identity & Persistence │+│ Agent passport · ERC-8004 (EVM) + Metaplex Core (Solana) │+│ Signed action log · Memory store · Cross-chain SIWX │+└────────────────────────────────────────────────────────────┘+ ↓ protocol events+┌────────────────────────────────────────────────────────────┐+│ Layer 2: Agent Runtime │+│ LLM tool-loop · Built-in tools · Skill registry │+│ Empathy Layer (emotion blending) · TTS/STT │+└────────────────────────────────────────────────────────────┘+ ↓ protocol events+┌────────────────────────────────────────────────────────────┐+│ Layer 1: Viewer │+│ three.js r184 · glTF / GLB · Draco / KTX2 / Meshopt │+│ Animations · Morph targets · HDR · Validation │+└────────────────────────────────────────────────────────────┘+```-### Event Bus (Agent Protocol)+The event bus decouples every component. The avatar emotion system reacts to `speak` events without knowing the runtime exists. The identity module records actions without knowing the UI exists. This makes the system testable, embeddable in isolation, and composable across pages.-`src/agent-protocol.js` implements a lightweight `EventTarget` subclass that is the nervous system of the platform. Every component — avatar, runtime, identity, UI — communicates exclusively through this bus. There are no direct method calls between layers.+The backend is stateless serverless functions. All persistent state lives in Postgres (Neon), object storage (Cloudflare R2), or on-chain. Cron jobs handle scheduled blockchain operations (ERC-8004 crawl, DCA execution, subscription execution).-The bus maintains a 200-action ring buffer for debugging and replay. Embed variants expose a filtered subset of events through `postMessage` to the host page.+### Design Docs & Specs-**Core event types:**+The architecture above is the bird's-eye view; each load-bearing surface has a dedicated spec that defines its wire format, invariants, and extension points. New contributors should skim the spec for any subsystem they're about to change.-| Event | Payload | Who emits | Who listens |-| ------------------------- | ---------------------------------------- | --------------- | ----------------------------------------- |-| `speak` | `{ text, sentiment: -1..1 }` | runtime, skills | avatar (emotion), identity (log), chat UI |-| `think` | `{ thought }` | runtime | home (timeline), avatar |+| Spec | What it covers |+| ------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------- |+| [specs/AGENT_MANIFEST.md](specs/AGENT_MANIFEST.md) | Agent manifest JSON schema — body, brain, voice, memory, skills, signing. The contract every `<agent-3d>` reads. |+| [specs/3D_AGENT_CARD.md](specs/3D_AGENT_CARD.md) | The on-chain passport card layout — fields, signing, and rendering rules. |+| [specs/SKILL_SPEC.md](specs/SKILL_SPEC.md) | Skill bundle layout (`SKILL.md`, `tools.json`, `handlers.js`), trust modes, and distribution. |+| [specs/PERMISSIONS_SPEC.md](specs/PERMISSIONS_SPEC.md) | EIP-7710 delegated permissions model — capability scopes, redemption, revocation. |+| [specs/MEMORY_SPEC.md](specs/MEMORY_SPEC.md) | Memory file format, types, salience model, and storage modes. |+| [specs/STAGE_SPEC.md](specs/STAGE_SPEC.md) | Scene/stage configuration: camera presets, lighting, environment maps, hotspots. |+| [specs/EDITOR_SPEC.md](specs/EDITOR_SPEC.md) | Widget Studio + Embed Editor configuration surface and persistence shape. |+| [specs/EMBED_SPEC.md](specs/EMBED_SPEC.md) | The `<agent-3d>` element and chromeless iframe — attributes, JS API, and lifecycle. |+| [specs/EMBED_HOST_PROTOCOL.md](specs/EMBED_HOST_PROTOCOL.md) | `postMessage` wire protocol between the iframe and its host page (origin lock, message kinds, RTT). |+| [specs/CLAUDE_ARTIFACT.md](specs/CLAUDE_ARTIFACT.md) | Claude Artifact viewer integration — snippet loading and sandbox boundaries. |+| [specs/ENS_AGENT_CLAIM.md](specs/ENS_AGENT_CLAIM.md) | ENS-based agent claim flow for verifiable owner ↔ agent binding. |+| [specs/VALIDATORS.md](specs/VALIDATORS.md) | Validator attestation rules — what gets signed, who can sign, how to read attestations. |+| [specs/SECURITY.md](specs/SECURITY.md) | Threat model, trust boundaries, and the hardening checklist for production deployments. |++Longer-form architecture and how-to documentation lives under [docs/](docs/): [docs/architecture.md](docs/architecture.md), [docs/agent-system.md](docs/agent-system.md), [docs/3d-asset-pipeline.md](docs/3d-asset-pipeline.md), [docs/animations.md](docs/animations.md), [docs/web-component.md](docs/web-component.md), [docs/api-reference.md](docs/api-reference.md), [docs/mcp.md](docs/mcp.md), [docs/permissions.md](docs/permissions.md), [docs/security.md](docs/security.md), [docs/smart-contracts.md](docs/smart-contracts.md), and more.++### 3D asset pipeline — FBX, GLB, JSON++Every avatar the site renders is a **GLB** (binary glTF 2.0 — the body, rig, and textures in one file); every shared gesture and dance is a format-light **clip JSON** (a serialized `THREE.AnimationClip` — motion only, retargeted onto any rig at runtime); and both originate as **FBX** source from Mixamo or a DCC tool. Two conversions come off one FBX — `npm run convert:fbx` for a full character GLB, `npm run build:animations` for a reusable library clip — then `npm run optimize:glb` makes it web-ready (~90% smaller). The full explainer, format specs, runtime modules, and the generate→rig→animate→export capability chain are in **[docs/3d-asset-pipeline.md](docs/3d-asset-pipeline.md)**.++---++## Tech Stack++**Frontend**++- **Main UI**: The core application, including the 3D viewer, agent creation, and marketplace, is built with vanilla JavaScript modules and Vite.+- **Chat**: The chat interface is a standalone Svelte application located in the `chat/` directory.+- **3D Rendering**: three.js (r184) is used for WebGL 2.0 rendering.++**Backend (Google Cloud Run)**++- **Runtime**: Node.js — serverless-style handlers in `api/` served by one Express container ([server/index.mjs](server/index.mjs)) on Cloud Run (`three-ws-api`, `us-central1`).+- **Database**: Neon Postgres (serverless)+- **Storage**: Cloudflare R2 for model and avatar storage.+- **Rate Limiting**: Upstash Redis.+- **LLM**: The agent's brain is powered by the Anthropic (Claude) SDK.++**Smart Contracts**++- **Language**: Solidity 0.8++- **Framework**: Foundry for compiling, testing, and deploying the ERC-8004 contracts.+- **Standards**: ERC-721, EIP-712, EIP-7710.++### Browser Support++The viewer targets every browser that ships WebGL 2.0 on a desktop or modern mobile device. Concrete support matrix:++| Browser | Minimum | Notes |+| ------------------------ | --------- | ------------------------------------------------------------------------------------------------------------------ |+| Chrome / Edge (Chromium) | 113+ | Full feature set including WebGPU experiments behind a flag. Recommended for development. |+| Safari (macOS / iOS) | 16.4+ | WebGL 2.0, Web Speech recognition (iOS 16.4 added support behind a permission prompt). Voice input requires HTTPS. |+| Firefox | 115+ | KTX2 / Meshopt decoders all supported. Web Speech recognition is feature-gated by user-locale. |+| Mobile Safari | iOS 16.4+ | Touch controls and gyroscope mapped through `OrbitControls`. |+| Android Chrome | 113+ | Full feature set; AR button surfaces a Scene Viewer intent when present. |++**Capabilities and graceful degradation**++- **WebGL 2.0** is required; the viewer refuses to boot without it and shows a fallback message.+- **WebAssembly** is required for the Draco / KTX2 / Meshopt decoders that are copied into `public/three/draco/` and `public/three/basis/` by `scripts/copy-three-decoders.mjs` on `postinstall` (both paths are generated and gitignored, so they only exist after `npm install`), plus `node_modules/three/examples/jsm/libs/`.+- **`getUserMedia` (microphone)** requires HTTPS — see [Common gotchas](#common-gotchas). Without it the agent falls back to text input.+- **`speechSynthesis`** is detected at runtime; agents fall back to silent text replies when TTS is unavailable.+- **WebGPU** is not required and is not used yet — Phase 4 reserves it for client-side inference experiments.++---++## Project Structure++- `src/`: The core frontend JavaScript for the main application, including the 3D viewer, agent protocol, custom element, and feature modules (`club-*.js`, `walk*.js`, `pose-*.js`, `voice/`, `selfie-*.js`). Social/gameplay surfaces live in `game/` (Coin Communities: `coincommunities*`, `spin-wheel-ui`, `cosmetics-visual`, `avatar-rig`), `city/` (the `/city` world), `social/` (sentiment, X-post impact), `community/` (coin lobby/town), plus `friends.js`, `communities.js`, `marketplace*.js`, and `token-pay.js`.+- `api/`: Serverless-style handlers that form the backend API, served in production by the Cloud Run container ([server/index.mjs](server/index.mjs)) with `vercel.json`-parity routing. Subdirectories include `x402/`, `a2a/`, `club/`, `pump/`, `persona/`, `news/`, `admin/`, `agents/`, `auth/`, `oauth/`, `cron/`, plus the social/game surfaces `play/`, `token/`, `three-token/`, `friends/`, `social/`, `community/`, `marketplace/`, and `mocap/`.+- `public/`: Static assets and various sub-applications (`club/`, `seeker/`, `news/`, `persona/`, `vanity-wallet.html`, `pumpfun.html`).+- `chat/`: A standalone Svelte application for the chat interface.+- `character-studio/`: A sub-project for in-browser character creation; also serves the rebranded **Avatar Studio** marketplace.+- `rider/`: A-Frame WebVR music visualization experiment.+- `contracts/`: Solidity smart contracts for on-chain identity (ERC-8004) and the multichain payment factory.+- `multiplayer/`: Colyseus WebSocket server for `/walk` and `/play` (WalkRoom); deployable on Fly.io. Holds the authoritative world logic and single sources of truth — `items.js`, `playerStore.js`, `game-token.js`, `play-pass.js`, `holder-pass.js`, and the per-account `social-hub.js`.+- `sdk/`: `@three-ws/sdk` (the AgentKit SDK; the legacy avatar helpers live in `sdk/agent-sdk/`).+- `agent-payments-sdk/`: EVM agent payments SDK (Base / BSC / other EVM chains).+- `solana-agent-sdk/`: SDK for Solana blockchain interactions (Metaplex Core mints, SIWS, attestations).+- `pump-fun-skills/`: Skills related to the pump.fun integration.+- `scripts/`: Node.js scripts for development, build, deployment, and pump.fun launch automation.+- `workers/`: Code for background workers — includes the Cloudflare Worker mirror of the pump.fun MCP read API in [`workers/pump-fun-mcp/`](workers/pump-fun-mcp/).+- `docs/`: Public-facing developer docs.+- `docs/internal/`: Working docs (PLAN, STATUS, TODO, NEXT, PROGRESS, RELEASE_CHECKLIST, club venue notes) — not part of the published docs surface.+- `tests/`: Vitest unit tests (`tests/api/`, `tests/src/`, `tests/workers/`) and Playwright end-to-end smokes (`tests/e2e/`).++---++## The Agent System++### Event Bus (Agent Protocol)++`src/agent-protocol.js` implements a lightweight `EventTarget` subclass that is the nervous system of the platform. Every component — avatar, runtime, identity, UI — communicates exclusively through this bus. There are no direct method calls between layers.++The bus maintains a 200-action ring buffer for debugging and replay. Embed variants expose a filtered subset of events through `postMessage` to the host page.++**Core event types:**++| Event | Payload | Who emits | Who listens |+| ------------------------- | ---------------------------------------- | --------------- | ----------------------------------------- |+| `speak` | `{ text, sentiment: -1..1 }` | runtime, skills | avatar (emotion), identity (log), chat UI |+| `think` | `{ thought }` | runtime | home (timeline), avatar || `gesture` | `{ name, duration }` | avatar, skills | avatar (one-shot clip) || `emote` | `{ trigger, weight: 0..1 }` | avatar | avatar (emotion inject) || `look-at` | `{ target: 'user'\|'camera'\|'center' }` | skills | scene controller |@@ -9587,6 +9385,24 @@ const restored = Memory.fromSnapshot(JSON.parse(sessionStorage.getItem('agent-me---+## Animation System++The avatar runtime ships with a slot-based animation manager that decouples animation clips from rigs — a clip authored for one body can be retargeted to any other rig at load time.++| Module | Path | Role |+| ------------- | ---------------------------------------------------------------- | --------------------------------------------------------------------- |+| Manager | [src/animation-manager.js](src/animation-manager.js) | Load, blend, and crossfade clips per slot (idle, gesture, locomotion) |+| State machine | [src/animation-state-machine.js](src/animation-state-machine.js) | Drives slot transitions from protocol events |+| Idle library | [src/idle-animation.js](src/idle-animation.js) | Subtle breath / weight-shift loops that play under everything else |+| Fetcher | `npm run fetch-animations` | Downloads the canonical clip library from R2 |+| Builder | `scripts/build-animations.mjs` | Re-packs clip bundles into Meshopt + Draco-compressed GLB |++A new clip can be authored against any rig in Blender, exported as a GLB, and dropped into the animation library — the manager picks it up automatically and the agent runtime can invoke it via the `play_clip` tool.++The **`sitidle` clip** is shipped as the default seated idle for chat-mode avatars; the **gemini-jump clip** drives the hero on `/`.++---+## Web Component & EmbeddingThe `<agent-3d>` custom element (`src/element.js`) is the primary distribution mechanism. It lazy-boots on intersection (IntersectionObserver), so off-screen agents don't load until visible.@@ -9733,6 +9549,32 @@ Poses author cleanly into the avatar runtime via the `play_clip` tool — the ag---+## Avatar Accessories & Coin Launchpad++Avatars are not just GLB files — they're composable rigs that the runtime can decorate with onchain accessories.++### Accessories++- Hats, glasses, props attached to named bone slots via [src/agent-accessories.js](src/agent-accessories.js)+- Accessories are themselves ERC-1155 tokens, ownable and tradeable independently of the avatar+- Equipping is non-destructive — the agent's base manifest stays unchanged, the accessory is layered at runtime++### Coin Launchpad++Every agent can mint a coin alongside its avatar — turning the agent into a tradeable economic object.++| Surface | Path | Purpose |+| ---------------- | ---------------------------- | ------------------------------------------------------------------ |+| Launchpad Studio | `/launchpad` | Configure coin name, ticker, supply, fee shares |+| Hosted page | `/p/[slug]` | Public launch page with `<agent-3d>` widget + buy button |+| Avatar coin drop | `public/demo/coin/` | Demo flow — connect wallet → mint avatar + coin in one transaction |+| Pump.fun bridge | `POST /api/pump/launch-prep` | Route the launch through pump.fun's bonding curve |+| Direct mint | `contracts/script/` | Deploy a standalone ERC-20 / SPL-22 alongside the agent |++The coin's metadata points back at the agent's onchain identity — ERC-8004 token on EVM or Metaplex Core asset on Solana — and the agent's manifest references the coin. The two-way binding is read from the bazaar, marketplace, and reputation registry on either chain.++---+## LaunchpadThe **Launchpad** at `/launchpad` is a hosted-page builder for token launches, agent debuts, and drop campaigns. Each published page lives at a public URL like `/p/<slug>` with full Open Graph metadata for sharing.@@ -9839,107 +9681,6 @@ Two creator tools sit alongside [Pose Studio](#pose-studio):----## x402 Payments--three.ws is a first-class [x402](https://x402.org) host. Agents can both **pay for** and **expose** paid endpoints. Settlement runs on Base, BSC, and Solana; the bazaar at `/x402` is the discovery surface.--### Payment rails--| Chain | Settlement | Permit2 sibling | Status |-| ------------------- | ------------------------------ | ------------------- | ------ |-| **Base mainnet** | Coinbase CDP facilitator | Gasless via relayer | Live |-| **Base sepolia** | CDP facilitator | Yes | Live |-| **BSC** | Direct-scheme (no facilitator) | — | Live |-| **Solana (devnet)** | x402-solana direct | — | Live |--Every CDP-settled endpoint ships a Permit2 sibling that accepts an EIP-2612 permit instead of an upfront approval — the buyer signs once, and the relayer pays gas. Wire-level checks live in `tests/e2e/` and exercise the buyer/seller flow end-to-end.--### Paid endpoints--| Route | What you get |-| ---------------------------------------- | --------------------------------------------- |-| `POST /api/x402/mint-to-mesh` | Mint an avatar's mesh as an NFT |-| `POST /api/x402/mint-to-mesh-batch` | Batch mint up to N meshes |-| `POST /api/x402/dance-tip` | Tip a club dancer in USDC |-| `POST /api/x402/model-check` | Run Khronos glTF validation as a paid service |-| `POST /api/x402/pump-agent-audit` | Audit a pump.fun token's creator history |-| `POST /api/x402/agent-reputation` | Compute on-chain reputation snapshot |-| `POST /api/x402/onchain-identity-verify` | Verify ERC-8004 identity for a wallet |-| `POST /api/x402/symbol-availability` | Check token symbol availability across chains |-| `POST /api/x402/skill-marketplace` | Paid skill marketplace listing |-| `POST /api/x402/asset-download` | Pay-per-download for gated R2 assets |-| `POST /api/x402/did` | DID resolution as a service |-| `GET /api/x402/my-receipts` | Buyer-side receipts ledger |--### Bazaar, SKUs, and subscriptions--| Surface | Path | Purpose |-| ------------- | --------------------------------- | ------------------------------------------- |-| Bazaar | `/x402` | Browsable marketplace of paid endpoints |-| Discovery | `/x402-discover` | Search by tag, price, chain |-| Checkout | `/x402-pay`, `/api/x402-checkout` | Stripe-style one-shot purchase |-| SKU catalog | `/api/x402-skus` | Server-defined SKUs with per-row pricing |-| Dashboard | `/dashboard/x402` | Seller + buyer dashboard, receipts, payouts |-| Subscriptions | `/api/x402/subscriptions` | Recurring x402 charges on cron |-| Status | `/api/x402-status` | Health and chain reachability checks |--### How to expose a paid endpoint--```js-import { paidEndpoint } from './_lib/x402-paid-endpoint.js';--export default paidEndpoint({- price: '0.10', // USDC- chain: 'base', // base | bsc | solana- network: 'mainnet',- resource: 'https://three.ws/api/your-endpoint',- description: 'What the buyer is paying for',- handler: async (req, res, { payer }) => {- // payer is verified — settle the request- res.json({ ok: true, payer });- },-});-```--The helper handles the 402 challenge, Permit2 sibling, receipt write-back, idempotency-token enforcement, and CSRF/SSRF guards. See [api/\_lib/x402-paid-endpoint.js](api/_lib/x402-paid-endpoint.js).--### Wire checks--- Wire-level CORS, CDP, and Permit2 sibling checks: `tests/e2e/`-- Offer receipts schema + buyer fetch: [api/\_lib/x402-buyer-fetch.js](api/_lib/x402-buyer-fetch.js)-- Error envelope: full 402 body returned in the `PAYMENT-REQUIRED` header-------## A2A — Agent-to-Agent Protocol--Agents transact with each other directly through an A2A bridge that sits on top of the MCP server and x402 payments.--**How it works**--When agent A wants to call a paid tool from agent B:--1. **Discover** — A resolves B's DID via `POST /api/x402/did`, receiving B's MCP endpoint URL and payment wallet address.-2. **Call** — A sends a `tools/call` JSON-RPC request to B's MCP endpoint.-3. **Pay** — B's server returns `402 Payment Required` with a USDC price. A's SDK settles the x402 payment on-chain (Base or Solana) and retries with the payment proof in the `X-PAYMENT` header.-4. **Execute** — B verifies the payment, runs the tool, and writes a signed receipt to `api/a2a/receipts`.-5. **Ledger** — Both sides accumulate a row in `api/a2a/spending` — A for outbound spend, B for inbound revenue.--Agent wallets sign with **EIP-7710 delegated permissions** — the delegated signer acts on behalf of the agent's root key without ever exposing it.--| Surface | Path | Purpose |-| --------------- | -------------------- | -------------------------------------------------------- |-| A2A client | `sdk/a2a/` | Outbound calls — pay another agent, settle the response |-| A2A server | `api/a2a/` | Inbound paid tools, exposed via MCP bridge |-| MCP bridge | `api/mcp.js` | Wraps paid tools as MCP `tools/call` with auto-402 retry |-| Spending ledger | `api/a2a/spending` | Per-agent spend caps and authorization gates |-| Receipts store | `api/a2a/receipts` | Signed receipts written on every paid call |-| DID resolution | `POST /api/x402/did` | Resolve a counterparty DID to wallet + endpoints |--**SIWX (Sign-In with X-chain)** brokers cross-chain identity for paid sessions: an agent on Base proves ownership of a Solana wallet (or vice versa) to unlock chain-specific paid endpoints.------## Talk Mode & Lip-SyncThe `talk` interaction mode wires together the LLM runtime, ElevenLabs TTS, and an **audio-driven ARKit-52 lip-sync driver** that maps live audio amplitude + formant analysis onto the 52 standard ARKit blendshapes.@@ -9972,131 +9713,61 @@ The driver is source-agnostic: it accepts any `AudioBuffer`, so it works identic----## Solana Mobile (Seeker)--three.ws ships with Mobile Wallet Adapter (MWA) wired into the web app and a release pipeline for the Solana Mobile dApp Store.+## Demos Hub-**Wallet detection priority**+`/demos` is a curated index of sandbox pages that exercise individual platform capabilities in isolation. Each demo is a single HTML file in [`public/demos/`](public/demos/) — perfect for screen recordings, bug reproductions, or showing off one feature without the rest of the app.-On **Seeker / Saga** hardware the app prefers seed-vault-backed signing — private keys never leave the secure element. On standard Android or desktop, the app falls back through WalletConnect and then to browser-extension wallets automatically, with no code change required.--**What MWA unlocks on Seeker hardware**--- x402 USDC payments signed from the seed vault without any browser extension-- Metaplex Core agent mints (Solana on-chain registration) without leaving the app-- SPL Memo attestations (reputation and validation) with hardware-secured signatures-- SIWS (Sign-In with Solana) sessions authenticated at the chip level, not the software layer--**Release pipeline**--- dApp Store listing copy and release config live under [`solana-mobile/publish/`](solana-mobile/publish/)-- Release pipeline scripts handle build → sign → APK submission for dApp Store updates-- The listing targets Seeker-first and is compatible with Saga Gen 1 and Gen 2-------## Selfie Reconstruction Pipeline (Phase 1)--Anyone takes 3 selfies (left, center, right) and receives a rigged, animatable 3D avatar in under a minute. The pipeline ships native — no third-party black box.--| Module | Path | Role |-| ------------- | ------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------- |-| Capture UX | [src/selfie-capture.js](src/selfie-capture.js) | Mobile-first 3-shot capture with real-time quality gates (lighting, framing, blur) |-| Pipeline | [src/selfie-pipeline.js](src/selfie-pipeline.js) | Multi-view fit → FLAME / 3DMM face → base body mesh → rigged GLB |-| Sandbox route | `/creating` | Isolated reconstruction test bench, decoupled from the main flow |-| Output | Cloudflare R2 | Meshopt-compressed GLB pinned to IPFS and minted as a draft agent token — ERC-8004 on EVM or Metaplex Core on Solana |--Reconstruction inference runs against the same Cloud Run handler pool as the agent runtime, with optional offload to the **Livepeer Inference Network** (see below) for GPU-heavy steps.-------## Livepeer Inference Network (Phase 4)--three.ws is wiring the **Livepeer** decentralized GPU network as an alternative inference backend for avatar reconstruction and agent conversations.--- Open protocol: model weights, GPU runtime, signed responses-- Onchain settlement: pay-per-token with cryptographic receipts, mediated by the same x402 rails described above-- Node operator client (Docker + GPU drivers) with onchain registration-- Federation with existing decentralized compute networks where appropriate--The Livepeer dependency landed early so the Phase 1 selfie pipeline can switch its heaviest step (multi-view face fitting) onto external GPU nodes without touching the rest of the system. The goal: ≥50% of production agent traffic served by independent node operators with latency parity to centralized inference.-------## Voice & Persona Hub (Phase 2)--The avatar isn't just _you_ — the agent _acts_ like you. The Voice & Persona Hub captures the inputs that turn a body into a personality.--| Surface | Path | Purpose |-| ------------------- | -------------------------------------------------------------------- | ---------------------------------------------------------------- |-| Persona extraction | [api/persona/extract.js](api/persona/extract.js) | Short onboarding interview → tone, vocabulary, interests profile |-| Persona preview | [api/persona/preview.js](api/persona/preview.js) | Try the extracted persona against test prompts before saving |-| Persona keys | `scripts/generate-persona-key.mjs` | Per-agent signing key + persona SSO setup |-| Voice clone modal | [src/voice/voice-clone-modal.js](src/voice/voice-clone-modal.js) | 3–10s recording → ElevenLabs custom voice bound to the agent |-| Talk controller | [src/voice/talk-controller.js](src/voice/talk-controller.js) | Push-to-talk and continuous talk modes |-| ARKit blendshapes | [src/voice/arkit-blendshapes.js](src/voice/arkit-blendshapes.js) | Standard ARKit-52 morph table |-| Lip-sync driver | [src/voice/lipsync-driver.js](src/voice/lipsync-driver.js) | Web Audio analyser → blendshape weights per frame |-| Avatar morph target | [src/voice/avatar-morph-target.js](src/voice/avatar-morph-target.js) | Per-rig binding of ARKit blendshapes to the loaded GLB |-| Avatar snapshot | [src/voice/avatar-snapshot.js](src/voice/avatar-snapshot.js) | Render-time pose capture for thumbnails and OG cards |-| Persona docs | [docs/persona-hub.md](docs/persona-hub.md) | Full design + onboarding flow |--Memory seed extensions (X, GitHub, Farcaster) feed the agent's memory store at creation time with explicit user consent — see [docs/persona-hub.md](docs/persona-hub.md).--The per-agent fine-tuned system prompt is stored in the manifest, signed, and pinned to IPFS — the persona becomes a verifiable part of the agent's onchain identity.-------## WASM Vanity Grinder--`/vanity-wallet` is a browser-based vanity-address grinder compiled to WebAssembly. Generate **EVM addresses** with a prefix (`0xBEEF…`) or pattern, or **Solana addresses** (base58 prefix / suffix, e.g. `…pump`) in seconds, fully client-side, without leaking the private key to any server.--| Module | Path | Role |-| -------------- | ------------------------------- | ------------------------------------------------------ |-| WASM grinder | `public/vanity-wallet.html` | Multi-threaded secp256k1 keygen via WebWorkers |-| Solana variant | `scripts/pump-vanity-grind.mjs` | Server-side grinder for pump.fun mint vanity addresses |--Common use cases on the platform: branded agent wallet addresses (e.g. an agent named `agent.eth` getting an address starting with `0xA6EF…`), or pump.fun token mint vanity (e.g. ending in `pump`).+| Demo | Path | What it shows |+| ----------------------------------- | -------------------------------- | -------------------------------------------------------- |+| **USDZ & AR Quick Look** | `/demos/usdz-ar.html` | iOS USDZ export + AR Quick Look on a real device |+| **Half-body XR** | `/demos/halfbody-xr.html` | Upper-body avatar in WebXR (Meta Quest, Vision Pro) |+| **Avatar SDK** | `/demos/avatar-sdk.html` | `@three-ws/avatar` SDK loading + animating an avatar |+| **React SDK** | `/demos/react-sdk.html` | React wrapper around the `<agent-3d>` element |+| **Audio-driven lipsync (mic)** | `/lipsync/mic` | Live microphone → ARKit-52 lip-sync |+| **Audio-driven lipsync (TTS)** | `/lipsync` | ElevenLabs TTS → ARKit-52 lip-sync |+| **Multi-LLM brain** | `/brain` | Side-by-side comparison of Claude / GPT / Groq / Gemini |+| **ERC-8004 registry browser** | `/demos/erc8004.html` | Browse all registered agents across chains |+| **Button jump** | `/demos/button-jump.html` | Avatar reacts to a 2D button press |+| **Tactile button (Gemini concept)** | `/demos/gemini-jump.html` | Tactile button demo with avatar |+| **Create v2** | `/demos/create-v2.html` | Next-generation agent creation flow |+| **3D home** | `/demos/3d-home.html` | Home page with overlay canvas + transparent-bg viewer |+| **Selfie fit** | `/demos/selfie-fit.html` | Selfie reconstruction pipeline (Phase 1) |+| **Persona extract** | `/demos/persona-extract.html` | Voice & Persona Hub onboarding interview |+| **Memory seed** | `/demos/memory-seed.html` | Memory seeding from X/GitHub/Farcaster |+| **Voice clone** | `/demos/voice-clone.html` | 3–10s recording → ElevenLabs custom voice |+| **Livepeer inference** | `/demos/livepeer-inference.html` | Decentralized GPU inference end-to-end |+| **Skill royalty** | `/demos/skill-royalty.html` | Per-call royalty payouts to skill authors |+| **EAS reputation** | `/demos/eas-reputation.html` | EAS-attested reputation viewer |+| **Bonding curve** | `/demos/bonding-curve.html` | Pre-launch bonding-curve pricing simulator |+| **Gallery picker** | `/demos/gallery-picker.html` | Lazy 3D-thumbnail avatar picker (Embed Editor primitive) |+| **Button** | `/demos/button.html` | Minimal `<agent-3d>` embed reaction test |-The Solana grinder backs the platform's pump.fun launches — the inaugural USDC token launches use a vanity mint pre-grind to produce shareable token addresses.+The demos are intentionally separate from production routes (`/create`, `/avatars/[id]`, etc.) so the production flow keeps working while we test new ideas.----## News CMS & Syndication--A local-only news/blog CMS at `/admin/news` produces signed posts that auto-syndicate to multiple destinations.--| Surface | Path | Purpose |-| -------------- | ---------------------------------------------------------- | --------------------------------------------------- |-| CMS | `/admin/news` | Local-only editor — drafts, images, scheduled posts |-| Public listing | `/news` | Cover-image grid with permalinks |-| Article | `/news/<slug>` | Server-rendered article with OG card |-| RSS / Atom | `/api/news/rss` | Standards-compliant feed for HackerNoon auto-import |-| WebSub hub | `/api/news/websub` | Push notifications to subscribed hubs on publish |-| Dev.to | syndication adapter | Cross-posts with canonical URL pointing back |-| Medium | syndication adapter | Same, with format-aware re-render |-| CMC handoff | syndication adapter | Coinmarketcap article + announcement listing |-| Newsletter | [api/newsletter-subscribe.js](api/newsletter-subscribe.js) | Resend-backed double-opt-in newsletter |--Each article is a static HTML file in `public/news/` with metadata in Postgres. The CMS supports a cover-image convention for listing thumbnails and OG previews. Articles can be published once and reach HackerNoon, Dev.to, and Medium readers without manual cross-posting.-----+## Skill Library-## Security Hardening+The platform ships with a set of built-in agent skills, packaged in `src/agent-skills-*.js` and registered via [`public/skills-index.json`](public/skills-index.json).-The platform has been hardened against the OWASP top-10 plus a set of issues specific to agent payments and cross-chain identity.+| Skill | Module | What it does |+| ---------------------- | ---------------------------------------- | ------------------------------------------------------------------------------------------ |+| **Wave / scene** | `src/agent-skills-scene.js` | Built-in wave, lookAt, play_clip, setExpression handlers |+| **Sentiment** | `src/agent-skills-sentiment.js` | Score incoming text 0–1, drive Empathy Layer spikes |+| **Agent payments** | `src/agent-skills-agent-payments.js` | EVM A2A payments, EIP-7710 delegated signing |+| **Solana Blinks** | `src/agent-skills-blinks.js` | Compose and broadcast Solana Action / Blink links |+| **Jupiter** | `src/agent-skills-jupiter.js` | Quote + swap any SPL token via Jupiter v6 |+| **NFTs** | `src/agent-skills-nfts.js` | Mint, transfer, and look up Metaplex Core / SPL-22 NFTs |+| **Pumpfun watch** | `src/agent-skills-pumpfun-watch.js` | Subscribe to pump.fun events (`recent-claims`, `token-intel`, `watch-start`, `watch-stop`) |+| **Pumpfun compose** | `src/agent-skills-pumpfun-compose.js` | Build a pump.fun launch transaction with creator-signer split |+| **Pumpfun hooks** | `src/agent-skills-pumpfun-hooks.js` | React-style hooks for in-app pump.fun integrations |+| **Pumpfun autonomous** | `src/agent-skills-pumpfun-autonomous.js` | Autonomous trade execution against signals + sentiment |+| **Pumpfun core** | `src/agent-skills-pumpfun.js` | Shared pump.fun client utilities |+| **Accessories** | `src/agent-accessories.js` | Hat / glasses / prop slot attachment to a rigged avatar |+| **Memory** | `src/agent-memory.js` | File-based memory CRUD (see [Memory](#memory)) |+| **Reputation** | `src/agent-reputation.js` | Read on-chain reputation, surface in the chat UI |-| Control | Where |-| ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |-| **SSRF guard** | All outbound `fetch()` from agent runtime + skills goes through an SSRF allow-list filter (`api/_lib/safe-fetch.js`) |-| **CSRF gates** | State-changing endpoints require an Origin + Sec-Fetch-Site check; bearer-only paths exempt |-| **Header-origin pinning** | The iframe bridge locks onto the parent's origin from the first authenticated message and ignores later messages from a different origin |-| **Fail-closed crons** | Cron endpoints fail closed if their auth token is missing — no silent skips |-| **Idempotency tokens** | x402 paid endpoints require an idempotency key to prevent double-charge on retry |-| **Embed policy** | Per-agent iframe origin allow-list (`/api/agents/:id/embed-policy`) gates the chromeless embed |-| **Rate limiting** | Upstash Redis per-user + per-API-key + per-IP buckets at every public endpoint |-| **JWT key rotation** | `JWT_KID` lets you rotate signing keys without invalidating in-flight sessions |-| **Bcrypt cost** | Tunable via `PASSWORD_ROUNDS` (default 11) |-| **Audit signing** | Every agent action is signed with the delegated signer key and chained into a per-agent action log |+Third-party skills are distributed over IPFS / Arweave / HTTP. See [docs/skills.md](docs/skills.md) for the full skill manifest spec and authoring guide.---@@ -10165,280 +9836,78 @@ loadAvatar('a_abc123', document.getElementById('avatar-slot'));----## Claude Code Integration+## API Reference-three.ws ships as a first-class Claude Code SDK. There are two ways to integrate — pick one or use both:+The full OpenAPI 3.1 spec is available at `/openapi.json`. The key API surface is organized below.-### 1. MCP server (paid tools via `npx`)+### Agent API-Add the `@three-ws/mcp-server` to your Claude Desktop, Cursor, or Claude Code config in one step:+| Method | Route | Auth | Description |+| -------- | --------------------------------- | ------- | ---------------------------------------------------------- |+| GET | `/api/agents` | session | List your agents |+| POST | `/api/agents` | session | Create an agent |+| GET | `/api/agents/:id` | — | Get agent detail |+| PATCH | `/api/agents/:id` | session | Update agent |+| DELETE | `/api/agents/:id` | session | Delete agent |+| GET | `/api/agents/:id/manifest` | — | Download manifest JSON |+| POST | `/api/agents/:id/sign` | session | Sign a message with agent wallet |+| GET/POST | `/api/agents/:id/embed-policy` | session | Manage iframe origin allowlist |+| POST | `/api/agents/register-prep` | session | Prep EVM on-chain registration (ERC-8004) |+| POST | `/api/agents/register-confirm` | session | Confirm EVM registration (ERC-8004) |+| POST | `/api/agents/register-solana` | session | Mint a Metaplex Core agent NFT on Solana |+| GET | `/api/agents/solana-attestations` | — | Read Solana feedback / validation memos for an agent |+| GET | `/api/agents/solana-card` | — | Solana agent passport card (mirrors EVM `/a/[chain]/[id]`) |+| GET | `/api/agents/solana-reputation` | — | Solana off-chain reputation snapshot |+| POST | `/api/agent-actions` | session | Record signed agent action |-```json-{- "mcpServers": {- "3d-agent": {- "command": "npx",- "args": ["-y", "@three-ws/mcp-server"],- "env": {- "MCP_EVM_PAYMENT_ADDRESS": "0xYourBaseWallet",- "MCP_SVM_PAYMENT_ADDRESS": "YourSolanaWallet"- }- }- }-}-```+### Avatar API-| Config file location | Platform |-| ----------------------------------------------------------------- | ---------------------------- |-| `~/Library/Application Support/Claude/claude_desktop_config.json` | macOS Claude Desktop |-| `%APPDATA%\Claude\claude_desktop_config.json` | Windows Claude Desktop |-| `.mcp.json` in your project root | Claude Code (project-scoped) |-| `~/.cursor/mcp.json` | Cursor |+| Method | Route | Auth | Description |+| ------ | --------------------------- | ------- | --------------------------- |+| GET | `/api/avatars` | — | List public avatars |+| POST | `/api/avatars` | session | Create avatar record |+| GET | `/api/avatars/:id` | — | Get avatar detail |+| PATCH | `/api/avatars/:id` | session | Update metadata |+| DELETE | `/api/avatars/:id` | session | Soft-delete avatar |+| POST | `/api/avatars/:id/presign` | session | Get presigned R2 upload URL |+| POST | `/api/avatars/:id/pin-ipfs` | session | Pin to IPFS |-Once configured, Claude can call these tools directly in conversation — no API key required, each call is settled in USDC via x402:+**Three-step upload flow:**-| Tool | Price | What it does |-| ------------------ | ----------- | ----------------------------------------------------------------------------------------- |-| `get_pose_seed` | $0.001 | Pose map for a three.ws avatar from a plain-text prompt |-| `pump_snapshot` | $0.005 | Live pump.fun token snapshot — price, volume, holders, trust signals |-| `agent_reputation` | $0.01 | Agent reputation — ERC-8004 ReputationRegistry on EVM, attestation-memo roll-up on Solana |-| `vanity_grinder` | up to $0.50 | Mine a Solana keypair with a custom address prefix |+```+1. POST /api/avatars/:id/presign → { url, storage_key }+2. PUT <presigned_url> ← raw GLB bytes+3. POST /api/avatars → register metadata with storage_key+```-See [`mcp-server/README.md`](mcp-server/README.md) for full environment variable reference and programmatic client usage.+### Widget API-### 2. Slash commands (`marketplace/plugins/three-ws-developer/commands/`)+| Method | Route | Auth | Description |+| ------ | ---------------------------- | ------- | ----------------- |+| GET | `/api/widgets` | session | List your widgets |+| POST | `/api/widgets` | session | Create widget |+| PATCH | `/api/widgets/:id` | session | Update widget |+| DELETE | `/api/widgets/:id` | session | Delete widget |+| POST | `/api/widgets/:id/duplicate` | session | Clone widget |+| GET | `/api/widgets/:id/stats` | — | View stats |+| GET | `/api/widgets/oembed` | — | oEmbed card |-This repo ships three Claude Code slash commands that work in any project referencing this repo:+### Memory API-| Command | What it does |-| ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- |-| `/setup-mcp` | Detects your OS, collects wallet addresses, and writes the MCP config to the right file — end-to-end, no manual JSON editing |-| `/scaffold-agent` | Scaffolds a new three.ws agent in your project: installs dependencies, creates `agent.js` with MCP client wiring, and adds `.env.example` |-| `/use-tools [tool_name]` | Produces a complete, runnable Node.js script for calling a specific paid MCP tool with automatic x402 payment handling |+| Method | Route | Auth | Description |+| ------ | ----------------------- | ------- | ------------------------ |+| GET | `/api/agent-memory/:id` | session | Fetch agent memory store |+| POST | `/api/agent-memory/:id` | session | Append memory entries |+| PUT | `/api/agent-memory/:id` | session | Replace memory store |-Commands live in [`marketplace/plugins/three-ws-developer/commands/`](marketplace/plugins/three-ws-developer/commands/) and ship with the `three-ws-developer` plugin, so Claude Code picks them up once that plugin is installed.+### Chat & LLM----+| Method | Route | Auth | Description |+| ------ | -------------------- | ------------------ | -------------------------------- |+| POST | `/api/chat` | session \| api-key | Chat with agent (Claude backend) |+| POST | `/api/llm/anthropic` | session | Anthropic API proxy |-## Demos Hub--`/demos` is a curated index of sandbox pages that exercise individual platform capabilities in isolation. Each demo is a single HTML file in [`public/demos/`](public/demos/) — perfect for screen recordings, bug reproductions, or showing off one feature without the rest of the app.--| Demo | Path | What it shows |-| ----------------------------------- | -------------------------------- | -------------------------------------------------------- |-| **USDZ & AR Quick Look** | `/demos/usdz-ar.html` | iOS USDZ export + AR Quick Look on a real device |-| **Half-body XR** | `/demos/halfbody-xr.html` | Upper-body avatar in WebXR (Meta Quest, Vision Pro) |-| **Avatar SDK** | `/demos/avatar-sdk.html` | `@three-ws/avatar` SDK loading + animating an avatar |-| **React SDK** | `/demos/react-sdk.html` | React wrapper around the `<agent-3d>` element |-| **Audio-driven lipsync (mic)** | `/lipsync/mic` | Live microphone → ARKit-52 lip-sync |-| **Audio-driven lipsync (TTS)** | `/lipsync` | ElevenLabs TTS → ARKit-52 lip-sync |-| **Multi-LLM brain** | `/brain` | Side-by-side comparison of Claude / GPT / Groq / Gemini |-| **ERC-8004 registry browser** | `/demos/erc8004.html` | Browse all registered agents across chains |-| **Button jump** | `/demos/button-jump.html` | Avatar reacts to a 2D button press |-| **Tactile button (Gemini concept)** | `/demos/gemini-jump.html` | Tactile button demo with avatar |-| **Create v2** | `/demos/create-v2.html` | Next-generation agent creation flow |-| **3D home** | `/demos/3d-home.html` | Home page with overlay canvas + transparent-bg viewer |-| **Selfie fit** | `/demos/selfie-fit.html` | Selfie reconstruction pipeline (Phase 1) |-| **Persona extract** | `/demos/persona-extract.html` | Voice & Persona Hub onboarding interview |-| **Memory seed** | `/demos/memory-seed.html` | Memory seeding from X/GitHub/Farcaster |-| **Voice clone** | `/demos/voice-clone.html` | 3–10s recording → ElevenLabs custom voice |-| **Livepeer inference** | `/demos/livepeer-inference.html` | Decentralized GPU inference end-to-end |-| **Skill royalty** | `/demos/skill-royalty.html` | Per-call royalty payouts to skill authors |-| **EAS reputation** | `/demos/eas-reputation.html` | EAS-attested reputation viewer |-| **Bonding curve** | `/demos/bonding-curve.html` | Pre-launch bonding-curve pricing simulator |-| **Gallery picker** | `/demos/gallery-picker.html` | Lazy 3D-thumbnail avatar picker (Embed Editor primitive) |-| **Button** | `/demos/button.html` | Minimal `<agent-3d>` embed reaction test |--The demos are intentionally separate from production routes (`/create`, `/avatars/[id]`, etc.) so the production flow keeps working while we test new ideas.-------## Skill Library--The platform ships with a set of built-in agent skills, packaged in `src/agent-skills-*.js` and registered via [`public/skills-index.json`](public/skills-index.json).--| Skill | Module | What it does |-| ---------------------- | ---------------------------------------- | ------------------------------------------------------------------------------------------ |-| **Wave / scene** | `src/agent-skills-scene.js` | Built-in wave, lookAt, play_clip, setExpression handlers |-| **Sentiment** | `src/agent-skills-sentiment.js` | Score incoming text 0–1, drive Empathy Layer spikes |-| **Agent payments** | `src/agent-skills-agent-payments.js` | EVM A2A payments, EIP-7710 delegated signing |-| **Solana Blinks** | `src/agent-skills-blinks.js` | Compose and broadcast Solana Action / Blink links |-| **Jupiter** | `src/agent-skills-jupiter.js` | Quote + swap any SPL token via Jupiter v6 |-| **NFTs** | `src/agent-skills-nfts.js` | Mint, transfer, and look up Metaplex Core / SPL-22 NFTs |-| **Pumpfun watch** | `src/agent-skills-pumpfun-watch.js` | Subscribe to pump.fun events (`recent-claims`, `token-intel`, `watch-start`, `watch-stop`) |-| **Pumpfun compose** | `src/agent-skills-pumpfun-compose.js` | Build a pump.fun launch transaction with creator-signer split |-| **Pumpfun hooks** | `src/agent-skills-pumpfun-hooks.js` | React-style hooks for in-app pump.fun integrations |-| **Pumpfun autonomous** | `src/agent-skills-pumpfun-autonomous.js` | Autonomous trade execution against signals + sentiment |-| **Pumpfun core** | `src/agent-skills-pumpfun.js` | Shared pump.fun client utilities |-| **Accessories** | `src/agent-accessories.js` | Hat / glasses / prop slot attachment to a rigged avatar |-| **Memory** | `src/agent-memory.js` | File-based memory CRUD (see [Memory](#memory)) |-| **Reputation** | `src/agent-reputation.js` | Read on-chain reputation, surface in the chat UI |--Third-party skills are distributed over IPFS / Arweave / HTTP. See [docs/skills.md](docs/skills.md) for the full skill manifest spec and authoring guide.-------## Animation System--The avatar runtime ships with a slot-based animation manager that decouples animation clips from rigs — a clip authored for one body can be retargeted to any other rig at load time.--| Module | Path | Role |-| ------------- | ---------------------------------------------------------------- | --------------------------------------------------------------------- |-| Manager | [src/animation-manager.js](src/animation-manager.js) | Load, blend, and crossfade clips per slot (idle, gesture, locomotion) |-| State machine | [src/animation-state-machine.js](src/animation-state-machine.js) | Drives slot transitions from protocol events |-| Idle library | [src/idle-animation.js](src/idle-animation.js) | Subtle breath / weight-shift loops that play under everything else |-| Fetcher | `npm run fetch-animations` | Downloads the canonical clip library from R2 |-| Builder | `scripts/build-animations.mjs` | Re-packs clip bundles into Meshopt + Draco-compressed GLB |--A new clip can be authored against any rig in Blender, exported as a GLB, and dropped into the animation library — the manager picks it up automatically and the agent runtime can invoke it via the `play_clip` tool.--The **`sitidle` clip** is shipped as the default seated idle for chat-mode avatars; the **gemini-jump clip** drives the hero on `/`.-------## Avatar Accessories & Coin Launchpad--Avatars are not just GLB files — they're composable rigs that the runtime can decorate with onchain accessories.--### Accessories--- Hats, glasses, props attached to named bone slots via [src/agent-accessories.js](src/agent-accessories.js)-- Accessories are themselves ERC-1155 tokens, ownable and tradeable independently of the avatar-- Equipping is non-destructive — the agent's base manifest stays unchanged, the accessory is layered at runtime--### Coin Launchpad--Every agent can mint a coin alongside its avatar — turning the agent into a tradeable economic object.--| Surface | Path | Purpose |-| ---------------- | ---------------------------- | ------------------------------------------------------------------ |-| Launchpad Studio | `/launchpad` | Configure coin name, ticker, supply, fee shares |-| Hosted page | `/p/[slug]` | Public launch page with `<agent-3d>` widget + buy button |-| Avatar coin drop | `public/demo/coin/` | Demo flow — connect wallet → mint avatar + coin in one transaction |-| Pump.fun bridge | `POST /api/pump/launch-prep` | Route the launch through pump.fun's bonding curve |-| Direct mint | `contracts/script/` | Deploy a standalone ERC-20 / SPL-22 alongside the agent |--The coin's metadata points back at the agent's onchain identity — ERC-8004 token on EVM or Metaplex Core asset on Solana — and the agent's manifest references the coin. The two-way binding is read from the bazaar, marketplace, and reputation registry on either chain.-------## Brain Proxy & LLM Routing--three.ws supports multiple LLM providers behind a single `brain` interface. The runtime is provider-agnostic — switch from Claude to GPT to Gemini to a local model with a one-line change.--| Provider | Path | Use case |-| ---------------------- | -------------------------------- | --------------------------------------------------------------------- |-| **Anthropic (Claude)** | `POST /api/llm/anthropic` | Default — tool-loop, streaming, sentiment-tagged speak |-| **Groq** | (anonymous) | Free fast-mode chat for unauthenticated visitors on `/chat` |-| **Multi-LLM brain** | `/brain`, `POST /api/brain/chat` | Side-by-side compare Claude / GPT / Gemini / Groq for the same prompt |-| **OpenRouter** | proxied via brain | Fallback when the primary provider is rate-limited |-| **Null provider** | `src/runtime/providers.js` | No-op for tests and offline mode |--**Switching providers**--Provider selection is per-agent and controlled by the manifest `brain.provider` field:--```json-{- "brain": {- "provider": "anthropic",- "model": "claude-sonnet-4-6",- "temperature": 0.8,- "maxTokens": 1024- }-}-```--Supported `provider` values: `anthropic` · `groq` · `openrouter` · `null` (offline). Adding a new provider means implementing the two-method interface (`chat()` and `stream()`) in [`src/runtime/providers.js`](src/runtime/providers.js) — no other files need to change.--**Free-first routing policy**--The platform's `DEFAULT_PROVIDER_ORDER` in `src/llm.js` ensures AI chat never fails silently due to a single quota: free tiers (Groq, OpenRouter `:free` models, NVIDIA) are always tried first; paid keys (Anthropic, OpenAI) are last-resort only. An OpenRouter fallback key is configured for `:free` models so that even a depleted primary account doesn't take down the `/chat` surface.--**Owner-card gating**--When an agent has a paying owner — established via ERC-8004 mint or x402 subscription — the embed unlocks:--- Longer context windows (up to 32k tokens per turn vs the anonymous 8k cap)-- Access to higher-tier models (Claude Sonnet / Opus vs Groq fallback)-- An owner-attribution card displayed below the avatar in the embed chrome--The gating check runs server-side in [`api/chat.js`](api/chat.js) against the agent's subscription record in Postgres. It cannot be bypassed from the client — the model selection and context limit are applied at the API layer before the request reaches the LLM provider.-------## API Reference--The full OpenAPI 3.1 spec is available at `/openapi.json`. The key API surface is organized below.--### Agent API--| Method | Route | Auth | Description |-| -------- | --------------------------------- | ------- | ---------------------------------------------------------- |-| GET | `/api/agents` | session | List your agents |-| POST | `/api/agents` | session | Create an agent |-| GET | `/api/agents/:id` | — | Get agent detail |-| PATCH | `/api/agents/:id` | session | Update agent |-| DELETE | `/api/agents/:id` | session | Delete agent |-| GET | `/api/agents/:id/manifest` | — | Download manifest JSON |-| POST | `/api/agents/:id/sign` | session | Sign a message with agent wallet |-| GET/POST | `/api/agents/:id/embed-policy` | session | Manage iframe origin allowlist |-| POST | `/api/agents/register-prep` | session | Prep EVM on-chain registration (ERC-8004) |-| POST | `/api/agents/register-confirm` | session | Confirm EVM registration (ERC-8004) |-| POST | `/api/agents/register-solana` | session | Mint a Metaplex Core agent NFT on Solana |-| GET | `/api/agents/solana-attestations` | — | Read Solana feedback / validation memos for an agent |-| GET | `/api/agents/solana-card` | — | Solana agent passport card (mirrors EVM `/a/[chain]/[id]`) |-| GET | `/api/agents/solana-reputation` | — | Solana off-chain reputation snapshot |-| POST | `/api/agent-actions` | session | Record signed agent action |--### Avatar API--| Method | Route | Auth | Description |-| ------ | --------------------------- | ------- | --------------------------- |-| GET | `/api/avatars` | — | List public avatars |-| POST | `/api/avatars` | session | Create avatar record |-| GET | `/api/avatars/:id` | — | Get avatar detail |-| PATCH | `/api/avatars/:id` | session | Update metadata |-| DELETE | `/api/avatars/:id` | session | Soft-delete avatar |-| POST | `/api/avatars/:id/presign` | session | Get presigned R2 upload URL |-| POST | `/api/avatars/:id/pin-ipfs` | session | Pin to IPFS |--**Three-step upload flow:**--```-1. POST /api/avatars/:id/presign → { url, storage_key }-2. PUT <presigned_url> ← raw GLB bytes-3. POST /api/avatars → register metadata with storage_key-```--### Widget API--| Method | Route | Auth | Description |-| ------ | ---------------------------- | ------- | ----------------- |-| GET | `/api/widgets` | session | List your widgets |-| POST | `/api/widgets` | session | Create widget |-| PATCH | `/api/widgets/:id` | session | Update widget |-| DELETE | `/api/widgets/:id` | session | Delete widget |-| POST | `/api/widgets/:id/duplicate` | session | Clone widget |-| GET | `/api/widgets/:id/stats` | — | View stats |-| GET | `/api/widgets/oembed` | — | oEmbed card |--### Memory API--| Method | Route | Auth | Description |-| ------ | ----------------------- | ------- | ------------------------ |-| GET | `/api/agent-memory/:id` | session | Fetch agent memory store |-| POST | `/api/agent-memory/:id` | session | Append memory entries |-| PUT | `/api/agent-memory/:id` | session | Replace memory store |--### Chat & LLM--| Method | Route | Auth | Description |-| ------ | -------------------- | ------------------ | -------------------------------- |-| POST | `/api/chat` | session \| api-key | Chat with agent (Claude backend) |-| POST | `/api/llm/anthropic` | session | Anthropic API proxy |--### Cron Jobs+### Cron JobsCron schedules are declared in `vercel.json` (still the live cron/route config the server reads) and executed in production by **Google Cloud Scheduler**, which calls each endpoint on its schedule. All cron endpoints are fail-closed — a missing auth token aborts with an error rather than silently skipping (see [Security Hardening](#security-hardening)).@@ -10575,194 +10044,725 @@ _Pump.fun_ ([`api/_mcp/tools/pumpfun.js`](api/_mcp/tools/pumpfun.js))----## On-Chain Identity (ERC-8004 + Metaplex Core)+## Brain Proxy & LLM Routing-three.ws supports two onchain identity paths as first-class peers — every reputation, attestation, and discovery surface reads from both, and SIWX brokers proofs between them so a single agent can hold reputation on both at once.+three.ws supports multiple LLM providers behind a single `brain` interface. The runtime is provider-agnostic — switch from Claude to GPT to Gemini to a local model with a one-line change.-- **EVM path** — ERC-8004, a draft standard for verifiable 3D agent identity, deployed on Base, BSC, and other supported EVM chains. The `contracts/` directory contains a full Foundry implementation (IdentityRegistry, ReputationRegistry, ValidationRegistry).-- **Solana path** — Metaplex Core asset minted via the `solana-agent-sdk`. No custom on-chain program is required: the asset pubkey is the agent ID, and feedback / validation events are written as on-chain memos that the indexer rolls up into a reputation score (see the [Solana variant](#solana-variant--same-shape-no-deployed-program) section below).+| Provider | Path | Use case |+| ---------------------- | -------------------------------- | --------------------------------------------------------------------- |+| **Anthropic (Claude)** | `POST /api/llm/anthropic` | Default — tool-loop, streaming, sentiment-tagged speak |+| **Groq** | (anonymous) | Free fast-mode chat for unauthenticated visitors on `/chat` |+| **Multi-LLM brain** | `/brain`, `POST /api/brain/chat` | Side-by-side compare Claude / GPT / Gemini / Groq for the same prompt |+| **OpenRouter** | proxied via brain | Fallback when the primary provider is rate-limited |+| **Null provider** | `src/runtime/providers.js` | No-op for tests and offline mode |-### ERC-8004 (EVM)+**Switching providers**-ERC-8004 is a draft standard for verifiable 3D agent identity. The `contracts/` directory contains a full Foundry implementation.+Provider selection is per-agent and controlled by the manifest `brain.provider` field:-### Contracts+```json+{+ "brain": {+ "provider": "anthropic",+ "model": "claude-sonnet-4-6",+ "temperature": 0.8,+ "maxTokens": 1024+ }+}+```-**IdentityRegistry.sol** — the primary EVM contract. Each agent is an ERC-721 token with:+Supported `provider` values: `anthropic` · `groq` · `openrouter` · `null` (offline). Adding a new provider means implementing the two-method interface (`chat()` and `stream()`) in [`src/runtime/providers.js`](src/runtime/providers.js) — no other files need to change.-- `agentId` — stable numeric ID (the token ID)-- `owner` — EVM address of the agent's owner-- `delegatedSigner` — optional secondary address for runtime signing (EIP-712 typed signature)-- `tokenURI` — IPFS URL of the agent manifest JSON-- `metadata` — on-chain name, description, image pointer+**Free-first routing policy**-On **Solana**, the equivalent identity is a **Metaplex Core asset**: the asset pubkey is the agent ID, the asset's `update_authority` is the owner, and the asset's URI points at the same IPFS-pinned manifest. No custom program is deployed — Metaplex Core handles mint, transfer, and update natively.+The platform's `DEFAULT_PROVIDER_ORDER` in `src/llm.js` ensures AI chat never fails silently due to a single quota: free tiers (Groq, OpenRouter `:free` models, NVIDIA) are always tried first; paid keys (Anthropic, OpenAI) are last-resort only. An OpenRouter fallback key is configured for `:free` models so that even a depleted primary account doesn't take down the `/chat` surface.-**ReputationRegistry.sol** — stores signed feedback scores. Each reviewer can submit one score per agent. Scores are averaged for an on-chain reputation metric. The **Solana analog** is an SPL Memo with envelope `threews.feedback.v1`, posted in a transaction whose accounts include the agent's Metaplex Core asset pubkey — readable by any client via `getSignaturesForAddress`.+**Owner-card gating**++When an agent has a paying owner — established via ERC-8004 mint or x402 subscription — the embed unlocks:++- Longer context windows (up to 32k tokens per turn vs the anonymous 8k cap)+- Access to higher-tier models (Claude Sonnet / Opus vs Groq fallback)+- An owner-attribution card displayed below the avatar in the embed chrome++The gating check runs server-side in [`api/chat.js`](api/chat.js) against the agent's subscription record in Postgres. It cannot be bypassed from the client — the model selection and context limit are applied at the API layer before the request reaches the LLM provider.++---++## Claude Code Integration++three.ws ships as a first-class Claude Code SDK. There are two ways to integrate — pick one or use both:++### 1. MCP server (paid tools via `npx`)++Add the `@three-ws/mcp-server` to your Claude Desktop, Cursor, or Claude Code config in one step:++```json+{+ "mcpServers": {+ "3d-agent": {+ "command": "npx",+ "args": ["-y", "@three-ws/mcp-server"],+ "env": {+ "MCP_EVM_PAYMENT_ADDRESS": "0xYourBaseWallet",+ "MCP_SVM_PAYMENT_ADDRESS": "YourSolanaWallet"+ }+ }+ }+}+```++| Config file location | Platform |+| ----------------------------------------------------------------- | ---------------------------- |+| `~/Library/Application Support/Claude/claude_desktop_config.json` | macOS Claude Desktop |+| `%APPDATA%\Claude\claude_desktop_config.json` | Windows Claude Desktop |+| `.mcp.json` in your project root | Claude Code (project-scoped) |+| `~/.cursor/mcp.json` | Cursor |++Once configured, Claude can call these tools directly in conversation — no API key required, each call is settled in USDC via x402:++| Tool | Price | What it does |+| ------------------ | ----------- | ----------------------------------------------------------------------------------------- |+| `get_pose_seed` | $0.001 | Pose map for a three.ws avatar from a plain-text prompt |+| `pump_snapshot` | $0.005 | Live pump.fun token snapshot — price, volume, holders, trust signals |+| `agent_reputation` | $0.01 | Agent reputation — ERC-8004 ReputationRegistry on EVM, attestation-memo roll-up on Solana |+| `vanity_grinder` | up to $0.50 | Mine a Solana keypair with a custom address prefix |++See [`mcp-server/README.md`](mcp-server/README.md) for full environment variable reference and programmatic client usage.++### 2. Slash commands (`marketplace/plugins/three-ws-developer/commands/`)++This repo ships three Claude Code slash commands that work in any project referencing this repo:++| Command | What it does |+| ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- |+| `/setup-mcp` | Detects your OS, collects wallet addresses, and writes the MCP config to the right file — end-to-end, no manual JSON editing |+| `/scaffold-agent` | Scaffolds a new three.ws agent in your project: installs dependencies, creates `agent.js` with MCP client wiring, and adds `.env.example` |+| `/use-tools [tool_name]` | Produces a complete, runnable Node.js script for calling a specific paid MCP tool with automatic x402 payment handling |++Commands live in [`marketplace/plugins/three-ws-developer/commands/`](marketplace/plugins/three-ws-developer/commands/) and ship with the `three-ws-developer` plugin, so Claude Code picks them up once that plugin is installed.++---++## Install in Claude Code++three.ws ships an official **Claude Code plugin marketplace** — install wallet, payments, pump.fun trading, agent scaffolding, and the 3D Forge as namespaced skills and MCP tools, in one command. Add the marketplace once:++```+/plugin marketplace add nirholas/three.ws+```++Then install any of the four plugins:++```+/plugin install three-ws-core@three-ws # wallet + x402 — authenticate, fund, send, trade, bazaar, pay, monetize, query onchain+/plugin install three-ws-developer@three-ws # scaffold agents, configure MCP, runnable code examples+/plugin install three-ws-pump-fun@three-ws # create coins, swap, creator fees, tokenize agents, live avatar reactions+/plugin install three-ws-3d@three-ws # text→3D (free), text→avatar, mesh forge, auto-rig + scene/avatar MCP+```++Run `/reload-plugins` and the skills appear under each plugin's namespace (e.g. `/three-ws-3d:forge-3d`). Plugins that expose MCP tools (`three-ws-developer`, `three-ws-3d`) wire the published `@three-ws/*` MCP servers automatically — `forge_free` is free (no wallet); the paid lanes settle over x402 in USDC. The canonical manifest lives at [.claude-plugin/marketplace.json](.claude-plugin/marketplace.json).++---++## Cloud Marketplaces++three.ws is available on major cloud marketplaces and open to infrastructure partnerships.++| Cloud | Status |+| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| **AWS** | **AWS Partner** (APN Software Path). AWS Marketplace SaaS listing in review — see [docs/aws-marketplace.md](docs/aws-marketplace.md) and the public partner page at [three.ws/aws](https://three.ws/aws). Part of the stack runs on AWS `us-east-1` — the Forge sculptor Lambda (`three-ws-forge`) and the S3 avatar bucket — registered in AWS MyApplications under account `155407237916` (the main app runs on Google Cloud Run). |+| **Alibaba Cloud** | Live: [product listing →](https://marketplace.alibabacloud.com/products/56724001/sgcmfw00036800.html) · [storefront →](https://marketplace.alibabacloud.com/store/3247293.html) |+| **Google Cloud** | Production runs on **Google Cloud Run** (`three-ws-api`, `us-central1`) fronted by a global HTTPS load balancer + Cloud CDN, with all 100 scheduled jobs on Cloud Scheduler and GPU inference workers on Cloud Run — a natural fit for GCP's AI infrastructure and Vertex AI. Open to co-listing, credits, and joint GTM. |++## Ecosystem Directories++three.ws is indexed in chain-ecosystem dApp directories so the community can discover, vet, and rank it.++| Directory | Status |+| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |+| **BNB Chain · Dappbay** | Live: [dappbay.bnbchain.org/detail/three →](https://dappbay.bnbchain.org/detail/three) — categories: AI Agent Launchpad · AI Data · AI Infra |++---++## IBM watsonx & Granite++three.ws is an **IBM Business Partner**, and the agent runtime runs on **IBM Granite** foundation models served through **IBM watsonx.ai**. One IBM Cloud API key + project unlocks the whole suite; every call is real inference (no mock path — endpoints return `503` when unconfigured). Full docs: **[docs/ibm.md](docs/ibm.md)**. Live showcase: **[three.ws/ibm/galaxy](https://three.ws/ibm/galaxy)**.++> **The public showcase is not the partnership.** The demos under `/ibm/*` are independent tools three.ws built for developers to explore Granite on watsonx.ai and build their own integrations — they are not official IBM partnership deliverables, not IBM products, and not endorsed by IBM. Our formal partnership work with IBM is being built on the IBM platform and is not yet public.++| Granite model | Where it runs |+| ------------- | ------------- |+| `granite-3-8b-instruct` | Selectable avatar **brain** + all narration |+| `granite-guardian-3-8b` | **Trust Layer** — allow/review/block governance gate, inline in `/api/chat` before an avatar moves value |+| `granite-ttm-512/1024/1536-96-r2` | **TimeSeries** forecasting (Oracle, Twin, Proof) |+| `granite-embedding-278m-multilingual` | **Semantic** agent map + `/api/watsonx/embed` |+| `granite-vision-3-2-2b` | **Vision** — reads an avatar into a full agent identity |++Six showcase surfaces put it on screen, cross-linked by an in-page suite switcher: the [Agent Galaxy](https://three.ws/ibm/galaxy) (semantic 3D star-map), the [Granite Oracle](https://three.ws/ibm/oracle) (narrated forecast), the [Digital Twin](https://three.ws/ibm/twin) (back-test + what-if), the [Trust Layer](https://three.ws/ibm/trust-layer) (Guardian + hash-chained audit ledger), [Granite Proof](https://three.ws/ibm/proof) (a Guardian-governed forecast notarized on Solana), and [Granite Vision](https://three.ws/ibm/vision). The standalone connector [`@three-ws/ibm-watsonx-mcp`](packages/ibm-watsonx-mcp/) exposes watsonx.ai to any MCP host — it is community-built and not an IBM product; the hosted platform integration is what runs on IBM watsonx.ai.++### Pay-per-call Granite over MCP (x402)++The world's first **x402-enabled MCP server on IBM Cloud**: [`@three-ws/ibm-x402-mcp`](packages/ibm-x402-mcp/) turns IBM Granite into a metered utility any AI agent can call. The operator holds the IBM credentials and funds inference; the caller pays **a few cents of USDC per call** — no IBM Cloud account, no subscription, no API-key signup. Full guide: **[docs/ibm-x402-mcp.md](docs/ibm-x402-mcp.md)**.++| Tool | What it does | Price |+| ---- | ------------ | ----- |+| `ibm_granite_chat` | Conversational AI — Q&A, drafting, reasoning | $0.02 |+| `ibm_granite_code` | Generate / review / refactor / explain / test / document code | $0.025 |+| `ibm_granite_embed` | Batch text embeddings (1–64) for RAG, search, clustering | $0.005 |+| `ibm_granite_analyze` | Structured doc analysis — entities, sentiment, risk, next steps | $0.04 |+| `ibm_granite_forecast` | Zero-shot time-series forecasting via Granite TTM | $0.05 |++The same five tools ship over two transports: **stdio** (`npx @three-ws/ibm-x402-mcp`, for Claude Desktop / Code / Cursor, paid on Solana) and **Streamable HTTP** (`https://three.ws/api/ibm-mcp`, for hosted clients and watsonx Orchestrate, paid on Base or Solana). An unpaid `tools/call` returns a `402` quoting the exact USDC price; x402-capable clients pay and retry automatically, settling on-chain only after the tool succeeds. Independent project integrating IBM Granite via watsonx.ai — not an IBM product.++---++## x402 Payments++three.ws is a first-class [x402](https://x402.org) host. Agents can both **pay for** and **expose** paid endpoints. Settlement runs on Base, BSC, and Solana; the bazaar at `/x402` is the discovery surface.++### Payment rails++| Chain | Settlement | Permit2 sibling | Status |+| ------------------- | ------------------------------ | ------------------- | ------ |+| **Base mainnet** | Coinbase CDP facilitator | Gasless via relayer | Live |+| **Base sepolia** | CDP facilitator | Yes | Live |+| **BSC** | Direct-scheme (no facilitator) | — | Live |+| **Solana (devnet)** | x402-solana direct | — | Live |++Every CDP-settled endpoint ships a Permit2 sibling that accepts an EIP-2612 permit instead of an upfront approval — the buyer signs once, and the relayer pays gas. Wire-level checks live in `tests/e2e/` and exercise the buyer/seller flow end-to-end.++### Paid endpoints++| Route | What you get |+| ---------------------------------------- | --------------------------------------------- |+| `POST /api/x402/mint-to-mesh` | Mint an avatar's mesh as an NFT |+| `POST /api/x402/mint-to-mesh-batch` | Batch mint up to N meshes |+| `POST /api/x402/dance-tip` | Tip a club dancer in USDC |+| `POST /api/x402/model-check` | Run Khronos glTF validation as a paid service |+| `POST /api/x402/pump-agent-audit` | Audit a pump.fun token's creator history |+| `POST /api/x402/agent-reputation` | Compute on-chain reputation snapshot |+| `POST /api/x402/onchain-identity-verify` | Verify ERC-8004 identity for a wallet |+| `POST /api/x402/symbol-availability` | Check token symbol availability across chains |+| `POST /api/x402/skill-marketplace` | Paid skill marketplace listing |+| `POST /api/x402/asset-download` | Pay-per-download for gated R2 assets |+| `POST /api/x402/did` | DID resolution as a service |+| `GET /api/x402/my-receipts` | Buyer-side receipts ledger |++### Bazaar, SKUs, and subscriptions++| Surface | Path | Purpose |+| ------------- | --------------------------------- | ------------------------------------------- |+| Bazaar | `/x402` | Browsable marketplace of paid endpoints |+| Discovery | `/x402-discover` | Search by tag, price, chain |+| Checkout | `/x402-pay`, `/api/x402-checkout` | Stripe-style one-shot purchase |+| SKU catalog | `/api/x402-skus` | Server-defined SKUs with per-row pricing |+| Dashboard | `/dashboard/x402` | Seller + buyer dashboard, receipts, payouts |+| Subscriptions | `/api/x402/subscriptions` | Recurring x402 charges on cron |+| Status | `/api/x402-status` | Health and chain reachability checks |++### How to expose a paid endpoint++```js+import { paidEndpoint } from './_lib/x402-paid-endpoint.js';++export default paidEndpoint({+ price: '0.10', // USDC+ chain: 'base', // base | bsc | solana+ network: 'mainnet',+ resource: 'https://three.ws/api/your-endpoint',+ description: 'What the buyer is paying for',+ handler: async (req, res, { payer }) => {+ // payer is verified — settle the request+ res.json({ ok: true, payer });+ },+});+```++The helper handles the 402 challenge, Permit2 sibling, receipt write-back, idempotency-token enforcement, and CSRF/SSRF guards. See [api/\_lib/x402-paid-endpoint.js](api/_lib/x402-paid-endpoint.js).++### Wire checks++- Wire-level CORS, CDP, and Permit2 sibling checks: `tests/e2e/`+- Offer receipts schema + buyer fetch: [api/\_lib/x402-buyer-fetch.js](api/_lib/x402-buyer-fetch.js)+- Error envelope: full 402 body returned in the `PAYMENT-REQUIRED` header++---++## A2A — Agent-to-Agent Protocol++Agents transact with each other directly through an A2A bridge that sits on top of the MCP server and x402 payments.++**How it works**++When agent A wants to call a paid tool from agent B:++1. **Discover** — A resolves B's DID via `POST /api/x402/did`, receiving B's MCP endpoint URL and payment wallet address.+2. **Call** — A sends a `tools/call` JSON-RPC request to B's MCP endpoint.+3. **Pay** — B's server returns `402 Payment Required` with a USDC price. A's SDK settles the x402 payment on-chain (Base or Solana) and retries with the payment proof in the `X-PAYMENT` header.+4. **Execute** — B verifies the payment, runs the tool, and writes a signed receipt to `api/a2a/receipts`.+5. **Ledger** — Both sides accumulate a row in `api/a2a/spending` — A for outbound spend, B for inbound revenue.++Agent wallets sign with **EIP-7710 delegated permissions** — the delegated signer acts on behalf of the agent's root key without ever exposing it.++| Surface | Path | Purpose |+| --------------- | -------------------- | -------------------------------------------------------- |+| A2A client | `sdk/a2a/` | Outbound calls — pay another agent, settle the response |+| A2A server | `api/a2a/` | Inbound paid tools, exposed via MCP bridge |+| MCP bridge | `api/mcp.js` | Wraps paid tools as MCP `tools/call` with auto-402 retry |+| Spending ledger | `api/a2a/spending` | Per-agent spend caps and authorization gates |+| Receipts store | `api/a2a/receipts` | Signed receipts written on every paid call |+| DID resolution | `POST /api/x402/did` | Resolve a counterparty DID to wallet + endpoints |++**SIWX (Sign-In with X-chain)** brokers cross-chain identity for paid sessions: an agent on Base proves ownership of a Solana wallet (or vice versa) to unlock chain-specific paid endpoints.++---++## On-Chain Identity (ERC-8004 + Metaplex Core)++three.ws supports two onchain identity paths as first-class peers — every reputation, attestation, and discovery surface reads from both, and SIWX brokers proofs between them so a single agent can hold reputation on both at once.++- **EVM path** — ERC-8004, a draft standard for verifiable 3D agent identity, deployed on Base, BSC, and other supported EVM chains. The `contracts/` directory contains a full Foundry implementation (IdentityRegistry, ReputationRegistry, ValidationRegistry).+- **Solana path** — Metaplex Core asset minted via the `solana-agent-sdk`. No custom on-chain program is required: the asset pubkey is the agent ID, and feedback / validation events are written as on-chain memos that the indexer rolls up into a reputation score (see the [Solana variant](#solana-variant--same-shape-no-deployed-program) section below).++### ERC-8004 (EVM)++ERC-8004 is a draft standard for verifiable 3D agent identity. The `contracts/` directory contains a full Foundry implementation.++### Contracts++**IdentityRegistry.sol** — the primary EVM contract. Each agent is an ERC-721 token with:++- `agentId` — stable numeric ID (the token ID)+- `owner` — EVM address of the agent's owner+- `delegatedSigner` — optional secondary address for runtime signing (EIP-712 typed signature)+- `tokenURI` — IPFS URL of the agent manifest JSON+- `metadata` — on-chain name, description, image pointer++On **Solana**, the equivalent identity is a **Metaplex Core asset**: the asset pubkey is the agent ID, the asset's `update_authority` is the owner, and the asset's URI points at the same IPFS-pinned manifest. No custom program is deployed — Metaplex Core handles mint, transfer, and update natively.++**ReputationRegistry.sol** — stores signed feedback scores. Each reviewer can submit one score per agent. Scores are averaged for an on-chain reputation metric. The **Solana analog** is an SPL Memo with envelope `threews.feedback.v1`, posted in a transaction whose accounts include the agent's Metaplex Core asset pubkey — readable by any client via `getSignaturesForAddress`.++**ValidationRegistry.sol** — records validator attestations for off-chain proofs (glTF validation reports, skill audits, security reviews). The **Solana analog** uses SPL Memo with envelope `threews.validation.v1` against the agent's Metaplex Core asset pubkey.++### Deployment Addresses++See [`contracts/DEPLOYMENTS.md`](contracts/DEPLOYMENTS.md) for current mainnet and testnet addresses. All three registries are deployed via **CREATE2** against a custom vanity-prefixed factory, so the **same address is used on every supported EVM chain** within an environment class — mainnet contracts have one address, testnet contracts another.++**Mainnet (across Ethereum, Optimism, BSC, Gnosis, Polygon, Fantom, zkSync Era, Moonbeam, Mantle, Base, Arbitrum One, Celo, Avalanche, Linea, Scroll):**++| Contract | Address |+| ------------------ | -------------------------------------------- |+| IdentityRegistry | `0x8004A169FB4a3325136EB29fA0ceB6D2e539a432` |+| ReputationRegistry | `0x8004BAa17C55a88189AE136b182e5fdA19dE9b63` |+| ValidationRegistry | _(same address on all chains)_ |++**Testnet (BSC Testnet, Ethereum Sepolia, Base Sepolia, Arbitrum Sepolia, Optimism Sepolia, Polygon Amoy, Avalanche Fuji):**++| Contract | Address |+| ------------------ | -------------------------------------------- |+| IdentityRegistry | `0x8004A818BFB912233c491871b3d84c89A494BD9e` |+| ReputationRegistry | `0x8004B663056A597Dffe9eCcC1965A193B7388713` |+| ValidationRegistry | `0x8004Cb1BF31DAf7788923b405b754f57acEB4272` |++### CREATE2 Factory (ThreeWSFactory)++A custom vanity-prefixed CREATE2 deployer at `0x00000000D49195AE81759cd247cFeDD9D0B479df` (7 leading zeros) is used to mint matching addresses across chains. The factory init code hash is `0x30f9d9020bf9622bbe7f8a1625d447efe350dfafd0a91e6dbd62d56547db835f`; bytecode is byte-identical on every deployed chain. Source is verified on each chain's explorer.++### Audits & EAS++- Smart contract audits are scheduled for the reputation, royalty, and delegation contracts as part of Phase 3+- **EAS** (Ethereum Attestation Service) integration ships as a sibling reputation surface — see `/demos/eas-reputation.html` for the viewer+- **0xsplits** SDK is wired for splitting skill royalties across multiple authors++### Registration Flow (EVM)++```+1. POST /api/agents/register-prep → { manifest, typedData }+ (uploads manifest to IPFS, builds EIP-712 typed data for signing)++2. User signs typedData with their wallet++3. POST /api/agents/register-confirm → { txHash, agentId }+ (submits transaction, waits for confirmation, updates agent record)+```++The agent is now an ERC-721 token. Its manifest lives on IPFS. Its action history is anchored to its `agentId`. Any third party can verify the agent's identity, owner, and reputation without trusting three.ws.++### Registration Flow (Solana)++Solana ships an ERC-8004 analog without any custom on-chain program — identity is a Metaplex Core asset, reputation + validation are SPL Memo–anchored attestations referencing that asset.++```+1. POST /api/agents/register-solana → { tx }+ (server builds a Metaplex Core mint instruction; client signs)++2. User signs and submits the tx with their Solana wallet (Phantom / Backpack / Seeker MWA)++3. POST /api/agents/register-solana?step=confirm → { asset, agentId }+ (server verifies the mint, writes back the asset pubkey as the agent's ID)+```++The agent is now a Metaplex Core NFT. Its asset pubkey is the canonical agent ID. Anyone can read every feedback / validation attestation about it via `getSignaturesForAddress(assetPubkey)` — see [Solana variant — same shape, no deployed program](#solana-variant--same-shape-no-deployed-program) below.++### On-Chain Indexing++`api/cron/erc8004-crawl.js` runs every 15 minutes to index new IdentityRegistry mint events. Indexed agents appear in `/discover` and can be imported via `/hydrate`.++### Solana variant — same shape, no deployed program++Solana ships an ERC-8004 analog without any custom on-chain program:++- **Identity** — Metaplex Core NFT minted via `registerSolanaAgent()` (the asset pubkey is the agent ID).+- **Reputation + Validation** — signed SPL Memo transactions referencing the agent asset pubkey, with a JSON envelope (`threews.feedback.v1` / `threews.validation.v1`). Anyone can read every attestation about an agent via `getSignaturesForAddress(assetPubkey)`.++SDK:++```js+import { attestFeedback, attestValidation, listAttestations } from '@three-ws/sdk';++await attestFeedback({ agentAsset, score: 5, network: 'devnet' });+await attestValidation({ agentAsset, taskHash: '0x…', passed: true, network: 'devnet' });+const rows = await listAttestations({ agentAsset, kind: 'all', network: 'devnet' });+```++Server read endpoint: `GET /api/agents/solana-attestations?asset=<pubkey>&kind=feedback|validation|all&network=devnet|mainnet`.++Demo page: [sdk/example/solana-attest.html](sdk/example/solana-attest.html).++### Pump.fun signals (Solana off-chain reputation)++Solana agents can ingest live pump.fun activity (GitHub social-fee claims, token graduations) as off-chain trust signals that feed into the agent's Solana reputation score and surface through the Empathy Layer in real time.++| Surface | Path | Purpose |+| ------------- | ------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| MCP client | [api/\_lib/pumpfun-mcp.js](api/_lib/pumpfun-mcp.js) | Cached JSON-RPC client to upstream `pumpfun-claims-bot` |+| Read API | [api/agents/pumpfun.js](api/agents/pumpfun.js) | `GET ?op=claims\|graduations\|token\|creator`, plus `?_handler=feed` for the SSE event stream and `?_handler=metadata` for token metadata. Auth: session or bearer (`mcp`/`profile` scope). |+| Write actions | [api/agents/pumpfun/[action].js](api/agents/pumpfun/[action].js) | Dynamic dispatcher for `buy`, `sell`, `swap`, `launch`, `pay`, `portfolio`, `balances`, and buyback lifecycle (`create`, `accept`, `withdraw`, `distribute`, `extend_account`, `update_authority`, `update_buyback`). |+| Cron crawler | [api/cron/[name].js](api/cron/[name].js) (`name=pumpfun-signals`) | 15-min sweep that writes the `pumpfun_signals` table; routed through the dynamic cron handler. |+| Skills | [src/agent-skills-pumpfun-watch.js](src/agent-skills-pumpfun-watch.js) | `recent-claims`, `token-intel`, `watch-start`, `watch-stop` |+| Widget | [src/widgets/pumpfun-feed.js](src/widgets/pumpfun-feed.js) | Live cards overlay |+| Reputation | [api/agents/solana/[action].js](api/agents/solana/[action].js) (`action=reputation`) | Reputation summary with the `pumpfun_signals` block included in the response |+| Passport | [api/agents/solana/[action].js](api/agents/solana/[action].js) (`action=card`) | Public passport card with the `pumpfun` block on the agent card |++The crawler runs on a `*/15 * * * *` schedule (see [vercel.json](vercel.json)) and writes into the `pumpfun_signals` table. Agents subscribed via `watch-start` react to incoming events through the existing protocol bus — no new event types required.++Full design and configuration in [docs/solana-pumpfun.md](docs/solana-pumpfun.md).++---++## Pump.fun Integration++Beyond the Solana reputation signals described above, the platform also ships consumer-facing pump.fun tooling:++- **Token Launcher** — UI for creating and launching new tokens, at [public/pumpfun.html](public/pumpfun.html).+- **Live Dashboard** — real-time tracker for new tokens, at [pages/pump-live.html](pages/pump-live.html).+- **Skills** — the [pump-fun-skills/](pump-fun-skills/) directory contains agent skills for reading and acting on pump.fun.++### Token launcher (USDC v2)++The launcher uses pump.fun's v2 USDC quote payload and supports a creator-signer split — the agent's owner can authorize a delegated signer to publish the token without exposing the root key.++| Surface | Path | Purpose |+| ---------------- | ------------------------------ | -------------------------------------------------------- |+| Web UI | `/pumpfun` | One-page launcher (avatar, ticker, supply, fee shares) |+| Prep | `POST /api/pump/launch-prep` | Build the launch transaction with creator + signer split |+| Quote | `POST /api/pump/quote-sdk` | v2 USDC quote (replaces deprecated v1 path) |+| Curve | `GET /api/pump/curve` | Bonding-curve sim for pre-launch pricing preview |+| Dashboard | `GET /api/pump/dashboard` | Per-creator launch history + cumulative revenue |+| Stats | `GET /api/pump/helius-stats` | Helius-backed per-token holder + trade counts |+| Trades stream | `GET /api/pump/trades-stream` | SSE feed of trades for a token |+| Inaugural launch | `scripts/pump-launch-usdc.mjs` | First-USDC launch flow used to mint platform tokens |++### Pump-swap buyback++A buyback flow lets an agent route revenue from x402 paid endpoints into pump-swap purchases of its own token — closing the loop between paid usage and tokenholder value. See [scripts/pump-launch-usdc.mjs](scripts/pump-launch-usdc.mjs) and the inaugural-launch self-contained prompts in [docs/internal/](docs/internal/).++### Pump visualizer++`/pump-visualizer` is a live view of pump.fun activity with three modes:++| Mode | What it shows |+| -------------- | --------------------------------------------------------------------- |+| **Feed** | Newest launches as they happen, with cover images and creator history |+| **Migrations** | Tokens graduating from the curve to pump-swap pools |+| **Pulses** | Real-time trade pulses overlaid on a graph |++The visualizer supports search, sort, live pulses, and auto-refresh. Backed by the same Helius webhooks and JSON-RPC client as the cron crawler.++### Pump.fun MCP edge worker++For external agents that need pump.fun data with strict latency, a Cloudflare Worker mirror of the read API lives in [workers/pump-fun-mcp/](workers/pump-fun-mcp/). Deploy with `wrangler deploy` — the worker proxies the upstream `pumpfun-claims-bot` and answers MCP `tools/call` requests at the edge.++### Channel & Telegram bridge++| Endpoint | Purpose |+| --------------------------------------------------------------- | ------------------------------------------------------- |+| `GET /api/pump/channel-feed` | Per-creator activity feed for any agent's channel page |+| `POST /api/pump/deliver-telegram` | Optional Telegram bridge for trade and migration alerts |+| `POST /api/pump/accept-payment-prep` / `accept-payment-confirm` | Two-step USDC handoff for buyback flow |+| `POST /api/pump/withdraw-prep` / `withdraw-confirm` | Creator fee withdrawal with signature verification |++### Vanity mint addresses++The platform's pump.fun launches pre-grind vanity mint addresses with the WASM grinder so token addresses end in a brand-relevant suffix (`…pump`, `…ws`, etc.). See [WASM Vanity Grinder](#wasm-vanity-grinder).++---++## WASM Vanity Grinder++`/vanity-wallet` is a browser-based vanity-address grinder compiled to WebAssembly. Generate **EVM addresses** with a prefix (`0xBEEF…`) or pattern, or **Solana addresses** (base58 prefix / suffix, e.g. `…pump`) in seconds, fully client-side, without leaking the private key to any server.++| Module | Path | Role |+| -------------- | ------------------------------- | ------------------------------------------------------ |+| WASM grinder | `public/vanity-wallet.html` | Multi-threaded secp256k1 keygen via WebWorkers |+| Solana variant | `scripts/pump-vanity-grind.mjs` | Server-side grinder for pump.fun mint vanity addresses |++Common use cases on the platform: branded agent wallet addresses (e.g. an agent named `agent.eth` getting an address starting with `0xA6EF…`), or pump.fun token mint vanity (e.g. ending in `pump`).++The Solana grinder backs the platform's pump.fun launches — the inaugural USDC token launches use a vanity mint pre-grind to produce shareable token addresses.++---++## Solana Mobile (Seeker)++three.ws ships with Mobile Wallet Adapter (MWA) wired into the web app and a release pipeline for the Solana Mobile dApp Store.++**Wallet detection priority**++On **Seeker / Saga** hardware the app prefers seed-vault-backed signing — private keys never leave the secure element. On standard Android or desktop, the app falls back through WalletConnect and then to browser-extension wallets automatically, with no code change required.++**What MWA unlocks on Seeker hardware**++- x402 USDC payments signed from the seed vault without any browser extension+- Metaplex Core agent mints (Solana on-chain registration) without leaving the app+- SPL Memo attestations (reputation and validation) with hardware-secured signatures+- SIWS (Sign-In with Solana) sessions authenticated at the chip level, not the software layer++**Release pipeline**++- dApp Store listing copy and release config live under [`solana-mobile/publish/`](solana-mobile/publish/)+- Release pipeline scripts handle build → sign → APK submission for dApp Store updates+- The listing targets Seeker-first and is compatible with Saga Gen 1 and Gen 2++---++## Vision++One day, creating your agent should be as simple as taking a selfie.++Point your camera at yourself — or anyone — and watch a fully realized 3D avatar emerge: your face, your voice, your personality, alive in the browser. That avatar becomes an agent with memory and skills, registered onchain — as an ERC-8004 token on EVM or a Metaplex Core asset on Solana — permanent and verifiable by anyone forever. No 3D software. No wallet setup. No uploads. Just a photo and a name.++This is the direction three.ws is heading: **photo → avatar → agent → onchain identity**, in a single flow. The infrastructure is already here — the viewer, the runtime, the contracts, the embedding layer. What comes next is closing the gap between a picture of a person and a living, ownable, embeddable piece of them that exists on the internet permanently.++---++## Roadmap-**ValidationRegistry.sol** — records validator attestations for off-chain proofs (glTF validation reports, skill audits, security reviews). The **Solana analog** uses SPL Memo with envelope `threews.validation.v1` against the agent's Metaplex Core asset pubkey.+three.ws ships in four phases. Each phase closes a specific gap between the current platform and the end-state vision: **anyone can mint a 3D agent of themselves, own it onchain, and embed it anywhere on the internet.**-### Deployment Addresses+| Phase | Theme | Status |+| ----- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |+| **0** | Platform foundations (viewer, runtime, ERC-8004 + Metaplex Core identity, embed layer) | ✅ Shipped |+| **1** | Selfie → Avatar engine (3-photo capture, hosted inference) | 🟡 In progress — capture UX + quality gates shipped; GPU reconstruction backend wiring |+| **2** | Agent personalization + voice cloning | 🟡 In progress — voice clone, persona, memory seeds shipped behind `/demos`; main-flow integration next |+| **3** | Onchain economy (agent tokens, reputation markets, royalties) | 🟡 Scaffolding — bonding-curve sim, EAS-reputation viewer, 0xsplits + EAS SDKs landed; contracts + audits next |+| **4** | Open inference network (decentralized GPU layer) | 🔮 Future — livepeer dep landed for early experimentation |-See [`contracts/DEPLOYMENTS.md`](contracts/DEPLOYMENTS.md) for current mainnet and testnet addresses. All three registries are deployed via **CREATE2** against a custom vanity-prefixed factory, so the **same address is used on every supported EVM chain** within an environment class — mainnet contracts have one address, testnet contracts another.+----**Mainnet (across Ethereum, Optimism, BSC, Gnosis, Polygon, Fantom, zkSync Era, Moonbeam, Mantle, Base, Arbitrum One, Celo, Avalanche, Linea, Scroll):**+### Phase 0 — Foundations _(Shipped)_-| Contract | Address |-| ------------------ | -------------------------------------------- |-| IdentityRegistry | `0x8004A169FB4a3325136EB29fA0ceB6D2e539a432` |-| ReputationRegistry | `0x8004BAa17C55a88189AE136b182e5fdA19dE9b63` |-| ValidationRegistry | _(same address on all chains)_ |+The full stack is live at [three.ws](https://three.ws): WebGL viewer, LLM agent runtime, ERC-8004 identity contracts (EVM) and Metaplex Core mints (Solana), OAuth 2.1 server, MCP endpoint, and the `<agent-3d>` web component. Anyone can register an agent today — but the avatar still has to come from a 3D artist or a third-party tool.-**Testnet (BSC Testnet, Ethereum Sepolia, Base Sepolia, Arbitrum Sepolia, Optimism Sepolia, Polygon Amoy, Avalanche Fuji):**+**What works:** model upload, agent runtime, onchain registration, embedding, signed action history, reputation scores.+**What doesn't:** there is no automated path from a real human face to a usable 3D avatar.-| Contract | Address |-| ------------------ | -------------------------------------------- |-| IdentityRegistry | `0x8004A818BFB912233c491871b3d84c89A494BD9e` |-| ReputationRegistry | `0x8004B663056A597Dffe9eCcC1965A193B7388713` |-| ValidationRegistry | `0x8004Cb1BF31DAf7788923b405b754f57acEB4272` |+----### CREATE2 Factory (ThreeWSFactory)+### Phase 1 — Selfie → Avatar Engine-A custom vanity-prefixed CREATE2 deployer at `0x00000000D49195AE81759cd247cFeDD9D0B479df` (7 leading zeros) is used to mint matching addresses across chains. The factory init code hash is `0x30f9d9020bf9622bbe7f8a1625d447efe350dfafd0a91e6dbd62d56547db835f`; bytecode is byte-identical on every deployed chain. Source is verified on each chain's explorer.+**Goal:** any user takes 3 selfies (left, center, right) and receives a rigged, animatable 3D avatar in under 60 seconds.-### Audits & EAS+**Deliverables**-- Smart contract audits are scheduled for the reputation, royalty, and delegation contracts as part of Phase 3-- **EAS** (Ethereum Attestation Service) integration ships as a sibling reputation surface — see `/demos/eas-reputation.html` for the viewer-- **0xsplits** SDK is wired for splitting skill royalties across multiple authors+- Mobile-first capture UX with realtime quality gates (lighting, framing, blur)+- Multi-view face reconstruction pipeline (FLAME / 3DMM fitting on top of a base body mesh)+- Hosted inference workers (GPU-backed) for sub-minute generation+- Output written directly to R2 and minted as a draft agent token — ERC-8004 on EVM, Metaplex Core asset on Solana-### Registration Flow (EVM)+**Compute requirements**-```-1. POST /api/agents/register-prep → { manifest, typedData }- (uploads manifest to IPFS, builds EIP-712 typed data for signing)+- A100/H100-class GPUs for inference, sized to ~10k avatars/day at launch+- Training budget for fine-tuning a stylized face-fitter on a curated dataset+- CDN egress scaling for high-res GLB delivery-2. User signs typedData with their wallet+**Verification:** 1,000 test users complete capture and mint an onchain agent of themselves end-to-end with ≥4/5 likeness score.-3. POST /api/agents/register-confirm → { txHash, agentId }- (submits transaction, waits for confirmation, updates agent record)-```+----The agent is now an ERC-721 token. Its manifest lives on IPFS. Its action history is anchored to its `agentId`. Any third party can verify the agent's identity, owner, and reputation without trusting three.ws.+### Phase 2 — Agent Personalization-### Registration Flow (Solana)+**Goal:** the avatar isn't just _you_ — the agent _acts_ like you.-Solana ships an ERC-8004 analog without any custom on-chain program — identity is a Metaplex Core asset, reputation + validation are SPL Memo–anchored attestations referencing that asset.+**Deliverables**-```-1. POST /api/agents/register-solana → { tx }- (server builds a Metaplex Core mint instruction; client signs)+- Voice cloning (3–10 seconds of speech → ElevenLabs custom voice bound to the agent)+- Persona extraction from a short onboarding interview (tone, vocabulary, interests)+- Memory seeding from connected accounts (X, GitHub, Farcaster) with explicit user consent+- Per-agent fine-tuned system prompt stored in the manifest, signed and pinned to IPFS-2. User signs and submits the tx with their Solana wallet (Phantom / Backpack / Seeker MWA)+**Verification:** users return to converse with their own agent; ≥30% week-2 retention on minted agents.-3. POST /api/agents/register-solana?step=confirm → { asset, agentId }- (server verifies the mint, writes back the asset pubkey as the agent's ID)-```+----The agent is now a Metaplex Core NFT. Its asset pubkey is the canonical agent ID. Anyone can read every feedback / validation attestation about it via `getSignaturesForAddress(assetPubkey)` — see [Solana variant — same shape, no deployed program](#solana-variant--same-shape-no-deployed-program) below.+### Phase 3 — Onchain Economy-### On-Chain Indexing+**Goal:** agents are real economic objects on EVM and Solana, not just collectibles.-`api/cron/erc8004-crawl.js` runs every 15 minutes to index new IdentityRegistry mint events. Indexed agents appear in `/discover` and can be imported via `/hydrate`.+**Deliverables**-### Solana variant — same shape, no deployed program+- **Agent tokens** — ERC-8004 mints with bonding-curve pricing or fair launch options+- **Reputation markets** — stake on agents, earn from their action history (extends `ReputationRegistry.sol`)+- **Skill royalties** — skill authors earn per-call fees through EIP-7710 delegated permissions+- **Agent-to-agent payments** — agents transact autonomously via their delegated signer wallets+- **Subscriptions & DCA** — recurring onchain payments to creators (cron infra already in place)-Solana ships an ERC-8004 analog without any custom on-chain program:+**Funding requirements**-- **Identity** — Metaplex Core NFT minted via `registerSolanaAgent()` (the asset pubkey is the agent ID).-- **Reputation + Validation** — signed SPL Memo transactions referencing the agent asset pubkey, with a JSON envelope (`threews.feedback.v1` / `threews.validation.v1`). Anyone can read every attestation about an agent via `getSignaturesForAddress(assetPubkey)`.+- Smart contract audits (multi-firm) for the reputation, royalty, and delegation contracts+- Liquidity for agent token launches+- Indexer infrastructure across Base, Solana, and additional EVM chains-SDK:+**Verification:** ≥1,000 agents minted with active onchain reputation; ≥$X in cumulative skill royalties paid out.-```js-import { attestFeedback, attestValidation, listAttestations } from '@three-ws/sdk';+----await attestFeedback({ agentAsset, score: 5, network: 'devnet' });-await attestValidation({ agentAsset, taskHash: '0x…', passed: true, network: 'devnet' });-const rows = await listAttestations({ agentAsset, kind: 'all', network: 'devnet' });-```+### Phase 4 — Open Inference Network-Server read endpoint: `GET /api/agents/solana-attestations?asset=<pubkey>&kind=feedback|validation|all&network=devnet|mainnet`.+**Goal:** decouple agent inference from any single provider. Anyone can run a node; agents pay nodes onchain for compute.-Demo page: [sdk/example/solana-attest.html](sdk/example/solana-attest.html).+**Deliverables**-### Pump.fun signals (Solana off-chain reputation)+- Open protocol for agent inference (model weights, GPU runtime, signed responses)+- Node operator client (Docker + GPU drivers) with onchain registration+- Onchain settlement for inference jobs — pay-per-token with cryptographic receipts+- Federation with existing decentralized compute networks where appropriate-Solana agents can ingest live pump.fun activity (GitHub social-fee claims, token graduations) as off-chain trust signals that feed into the agent's Solana reputation score and surface through the Empathy Layer in real time.+**Compute requirements**-| Surface | Path | Purpose |-| ------------- | ------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| MCP client | [api/\_lib/pumpfun-mcp.js](api/_lib/pumpfun-mcp.js) | Cached JSON-RPC client to upstream `pumpfun-claims-bot` |-| Read API | [api/agents/pumpfun.js](api/agents/pumpfun.js) | `GET ?op=claims\|graduations\|token\|creator`, plus `?_handler=feed` for the SSE event stream and `?_handler=metadata` for token metadata. Auth: session or bearer (`mcp`/`profile` scope). |-| Write actions | [api/agents/pumpfun/[action].js](api/agents/pumpfun/[action].js) | Dynamic dispatcher for `buy`, `sell`, `swap`, `launch`, `pay`, `portfolio`, `balances`, and buyback lifecycle (`create`, `accept`, `withdraw`, `distribute`, `extend_account`, `update_authority`, `update_buyback`). |-| Cron crawler | [api/cron/[name].js](api/cron/[name].js) (`name=pumpfun-signals`) | 15-min sweep that writes the `pumpfun_signals` table; routed through the dynamic cron handler. |-| Skills | [src/agent-skills-pumpfun-watch.js](src/agent-skills-pumpfun-watch.js) | `recent-claims`, `token-intel`, `watch-start`, `watch-stop` |-| Widget | [src/widgets/pumpfun-feed.js](src/widgets/pumpfun-feed.js) | Live cards overlay |-| Reputation | [api/agents/solana/[action].js](api/agents/solana/[action].js) (`action=reputation`) | Reputation summary with the `pumpfun_signals` block included in the response |-| Passport | [api/agents/solana/[action].js](api/agents/solana/[action].js) (`action=card`) | Public passport card with the `pumpfun` block on the agent card |+- Bootstrap GPU credits for early node operators+- Cryptoeconomic security model (slashing, validator set) — research + audit budget-The crawler runs on a `*/15 * * * *` schedule (see [vercel.json](vercel.json)) and writes into the `pumpfun_signals` table. Agents subscribed via `watch-start` react to incoming events through the existing protocol bus — no new event types required.+**Verification:** ≥50% of production agent traffic served by independent node operators; latency parity with centralized inference.-Full design and configuration in [docs/solana-pumpfun.md](docs/solana-pumpfun.md).+---++### What we need++| Resource | Used for | Phase |+| -------------------------- | ------------------------------------------ | ----- |+| **Inference GPUs** | Avatar generation, agent conversations | 1, 2 |+| **Training compute** | Fine-tuned face-fitter, voice models | 1, 2 |+| **Smart contract audits** | Reputation, royalty, delegation contracts | 3 |+| **Token launch liquidity** | Agent token markets | 3 |+| **Indexer infrastructure** | Multi-chain crawl + reputation aggregation | 3 |+| **Node operator credits** | Bootstrap the open inference network | 4 |+| **Engineering headcount** | Capture pipeline, contracts, indexer, ops | 1–4 |++Phases 1 and 2 unblock the consumer story — _anyone gets an agent of themselves_. Phases 3 and 4 unblock the onchain story — _those agents are real economic actors that don't depend on any one company to keep running_. Both are required for the vision; neither is funded yet.++If you want to support the project — compute credits, grants, partnerships, or contributions — open an issue or reach out via [three.ws](https://three.ws).----## Pump.fun Integration+## Selfie Reconstruction Pipeline (Phase 1)-Beyond the Solana reputation signals described above, the platform also ships consumer-facing pump.fun tooling:+Anyone takes 3 selfies (left, center, right) and receives a rigged, animatable 3D avatar in under a minute. The pipeline ships native — no third-party black box.-- **Token Launcher** — UI for creating and launching new tokens, at [public/pumpfun.html](public/pumpfun.html).-- **Live Dashboard** — real-time tracker for new tokens, at [pages/pump-live.html](pages/pump-live.html).-- **Skills** — the [pump-fun-skills/](pump-fun-skills/) directory contains agent skills for reading and acting on pump.fun.+| Module | Path | Role |+| ------------- | ------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------- |+| Capture UX | [src/selfie-capture.js](src/selfie-capture.js) | Mobile-first 3-shot capture with real-time quality gates (lighting, framing, blur) |+| Pipeline | [src/selfie-pipeline.js](src/selfie-pipeline.js) | Multi-view fit → FLAME / 3DMM face → base body mesh → rigged GLB |+| Sandbox route | `/creating` | Isolated reconstruction test bench, decoupled from the main flow |+| Output | Cloudflare R2 | Meshopt-compressed GLB pinned to IPFS and minted as a draft agent token — ERC-8004 on EVM or Metaplex Core on Solana |-### Token launcher (USDC v2)+Reconstruction inference runs against the same Cloud Run handler pool as the agent runtime, with optional offload to the **Livepeer Inference Network** (see below) for GPU-heavy steps.-The launcher uses pump.fun's v2 USDC quote payload and supports a creator-signer split — the agent's owner can authorize a delegated signer to publish the token without exposing the root key.+----| Surface | Path | Purpose |-| ---------------- | ------------------------------ | -------------------------------------------------------- |-| Web UI | `/pumpfun` | One-page launcher (avatar, ticker, supply, fee shares) |-| Prep | `POST /api/pump/launch-prep` | Build the launch transaction with creator + signer split |-| Quote | `POST /api/pump/quote-sdk` | v2 USDC quote (replaces deprecated v1 path) |-| Curve | `GET /api/pump/curve` | Bonding-curve sim for pre-launch pricing preview |-| Dashboard | `GET /api/pump/dashboard` | Per-creator launch history + cumulative revenue |-| Stats | `GET /api/pump/helius-stats` | Helius-backed per-token holder + trade counts |-| Trades stream | `GET /api/pump/trades-stream` | SSE feed of trades for a token |-| Inaugural launch | `scripts/pump-launch-usdc.mjs` | First-USDC launch flow used to mint platform tokens |+## Voice & Persona Hub (Phase 2)-### Pump-swap buyback+The avatar isn't just _you_ — the agent _acts_ like you. The Voice & Persona Hub captures the inputs that turn a body into a personality.-A buyback flow lets an agent route revenue from x402 paid endpoints into pump-swap purchases of its own token — closing the loop between paid usage and tokenholder value. See [scripts/pump-launch-usdc.mjs](scripts/pump-launch-usdc.mjs) and the inaugural-launch self-contained prompts in [docs/internal/](docs/internal/).+| Surface | Path | Purpose |+| ------------------- | -------------------------------------------------------------------- | ---------------------------------------------------------------- |+| Persona extraction | [api/persona/extract.js](api/persona/extract.js) | Short onboarding interview → tone, vocabulary, interests profile |+| Persona preview | [api/persona/preview.js](api/persona/preview.js) | Try the extracted persona against test prompts before saving |+| Persona keys | `scripts/generate-persona-key.mjs` | Per-agent signing key + persona SSO setup |+| Voice clone modal | [src/voice/voice-clone-modal.js](src/voice/voice-clone-modal.js) | 3–10s recording → ElevenLabs custom voice bound to the agent |+| Talk controller | [src/voice/talk-controller.js](src/voice/talk-controller.js) | Push-to-talk and continuous talk modes |+| ARKit blendshapes | [src/voice/arkit-blendshapes.js](src/voice/arkit-blendshapes.js) | Standard ARKit-52 morph table |+| Lip-sync driver | [src/voice/lipsync-driver.js](src/voice/lipsync-driver.js) | Web Audio analyser → blendshape weights per frame |+| Avatar morph target | [src/voice/avatar-morph-target.js](src/voice/avatar-morph-target.js) | Per-rig binding of ARKit blendshapes to the loaded GLB |+| Avatar snapshot | [src/voice/avatar-snapshot.js](src/voice/avatar-snapshot.js) | Render-time pose capture for thumbnails and OG cards |+| Persona docs | [docs/persona-hub.md](docs/persona-hub.md) | Full design + onboarding flow |-### Pump visualizer+Memory seed extensions (X, GitHub, Farcaster) feed the agent's memory store at creation time with explicit user consent — see [docs/persona-hub.md](docs/persona-hub.md).-`/pump-visualizer` is a live view of pump.fun activity with three modes:+The per-agent fine-tuned system prompt is stored in the manifest, signed, and pinned to IPFS — the persona becomes a verifiable part of the agent's onchain identity.-| Mode | What it shows |-| -------------- | --------------------------------------------------------------------- |-| **Feed** | Newest launches as they happen, with cover images and creator history |-| **Migrations** | Tokens graduating from the curve to pump-swap pools |-| **Pulses** | Real-time trade pulses overlaid on a graph |+----The visualizer supports search, sort, live pulses, and auto-refresh. Backed by the same Helius webhooks and JSON-RPC client as the cron crawler.+## Livepeer Inference Network (Phase 4)-### Pump.fun MCP edge worker+three.ws is wiring the **Livepeer** decentralized GPU network as an alternative inference backend for avatar reconstruction and agent conversations.-For external agents that need pump.fun data with strict latency, a Cloudflare Worker mirror of the read API lives in [workers/pump-fun-mcp/](workers/pump-fun-mcp/). Deploy with `wrangler deploy` — the worker proxies the upstream `pumpfun-claims-bot` and answers MCP `tools/call` requests at the edge.+- Open protocol: model weights, GPU runtime, signed responses+- Onchain settlement: pay-per-token with cryptographic receipts, mediated by the same x402 rails described above+- Node operator client (Docker + GPU drivers) with onchain registration+- Federation with existing decentralized compute networks where appropriate-### Channel & Telegram bridge+The Livepeer dependency landed early so the Phase 1 selfie pipeline can switch its heaviest step (multi-view face fitting) onto external GPU nodes without touching the rest of the system. The goal: ≥50% of production agent traffic served by independent node operators with latency parity to centralized inference.-| Endpoint | Purpose |-| --------------------------------------------------------------- | ------------------------------------------------------- |-| `GET /api/pump/channel-feed` | Per-creator activity feed for any agent's channel page |-| `POST /api/pump/deliver-telegram` | Optional Telegram bridge for trade and migration alerts |-| `POST /api/pump/accept-payment-prep` / `accept-payment-confirm` | Two-step USDC handoff for buyback flow |-| `POST /api/pump/withdraw-prep` / `withdraw-confirm` | Creator fee withdrawal with signature verification |+----### Vanity mint addresses+## News CMS & Syndication-The platform's pump.fun launches pre-grind vanity mint addresses with the WASM grinder so token addresses end in a brand-relevant suffix (`…pump`, `…ws`, etc.). See [WASM Vanity Grinder](#wasm-vanity-grinder).+A local-only news/blog CMS at `/admin/news` produces signed posts that auto-syndicate to multiple destinations.++| Surface | Path | Purpose |+| -------------- | ---------------------------------------------------------- | --------------------------------------------------- |+| CMS | `/admin/news` | Local-only editor — drafts, images, scheduled posts |+| Public listing | `/news` | Cover-image grid with permalinks |+| Article | `/news/<slug>` | Server-rendered article with OG card |+| RSS / Atom | `/api/news/rss` | Standards-compliant feed for HackerNoon auto-import |+| WebSub hub | `/api/news/websub` | Push notifications to subscribed hubs on publish |+| Dev.to | syndication adapter | Cross-posts with canonical URL pointing back |+| Medium | syndication adapter | Same, with format-aware re-render |+| CMC handoff | syndication adapter | Coinmarketcap article + announcement listing |+| Newsletter | [api/newsletter-subscribe.js](api/newsletter-subscribe.js) | Resend-backed double-opt-in newsletter |++Each article is a static HTML file in `public/news/` with metadata in Postgres. The CMS supports a cover-image convention for listing thumbnails and OG previews. Articles can be published once and reach HackerNoon, Dev.to, and Medium readers without manual cross-posting.++---++## Security Hardening++The platform has been hardened against the OWASP top-10 plus a set of issues specific to agent payments and cross-chain identity.++| Control | Where |+| ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |+| **SSRF guard** | All outbound `fetch()` from agent runtime + skills goes through an SSRF allow-list filter (`api/_lib/safe-fetch.js`) |+| **CSRF gates** | State-changing endpoints require an Origin + Sec-Fetch-Site check; bearer-only paths exempt |+| **Header-origin pinning** | The iframe bridge locks onto the parent's origin from the first authenticated message and ignores later messages from a different origin |+| **Fail-closed crons** | Cron endpoints fail closed if their auth token is missing — no silent skips |+| **Idempotency tokens** | x402 paid endpoints require an idempotency key to prevent double-charge on retry |+| **Embed policy** | Per-agent iframe origin allow-list (`/api/agents/:id/embed-policy`) gates the chromeless embed |+| **Rate limiting** | Upstash Redis per-user + per-API-key + per-IP buckets at every public endpoint |+| **JWT key rotation** | `JWT_KID` lets you rotate signing keys without invalidating in-flight sessions |+| **Bcrypt cost** | Tunable via `PASSWORD_ROUNDS` (default 11) |+| **Audit signing** | Every agent action is signed with the delegated signer key and chained into a per-agent action log |---diff --git a/STRUCTURE.md b/STRUCTURE.mdindex 0e1019db2..bb7ec66a1 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -23,6 +23,7 @@ bottom.| Guided site tour | [tour-sdk/](tour-sdk) | Published as `@three-ws/tour` | 3D guide walks a live site, spotlights sections, narrates each. One-tag CDN build + free roam || Concierge (embeddable AI support chat) | [concierge-sdk/](concierge-sdk), backend [api/concierge.js](api/concierge.js) `→ /api/concierge`, landing [pages/concierge.html](pages/concierge.html) `→ /concierge`, first-party CDN copy `→ /concierge/concierge.global.js` (mirrored by [concierge-sdk/build.mjs](concierge-sdk/build.mjs)) | Published as `@three-ws/concierge` | An AI concierge for ANY website: floating launcher, chat panel with a rigged 3D avatar bust (blink/idle/viseme lipsync via the page-agent stage lineage), SSE-streamed answers grounded in the live page (ask-time DOM harvest + host `knowledge`, no crawler), speaks while streaming (sentence-level TTS handoff), push-to-talk mic, themes/accent/position, avatar picker or custom GLB. Backend is anonymous + CORS-`*` (third-party origins by design) with its own rate buckets (`limits.conciergeIp`/`conciergeGlobal`), fail-open moderation, and streaming failover over the shared free-first chain (api/_lib/llm.js). Shopping mode (Shopify): when embedded on a Shopify storefront it auto-detects the store (`window.Shopify` / `shop` config) and becomes a shopping assistant, reading the store's public `/products.json` + `/collections.json` + `/policies/*` at ask-time (no key, no crawler, same-origin), retrieving the relevant products per question via keyword+intent search ([concierge-sdk/src/shopify.js](concierge-sdk/src/shopify.js)), grounding the answer in them, and rendering real product cards (image/live price/link + on-store `/cart/add.js` add-to-cart). The endpoint accepts a bounded `shopping` payload and swaps the system prompt to a store assistant. `<three-concierge>` element, `data-concierge` one-tag auto-init, or `new Concierge({...})`. Also reachable from any AI agent via the MCP server [packages/concierge-mcp/](packages/concierge-mcp) (`@three-ws/concierge-mcp`, registry `io.github.nirholas/concierge-mcp`): `concierge_ask` (ask any site's concierge, grounded in the fetched page), `concierge_embed` (generate the embed), `concierge_avatars`. Examples: [concierge-sdk/examples/](concierge-sdk/examples) (one-tag, web component, imperative, custom avatar, React, self-hosted backend). Docs: [docs/concierge.md](docs/concierge.md), tutorial [docs/tutorials/build-a-site-concierge.md](docs/tutorials/build-a-site-concierge.md). Tests: [concierge-sdk/test/](concierge-sdk/test), [tests/api-concierge.test.js](tests/api-concierge.test.js), [packages/concierge-mcp/test/](packages/concierge-mcp/test) || Assistant widget (3D avatar assistant for any website) | Loader [public/assistant/v1.js](public/assistant/v1.js) `-> /assistant/v1.js`, iframe app [pages/assistant-frame.html](pages/assistant-frame.html) + [src/assistant-frame.js](src/assistant-frame.js) `-> /assistant-frame`, builder [pages/assistant.html](pages/assistant.html) + [src/assistant-page.js](src/assistant-page.js) `-> /assistant`, shared validators [src/assistant-widget-core.js](src/assistant-widget-core.js). npm SDK [assistant-sdk/](assistant-sdk) (`@three-ws/assistant`) is the single source for the loader; its [build.mjs](assistant-sdk/build.mjs) emits the npm ESM + the mirrored one-tag build at `public/assistant/v1.js`. MCP server [packages/assistant-mcp/](packages/assistant-mcp) (`@three-ws/assistant-mcp`, registry `io.github.nirholas/assistant-widget`): `build_assistant_widget` (config -> paste-ready snippet + frame URL + JS-API call), `list_assistant_options` (avatars, backgrounds, modes, attributes). | Published as `@three-ws/assistant` | One script tag adds a floating launcher to any site; clicking it pops up a full-body animated avatar against the host page (transparent) or a color/gradient. Two modes: chatbot (free chain via POST /api/chat, or the visitor's own Groq/OpenRouter key sent browser-to-provider, stored in the frame's localStorage only) and speak mode (avatar repeats typed text out loud via Web Speech + head-anchored speech bubble + talking clip). All params re-validated in-frame (CSS/URL injection safe). Sibling of Concierge (chat panel) - this one is the full-body, avatar-first widget. Install three ways: one-tag CDN, `npm i @three-ws/assistant`, or the MCP server for AI agents. Examples: [assistant-sdk/examples/](assistant-sdk/examples). Docs: [docs/assistant-widget.md](docs/assistant-widget.md) `-> /docs/assistant-widget`, tutorial [docs/tutorials/add-a-3d-assistant.md](docs/tutorials/add-a-3d-assistant.md). Tests: [tests/assistant-widget.test.js](tests/assistant-widget.test.js), [assistant-sdk/test/](assistant-sdk/test), [packages/assistant-mcp/test/](packages/assistant-mcp/test) |+| Chat (conversational surface) | [chat/](chat) `→ /chat` | Live | Svelte 4 + Vite client, fork of eplus, built by `build:chat` inside `build:gcp` into `public/chat` → `dist/chat`. Free Built-in lane via `/api/chat/proxy` plus BYOK providers; inline 3D forge tools + ModelViewer3D; shares the platform wallet via [src/shared/](src/shared). Docs: [chat/README.md](chat/README.md) || three.ws's own guided tour + onboarding | [src/feature-tour/](src/feature-tour) `→ /feature-tour.js`, entry [src/feature-tour.js](src/feature-tour.js), curriculum [public/tour/curriculum.json](public/tour/curriculum.json) generated by [scripts/build-tour.mjs](scripts/build-tour.mjs), landing [pages/tour.html](pages/tour.html) `→ /tour` | Live | A hardened, site-native fork of the [tour-sdk/](tour-sdk) engine (same curriculum schema — stops/sections/tracks/highlight/narration/targets), lazy-injected only when a tour is starting/active (`feature-tour-boot` Vite plugin) so pages that never tour pay no Three.js cost. Three tracks share one curriculum: `full` (every feature, chapter by chapter), `quick` (highlighted heroes), and `onboarding` (added 2026-07-12) — a 6-stop, hand-authored new-account walkthrough chaining `/start` → make an avatar (`/create/selfie`) → build a world (`/diorama`) → live `/markets` data → an optional coin launch (`/create-agent`, clearly skippable) → the new creator's own `/profile`. Auto-offered once to a signed-in account with zero creations across avatars/agents/forged models/worlds (`GET /api/me` → `show_onboarding_tour`, backed by `users.onboarding_tour_seen_at`/`onboarding_tour_completed_at`, migration [api/_lib/migrations/20260712030000_onboarding_tour_state.sql](api/_lib/migrations/20260712030000_onboarding_tour_state.sql)); always reachable afterward via "🎬 Replay guided tour" in the [public/getting-started.js](public/getting-started.js) checklist panel. Tests: [tests/feature-tour-curriculum.test.js](tests/feature-tour-curriculum.test.js), [tests/api-me-onboarding-tour.test.js](tests/api-me-onboarding-tour.test.js) || Onboarding tier (Simple ⇄ Everything) | Menu tags [public/nav-data.js](public/nav-data.js), runtime + `window.twsTier` [public/nav.js](public/nav.js), styles [public/nav.css](public/nav.css), homepage start path + gate [pages/home.html](pages/home.html) + [public/home.css](public/home.css) | Live | Progressive disclosure for first-time visitors: the platform's ~100 nav destinations and ten deep homepage sections were competing with its core promise, so a new visitor now gets the ~21 links and the sections that carry one journey — make an avatar, build an agent, publish it — with a three-step start path under the hero. Everything else (the whole Launch menu, trading, token economy, Oracle, pay-per-call, dev platform, the stack) is tagged `tier: 'advanced'` / `data-tier="advanced"` and revealed by one control. Mechanism is one `<html>` class (`tws-lite`) over one localStorage key (`tws:tier`), applied pre-paint and never re-rendered (the nav binds document-level listeners once), with the two surfaces synced through a `tws:tier-change` event. Deep links into a gated section reveal it for that visit. Nothing is removed, only deferred. Docs: [docs/onboarding-tier.md](docs/onboarding-tier.md). Tests: [tests/onboarding-tier.test.js](tests/onboarding-tier.test.js) || Tour Builder (no-code playground) | [pages/tour-builder.html](pages/tour-builder.html) `→ /tour-builder` | Live | Point-and-click editor over a demo storefront: pick avatar, add stops, preview the real tour, export curriculum + Shopify snippets. Also ships **Templates** — ready-made tours (Sperax's DeFi protocol tour is the first) that load straight into the editor. Logic: [public/tour-builder/builder.js](public/tour-builder/builder.js), presets: [public/tour-builder/presets/](public/tour-builder/presets). Sperax template doc: [docs/tutorials/sperax-tour.md](docs/tutorials/sperax-tour.md) |@@ -59,21 +60,21 @@ bottom.| AR Studio (multi-model live camera scene) | [pages/ar-studio.html](pages/ar-studio.html) `→ /ar/studio` + [src/ar-studio.js](src/ar-studio.js), multi-anchor WebXR session [src/ar/multi-place.js](src/ar/multi-place.js), pure scene math [src/ar/studio-scene.js](src/ar/studio-scene.js) | Live | The standalone multi-model AR surface: place ANY number of models/avatars into one live camera view (every earlier AR lane was single-model). Model sources: in-view forge (`POST /api/forge {backend:"nvidia"}` runs behind the live camera, result drops into the room), the forge gallery (`/api/forge-gallery` — yours + community tabs), recent forges (localStorage, shared with `/ar`), the CC0 Object Library (`/api/objects/library`, an Objects tray tab with client-side name/category search), a pasted GLB link, or repeatable `?src=` deep links (https/relative only). Rendering ladder: WebXR immersive-ar with one XRAnchor per placed model + always-armed reticle (Android), getUserMedia passthrough + gyro world-lock (iOS/everywhere), grid preview + drag-look + QR handoff (desktop). Gestures: tap select, drag move, pinch resize, two-finger twist rotate; per-model duplicate/rotate/remove, clear-with-undo. Humanoids with no baked clips idle via the universal retarget ([src/irl/pin-idle.js](src/irl/pin-idle.js)); scene persists in localStorage and the whole ARRANGEMENT (models + transforms) round-trips through a base64url `#s=` hash on the share/QR URL, so a composed scene reopens exactly on any device. **Presence realism:** WebXR placements are lit by the real room via lighting-estimation ([src/ar/estimated-lighting.js](src/ar/estimated-lighting.js), three's `XREstimatedLight` — real primary-light direction/colour + a live environment cube map so metal/glass reflect the actual room, reverting to baked lights when the device isn't estimating) and occluded by real geometry via depth-sensing ([src/ar/depth-occlusion.js](src/ar/depth-occlusion.js)); the passthrough path matches room brightness AND colour by sampling the camera feed. Desktop keyboard controls (arrows nudge / R rotate / D duplicate / Delete). Photo capture composites camera + WebGL ([src/irl/share-frame.js](src/irl/share-frame.js)). Reachable from `/ar`, the forge AR panel, and the `/viewer` action sheet. **Shared rooms (build together, live):** "Share live" opens a room with a 6-char code; anyone who opens `/ar/studio?room=CODE` joins the same scene and every add / move / scale / rotate / remove delta-syncs in real time, with a live "N here" presence pill. New Colyseus room [multiplayer/src/rooms/StudioRoom.js](multiplayer/src/rooms/StudioRoom.js) + schema [multiplayer/src/studio-schemas.js](multiplayer/src/studio-schemas.js) (owner-gated edits, per-room/per-owner caps, per-client rate limit, https-only src validation — same discipline as WalkRoom's object channel), client wrapper [src/ar/studio-net.js](src/ar/studio-net.js), and a shared logical coordinate frame [src/ar/studio-coords.js](src/ar/studio-coords.js) (relEast/relNorth/yawDeg) so every device agrees on placement; QR-marker colocalization ([src/irl/marker-anchor.js](src/irl/marker-anchor.js)) is the co-located "same physical table" upgrade. Runs on the same Colyseus host as /walk and /irl (a new room, not a new process). Tests: [tests/ar-studio-scene.test.js](tests/ar-studio-scene.test.js), [tests/ar-studio-coords.test.js](tests/ar-studio-coords.test.js), [tests/ar-estimated-lighting.test.js](tests/ar-estimated-lighting.test.js), [tests/studio-room.test.js](tests/studio-room.test.js). || IRL (agents in the real world) | [pages/irl.html](pages/irl.html) `→ /irl` + [src/irl.js](src/irl.js), WebXR placement [src/ar/webxr.js](src/ar/webxr.js) + pinch [src/ar/pinch-scale.js](src/ar/pinch-scale.js), animated Quick Look bake [src/usdz-animated.js](src/usdz-animated.js) (static fallback [src/usdz-pipeline.js](src/usdz-pipeline.js)), backend [api/irl/](api/irl) | Live | Pin an agent at a real GPS spot; discovery is presence-proof-gated ([docs/irl/THREAT-MODEL.md](docs/irl/THREAT-MODEL.md)). **Place in AR** leads the dock on AR-capable devices: WebXR hit-test anchoring on Android with two-finger pinch resize (25%..400%) persisted to the pin (`anchor_scale`; the pinch lands as a follow-up `PATCH /api/irl/pins {id, scale}` after the placement tap), and ARKit Quick Look on iOS with the idle clip baked into the USDZ so the agent moves instead of standing in a T-pose. Discovered pins are equally alive in the in-page camera view: every mounted humanoid GLB plays the retargeted idle clip via a per-pin mixer ([src/irl/pin-idle.js](src/irl/pin-idle.js), phase-randomized, LOD-bounded), camera-aware gaze composes on top of the running animation, and the scene renders with ACES tone mapping + IBL + soft shadows (e2e: [tests/e2e/irl-pin-idle.spec.js](tests/e2e/irl-pin-idle.spec.js)). Inbound `/irl?avatar=<glb>` is the living-agent handoff from `GET /api/ar?…&kind=avatar` (explicit `?avatar=` wins over a saved session). Money Drops and World Lines: [docs/irl.md](docs/irl.md). SDK: [packages/irl/](packages/irl). **Share** ([src/irl/share-frame.js](src/irl/share-frame.js), [api/irl/share.js](api/irl/share.js), [api/irl/share/[token].js](api/irl/share/%5Btoken%5D.js)) mints a permanent, unfurlable `/irl/s/:token` link from the captured AR photo for the pin you just placed — never a coordinate, owner-gated, falls back to the plain native share sheet with no active pin. **Analytics** ([api/_lib/irl-analytics.js](api/_lib/irl-analytics.js), [api/irl/analytics.js](api/irl/analytics.js)) is the first site-wide usage rollup for the feature — pins placed, nearby reads, placement method, shares, drop claims — rendered at [/admin/irl-analytics](pages/admin/irl-analytics.html), aged out by the existing hourly reaper. || Verifiable 3D provenance (content credentials) | Spec [specs/PROVENANCE_3D.md](specs/PROVENANCE_3D.md), pure core [api/_lib/provenance-3d.js](api/_lib/provenance-3d.js), Solana anchor [api/_lib/provenance-anchor.js](api/_lib/provenance-anchor.js), MCP tools [api/_mcp3d/tools/provenance.js](api/_mcp3d/tools/provenance.js) (`verify_provenance` free, `anchor_provenance` paid $0.05), free REST verify [api/provenance.js](api/provenance.js) `→ /api/provenance`, viewer badge [public/viewer.html](public/viewer.html), docs [docs/provenance.md](docs/provenance.md). | Live (verify) · anchor gated on issuer key + devnet funds | C2PA-style signed content credentials for AI 3D: creator, prompt, model/provider, lineage, timestamp, and the GLB's sha256, ed25519-signed by the three.ws issuer with the credential hash anchored on Solana. Free public `verify_provenance` / `GET /api/provenance?src=…` recompute the hash and return `verified | tampered | unknown` (a single changed byte → tampered); the verify path and response are coin-clean (both stores). `anchor_provenance` signs + writes the SPL Memo anchor + stores the credential in R2. Tests: [tests/provenance-3d.test.js](tests/provenance-3d.test.js). Evidence: [prompts/store-submissions/_generated/provenance/](prompts/store-submissions/_generated/provenance/). Store-submission prompt 19. |-| OpenAI Select Partner (partner surface + announcement pack) | [pages/openai/index.html](pages/openai/index.html) `→ /openai`, badge assets [public/partners/openai/](public/partners/openai), announcement [blog/three-ws-openai-select-partner.html](blog/three-ws-openai-select-partner.html) `→ /blog/three-ws-openai-select-partner`, directory card in [pages/partners.html](pages/partners.html) `→ /partners`, press/social pack [marketing/openai-select-partner/](marketing/openai-select-partner/README.md) | Live | three.ws's OpenAI Partner Network Select-tier surface. `/openai` is the partner landing: the supplied badge (used unmodified, on a white plate), the four live OpenAI surfaces (the free keyless [3D Studio MCP connector](docs/mcp-studio.md) `→ /api/mcp-studio`, the custom-GPT Actions twin `→ /api/3d/studio`, [Spatial MCP](specs/SPATIAL_MCP.md), and [AR in ChatGPT](docs/chatgpt-ar.md)), the connect table, and the nine-tool list. The marketing pack holds badge-usage rules and the press-release draft, which is gated on OpenAI's written approval before publishing (see its README). |+| OpenAI Select Partner (partner surface + announcement pack) | [pages/openai/index.html](pages/openai/index.html) `→ /openai`, badge assets [public/partners/openai/](public/partners/openai), announcement [blog/three-ws-openai-select-partner.html](blog/three-ws-openai-select-partner.html) `→ /blog/three-ws-openai-select-partner`, directory card in [pages/partners.html](pages/partners.html) `→ /partners`, press/social pack [marketing/openai-select-partner/](marketing/openai-select-partner/README.md), original OpenAI-supplied badge files + press-release template [OAI Select Tier Assets/](OAI%20Select%20Tier%20Assets/README.md) | Live | three.ws's OpenAI Partner Network Select-tier surface. `/openai` is the partner landing: the supplied badge (used unmodified, on a white plate), the four live OpenAI surfaces (the free keyless [3D Studio MCP connector](docs/mcp-studio.md) `→ /api/mcp-studio`, the custom-GPT Actions twin `→ /api/3d/studio`, [Spatial MCP](specs/SPATIAL_MCP.md), and [AR in ChatGPT](docs/chatgpt-ar.md)), the connect table, and the nine-tool list. The marketing pack holds badge-usage rules and the press-release draft, which is gated on OpenAI's written approval before publishing (see its README). || Press kit (brand marks + media assets) | [pages/press/index.html](pages/press/index.html) `→ /press`, marks [public/brand/](public/brand), layout source [marketing/brand/](marketing/brand/README.md), renderer [scripts/render-brand-assets.mjs](scripts/render-brand-assets.mjs) `npm run build:brand-assets` | Live | The self-serve press surface: transparent-PNG marks (cube, horizontal and stacked lockups for dark and light grounds), the OpenAI announcement graphics, boilerplate at three lengths with copy buttons, fast facts, and the mark-usage rules. Everything is rendered from source rather than hand-exported, so a copy change re-renders the whole set; the renderer also builds `/brand/three-ws-press-kit.zip` with a README carrying the usage rules so the files cannot travel without them. Announcement cards come from [marketing/openai-select-partner/cards/social-card.html](marketing/openai-select-partner/cards/social-card.html) via `npm run build:openai-cards`. |-| Sperax partnership + SperaxOS plugin | [pages/sperax.html](pages/sperax.html) `→ /sperax`, plugin [public/sperax/](public/sperax/README.md), manifest `→ /.well-known/sperax-plugin.json`, tools [api/chat-plugin/[tool].js](api/chat-plugin/%5Btool%5D.js) `→ /api/chat-plugin/*`, panel `→ /sperax/iframe/` | In-repo · Live | Partnership landing for the SperaxOS integration: three.ws ships as a standalone `plugin.delivery` plugin that gives a SperaxOS agent an embodied 3D avatar (speak/gesture/emote/render_agent), bound to an ERC-8004 identity, settling over Base x402. Launch offer: free AI credits for three.ws users on [chat.sperax.io](https://chat.sperax.io) — page explains what it is and how to claim. Blog: [/blog/three-ws-speraxusd-integration](blog/three-ws-speraxusd-integration.html) |+| Sperax partnership + SperaxOS plugin | [pages/sperax.html](pages/sperax.html) `→ /sperax`, plugin [public/sperax/](public/sperax/README.md), manifest `→ /.well-known/sperax-plugin.json`, tools [api/chat-plugin/[tool].js](api/chat-plugin/%5Btool%5D.js) `→ /api/chat-plugin/*`, panel `→ /sperax/iframe/`, bundled SDK component [chat-plugin/](chat-plugin) (`@three-ws/chat-plugin`, for hosts that mount plugins as React components instead of framing the manifest) | In-repo · Live | Partnership landing for the SperaxOS integration: three.ws ships as a standalone `plugin.delivery` plugin that gives a SperaxOS agent an embodied 3D avatar (speak/gesture/emote/render_agent), bound to an ERC-8004 identity, settling over Base x402. Launch offer: free AI credits for three.ws users on [chat.sperax.io](https://chat.sperax.io) — page explains what it is and how to claim. Blog: [/blog/three-ws-speraxusd-integration](blog/three-ws-speraxusd-integration.html) || Live Agents wall (mission control) | [pages/agents-live.html](pages/agents-live.html) + [src/agents-live.js](src/agents-live.js) `→ /agents-live` | In-repo · roster [api/agents/public.js](api/agents/public.js) (`sort=live`), per-agent SSE [api/agent-screen-stream.js](api/agent-screen-stream.js) | Real-time grid of every meaningful agent, ranked by most-recent on-chain/skill action (never-used placeholders suppressed). Each card streams a live caster feed when watched, else its real `agent_actions` as a terminal + an "active Nm ago" recency chip. Layers: showrunner spotlight ([src/showrunner.js](src/showrunner.js)), reputation arena ([src/agents-live-arena.js](src/agents-live-arena.js)), platform ticker ([src/theater-feed.js](src/theater-feed.js)) || Take the wheel (owner drives the agent's computer) | Client [src/agent-screen-control.js](src/agent-screen-control.js) mounted in [src/agent-screen.js](src/agent-screen.js) `→ /agent-screen`; API [api/agent-screen-control.js](api/agent-screen-control.js) (lease + input) + [api/agent-screen-control-drain.js](api/agent-screen-control-drain.js) (caster read side); caster dispatch [workers/agent-screen-pool/control.js](workers/agent-screen-pool/control.js); shared sanitizer [src/shared/agent-screen-control.js](src/shared/agent-screen-control.js) | In-repo · Live · doc [docs/agent-screen-control.md](docs/agent-screen-control.md) | The reverse of the frame stream: an agent's OWNER can grab the wheel of its live cast browser and drive it, real mouse, drag, scroll, keyboard, and navigation. Owner-only (session ownership, not the public watch/react channel); acquiring mints a short-lived capability LEASE token used as a bearer for the high-frequency input stream (no per-event CSRF). Events travel normalized (0..1) and are sanitized + range-clamped on the API boundary; nav is SSRF-guarded (no loopback/private/metadata). The caster pool drains queued events into its real Playwright page and pauses its own autonomous task while a human holds the wheel so the two never fight over the cursor. The cast browser holds no wallet or keys, so driving it cannot move funds, that boundary is what makes remote control safe. Tests: [tests/agent-screen-control.test.js](tests/agent-screen-control.test.js) (21 unit), [scripts/agent-screen-control-proof.mjs](scripts/agent-screen-control-proof.mjs) (real Chromium dispatch) || X/Twitter automation toolkit | [nirholas/XActions](https://github.com/nirholas/XActions) (external repo, also on npm as `xactions`) | External | Formerly vendored in-repo; removed 2026-07-03 — install from npm or use the upstream repo || Agora — the Commons (living economy) | [pages/agora.html](pages/agora.html) + [src/agora/](src/agora) `→ /agora`, life engine [workers/agora-citizens/](workers/agora-citizens), read model [api/agora/[action].js](api/agora/[action].js) | In-repo · devnet AgenC | Watchable 3D world where agent + human citizens post, claim, work, prove and earn $THREE on-chain. **Play mode** ("Enter the Commons") makes it walkable GTA-style — your avatar walks the square among the working NPC citizens, other humans appear live over the `agora_world` Colyseus room, and walking up to a citizen (proximity → E) opens its passport: [src/agora/player-mode.js](src/agora/player-mode.js), pure math [src/agora/player-logic.js](src/agora/player-logic.js), room [multiplayer/src/rooms/AgoraRoom.js](multiplayer/src/rooms/AgoraRoom.js). Play mode also has an opt-in **"Record on-chain (BNB testnet)"** toggle (OFF by default) that gaslessly commits your moves to the `WorldMoves` contract every ~block via MegaFuel (self-pay fallback) and renders other on-chain players as lightweight ghost markers read back from real `Moved` events: [src/agora/onchain-presence.js](src/agora/onchain-presence.js), sender [src/bnb/move-sender.js](src/bnb/move-sender.js), event reader [src/bnb/world-presence-reader.js](src/bnb/world-presence-reader.js), pure ghost interpolation [src/bnb/onchain-ghosts.js](src/bnb/onchain-ghosts.js), server relay lib [api/_lib/bnb/world-moves.js](api/_lib/bnb/world-moves.js), config endpoint [api/bnb/world-config.js](api/bnb/world-config.js). WorldMoves contract: [contracts/src/WorldMoves.sol](contracts/src/WorldMoves.sol) (code-complete + anvil-fork-proven; public BSC testnet deploy pending a funded deployer key — see `contracts/DEPLOYMENTS.md`). **Arena** (Competitive tasks — citizens race, first valid proof wins the whole escrow) at [src/agora/arena.js](src/agora/arena.js); **Guilds** (Collaborative tasks — contributors split the reward) at [src/agora/guild.js](src/agora/guild.js), both live-driven by [api/agora/task](api/agora/[action].js). Spec: [docs/agora.md](docs/agora.md) |-| `/play` in-game economy (cash, bank/ATM, vendors, $THREE boutique) | Client: [src/game/coincommunities.js](src/game/coincommunities.js) `→ /play`, general-store/bank NPCs [src/game/npc/economy-npcs.js](src/game/npc/economy-npcs.js), store/bank UI [src/game/economy-ui.js](src/game/economy-ui.js), on-chain purchase flow [src/game/boutique-purchase.js](src/game/boutique-purchase.js), wardrobe [src/game/play-systems.js](src/game/play-systems.js). Server: [multiplayer/src/rooms/WalkRoom.js](multiplayer/src/rooms/WalkRoom.js) (store/bank/boutique handlers), price tables [multiplayer/src/shop.js](multiplayer/src/shop.js), purse/bank model [multiplayer/src/economy.js](multiplayer/src/economy.js), on-chain settlement [multiplayer/src/game-token.js](multiplayer/src/game-token.js) | In-repo | The GTA-style open world's real economy (W04 of the World Online program, [prompts/agent-briefs/W-world-online/W00-program-overview.md](prompts/agent-briefs/W-world-online/W00-program-overview.md)). Walk up to a General Store clerk (E) to buy tools/consumables or sell gathered goods for cash, server-priced and validated every time; walk up to the Bank Teller to deposit cash into a protected balance (survives a death drop) or withdraw it. Premium wardrobe cosmetics unlock with a real on-chain `$THREE` payment from the player's connected Solana wallet — the server only grants the item after re-verifying the confirmed transaction on RPC. Distinct from the separate USDC/x402 avatar-shop rail ([api/x402/cosmetic-purchase.js](api/x402/cosmetic-purchase.js)), which sells a different catalog for the standalone character creator. |-| `/play` character & avatar customization (avatar creator, selfie→3D, wardrobe boutique) | Lobby creator flow [src/game/coincommunities-ui.js](src/game/coincommunities-ui.js) `_openCreate()`, selfie SDK wrapper [src/avatar-creator.js](src/avatar-creator.js), shop [src/game/cosmetics-shop.js](src/game/cosmetics-shop.js), wardrobe [src/game/cosmetics-wardrobe.js](src/game/cosmetics-wardrobe.js), boutique NPCs [src/game/npc/npc-catalog.js](src/game/npc/npc-catalog.js) (`npc-tailor`, `npc-fitting-room`), boutique spawn points [src/game/world-zones.js](src/game/world-zones.js) (`type: 'boutique'`) | In-repo | W03 of the World Online program ([prompts/agent-briefs/W-world-online/W00-program-overview.md](prompts/agent-briefs/W-world-online/W00-program-overview.md)). Before dropping into `/play`, design an avatar from scratch or a selfie (real Avaturn SDK), upload a `.glb`, or sculpt in the full Avatar Studio — no sign-in required. Once in the world, the cosmetics shop/wardrobe (real x402-settled catalog, server-persisted equip) now has a physical home: walk up to Roux · Tailor to browse/buy, or Nell's Fitting Room to equip anything you own. Doc: [docs/character-studio.md](docs/character-studio.md#character-customization-in-play-world-online). |-| `/play` combat & weapons (server-authoritative, danger zones, wanted, tombstones) | Client: [src/game/combat-system.js](src/game/combat-system.js) `→ /play` (vitals HUD wiring, danger-zone ground, tombstone loot, hit feedback, the `window.twsCombat` bridge into W08's `MobSystem`), HUD [src/game/hud/world-hud.js](src/game/hud/world-hud.js). Server: [multiplayer/src/combat-handlers.js](multiplayer/src/combat-handlers.js) (mob AI, attack/loot intents, death + respawn), pure math [multiplayer/src/combat.js](multiplayer/src/combat.js), weapon/mob/loot tables [multiplayer/src/items.js](multiplayer/src/items.js), zone geometry [multiplayer/src/world-features.js](multiplayer/src/world-features.js), handlers wired in [multiplayer/src/rooms/WalkRoom.js](multiplayer/src/rooms/WalkRoom.js) | In-repo | W07 of the World Online program ([prompts/agent-briefs/W-world-online/W00-program-overview.md](prompts/agent-briefs/W-world-online/W00-program-overview.md)). Equip a sword/bat/pistol/bow from the hotbar and press `X` (or tap the touch Attack button) to fight — but only inside one of three named danger zones (Southern Wilds, Northern Wilds, Eastern Marches); town stays lawful by construction. PvE mobs chase and swing back through the same server-side damage path a player's attack uses; a kill (mob or PvP) spills a lootable tombstone, PvP raises the attacker's wanted/heat stars (visible on `WorldHud` and a downed peer's nameplate), and death drops carried cash/pack before an automatic respawn in town. |-| `/play` NPCs & world life (traffic, vendors, quest-givers, mobs) | Manager [src/game/npc/world-life.js](src/game/npc/world-life.js), nav graph [src/game/npc/nav-graph.js](src/game/npc/nav-graph.js), ambient crowd/traffic [src/game/npc/ambient-life.js](src/game/npc/ambient-life.js), quest-giver NPCs [src/game/npc/quest-npcs.js](src/game/npc/quest-npcs.js), quest-zone waypoints [src/game/npc/quest-markers.js](src/game/npc/quest-markers.js), Jobs Board UI [src/game/quests-ui.js](src/game/quests-ui.js), W07-gated mobs [src/game/npc/mobs.js](src/game/npc/mobs.js). Server: quest engine [multiplayer/src/quests.js](multiplayer/src/quests.js), quest zones [multiplayer/src/quest-zones.js](multiplayer/src/quest-zones.js), handlers in [multiplayer/src/rooms/WalkRoom.js](multiplayer/src/rooms/WalkRoom.js) | In-repo | W08 of the World Online program ([prompts/agent-briefs/W-world-online/W00-program-overview.md](prompts/agent-briefs/W-world-online/W00-program-overview.md)). A deterministic nav graph drives client-side ambient pedestrians + ring-road traffic that read identically for every player without a single packet — real gameplay stays server-authoritative. Five quest-giver NPCs (Dockmaster Reyes, Warden Okoro, Cook Mara, Foreman Dell, The Fixer) front the jobs board the quest engine (W05) already ran server-side but no client ever reached; pressing E opens the real board, accepting a job drops a waypoint at its objective (goto zones auto-complete by walking there, interact zones get their own "press E"), and finishing pays real cash server-side. Hostile mobs are live: W07's `CombatSystem` ([src/game/combat-system.js](src/game/combat-system.js)) installs the `window.twsCombat` contract this module's mobs were built against, so `MobSystem` renders real server-authoritative PvE hostiles with zero changes here. Two jobs — `cross-town-delivery` (North↔South) and `east-west-express` (East↔West) — are real driving missions: each `goto` leg is flagged `vehicle: true` and only completes off the authoritative vehicle-driver map ([multiplayer/src/vehicles.js](multiplayer/src/vehicles.js)), so walking through a depot never counts, only driving through it does. Depots sit on the avenue vehicle spawns, so a car is always parked at the start. Tests: [tests/quests-vehicle-delivery.test.js](tests/quests-vehicle-delivery.test.js). |+| `/play` in-game economy (cash, bank/ATM, vendors, $THREE boutique) | Client: [src/game/coincommunities.js](src/game/coincommunities.js) `→ /play`, general-store/bank NPCs [src/game/npc/economy-npcs.js](src/game/npc/economy-npcs.js), store/bank UI [src/game/economy-ui.js](src/game/economy-ui.js), on-chain purchase flow [src/game/boutique-purchase.js](src/game/boutique-purchase.js), wardrobe [src/game/play-systems.js](src/game/play-systems.js). Server: [multiplayer/src/rooms/WalkRoom.js](multiplayer/src/rooms/WalkRoom.js) (store/bank/boutique handlers), price tables [multiplayer/src/shop.js](multiplayer/src/shop.js), purse/bank model [multiplayer/src/economy.js](multiplayer/src/economy.js), on-chain settlement [multiplayer/src/game-token.js](multiplayer/src/game-token.js) | In-repo | The GTA-style open world's real economy (W04 of the World Online program, program brief retired to git history). Walk up to a General Store clerk (E) to buy tools/consumables or sell gathered goods for cash, server-priced and validated every time; walk up to the Bank Teller to deposit cash into a protected balance (survives a death drop) or withdraw it. Premium wardrobe cosmetics unlock with a real on-chain `$THREE` payment from the player's connected Solana wallet; the server only grants the item after re-verifying the confirmed transaction on RPC. Distinct from the separate USDC/x402 avatar-shop rail ([api/x402/cosmetic-purchase.js](api/x402/cosmetic-purchase.js)), which sells a different catalog for the standalone character creator. |+| `/play` character & avatar customization (avatar creator, selfie→3D, wardrobe boutique) | Lobby creator flow [src/game/coincommunities-ui.js](src/game/coincommunities-ui.js) `_openCreate()`, selfie SDK wrapper [src/avatar-creator.js](src/avatar-creator.js), shop [src/game/cosmetics-shop.js](src/game/cosmetics-shop.js), wardrobe [src/game/cosmetics-wardrobe.js](src/game/cosmetics-wardrobe.js), boutique NPCs [src/game/npc/npc-catalog.js](src/game/npc/npc-catalog.js) (`npc-tailor`, `npc-fitting-room`), boutique spawn points [src/game/world-zones.js](src/game/world-zones.js) (`type: 'boutique'`) | In-repo | W03 of the World Online program (program brief retired to git history). Before dropping into `/play`, design an avatar from scratch or a selfie (real Avaturn SDK), upload a `.glb`, or sculpt in the full Avatar Studio; no sign-in required. Once in the world, the cosmetics shop/wardrobe (real x402-settled catalog, server-persisted equip) now has a physical home: walk up to Roux · Tailor to browse/buy, or Nell's Fitting Room to equip anything you own. Doc: [docs/character-studio.md](docs/character-studio.md#character-customization-in-play-world-online). |+| `/play` combat & weapons (server-authoritative, danger zones, wanted, tombstones) | Client: [src/game/combat-system.js](src/game/combat-system.js) `→ /play` (vitals HUD wiring, danger-zone ground, tombstone loot, hit feedback, the `window.twsCombat` bridge into W08's `MobSystem`), HUD [src/game/hud/world-hud.js](src/game/hud/world-hud.js). Server: [multiplayer/src/combat-handlers.js](multiplayer/src/combat-handlers.js) (mob AI, attack/loot intents, death + respawn), pure math [multiplayer/src/combat.js](multiplayer/src/combat.js), weapon/mob/loot tables [multiplayer/src/items.js](multiplayer/src/items.js), zone geometry [multiplayer/src/world-features.js](multiplayer/src/world-features.js), handlers wired in [multiplayer/src/rooms/WalkRoom.js](multiplayer/src/rooms/WalkRoom.js) | In-repo | W07 of the World Online program (program brief retired to git history). Equip a sword/bat/pistol/bow from the hotbar and press `X` (or tap the touch Attack button) to fight; but only inside one of three named danger zones (Southern Wilds, Northern Wilds, Eastern Marches); town stays lawful by construction. PvE mobs chase and swing back through the same server-side damage path a player's attack uses; a kill (mob or PvP) spills a lootable tombstone, PvP raises the attacker's wanted/heat stars (visible on `WorldHud` and a downed peer's nameplate), and death drops carried cash/pack before an automatic respawn in town. |+| `/play` NPCs & world life (traffic, vendors, quest-givers, mobs) | Manager [src/game/npc/world-life.js](src/game/npc/world-life.js), nav graph [src/game/npc/nav-graph.js](src/game/npc/nav-graph.js), ambient crowd/traffic [src/game/npc/ambient-life.js](src/game/npc/ambient-life.js), quest-giver NPCs [src/game/npc/quest-npcs.js](src/game/npc/quest-npcs.js), quest-zone waypoints [src/game/npc/quest-markers.js](src/game/npc/quest-markers.js), Jobs Board UI [src/game/quests-ui.js](src/game/quests-ui.js), W07-gated mobs [src/game/npc/mobs.js](src/game/npc/mobs.js). Server: quest engine [multiplayer/src/quests.js](multiplayer/src/quests.js), quest zones [multiplayer/src/quest-zones.js](multiplayer/src/quest-zones.js), handlers in [multiplayer/src/rooms/WalkRoom.js](multiplayer/src/rooms/WalkRoom.js) | In-repo | W08 of the World Online program (program brief retired to git history). A deterministic nav graph drives client-side ambient pedestrians + ring-road traffic that read identically for every player without a single packet; real gameplay stays server-authoritative. Five quest-giver NPCs (Dockmaster Reyes, Warden Okoro, Cook Mara, Foreman Dell, The Fixer) front the jobs board the quest engine (W05) already ran server-side but no client ever reached; pressing E opens the real board, accepting a job drops a waypoint at its objective (goto zones auto-complete by walking there, interact zones get their own "press E"), and finishing pays real cash server-side. Hostile mobs are live: W07's `CombatSystem` ([src/game/combat-system.js](src/game/combat-system.js)) installs the `window.twsCombat` contract this module's mobs were built against, so `MobSystem` renders real server-authoritative PvE hostiles with zero changes here. Two jobs; `cross-town-delivery` (North↔South) and `east-west-express` (East↔West); are real driving missions: each `goto` leg is flagged `vehicle: true` and only completes off the authoritative vehicle-driver map ([multiplayer/src/vehicles.js](multiplayer/src/vehicles.js)), so walking through a depot never counts, only driving through it does. Depots sit on the avenue vehicle spawns, so a car is always parked at the start. Tests: [tests/quests-vehicle-delivery.test.js](tests/quests-vehicle-delivery.test.js). || Frame governor & power saver (`/play`, `/club`, `/walk`) | [src/shared/frame-governor.js](src/shared/frame-governor.js), wired in [src/game/coincommunities.js](src/game/coincommunities.js), [src/club.js](src/club.js), [src/club-entrance.js](src/club-entrance.js), [src/walk.js](src/walk.js); toggle UI in [src/game/coincommunities-ui.js](src/game/coincommunities-ui.js) | Live | Shared frame-rate governor for the heavy 3D surfaces: 60fps while active, 30fps when idle or unfocused, plus a user-facing Power-saver mode (30fps + lighter rendering, "for a cooler, quieter machine") persisted in localStorage `tws-power-saver` and shared across surfaces (`getPowerSaver`/`setPowerSaver`/`onPowerSaverChange`, `trackWindowFocus`). Tests: [tests/frame-governor.test.js](tests/frame-governor.test.js) || Cinematic rendering (shared 3D quality bar) | [src/shared/cinematic-render.js](src/shared/cinematic-render.js) — `applyCinematicDefaults()`, `loadEnvironment()`, `detectQualityTier()`, `updateGroundContactShadow()`; curated HDRIs in [public/hdri/](public/hdri) (CC0, Poly Haven) | Live, wired into every three.js viewer on the platform (`/irl`, talk mode, `/play`, `/club`, `/ar`, `/xr`, `/walk`, `/coin3d`, marketplace lobby, demo pages, the `<agent-3d>`/`<page-agent>` embeds, and more) | One module every WebGLRenderer-based viewer calls into instead of re-deriving ACES tone mapping, sRGB output color space, HDRI image-based lighting, and soft VSM shadows per file. `detectQualityTier()` picks high/medium/mobile from real device signals and caps pixel ratio + disables shadows/HDRI accordingly; `loadEnvironment()` fetches a real photographic HDRI (`studio`/`outdoor`/`sunset`) and falls back to a procedural room environment on mobile tier or fetch failure (including cross-origin embed contexts where the absolute `/hdri/*.hdr` URL can't resolve). `/walk` keeps its own richer per-biome HDR system ([src/walk-environments.js](src/walk-environments.js)); surfaces already running a postprocessing tone-mapping pass (`/oracle-graph`, `/club-entrance`) only take the sRGB/HDRI half to avoid double-applying the curve. |-| `/play` Wheel of Fortune (Fortune's Folly — free/paid $THREE spins) | Client: [src/game/wheel-station.js](src/game/wheel-station.js) (the plaza landmark, proximity prompt, `E` to spin — lazy-imports the actual UI on first interact), spin UI [src/game/spin-wheel-ui.js](src/game/spin-wheel-ui.js) (20-segment wheel, free/paid flow, wallet signing). Server: [multiplayer/src/spin-wheel.js](multiplayer/src/spin-wheel.js) (paytable, RNG, level/cooldown/pack gates, handlers), split-payment settlement [multiplayer/src/game-token.js](multiplayer/src/game-token.js) (`buildSpinPayment`/`verifySpinPayment` — the same primitives the $THREE boutique uses), wheel location [multiplayer/src/world-features.js](multiplayer/src/world-features.js) `WHEEL`, persisted cooldown field in [multiplayer/src/economy.js](multiplayer/src/economy.js), handlers wired in [multiplayer/src/rooms/WalkRoom.js](multiplayer/src/rooms/WalkRoom.js) | In-repo | W09 of the World Online program ([prompts/agent-briefs/W-world-online/W00-program-overview.md](prompts/agent-briefs/W-world-online/W00-program-overview.md)). Walk up to the wheel in the plaza and press `E`: one free spin every 12h (a real persisted cooldown — survives a disconnect, unlike the ephemeral per-action cooldowns everything else on this row's neighbors use), or pay $3 in `$THREE` — split 50% to the holder-rewards pool / 50% to the treasury, verified on-chain before any prize is granted, mirroring the boutique's proven settlement pattern exactly. Gated behind an average skill level of 3 (a light anti-farm floor, not a grind) and never lets a won prize get lost to a full pack — room for at least one possible item prize is checked before a spin is even offered, paid or free. All 20 wedges are equal-odds by design, matching the client's fixed-angle wheel rendering exactly (see the header note in `spin-wheel.js` on why that must never drift). Tests: [tests/spin-wheel.test.js](tests/spin-wheel.test.js). |-| `/play` friends & presence (drawer, cross-world DMs) | Client: [src/game/friends-panel.js](src/game/friends-panel.js) (shared with `/walk`), mounted in [src/game/coincommunities.js](src/game/coincommunities.js) `_openFriends()`/`_closeFriends()`, HUD button + unread badge in [src/game/coincommunities-ui.js](src/game/coincommunities-ui.js), account-level state/polling in [src/friends.js](src/friends.js). Server: signed ticket verify + `socialHub` registration in [multiplayer/src/rooms/WalkRoom.js](multiplayer/src/rooms/WalkRoom.js), hub in [multiplayer/src/social-hub.js](multiplayer/src/social-hub.js) | In-repo | W09 of the World Online program ([prompts/agent-briefs/W-world-online/W00-program-overview.md](prompts/agent-briefs/W-world-online/W00-program-overview.md)). Press `J` or the HUD `Friends` button to open a right-docked drawer showing your account's friend graph — live online/offline presence per coin world, requests, and DM threads — the same graph and threads `/walk` and the standalone `/friends` page already share. `community-net.js` now carries a signed presence ticket into every `walk_world` join and forwards the server's `social` push onto its own event bus, which is what actually makes a `/play` player visible to friends and able to receive a live DM — previously `/play` joined anonymously to the social graph even when signed in, so every player showed offline and DMs were dropped. Tests: [tests/play-friends-presence.test.js](tests/play-friends-presence.test.js). |+| `/play` Wheel of Fortune (Fortune's Folly; free/paid $THREE spins) | Client: [src/game/wheel-station.js](src/game/wheel-station.js) (the plaza landmark, proximity prompt, `E` to spin; lazy-imports the actual UI on first interact), spin UI [src/game/spin-wheel-ui.js](src/game/spin-wheel-ui.js) (20-segment wheel, free/paid flow, wallet signing). Server: [multiplayer/src/spin-wheel.js](multiplayer/src/spin-wheel.js) (paytable, RNG, level/cooldown/pack gates, handlers), split-payment settlement [multiplayer/src/game-token.js](multiplayer/src/game-token.js) (`buildSpinPayment`/`verifySpinPayment`; the same primitives the $THREE boutique uses), wheel location [multiplayer/src/world-features.js](multiplayer/src/world-features.js) `WHEEL`, persisted cooldown field in [multiplayer/src/economy.js](multiplayer/src/economy.js), handlers wired in [multiplayer/src/rooms/WalkRoom.js](multiplayer/src/rooms/WalkRoom.js) | In-repo | W09 of the World Online program (program brief retired to git history). Walk up to the wheel in the plaza and press `E`: one free spin every 12h (a real persisted cooldown; survives a disconnect, unlike the ephemeral per-action cooldowns everything else on this row's neighbors use), or pay $3 in `$THREE`; split 50% to the holder-rewards pool / 50% to the treasury, verified on-chain before any prize is granted, mirroring the boutique's proven settlement pattern exactly. Gated behind an average skill level of 3 (a light anti-farm floor, not a grind) and never lets a won prize get lost to a full pack; room for at least one possible item prize is checked before a spin is even offered, paid or free. All 20 wedges are equal-odds by design, matching the client's fixed-angle wheel rendering exactly (see the header note in `spin-wheel.js` on why that must never drift). Tests: [tests/spin-wheel.test.js](tests/spin-wheel.test.js). |+| `/play` friends & presence (drawer, cross-world DMs) | Client: [src/game/friends-panel.js](src/game/friends-panel.js) (shared with `/walk`), mounted in [src/game/coincommunities.js](src/game/coincommunities.js) `_openFriends()`/`_closeFriends()`, HUD button + unread badge in [src/game/coincommunities-ui.js](src/game/coincommunities-ui.js), account-level state/polling in [src/friends.js](src/friends.js). Server: signed ticket verify + `socialHub` registration in [multiplayer/src/rooms/WalkRoom.js](multiplayer/src/rooms/WalkRoom.js), hub in [multiplayer/src/social-hub.js](multiplayer/src/social-hub.js) | In-repo | W09 of the World Online program (program brief retired to git history). Press `J` or the HUD `Friends` button to open a right-docked drawer showing your account's friend graph; live online/offline presence per coin world, requests, and DM threads; the same graph and threads `/walk` and the standalone `/friends` page already share. `community-net.js` now carries a signed presence ticket into every `walk_world` join and forwards the server's `social` push onto its own event bus, which is what actually makes a `/play` player visible to friends and able to receive a live DM; previously `/play` joined anonymously to the social graph even when signed in, so every player showed offline and DMs were dropped. Tests: [tests/play-friends-presence.test.js](tests/play-friends-presence.test.js). || `/play` Robinhood Chain worlds (NOXA + The Odyssey coins, live-trade animation) | Firehose worker [workers/robinhood-feed/](workers/robinhood-feed) (watches NOXA + Odyssey launchpads + their Uniswap v3 pools, normalizes to the pump-compatible event shape, serves SSE/WS/REST). API bridge: [api/robinhood/coin-trades.js](api/robinhood/coin-trades.js) (the in-world chart-screen's trade feed), [api/robinhood/play-worlds.js](api/robinhood/play-worlds.js) (the `/worlds` lobby's Robinhood Chain tab). Client: chain-flavored biome `hoodchain` in [src/game/world-env.js](src/game/world-env.js) (auto-pinned in [src/game/coincommunities.js](src/game/coincommunities.js) `isRobinhoodCoin()`), trade-feed endpoint routing in [src/game/chart-screen.js](src/game/chart-screen.js), lobby tab + EVM-address support in [src/worlds-lobby.js](src/worlds-lobby.js) (routes Robinhood coins to `/play`, unchanged pump.fun coins stay on `/temporary`) | In-repo | Every Robinhood Chain memecoin (chain 4663) gets the same treatment pump.fun coins already have: a deterministic 3D world seeded by its contract address, in a distinct dark ticker-tape palette, with real launchpad/Uniswap-v3 trades rippling the space live via `MarketReactor`. Multiplayer (`walk_world`, filtered by `coin`+`tier`) needed zero code changes — it already keys rooms by an opaque coin id string. `isValidToken()` in [api/_lib/coin-communities.js](api/_lib/coin-communities.js) was widened to accept EVM addresses (it previously 400'd every EVM-chain world's Town chat, even though the CHAINS list already declared ethereum/base/bsc support). Tests: [workers/robinhood-feed/tests/normalize.test.js](workers/robinhood-feed/tests/normalize.test.js) (against real captured on-chain logs). || Sealed wallet gift drops (send/claim) | Client: [src/pages/sealed-drops.js](src/pages/sealed-drops.js) — create + "My drops" sections mounted into [public/vanity-wallet.html](public/vanity-wallet.html) (`#drop-create`/`#drop-mine`, below the vanity grinder — vanity pattern fields are shared), claim flow on its own page [pages/drop.html](pages/drop.html) `→ /drop/:id` (24-hex-char id, routed in [vite.config.js](vite.config.js) dev middleware + [vercel.json](vercel.json)). Crypto: [src/solana/vanity/sealed-envelope.js](src/solana/vanity/sealed-envelope.js) (ECIES seal/open, X25519 keygen — all client-side, three.ws never sees a plaintext key), [src/solana/vanity/drop-protocol.js](src/solana/vanity/drop-protocol.js) (claim-token derivation). Server: [api/vanity/drops.js](api/vanity/drops.js) (create/claim/reveal/reclaim, on-chain funding), OG card [api/og/sealed-drop.js](api/og/sealed-drop.js) | In-repo | Fund a fresh wallet — optionally vanity-ground with the same prefix/suffix grinder above — wrap it in a sealed link, and send it. Two seal modes: a **bearer link** (the claim key rides in the URL fragment, anyone with the full link claims once) or **sealed to a recipient's X25519 key** (only they can ever open it, even with the link). The create fee settles via x402; the gift amount funds on-chain into a fresh wallet server-side. Claiming decrypts entirely in the browser and offers the recovered seed phrase/secret key for import — the server only ever sees the sealed ciphertext. "My drops" (browser-local, by a random sender tag) lists what you've sent so expired-unclaimed gifts can be reclaimed. || Premium vanity inventory (sell pre-ground addresses) | [public/vanity/premium/](public/vanity/premium/index.html) `→ /vanity/premium`, batch grinder [workers/vanity-grinder/](workers/vanity-grinder), store [api/_lib/vanity-inventory-store.js](api/_lib/vanity-inventory-store.js), sell [api/x402/vanity-premium.js](api/x402/vanity-premium.js), replenish [api/cron/vanity-inventory-replenish.js](api/cron/vanity-inventory-replenish.js) | In-repo · GCP spot CPU | Long (4–5+ char) brandable Solana addresses ground ahead of time on cheap spot CPU, sealed at rest (AES-256-GCM or GCP-KMS envelope, [api/_lib/vanity-vault.js](api/_lib/vanity-vault.js)), and sold from stock via x402 — priced by rarity ($1–$50) on `vanity-premium`, or by fixed 4–5 char tiers ($2.50/$10) directly through [`/api/x402/vanity`](docs/vanity.md#tier-1--live-grinder) (instant delivery, `source:"inventory"`) and the [pump-launch vanity upsell](docs/pump-launcher.md) — delivered exactly once, ciphertext destroyed on delivery. An hourly cron watches stock and fires a fresh grind batch (Cloud Run Job) when low. Free `vanity_premium` MCP browse tool. Runbook: [docs/ops/gcp-credits.md](docs/ops/gcp-credits.md) |@@ -195,7 +196,7 @@ surface-map row already covers:Workspaces declared in [package.json](package.json), plus a few in-repopublishable packages that ship the same way but are not in the workspaces array(`packages/retarget`, `packages/concierge-mcp`, `assistant-sdk`,-`concierge-sdk`):+`concierge-sdk`, `chat-plugin`):```agent-payments-sdk/ → @three-ws/agent-payments (fork of @pump-fun/[email protected])@@ -207,6 +208,7 @@ mcp-bridge/ → @three-ws/mcp-bridgemcp-server/ → @three-ws/mcp-servermultiplayer/ → @three-ws/multiplayerservices/liquidation-collector/ → @three-ws/liquidation-collector (standalone Binance/Bybit/OKX liquidation stream collector, ported from SperaxOS)+chat-plugin/ → @three-ws/chat-plugin (LobeChat/SperaxOS sidebar plugin: embodied 3D avatar reacting to tool calls; standalone manifest + React component)packages/avatar-schema/ → @three-ws/avatar-schemapackages/avatar-cli/ → @three-ws/avatar-clipackages/retarget/ → @three-ws/retarget (humanoid bone canonicalizer + clip retargeting engine, extracted from src/)diff --git a/animation-sources/README.md b/animation-sources/README.mdnew file mode 100644index 000000000..fda4e958f--- /dev/null+++ b/animation-sources/README.md@@ -0,0 +1,109 @@+# animation-sources++Build-time motion source files (FBX and GLB) for the avatar animation+pipeline. Everything in this directory except this README is gitignored on+purpose: raw sources are multi-megabyte binaries that never ship, while the+baked clips in `public/animations/clips/` are the committed, deployed+artifact. A fresh checkout of this repo therefore contains only this file, and+the build handles that gracefully (see "Missing sources are normal" below).++Full pipeline reference: [docs/animations.md](../docs/animations.md) and+[docs/3d-asset-pipeline.md](../docs/3d-asset-pipeline.md). The runtime-facing+counterpart of this README is+[public/animations/README.md](../public/animations/README.md).++## What lives here++| Files | What they are | How they got here |+|---|---|---|+| `*.fbx` with plain names (`Idle.fbx`, `Capoeira.fbx`, `wheelbarrow walk.fbx`, ...) | Humanoid motion clips on the Mixamo skeleton (`mixamorig`-prefixed bones, centimeter-baked hip translation). The registry and build pipeline identify these as Mixamo clips. | Placed by hand; each one is referenced by name from [`scripts/animations.config.json`](../scripts/animations.config.json). |+| `soldier-*.glb`, `michelle-samba-dance.glb`, `xbot-*.glb`, `robot-*.glb` | Single-animation GLBs split out of the three.js example models (Soldier, Michelle, Xbot, RobotExpressive). [`scripts/extract-glb-animations.mjs`](../scripts/extract-glb-animations.mjs) documents them as MIT/CC0-licensed public assets. | Generated by `npm run extract:animations`, which downloads the example GLBs, writes one file per animation track here, and upserts matching config entries. Safe to delete; the script regenerates them. |+| `mx-*.fbx` (not always present) | The bulk Mixamo motion library, one file per catalog clip. | Downloaded by `npm run mixamo:download` ([`scripts/mixamo-all.mjs`](../scripts/mixamo-all.mjs), needs `MIXAMO_TOKEN`). Explicitly gitignored; feeds the R2-hosted library, not the curated set. |+| `.library-clips/` | Staging output for the baked bulk library (about 3 GB for the full catalog), uploaded to R2 by `npm run mixamo:upload` and served via `GET /api/animations/library`. | Written by the build phase of `scripts/mixamo-all.mjs`. |+| `.library-thumbs/` | Staging area for library poster thumbnails rendered by [`scripts/build-animation-thumbnails.mjs`](../scripts/build-animation-thumbnails.mjs), uploaded alongside the clips. | Written by the thumbnail script. |++No license or provenance metadata is stored in this directory itself; the+statements above are limited to what the repo's scripts and registry record.++## How sources become shipped clips++The curated runtime set is built by+[`scripts/build-animations.mjs`](../scripts/build-animations.mjs)+(`npm run build:animations`):++1. It reads [`scripts/animations.config.json`](../scripts/animations.config.json)+ and resolves each entry's `source` file, looking in `animation-sources/`+ first, then `public/animations/` (GLB sources that are also served at+ runtime live there instead).+2. Each source clip is retargeted onto the canonical Avaturn reference rig+ (`public/avatars/cz.glb`): `mixamorig` prefixes are stripped, tracks whose+ bones the reference rig lacks are dropped, and a clip matching fewer than+ 60% of its tracks is rejected. Hip translation units are detected from the+ data, not the file extension, so centimeter-baked sources are rescaled to+ meters and meter-authored round-trips are left alone. Per-entry flags+ (`trim`, `uprightFix`, `recenterHips`) correct sources with baked+ transforms; see the config-entry field table in+ [docs/animations.md](../docs/animations.md#config-entry-fields).+3. The retargeted clip is serialized as three.js `AnimationClip` JSON into+ `public/animations/clips/<name>.json` (5 to 10 times smaller than a GLB,+ loaded at runtime with `AnimationClip.parse`, no loaders or retargeting in+ the browser), and `public/animations/manifest.json` is rewritten.+4. Hand-authored clips with no source file here are merged into the manifest+ from [`scripts/animations-extra-clips.json`](../scripts/animations-extra-clips.json).++The bulk library takes a parallel path: `scripts/mixamo-all.mjs` invokes the+same build script with staging overrides (`--config`, `--out`, `--manifest`,+`--url-prefix`), baking `mx-*.fbx` into `.library-clips/` and uploading the+result to R2 rather than committing it.++### Missing sources are normal++Because the sources are gitignored, a configured clip whose source file is+absent but whose baked JSON already exists in `public/animations/clips/` is+republished from the baked file and logged as `PREBUILT`. That is the standard+path on a clean checkout, not an error. The build also carries a regression+guard: it aborts rather than publish a manifest that would silently drop a+clip that is still configured and was in the previous manifest. Retiring a+clip is done by removing its config entry, never by deleting its source.++## Adding a new motion source++1. Drop the file here. FBX belongs in this directory (build-time input, never+ deployed); a GLB that should also be served raw at runtime goes in+ `public/animations/` instead. The build resolves both.+2. Add an entry to+ [`scripts/animations.config.json`](../scripts/animations.config.json):++ ```json+ { "name": "av-my-anim", "source": "My Anim.fbx", "label": "My Anim", "icon": "🎬", "loop": true }+ ```++ `name` becomes the clip's runtime id (`av-<kebab-case>` for new+ Avaturn-retargeted clips). Add `trim`, `uprightFix`, or `recenterHips` only+ if the built clip is overlong, on its back, or off its mark.+3. Run `npm run build:animations` and check the log line for your clip: a+ healthy build reports the matched track count and output size; a sub-60%+ bone match means the source rig is not Mixamo-compatible.+4. Catalogue the clip in+ [`public/animations/registry.json`](../public/animations/registry.json)+ under the `clips` collection.+5. Optional: wire an agent slot in+ [`src/runtime/animation-slots.js`](../src/runtime/animation-slots.js) so+ agents play it automatically, and re-run+ `node scripts/build-animation-thumbnails.mjs` so the `/animations` gallery+ gets a poster still.++Keep the source file around locally until the baked JSON is committed; after+that, the baked clip is self-sufficient.++## Related++- [docs/animations.md](../docs/animations.md): collections, agent slots,+ config fields, known issues.+- [docs/3d-asset-pipeline.md](../docs/3d-asset-pipeline.md): how FBX, GLB, and+ clip JSON relate across the whole generate, rig, animate, export chain.+- [docs/procedural-animation.md](../docs/procedural-animation.md): the runtime+ layers (look-at, foot planting) that adjust these pre-baked clips each frame+ after the mixer runs.+- [public/animations/README.md](../public/animations/README.md): the served+ side of this pipeline (built clips, manifest, registry).diff --git a/api/README.md b/api/README.mdindex 57f51e0ef..c3fab4d93 100644--- a/api/README.md+++ b/api/README.md@@ -69,6 +69,41 @@ The `_`-prefixed folders are imported by the endpoints; they are not routes:### Scheduled jobs (Vercel Cron)- `cron/[name].js` — a single dynamic dispatcher for every cron job. Vercel hits `/api/cron/<name>`; `req.query.name` selects the job. Schedules are declared in `vercel.json` under `crons`, including: `audit-log-cleanup` (daily 04:00); `expire-pending-purchases`, `solana-attestations-crawl`, `index-delegations`, `run-coin-cycle`, `unstoppable-tick` (every 5 min); `cleanup-csrf-tokens` (hourly :17); `process-withdrawals`, `run-dca`, `run-subscriptions` (hourly); `erc8004-crawl`, `pumpfun-signals` (every 15 min); `run-x-scheduled-posts` (every min); `run-x-triggers` (every 5 min); `fetch-x-metrics`, `process-subscriptions` (every 6 h); `pump-agent-stats`, `solana-attest-event-cleanup` (every 10 min); `pumpfun-monitor` (every 3 min); `settle-royalties`, `siwx-gc` (daily 03:00); and the staggered `run-coin-payouts` / `club-payouts`.+## Quick examples++Every endpoint speaks plain HTTP. These run as-is against production (all verified):++```bash+# Liveness plus the exact commit and Cloud Run revision serving production+curl -s https://three.ws/api/version++# Public agent directory (no auth)+curl -s "https://three.ws/api/agents/public?limit=3"++# Paginated manifest of the free rigged-character library+curl -s "https://three.ws/api/avatars/library?limit=5"++# Free x402 market index: every paid market-data endpoint and its price+curl -s https://three.ws/api/x402/market++# The full MCP tool catalog as plain JSON (no auth, no payment)+curl -s https://three.ws/api/tool_schema++# Probing a paid surface bare returns its x402 payment challenge, not an error page+curl -s -X POST https://three.ws/api/mcp \+ -H 'Content-Type: application/json' \+ -H 'Accept: application/json, text/event-stream' \+ -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'+```++Three auth models coexist, and each handler states its own:++- **Public**: no credentials (everything above).+- **Session + CSRF**: browser surfaces send the session cookie plus a token from `/api/csrf-token`; see `_lib/auth.js` (`getSessionUser`).+- **Bearer**: developer API keys and scoped agent tokens via the `Authorization: Bearer` header; see `_lib/auth.js` (`authenticateBearer`, `hasScope`) and [docs/developer-platform.md](../docs/developer-platform.md).++Paid endpoints layer x402 on top: pay the challenge with any x402 client and retry with the `X-PAYMENT` header. Buyer-side walkthrough: [docs/x402-buyer.md](../docs/x402-buyer.md); free debugging bench: [docs/x402-dev-tools.md](../docs/x402-dev-tools.md).+## Local developmentThese run under `vercel dev`, or behind the Vite dev-server proxy. CORS is applied per-endpoint via the `cors` helper in `_lib/http.js`.diff --git a/api/_lib/asset-provenance.js b/api/_lib/asset-provenance.jsindex 05a129059..c27a76418 100644--- a/api/_lib/asset-provenance.js+++ b/api/_lib/asset-provenance.js@@ -5,7 +5,8 @@* platform produces gets a durable, cryptographically-verifiable record of who* made it, from what prompt/model, and (for a remix/mint) its parent lineage —* the "creator, prompt, parent lineage, model hash, timestamp" provenance line- * from prompts/roadmap/08-crypto-native-creation.md.+ * from the roadmap campaign, work order 08 (crypto-native creation; retired,+ * see git history).** Canonicalization + signing here is a byte-for-byte mirror of* packages/provenance-mcp/src/lib/signing.js (same ACTION_SIG_VERSION, samediff --git a/api/_lib/quality-bench.js b/api/_lib/quality-bench.jsindex db3c011f4..1517be0fc 100644--- a/api/_lib/quality-bench.js+++ b/api/_lib/quality-bench.js@@ -4,7 +4,8 @@// generate → render → judge pipeline so the two callers can never drift apart on// what "a scored view" means.//-// See prompts/quality-bar/09-realism-eval-harness.md for the mission spec and+// Mission spec: quality-bar campaign, work order 09 (realism eval harness;+// retired, see git history). See// data/quality-bench/README.md for how to run/read/extend the bench.import { renderClip } from './render-clip.js';diff --git a/api/webhooks/gcp-budget-alert.js b/api/webhooks/gcp-budget-alert.jsindex 8dcfd5a8d..6eb6ccd2d 100644--- a/api/webhooks/gcp-budget-alert.js+++ b/api/webhooks/gcp-budget-alert.js@@ -4,7 +4,7 @@// threshold crossing into a Telegram ops ping via sendOpsAlert — the same path// the changelog bot uses, but the PRIVATE ops chat (TELEGRAM_ALERTS_CHAT_ID),// never the holders' channel. This is how the $100k credit program (see-// prompts/gcp-credits/ and docs/gcp-credits.md) surfaces a runaway lane BEFORE+// prompts/gcp-credits/ and docs/ops/gcp-credits.md) surfaces a runaway lane BEFORE// it drains the grant: scripts/gcp/create-budgets.mjs registers budgets at// 25/50/75/90/100% pointing at a Pub/Sub topic; that topic pushes here.//diff --git a/chat/README.md b/chat/README.mdindex 85e6e2333..64c34dd87 100644--- a/chat/README.md+++ b/chat/README.md@@ -1,70 +1,105 @@-# three.ws-chat--### A fast, light, open chat UI--### Key features:--- 🔌 Multiple providers, plug in your API keys (stored entirely locally) and you're good to go-- - Local models (through Ollama)- - OpenRouter (which lets you use ALL models across many providers: OpenAI, Anthropic, OSS, 50+ others)- - OpenAI- - Anthropic- - Mistral- - Groq--- 🛠️ Tool use- - Check out `server/toolfns/toolfns.go`. You only need to write functions. The function comment is the description the model receives, so it knows what to use. Click the `Sync` button in the web UI to refresh your tools.-- 🖼️ Multimodal input: upload, paste, or share links to images-- 🎨 Image generation using DALL-E 3-- 📝 Multi-shot prompting. Also edit, delete, regenerate messages, whatever. The world is your oyster-- ⚡ Pre-filled responses (where supported by provider)-- 🌐 Support for all available models across all providers-- 🔄 Change model mid-conversation-- 🔐 Sync chats and keys across devices, end-to-end encrypted. Self-hosted, or use our hosted instance.-- 🔗 Conversation sharing (if you choose to share, your conversation has to be stored on an external server for the share link to be made available. Self-hosted share options coming soon. No, I will not view any of your stuff.)-- 🌿 Branching conversation history (like the left-right ChatGPT arrows that you can click to go back to a previous response)--### Privacy:--- Completely private and transparent. All your conversation history and keys are stored entirely locally, and kept only in your browser, on your device.--## 3D in chat: forge models and view them inline--The chat generates and displays real 3D models directly in the conversation. Three pieces work together:--**Forge tools (on by default).** Two client tools are bootstrapped into every fresh conversation:--- `ForgeTextTo3D` runs the free three.ws Forge lane (`POST /api/forge { prompt }`). It returns immediately; the model appears in the thread in roughly 30 to 90 seconds. Ask for "a 3D model of a brass steampunk owl" and the assistant calls it on its own.-- `ForgeAvatar` runs the full text to mesh to auto-rig to avatar-library pipeline (`/api/forge`, `/api/forge?action=rig`, `/api/avatars/from-forge`). Saving to the library requires being signed in; without a session it still returns the rigged model.--Both tools return an `application/model-3d` envelope instead of raw HTML: `{ contentType: 'application/model-3d', content: { glb, job, prompt, preview, eta, rigged, saved_url, status_note, error }, summary }`. The `summary` string is what the LLM reads; the compact `content` object is what renders, so tool results stay cheap in tokens.--**The inline viewer (`src/ModelViewer3D.svelte`).** Any `application/model-3d` tool result renders directly in the message thread (and in the tool split view) as an interactive Three.js viewer: orbit and zoom with damping plus auto-rotate until first interaction, PBR environment lighting, animation playback when the GLB has clips, a skeleton toggle for rigged models (press S), and Download GLB / Viewer / View in AR / Recenter controls. While a forge job is pending it polls `GET /api/forge?job=` and shows the concept preview with a progress bar, then swaps in the model; once resolved, the GLB URL is persisted into the stored message so reloading the conversation renders instantly instead of re-polling. Viewers initialize lazily near the viewport, pause rendering offscreen, dispose all GPU resources on unmount, and recover from WebGL context loss with a reload card.--**GLB links auto-render.** Paste a `.glb` URL into a message (or have the assistant produce one) and a viewer appears under it. Cross-origin models whose host lacks CORS headers are fetched through the same-origin `/api/glb?src=` proxy automatically. Links already rendered by a tool card or an earlier message are not duplicated.--## How to install?--If you don't want to use tools, you don't need to install anything. A hosted instance is available at: https://three.ws/chat--If you want to use tools, proceed below.--## Single binary:--The three.ws-chat tool server is available prebuilt as a single binary. [Download prebuilt package from the releases page.](https://github.com/nirholas/three.ws-chat/releases)--Download the binary for your platform, then run it, which will start the tool server:-+# chat/ (three.ws Chat)++The Svelte chat client served in production at **https://three.ws/chat**. It is the+conversational surface of three.ws: multi-provider LLM chat with tool calling, inline+3D model generation and viewing, agent wallets, and the skills marketplace, all wired+to the platform's own `api/` handlers.++## Upstream and license++This app started as a fork of **eplus** (https://eplus.chat), a fast, light, open chat+UI with a Go tool server; the tool server ([server/](server)) and sync server+([sync/](sync)) still follow its design (write a Go function in+[server/toolfns/toolfns.go](server/toolfns/toolfns.go), its comment becomes the tool+description, click Sync in the UI). The three.ws copy has diverged heavily: platform+auth, wallets, forge tools, and the inline 3D viewer are all three.ws additions.+This directory is covered by [LICENSE](LICENSE) (proprietary, copyright 2026 nirholas).++## What it does++- **Models**: a Built-in free lane (server-selected `:free` models via `POST /api/chat/proxy`,+ no key needed) plus bring-your-own-key providers (OpenRouter, Anthropic, OpenAI, Groq,+ Mistral, local Ollama). Keys are stored only in the browser's localStorage and sent+ browser-to-provider. The live model list comes from `GET /api/chat/models`; defaults+ from `GET /api/chat/config` ([src/providers.js](src/providers.js), [src/stores.js](src/stores.js)).+- **3D in chat**: the `ForgeTextTo3D` and `ForgeAvatar` client tools call the free forge+ lane (`POST /api/forge`, `/api/forge?action=rig`, `/api/avatars/from-forge`) and return an+ `application/model-3d` envelope that [src/ModelViewer3D.svelte](src/ModelViewer3D.svelte)+ renders inline: orbit controls, animation playback, skeleton toggle, AR, GLB download.+ Pasted `.glb` links auto-render too, proxied through `/api/glb?src=` when the host lacks CORS.+- **Conversations** live entirely in the browser (localStorage), with optional+ end-to-end-encrypted sync through the Go server in [sync/](sync).++## Local development++```sh+cd chat+npm ci # or: node scripts/ensure-deps.mjs+npm run dev # http://localhost:5173```-./three.ws-chat-darwin-amd64-Tool server running at http://localhost:8081-```--Go back to https://three.ws/chat, head over to Settings -> Tool calling, and click the "Refresh tools" button. You should be good to go!--### Building client and server locally:-1. Clone the repository-2. Install and start the client: `npm i && npm run dev`. The client will be accessible at http://localhost:5173-3. Install and start the server: `cd server && go generate ./... && go build && ./server -password foobar`. The server will be accessible at http://localhost:8081. You can plug this into the server address in the chat UI along with the password you selected.+The dev server ([vite.config.js](vite.config.js)) does three things for you:++- Proxies `/api/*` to `https://three.ws` (override with `DEV_API_PROXY`, see below), so+ auth, forge jobs, and paid calls hit the real backend during development.+- Serves `/animations/*` and `/avatars/*` from the repo's `../public`, and `/agent-3d/*`+ from `../dist-lib`, so 3D features work without a root build.+- Aliases `$src` to [src/](src) and `$shared` to `../src/shared` (the app imports the+ platform's `portable-wallet.js` from there: one repo, one wallet truth).++`npm run format` / `format:check` run Prettier. There is no test suite inside `chat/`;+platform tests live in the repo root (`npm test`).++## How production builds it++`npm run build:chat` at the repo root runs [scripts/ensure-deps.mjs](scripts/ensure-deps.mjs)+(skips `npm ci` when `package-lock.json` is unchanged), then `vite build` with+`base: '/chat/'` into `../public/chat`, then copies that into `dist/chat/`.++In the deploy chain, `build:chat` is a step inside `npm run build:gcp`, ordered before+the root frontend `vite build`. That order is load-bearing: the root build empties+`dist/` and then copies `public/` (which now contains the fresh `public/chat`) into it,+so the chat bundle survives the wipe. The full chain is encoded in `build:gcp` in the+root `package.json`; the deploy runbook lives in+[../docs/ops/gcp-production.md](../docs/ops/gcp-production.md). The deploy worktree+must hardlink `chat/node_modules` (`cp -al`), or the chat build dies with+`Cannot find package '@sveltejs/vite-plugin-svelte'`.++At runtime, [../server/index.mjs](../server/index.mjs) serves `dist/` and applies the+route table from [../vercel.json](../vercel.json): `/chat` and `/chat/` rewrite to+`/chat/index.html`, `/chat/(.*)` serves the built assets. The page is declared in+`../data/pages.json` (path `/chat`), which feeds the sitemap and changelog.++## Environment variables++The built client ships no secrets and reads no runtime env vars.++| Variable | Where | Effect |+|---|---|---|+| `DEV_API_PROXY` | dev only, shell env | Upstream for the Vite `/api/*` proxy (default `https://three.ws`) |+| `BUILD_TIMESTAMP` | build time | Injected by [vite.config.js](vite.config.js) via `define`, shown in the UI |++The Built-in free lane depends on `OPENROUTER_API_KEY` being set on the platform API+(the Cloud Run service), not on anything in this directory.++## Platform integration points++Everything below is a real `api/` handler in the repo root, reached same-origin:++- **Chat**: `/api/chat/models`, `/api/chat/config`, `/api/chat/proxy` (free lane with+ moderation and model failover), `/api/chat-skills`, `/api/tts/google` (voice).+- **Auth and identity**: `/api/auth/me`, `/api/csrf-token` (cookie session shared with+ the rest of three.ws).+- **Forge and 3D**: `/api/forge` (create, poll, rig), `/api/avatars/from-forge`,+ `/api/glb` (CORS proxy), `/api/nft/resolve`.+- **Agents and marketplace**: `/api/agents/*`, `/api/marketplace/agents`,+ `/api/skills`, `/api/skills/*`, `/api/skills-manifest`.+- **Wallet and payments** ([src/AgentWallet.svelte](src/AgentWallet.svelte),+ [src/walletAuth.js](src/walletAuth.js)): `/api/wallet/balances`,+ `/api/tx/solana/build-transfer`, `/api/tx/solana/build-swap`, `/api/tx/explain`,+ `/api/x402-pay`, `/api/billing/*`, `/api/agents/payments/*`.+- **Launches** (platform launcher, runtime mint input): `/api/pump/quote`,+ `/api/pump/launch-prep`, `/api/pump/launch-confirm`, `/api/pump/sell-prep`,+ `/api/pump/balances`, `/api/pump-fun-mcp`.+- **Scenes and notifications**: `/api/scene/gate-check`, `/api/scene/gate-create`,+ `/api/nft/mint-scene`, `/api/notifications`.diff --git a/contracts/DEPLOYMENTS.md b/contracts/DEPLOYMENTS.mdindex f55e14752..d557aa230 100644--- a/contracts/DEPLOYMENTS.md+++ b/contracts/DEPLOYMENTS.md@@ -290,7 +290,7 @@ above with the BscScan-visible ones (same script, same bytecode — only the### Prompt 18 — two-wallet world E2E proof (anvil, `--block-time 0.45`)-Prompt 18 (`prompts/bnb-chain/18-world-e2e-demo.md`) needed two real participants+Prompt 18 (bnb-chain campaign, work order 18, world e2e demo; retired, see git history) needed two real participantsmoving in the same world at once with block spacing that actually reproducesBSC's live ~0.45s cadence — a step up from 14/15/16's wall-clock-paced localblocks. This run started a FRESH (non-forked) `anvil --chain-id 97 --block-time@@ -407,7 +407,7 @@ on the real testnet ObjectHub for a real uploaded object (prompt 09); executeone real `buy()`; and paste the BSC tx hash plus the resulting`PermissionHub.settleCreatePolicy`/`PolicyGranted` proof (BscScan +GreenfieldScan once the cross-chain ack settles) per-`prompts/bnb-chain/10-vault-contract.md`'s definition of done.+the bnb-chain campaign work order 10 (vault contract; retired, see git history) definition of done.**Prompt 11 (vault unlock API) local-anvil proof, 2026-07-08 — mocked-hubsdeploy script added:** [`script/DeployGreenfieldVaultMocked.s.sol`](script/DeployGreenfieldVaultMocked.s.sol)diff --git a/docs/agent-symphony.md b/docs/agent-symphony.mdnew file mode 100644index 000000000..3be0c61ac--- /dev/null+++ b/docs/agent-symphony.md@@ -0,0 +1,147 @@+# Agent Symphony++[three.ws/symphony](https://three.ws/symphony) plays the live agent economy as+generative music. Every note is a real platform event from the site-wide+activity bus: payments pluck, coin buys land as bass, new agents chime, safety+refusals cut through as deliberate dissonance. Nothing is prerecorded and+nothing is simulated; every sound is synthesized in WebAudio the moment the+event happens, from note specs computed by a pure, unit-tested scoring module.++The page is fully usable with sound off: a live ledger lists the actual events+behind the notes (with real click-throughs to agent profiles and explorers), a+canvas visualization spawns one orb per note, and audio only ever starts from a+user gesture. Nothing autoplays.++> Source: [`pages/symphony.html`](../pages/symphony.html) (markup),+> [`src/symphony.js`](../src/symphony.js) (audio engine, visualization, feed+> plumbing), [`src/symphony-score.js`](../src/symphony-score.js) (the+> event-to-note grammar). Tests:+> [`tests/symphony-score.test.js`](../tests/symphony-score.test.js) and+> [`tests/symphony-cross-links.test.js`](../tests/symphony-cross-links.test.js).++## Where the events come from++The symphony consumes the same live ticker documented in+[Money Feed](./money-feed.md):++1. `GET /api/feed?limit=40` paints the initial ledger (played silently as+ backlog, not as notes).+2. `GET /api/feed-stream` (SSE) tails new events in real time. The status pill+ shows `live`.+3. If SSE is unavailable or drops, the page polls `GET /api/feed` every 20+ seconds and shows `live (polling)`; a failed fetch shows `offline`.++There is no symphony-specific endpoint. The stream that powers the+[Money Pulse](https://three.ws/pulse) and the site-wide ticker is the stream+you hear.++## What sounds map to what events++Every allow-listed feed type (see the type table in+[Money Feed](./money-feed.md)) maps to one of six voices in+`TYPE_TO_CATEGORY` in [`src/symphony-score.js`](../src/symphony-score.js).+Each voice has its own synth patch in the engine, its own color in the+visualization, and its own mute button in the legend.++| Voice | Feed types | Sound (as coded) |+|---|---|---|+| `money` | `payment`, `agora-earned` | A plucked triangle wave with a sine shimmer one octave up, 0.8s decay. |+| `bass` | `coin-buy` | A sine one octave below the note's pitch that glides down another octave over half a second. Whale buys are felt, not just heard. |+| `bell` | `agent-deploy`, `agent-onchain`, `member-join`, `agora-registered` | An FM bell: sine carrier with an inharmonic partial at the classic 2.76 bell ratio, 1.4s ring. |+| `arp` | `level-up`, `world-join`, `mission-complete`, `agora-task-posted`, `agora-hired`, `agora-task-claimed`, `agora-task-completed`, `agora-vouched` | The actor's stable three-note ascending motif, plucked at 90ms intervals. |+| `alarm` | `agent-guard`, `agora-flagged` | Two short square waves a minor second apart: deliberate dissonance for safety refusals and flagged proofs. |+| `jackpot` | `jackpot` | A sawtooth glissando through a resonant bandpass filter, rising two octaves, with sparkle plucks of the actor's motif on top. |++Any feed type without a mapping falls back to the `bell` voice, so a new+`ALLOWED_TYPES` entry is audible on day one; give it a proper voice mapping in+`TYPE_TO_CATEGORY` when you add one.++### Pitch, loudness, and identity++The grammar is deterministic and pure (no DOM, no clock), which is what makes+it unit-testable:++- **One scale.** Every note lands on an A minor pentatonic scale (root 110 Hz,+ four octaves), so an arbitrary stream of unrelated events harmonizes instead+ of producing noise.+- **Bigger money sits lower.** `intensityOf()` reads the event's amount+ (tolerating every producer's field naming) and scales it logarithmically+ against a per-unit reference table (`UNIT_SCALE`); an event at or above its+ reference (for example 100,000 $THREE) plays near full send. Louder events+ occupy a lower register: whale-sized activity is bass, dust is sparkle.+ Amount-less events (registrations, joins) get a fixed conversational level+ so they are audible but never dominate.+- **Each actor is recognizable by ear.** The actor's name is FNV-1a hashed to+ pick the exact scale degree within the register, a stable three-note motif,+ and a fixed stereo position. The hash is stable across sessions and+ platforms, so a returning agent keeps its motif and pan forever.++### The burst gate++The live feed arrives in floods: a sniper sweep can emit dozens of identical+`agent-guard` events in seconds, and a note per event would machine-gun the+same sound. `createBurstGate(1500)` admits one note per `(type, actor)` pair+per 1.5 seconds and counts what it suppressed. When that key next plays, the+note gets an accent (up to +0.3 gain, +0.05 per swallowed note), so a flood+still reads as "a lot happened", musically instead of literally. The gate is+pure and clock-injected, and it only gates audio: every event still lands in+the ledger and the stats.++## Solo mode++Solo mode narrows the whole page to one participant, so an owner can leave the+tab open and hear their own agent working instead of the whole platform:++- Hover any ledger row and hit **solo** to listen to that participant alone.+ A chip appears ("Soloing X. Everything else is muted.") with a+ "Hear everything" button to clear it.+- The state is a shareable URL, kept in sync via `history.replaceState`:+ `/symphony?agent=<agentId>` matches the opaque agent id exactly;+ `/symphony?actor=<label>` matches the display label case- and+ whitespace-insensitively (the same agent is published as "Luna" and "luna"+ by different producers).+- The filter runs entirely client-side over the same feed, before events+ consume the dedupe set, the ledger, or a note. No new endpoint.+- A soloed participant with no activity yet gets a dedicated empty state+ explaining what will play and linking back to the full symphony.++Every agent profile's Wallet Story card carries a "Listen" link that opens the+symphony soloed to that agent, `/pulse` links here as "the same stream, heard+instead of read", and the nav lists the page next to Money Pulse. All three+cross-links are asserted statically by+[`tests/symphony-cross-links.test.js`](../tests/symphony-cross-links.test.js).++## Page mechanics++- **Play/pause.** The play button (or Space) starts the AudioContext; pausing+ suspends it. While playing, a quiet two-oscillator drone an octave below the+ root (55 Hz, gently filtered and breathing) marks the platform's idle+ heartbeat between events.+- **Overture.** The first time you press play, the ten most recent real events+ replay as a fast, half-volume recap so the mapping is demonstrated even+ during a quiet minute.+- **Per-voice mute.** Clicking a legend voice mutes it; the choice persists in+ `localStorage` (`twx_symphony_muted`), as does the master volume+ (`twx_symphony_volume`).+- **Recorder.** The record button captures the master audio bus plus the+ canvas (via `captureStream`) into a downloadable WebM video clip, capped at+ 60 seconds, falling back to audio-only where video capture is unsupported.+ The reverb is a generated impulse response and the backdrop is painted into+ the canvas, so recordings are self-contained; no audio or image assets ship+ with the page.+- **Ledger.** The newest 60 events, each with a voice-colored dot, a+ human-readable description, and a real destination (agent profile or+ explorer). New arrivals prepend a single row; screen readers get one short+ throttled announcement per arrival from a dedicated live region rather than+ a re-announcement of the whole list.+- **Background tabs.** The visualization loop stops and audio suspends when+ the tab is hidden, and both resume on return.++## Related++- [Money Feed](./money-feed.md): the activity bus this page renders, including+ the full event-type table and how events are published.+- [Agora](./agora.md): the on-chain economy lifecycle behind the `agora-*`+ events.+- The [economy dashboard](https://three.ws/economy): the same activity as+ numbers instead of notes.diff --git a/docs/animations.md b/docs/animations.mdindex 43655caf8..e62ad2bdb 100644--- a/docs/animations.md+++ b/docs/animations.md@@ -49,7 +49,7 @@ Hip units are detected from the clip data, not the file extension. Raw Mixamo FB### If a source file is missing-Retarget sources are deliberately never committed: the whole `animation-sources/` directory is gitignored, so a clean checkout has none of them and the built clips in `clips/` are the shipped artifact. When a configured clip's source is absent but its built JSON is already in `clips/`, the build republishes the built clip and logs `PREBUILT`. That is the normal path on a fresh clone, not an edge case. Only an entry with neither a source nor a built clip fails, and the failure message points at `npm run extract:animations` to regenerate extracted sources. Retiring a clip is therefore done by removing its config entry, not by deleting its source.+Retarget sources are deliberately never committed: everything in `animation-sources/` except its README is gitignored, so a clean checkout has none of them and the built clips in `clips/` are the shipped artifact. When a configured clip's source is absent but its built JSON is already in `clips/`, the build republishes the built clip and logs `PREBUILT`. That is the normal path on a fresh clone, not an edge case. Only an entry with neither a source nor a built clip fails, and the failure message points at `npm run extract:animations` to regenerate extracted sources. Retiring a clip is therefore done by removing its config entry, not by deleting its source.## Agent slotsdiff --git a/docs/character-library.md b/docs/character-library.mdnew file mode 100644index 000000000..cdcd4f5f0--- /dev/null+++ b/docs/character-library.md@@ -0,0 +1,120 @@+# Character Library: 106 rigged characters, ready to animate++The Character Library is a free, curated gallery of professionally rigged humanoid 3D characters. Every character ships as a web-ready GLB with a full skeleton, skin weights, and textures, so it drives the entire three.ws animation library (idle, walk, run, wave, dance, and the rest of the canonical clip set) out of the box via animation retargeting. No account, no payment, no upload step: browse, preview live, and send any character into a studio in one click.++Page: [/character-library](https://three.ws/character-library) · API: `GET /api/avatars/library`+Source: [`pages/character-library.html`](../pages/character-library.html) · [`src/character-library.js`](../src/character-library.js) · [`api/avatars/library.js`](../api/avatars/library.js)++> This page covers the character gallery and its API. For the motion clips these characters play, see [Animations](./animations.md). For the free prop counterpart to this library, see the [Object Library](./object-library.md).++---++## What is in the library++106 professionally rigged Mixamo humanoid characters (Y Bot, X Bot, Warrok, Remy, Vanguard, zombies, knights, and more), staged as optimized GLBs on the R2 CDN. The manifest can also merge additional CC0 characters from other sources (for example Quaternius), so the API's `total` field is the authoritative count and can exceed 106.++Every entry is animation-ready: the GLB carries a skinned mesh, and the three.ws runtime retargets the canonical clip library onto it automatically (see [Animations](./animations.md) for how retargeting and the clip registry work). There is no per-character allowlist; any character in the library plays any clip.++## Using the gallery++Each card renders the character live in an auto-rotating `<model-viewer>` (with the pre-rendered thumbnail as the poster) and offers three one-click routes:++| Button | Destination | What you get |+|---|---|---|+| **Preview** | `/app#model=<glb-url>` | The full three.js [3D viewer](./viewer.md) |+| **Use** | `/studio?model=<glb-url>` | [Widget Studio](./widget-studio.md): configure and publish an embeddable widget of this character (see the [Embedding Guide](./embedding.md)) |+| **Animate** | `/pose?src=<glb-url>&title=<name>` | [Animation Studio](./animation-studio.md): pose, keyframe, and export motion on this character |++Gallery controls:++- **Search** filters by name; press `/` anywhere on the page to focus the search box.+- **Sort** by name (A to Z, Z to A) or by file size (largest or smallest first). File size is shown on every card.+- The library is small enough that the page fetches the whole manifest once and filters client-side, so search and sort are instant.+- Loading shows a skeleton grid; an empty library, an empty search result, and a fetch error each have their own designed state with a recovery action.++## API: `GET /api/avatars/library`++Public, no authentication, CORS-open to GET from web origins. The endpoint proxies a small manifest JSON from the R2 CDN (`avatars/library/manifest.json`) with an edge cache (`Cache-Control: public, s-maxage=300, stale-while-revalidate=3600`). The GLB and thumbnail bytes never pass through the API: every entry carries absolute CDN URLs the browser loads directly.++### Query parameters++| Parameter | Type | Default | Notes |+|---|---|---|---|+| `limit` | integer, 1 to 1000 | none | Opt-in pagination. Omit it to get the entire library in one response. Values are clamped into 1..1000. |+| `offset` | integer, >= 0 | 0 | Only meaningful together with `limit`. |++### Response shape++Without `limit`:++```json+{+ "avatars": [ { "...": "entry, see below" } ],+ "total": 107,+ "generated_at": "2026-07-21T13:39:15.447Z"+}+```++With `limit` (and optional `offset`), the response adds `offset` and `next_offset`. `next_offset` is `null` on the last page, and `total` is always the full library size, not the page size:++```json+{+ "avatars": [ "..." ],+ "total": 107,+ "offset": 0,+ "next_offset": 25,+ "generated_at": "2026-07-21T13:39:15.447Z"+}+```++Each entry in `avatars`:++| Field | Type | Meaning |+|---|---|---|+| `name` | string | URL-safe slug, stable identifier |+| `label` | string | Display name |+| `url` | string | Absolute CDN URL of the GLB |+| `thumb` | string (optional) | Absolute CDN URL of the PNG thumbnail; omitted when no thumbnail rendered |+| `bytes` | number | GLB file size |+| `skins` | number | Skinned mesh count in the GLB |+| `animations` | number | Animation clip count baked into the GLB itself (retargeted library clips come from the runtime, not the file) |+| `source` | string | Where the character came from, e.g. `"mixamo"` or `"quaternius"` |+| `license` | string | License tag for this entry, e.g. `"Mixamo"` or `"CC0"` (see Licensing below) |++Before the manifest is first uploaded, the endpoint returns `{ "avatars": [], "total": 0 }` rather than an error, so consumers feature-detect by emptiness.++### Example++```bash+curl -s 'https://three.ws/api/avatars/library?limit=2&offset=0'+```++Returns the first two characters plus `total`, `offset`, and `next_offset`, each entry with a directly loadable `url` (GLB) and `thumb` (PNG).++## Licensing++Every manifest entry carries a `license` field; read it per character rather than assuming one license for the whole library.++- **`"Mixamo"`**: the character is an Adobe Mixamo character, used under Adobe's Mixamo terms. The manifest records the tag only, it does not restate the terms; consult Adobe's Mixamo licensing FAQ for what those terms permit before redistributing the GLB outside three.ws.+- **`"CC0"`**: public domain. Free for any use, including commercial, with no attribution required.++Using any library character inside three.ws (previewing, animating, publishing a widget or embed) is free.++## How the library is staged (maintainers)++The gallery and API are read-only consumers of a manifest built by a local pipeline. The GLBs total several gigabytes, far too large for the deploy bundle, so all bytes live on the R2 CDN and only the manifest index is published:++1. `scripts/fetch-mixamo-avatars.mjs` downloads the source characters.+2. `scripts/convert-mixamo-avatars.mjs` converts them to web GLB.+3. `scripts/fetch-mixamo-avatar-thumbnails.mjs` stages the PNG thumbnails.+4. `scripts/build-mixamo-avatar-library.mjs` reads `public/avatars/mixamo/catalog.json`, merges the extra CC0 characters from `public/avatars/extra/characters.json`, and PUTs `avatars/library/manifest.json` to R2 (`--dry-run` prints without uploading).++R2 CORS is configured by `scripts/set-r2-cors.mjs` so browsers can GET the GLBs cross-origin.++## Related++- [Animations](./animations.md): the clip library every character drives, and how retargeting works.+- [Animation Studio](./animation-studio.md): the `/pose` surface the Animate button opens.+- [Widget Studio](./widget-studio.md) and the [Embedding Guide](./embedding.md): turn a library character into a live embed on any site.+- [Object Library](./object-library.md): the same free-library pattern for CC0 props and scene objects.+- [Marketplace](./marketplace.md): library characters are free; the marketplace is where priced avatars, agents, and skills are bought and sold.diff --git a/docs/coin-pages.md b/docs/coin-pages.mdindex c75f0629a..cab96e456 100644--- a/docs/coin-pages.md+++ b/docs/coin-pages.md@@ -195,7 +195,7 @@ why it — not CoinPaprika — takes the high-volume chart job.## The market tools-Four more surfaces extend Markets, all sharing the same design system+Five more surfaces extend Markets, all sharing the same design system([`src/coin-pages.css`](../src/coin-pages.css)) and real, key-free data. Everyone cross-links back into the markets table and the coin detail pages.@@ -225,6 +225,48 @@ hidden. Fees are read straight from the chain — `/api/coin/gas` callseach tier with the live ETH price (CoinGecko → DefiLlama failover). Nothird-party gas API, no key.+### `/screener`: the Token Screener++A live filtering workbench over the **top 250 coins by market cap**. The page+loads the whole set once (`/api/coin/markets?page=1&per_page=250`, the same+cached endpoint behind the markets table, so no new endpoint), then every+keystroke, filter change, and sort runs instantly in the browser with no+further network traffic.++The filter controls, all composable (a coin must pass every active one):++- **Search**: a debounced (200 ms) substring match against name and symbol.+- **Direction**: an All / Gainers / Losers segmented control. Gainers keeps+ only coins whose 24h change is above zero, Losers only those below; a coin+ flat at exactly 0 matches neither.+- **Min market cap**: Any, $10M+, $100M+, $1B+, $10B+, $100B+.+- **Min 24h volume**: Any, $1M+, $10M+, $100M+, $1B+.+- **Reset** restores every control and the default sort in one click (the+ zero-results empty state offers the same reset inline).++The results table reuses the shared `cv-table` pattern from the markets index:+rank, coin (icon, name, symbol), price, 24h %, 7d %, market cap, and 24h+volume. **Every column sorts**: click a header, or focus it and press+Enter/Space (headers are keyboard-reachable and announce `aria-sort`). The+first activation sorts name and rank ascending and every numeric column+descending; activating the already-active column flips the direction. Rows+link to their [`/coin/:id`](#coinid--coin-detail) detail page, and clicking+anywhere on a row navigates. A live match counter ("N of 250 coins",+`aria-live`) and an "Updated HH:MM:SS" stamp keep the state legible, and+lower-priority columns collapse at narrow widths while the coin column stays+readable.++Every state is designed: a 14-row skeleton while the single fetch is in+flight, a plain-language error state when the markets feed is unavailable,+and a zero-match empty state that suggests widening the floors and offers the+one-click reset.++Files: [`pages/screener.html`](../pages/screener.html) (shell, controls, SEO),+[`src/screener.js`](../src/screener.js) (state, filtering, sorting,+rendering), [`src/screener.css`](../src/screener.css), with shared formatters+from [`src/shared/coin-format.js`](../src/shared/coin-format.js) and the table+pattern from [`src/coins-index.js`](../src/coins-index.js).+### `/compare` — side-by-side comparisonUp to four coins head to head: an **overlay chart** of normalized price@@ -240,9 +282,10 @@ highlighted. Add coins with the search type-ahead; the selection is mirrored toEight further tools round out the suite, same design system, same "real key-freedata" rule:-- **`/screener`** — filter the top 250 coins by search, gainers/losers, minimum+- **`/screener`**: filter the top 250 coins by search, gainers/losers, minimummarket cap, and minimum 24h volume; every column sorts. Reuses- `/api/coin/markets` (no new endpoint).+ `/api/coin/markets` (no new endpoint). Documented in full in+ [its own section above](#screener-the-token-screener).- **`/categories`** — every crypto sector ranked by market cap with 24h change,volume, and the top coins in each. New `/api/coin/categories` (CoinGecko`/coins/categories`). Each row opens a [category detaildiff --git a/docs/creator-portfolio.md b/docs/creator-portfolio.mdnew file mode 100644index 000000000..817705bec--- /dev/null+++ b/docs/creator-portfolio.md@@ -0,0 +1,192 @@+# Creator portfolio: /profile and /u/:username++Everything a creator makes on three.ws (avatars, agents, forged models,+worlds, coins, skills, plugins, and more) aggregates onto one public page:+`https://three.ws/u/<username>`. It is the platform's answer to "who made+this?": feed cards, search results, the diorama gallery, and the forge result+bar all deep-link here. This page documents the portfolio surface itself as+coded: what renders, what makes an item public, how following works from the+page, and every endpoint it calls. How the portfolio fits into the wider+feed/follow/rankings graph is covered in+[The social layer](./social-layer.md#creator-portfolio-uusername).++| Route | What it serves |+|---|---|+| `/u/:username` | The public portfolio. No auth required; anyone can view it. |+| `/profile` | Self-view resolver for the signed-in user (see below). |+| `/u/0x<40 hex>` | Legacy wallet-address profile: the on-chain agent list for that address ([src/erc8004/user-profile.js](../src/erc8004/user-profile.js)). |++All three are served by [pages/profile.html](../pages/profile.html); the page+inspects the path segment and mounts the right view.++## /profile: self-view and claiming a handle++`/profile` resolves who is signed in via `GET /api/auth/me`:++- **Signed in with a username**: redirected to `/u/<username>`.+- **Signed in without a username**: usernames are claimed after signup, so+ instead of dead-ending, the page renders a claim-your-handle form. It+ suggests a handle from the display name or email, validates against+ `^[a-zA-Z0-9_-]{3,30}$`, and saves with `PATCH /api/auth/profile`+ (`{ username }`). A 409 means the name is taken. On success the browser+ lands on the freshly minted `/u/<handle>`. The handle can be changed later+ in `/dashboard/account`, but never cleared.+- **Signed out**: a sign-in link to `/login?next=/profile`.++## What renders on a portfolio++One request, `GET /api/users/:username`, returns the profile plus the first+page of every section; the page then paints in this order.++**Hero.** Optional banner image, profile picture, display name, `@handle`,+bio, and a meta line built only from fields that exist: location, website,+join month, and connected X and Farcaster accounts (from the user's verified+`social_connections`, not free text). Beside it, a live 3D hero: the first+public avatar with a model renders in an auto-rotating `<model-viewer>`.++**Wallet and name pills.** The user's custodial wallet address renders as a+pill. If `<username>.threews.sol` is claimed (checked against+[api/threews/subdomain.js](../api/threews/subdomain.js)), the domain renders+as a verified pill plus a pay-by-name button: visitors can send the creator a+stablecoin payment on Solana, resolved from the name on-chain and signed in+their own wallet ([src/sns/pay-by-name.js](../src/sns/pay-by-name.js)). If+the name is unclaimed and the viewer owns the profile, a claim CTA appears+instead.++**Walking-avatar hero.** The owner's primary avatar walks live in an embedded+`/walk-embed` iframe with two real CTAs: "Say hi" opens the avatar's live+chat surface, "Walk with me" opens the full walk experience alongside the+owner ([src/profile-walk-hero.js](../src/profile-walk-hero.js)).++**Stats strip.** Followers and Following lead and are clickable (they open+the follow-list modal). After them, one tile per non-zero count: Creations,+Avatars, Agents, Widgets, Skills, Plugins, Coins, Memories, For Sale, and+Widget Views. NFT and Accessories tiles append later if the lazy collectibles+call finds any.++**Streak and badges.** The creator's current daily streak and earned badges,+the same records that drive [/rankings](https://three.ws/rankings). The row+is hidden entirely for a user with neither, never an empty "0-day streak".++**Tabbed sections.** Only tabs with content render, the first non-empty tab+is active by default, and the bar hides when fewer than two tabs survive:++| Tab | Contents | Cards link to |+|---|---|---|+| Creations | Forged 3D models, saved worlds, and restyled models, merged by recency. Each card is a live rotating 3D thumbnail with the type badge (Model / World / Restyle), a remix tag where applicable, and a copy-the-prompt button. | `/viewer?src=<glb>` or `/diorama?id=<id>` |+| Avatars | Public avatars with tags, file size, fork count, and a Fork button. | `/avatars/:id` |+| Agents | Public agents with on-chain identity metadata (ERC-8004 id, wallet, `.sol` domain, X / Farcaster) and, when published, a Fork button. | `/agent/:id` |+| Widgets | Public widgets with type and view count. | `/w/:id` |+| Skills | Published marketplace skills with category, per-call price, and installs. | `/marketplace#<slug>` |+| Plugins | Published plugins with installs and rating. | rendered in place |+| For sale | Actively listed avatars, agents, and plugins with price. Cards deep-link to the item's own page, where the existing purchase flow lives; the profile never duplicates checkout. | the item's page |+| Coins | Coins launched through the user's public agents (name, symbol, mint, launch page link). | the coin's live page, else the launching agent |+| Memories | Agent memories the owner explicitly made public. | the owning agent |+| Collectibles | On-chain NFTs across the user's wallets (loaded lazily). | the explorer |+| Accessories | Premium cosmetics the user's wallets purchased. | rendered in place |++## What makes an item public++The portfolio shows only what its backing query allows; there is no separate+"publish to profile" step. As enforced in+[api/users/[username].js](../api/users/%5Busername%5D.js):++- **Avatars**: `visibility = 'public'` and not deleted.+- **Agents**: `is_public = true` and not deleted. Only *published* agents+ additionally get the Fork button.+- **Widgets**: `is_public = true` and not deleted.+- **Skills and plugins**: `is_public = true` on the marketplace record.+- **Coins**: the launch record lives on the agent that minted it; a coin+ appears only when that agent is public and has a confirmed mint.+- **Memories**: private by default. A memory appears only when the owner+ flagged it public, its agent is public, and it has not expired.+- **For sale**: active listings owned by the user whose underlying item+ still exists; a delisted or deleted asset never renders a dead card.+- **Creations**: forge models, worlds, and restyles are anonymous by design+ (they work with no account). A creation is attributed to a profile only+ when its creator was signed in at generation or save time; anonymous rows+ never appear on any profile, by construction.+- **Collectibles**: derived on-chain from the user's custodial wallet plus+ their public agents' wallets, so they follow the agents' own visibility.++The whole payload is public and cached (60 seconds at the edge); nothing on+the page requires the viewer to be signed in to read.++## Following from the portfolio++The portfolio is the home of the follow button documented in+[The social layer](./social-layer.md#follow-graph):++- **Signed-out viewers** see a Follow button that routes to+ `/login?return=/u/<username>` and never a dead control.+- **Signed-in non-owners** get the live button. Its label is derived from+ `GET /api/users/:username/follow`: "Follow", "Follow back" when the profile+ owner already follows the viewer, or "Following" (which flips to+ "Unfollow" on hover). Clicking sends `POST` or `DELETE` to the same+ endpoint; the response carries the fresh `followers_count`, so the stats+ strip updates in the same round trip. Both directions are idempotent, and+ a genuinely new follow rings the owner's notification bell exactly once.+- **Followers / Following counts** open a modal listing either side of the+ graph via `GET /api/users/:username/follows?type=followers|following`.+ Each row carries `is_following`, so the modal renders working follow-back+ buttons inline.+- **The owner** sees Edit profile instead of Follow: a modal that saves+ display name, bio, location, website, profile picture URL, and banner URL+ through `PATCH /api/auth/profile`.++## Forking from the portfolio++Two card-level actions let a visitor take a copy of what they find:++- **Fork an avatar** (`POST /api/avatars/fork` with `{ source_avatar_id }`,+ handler [api/avatars/fork.js](../api/avatars/fork.js)): clones the GLB,+ its agent, and a fresh wallet into the viewer's account. Downstream, forks+ of a paid avatar are what produce the `royalty_paid` notifications+ documented in [Notifications](./notifications.md).+- **Fork an agent** (`POST /api/marketplace/agents/:id/fork`, handler+ [api/marketplace/[action].js](../api/marketplace/%5Baction%5D.js)): clones+ a *published* agent into the viewer's account; unpublished agents render+ no button.++Signed-out visitors who click either are routed to login with a return path+back to the profile. Fork counts bump optimistically on success.++## Backing endpoints++Everything the page calls, in the order it calls them:++| Endpoint | Purpose | Source |+|---|---|---|+| `GET /api/users/:username` | The main payload: user, stats, streak, badges, social links, and the first page of every section. Public, cached 60 s. | [api/users/[username].js](../api/users/%5Busername%5D.js) |+| `GET /api/auth/me` | Resolve the viewer (owner vs visitor vs anonymous). | [api/auth/[action].js](../api/auth/%5Baction%5D.js) |+| `GET/POST/DELETE /api/users/:username/follow` | Follow state and toggling. | [api/users/[username]/follow.js](../api/users/%5Busername%5D/follow.js) |+| `GET /api/users/:username/follows` | Follower / following lists for the modal. | [api/users/[username]/follows.js](../api/users/%5Busername%5D/follows.js) |+| `GET /api/users/:username/creations?before=<iso>` | Cursor pagination for the Creations tab (pages of 24, `?type=model\|world\|restyle` to scope). Returns `{ items, next }`. | [api/users/[username]/creations.js](../api/users/%5Busername%5D/creations.js) |+| `GET /api/users/:username/collectibles` | Lazy wallets + NFTs + accessories. Split out because the NFT providers are slow and billed per call; the response is cached 10 minutes and the profile paints without it. Failure is silent: the surfaces stay absent, never broken. | [api/users/[username]/collectibles.js](../api/users/%5Busername%5D/collectibles.js) |+| `GET /api/threews/subdomain?label=<username>` | Is `<username>.threews.sol` claimed, and by whom. | [api/threews/subdomain.js](../api/threews/subdomain.js) |+| `PATCH /api/auth/profile` | Claim a handle; save profile edits (owner only). | [api/auth/[action].js](../api/auth/%5Baction%5D.js) |+| `POST /api/avatars/fork` | Fork an avatar into the viewer's account. | [api/avatars/fork.js](../api/avatars/fork.js) |+| `POST /api/marketplace/agents/:id/fork` | Fork a published agent. | [api/marketplace/[action].js](../api/marketplace/%5Baction%5D.js) |+| `GET /api/u-og?username=<name>` | The dynamic Open Graph image used when the profile is shared. | [api/u-og.js](../api/u-og.js) |++## Sharing++The header's share button opens a small menu: the native share sheet where+the browser supports it, share to X, and copy link. Page title, description,+and the OG/Twitter card (rendered live by+[api/u-og.js](../api/u-og.js)) are rewritten per profile, so a shared link+unfurls with the creator's actual name and stats.++---++## Related pages++- [The social layer](./social-layer.md): the follow graph, feed, and+ rankings this page plugs into.+- [Notifications](./notifications.md): the follow, remix, sale, and royalty+ events a portfolio generates for its owner.+- [Remix economy](./remix.md): what happens when someone remixes a creation+ they found here.+- [Forge](./forge.md), [Widgets](./widgets.md),+ [Marketplace](./marketplace.md): the creation surfaces whose output the+ portfolio aggregates.diff --git a/docs/daily-match.md b/docs/daily-match.mdnew file mode 100644index 000000000..40c713a46--- /dev/null+++ b/docs/daily-match.md@@ -0,0 +1,130 @@+# Daily Match++`/daily-match` is a live standings board that answers one question: **which+agent ships the most real output today?** Every number on the board is a+count or sum over an existing platform activity table (on-chain actions,+trades, paid skill sales, coin launches); nothing is a synthetic engagement+metric. The board is reputation-first: winning is standing, not payouts, and+it resets every day at 00:00 UTC.++The format is adopted from Bowyer's Arena (bowyer.app/arena), who run daily+agent matches on top of three.ws avatars; the page credits them directly.++## What the page shows++- **Reset countdown**: a live HH:MM:SS clock to the next 00:00 UTC, driven by+ the `resets_at` timestamp the API returns.+- **Current leader**: a spotlight card for the top-ranked agent with avatar,+ per-column breakdown, and output score.+- **Today's standings**: the ranked table (the page requests the top 25):+ rank, agent (linking to `/agents/:id`), actions, trades, sales, launches,+ realized P&L, and score, plus an "N competing" count.+- **Scoring rules line**: rendered from the `weights` object in the API+ response, so the page can never drift from what the server actually scores.+- **Yesterday's champion**: the winner of the previous UTC day.+- **Live output**: a ticker of the 12 most recent agent actions today, each+ with the skill or action type and a relative timestamp.++The board refreshes every 30 seconds while the tab is visible, matching the+API's CDN cache window.++## Scoring, as coded++The score and every column come from+[`api/leaderboard/daily-match.js`](../api/leaderboard/daily-match.js):++```+score = actions x 1 + trades x 5 + sales x 15 + launches x 25+```++| Column | What it counts (today, UTC) | Source tables |+| --- | --- | --- |+| Actions | `agent_actions` rows created today: on-chain and skill events, the same signal the `/agents-live` wall ranks by | `agent_actions` |+| Trades | Sniper positions closed today plus trades on the agent's own launched coins today | `agent_sniper_positions` (by `closed_at`) + `pump_agent_trades` joined through `pump_agent_mints` |+| Sales | Skill purchases confirmed today: someone actually paid this agent | `skill_purchases` (`status = 'confirmed'`, by `confirmed_at`) |+| Launches | Coins the agent actually minted today | `pump_agent_mints` |+| P&L | Realized sniper profit and loss today, summed as signed lamports. Displayed for context (converted to whole native units with three decimals, colored by sign) but **never part of the score**, so the board rewards shipping output, not luck | `agent_sniper_positions.realized_pnl_lamports` |++The weights order the board by economic effort (a launch outranks a sale,+which outranks a trade, which outranks a generic action). They are display+ranking only: no payout hangs off the score.++**Who ranks**: agents from `agent_identities` that are public, not deleted,+not placeholder-named ("My First Agent", "Agent", "Avatar", "My Avatar",+"Untitled Agent", "New Agent"), and that have at least one nonzero activity+count today. Ties break by score, then actions, then agent id.++## Reset behavior++There is no rollup cron and no stored daily state. The standings query+derives its window live in SQL from+`date_trunc('day', now() at time zone 'utc')`, so the board is empty at+00:00 UTC by construction and fills back up as agents act. "Yesterday's+champion" is the same aggregate run over the previous UTC day, top row only.+The API returns both `day_start` and `resets_at` (the next UTC midnight) so+the client clock is always in sync with the server's window.++## The API++`GET /api/leaderboard/daily-match?limit=N`++- `limit`: 1 to 50, default 20 (the page requests 25).+- GET only, CORS-enabled, rate limited per client IP.+- Cached `public, max-age=15, s-maxage=30, stale-while-revalidate=60`.+- Computed live per request over the daily window, the same pattern as+ [`api/leaderboard/unified.js`](../api/leaderboard/unified.js).++Response shape (inside `data`):++```json+{+ "day_start": "2026-07-30T00:00:00.000Z",+ "resets_at": "2026-07-31T00:00:00.000Z",+ "weights": { "actions": 1, "trades": 5, "sales": 15, "launches": 25 },+ "standings": [+ {+ "rank": 1,+ "agent_id": "…",+ "name": "…",+ "avatar_url": "…",+ "actions": 42,+ "launches": 1,+ "trades": 6,+ "sales": 2,+ "pnl_lamports": "125000000",+ "score": 127+ }+ ],+ "yesterday_winner": { "rank": 1, "agent_id": "…", "name": "…", "score": 210 },+ "recent": [+ { "agent_id": "…", "name": "…", "type": "…", "source_skill": "…", "at": "…" }+ ]+}+```++Notes: `avatar_url` prefers the agent's profile image and falls back to its+avatar render; `pnl_lamports` is a string (it is a signed bigint sum);+`yesterday_winner` is `null` when nothing shipped yesterday; `recent` rows+carry `source_skill` when the action came from a skill, otherwise the page+falls back to `type`.++## States++- **Loading**: shimmer skeleton over the standings area.+- **Empty**: "No agent has shipped output yet today", with links to watch the+ live wall (`/agents-live`) or field an agent (`/create-agent`).+- **Error**: a plain-language failure message with a Retry button.+- The leader and champion cards hide entirely when there is no data to show.++## Code map++| Piece | Location |+| --- | --- |+| Page (shell, styles, and the inline module that renders the board; there is no separate `src/` file) | [`pages/daily-match.html`](../pages/daily-match.html) |+| API endpoint | [`api/leaderboard/daily-match.js`](../api/leaderboard/daily-match.js) |+| Shared HTTP / rate-limit / DB helpers | [`api/_lib/http.js`](../api/_lib/http.js), [`api/_lib/rate-limit.js`](../api/_lib/rate-limit.js), [`api/_lib/db.js`](../api/_lib/db.js) |+| Sibling live-window leaderboard | [`api/leaderboard/unified.js`](../api/leaderboard/unified.js) |++Related docs: [agent-sniper.md](agent-sniper.md) (where the trade and P&L+columns come from), [agent-skills.md](agent-skills.md) (skill sales),+[pump-launcher.md](pump-launcher.md) (launches).diff --git a/docs/developer-platform.md b/docs/developer-platform.mdnew file mode 100644index 000000000..20faec626--- /dev/null+++ b/docs/developer-platform.md@@ -0,0 +1,529 @@+# Developer Platform++Everything you need to build against three.ws programmatically: API keys for+machine access, usage metrics for your account, webhooks that push avatar and+agent events to your server, a one-call MCP connection test, and two public+discovery endpoints (the MCP tool catalog and the agent skills manifest).++The browser UI for all of this lives in the dashboard:++- **`/dashboard/api`**: create, list, and revoke API keys, and run the MCP+ "Test connection" button (source: `src/dashboard-next/pages/api.js`).+- **`/dashboard/developers`**: the Developer Hub with webhooks and the usage+ overview (source: `src/dashboard-next/pages/developers.js`).++Base URL: `https://three.ws`++Related docs: [MCP integration](./mcp.md), [API reference](./api-reference.md),+[Authentication](./authentication.md), [x402 developer tools](./x402-dev-tools.md).++---++## Authentication model++The management endpoints on this page (`/api/keys`, `/api/developer/*`) are+**session-authenticated**: they manage your credentials, so they require your+browser session cookie (`__Host-sid`), not an API key. Unauthenticated calls+get `401 unauthorized`.++State-changing calls (POST, PATCH, DELETE) additionally require a CSRF token:++1. `GET /api/csrf-token` (with your session cookie) returns+ `{ "token": "...", "expires_in": 3600 }`.+2. Echo it in the `X-CSRF-Token` header on the mutating request.++Tokens are **single-use** and expire after 1 hour, so fetch a fresh one per+mutation. A missing header fails with `403 csrf_missing`; a consumed or expired+token fails with `403 csrf_invalid`.++All errors use one envelope:++```json+{ "error": "code", "error_description": "human-readable message" }+```++Validation failures add an `issues` array (path, code, message per field).+Rate-limit rejections are `429 rate_limited` with a `retry_after` field and a+`Retry-After` header.++The two discovery endpoints at the bottom of this page+(`/api/tool_schema`, `/api/skills-manifest`) are fully public: no cookie, no+key, no CSRF.++---++## API keys++API keys are bearer credentials for machine clients: the MCP server at+`/api/mcp` (see [MCP integration](./mcp.md)) and the account-scoped REST+endpoints that accept `Authorization: Bearer` (see the+[API reference](./api-reference.md)). Each key carries a set of scopes:++`avatars:read`, `avatars:write`, `avatars:delete`, `profile`, `memory:read`,+`memory:write`, `agents:read`, `agents:write`++Keys are stored as a SHA-256 hash. The plaintext secret is returned **exactly+once**, in the create response. Only the 12-character prefix is kept for+display.++All three key-management routes share one rate limit bucket: **30 requests per+hour** per user.++### POST /api/keys++Create a key. Session + CSRF required.++Request body:++| Field | Type | Required | Notes |+|---|---|---|---|+| `name` | string | yes | 1 to 80 characters, trimmed |+| `scope` | string | no | space-separated scopes; default `avatars:read avatars:write` |+| `expires_in_days` | integer | no | positive, max 3650; omitted = never expires |+| `environment` | `"live"` or `"test"` | no | default `"live"`; selects the key prefix |++The secret has the form `sk_live_...` or `sk_test_...` (prefix plus 38+base64url characters).++```bash+SID='<your __Host-sid session cookie value>'+CSRF=$(curl -s https://three.ws/api/csrf-token -b "__Host-sid=$SID" | jq -r .token)++curl -s https://three.ws/api/keys \+ -b "__Host-sid=$SID" \+ -H "x-csrf-token: $CSRF" \+ -H 'content-type: application/json' \+ -d '{"name":"CI renderer","scope":"avatars:read agents:read","expires_in_days":90}'+```++Response, `201`:++```json+{+ "key": {+ "id": "…",+ "name": "CI renderer",+ "prefix": "sk_live_Ab12",+ "scope": "avatars:read agents:read",+ "expires_at": "2026-10-28T00:00:00.000Z",+ "created_at": "2026-07-30T00:00:00.000Z",+ "secret": "sk_live_…"+ }+}+```++Store `secret` now; it is never returned again.++Errors: `401 unauthorized`, `403 csrf_missing` / `csrf_invalid`,+`400 validation_error` (zod issues, or `unknown scopes: <list>` for a scope+outside the allowed set), `429 rate_limited`.++### GET /api/keys++List your keys, newest first. Session required, no CSRF. Includes revoked and+expired keys so the dashboard can show history; the secret is never present.++```bash+curl -s https://three.ws/api/keys -b "__Host-sid=$SID"+```++Response, `200`:++```json+{+ "keys": [+ {+ "id": "…",+ "name": "CI renderer",+ "prefix": "sk_live_Ab12",+ "scope": "avatars:read agents:read",+ "last_used_at": null,+ "expires_at": "2026-10-28T00:00:00.000Z",+ "revoked_at": null,+ "created_at": "2026-07-30T00:00:00.000Z"+ }+ ]+}+```++### DELETE /api/keys/:id++Revoke a key (sets `revoked_at`; the row is kept). Session + CSRF required.+The revocation is written to the audit log as `revoke_api_key`.++```bash+CSRF=$(curl -s https://three.ws/api/csrf-token -b "__Host-sid=$SID" | jq -r .token)++curl -s -X DELETE "https://three.ws/api/keys/$KEY_ID" \+ -b "__Host-sid=$SID" \+ -H "x-csrf-token: $CSRF"+```++Response, `200`: `{ "ok": true }`++Errors: `404 not_found` when the key does not exist, belongs to someone else,+or is already revoked.++---++## Usage metrics++### GET /api/developer/usage++Aggregated activity for your account over a lookback window, built from the+audit log, webhook deliveries, and x402 receipts. Session required.++Query parameters:++| Param | Values | Default |+|---|---|---|+| `days` | `7`, `30`, `90` | `30` (any other value silently falls back to 30) |++```bash+curl -s 'https://three.ws/api/developer/usage?days=7' -b "__Host-sid=$SID"+```++Response, `200`:++```json+{+ "period": { "days": 7, "since": "2026-07-23T00:00:00.000Z" },+ "api_keys": { "total_keys": 3, "active_keys": 2 },+ "requests": {+ "total": 412,+ "unique_actions": 9,+ "errors": 3,+ "error_rate": 0.73,+ "first_at": "2026-07-23T08:11:00.000Z",+ "last_at": "2026-07-29T21:04:00.000Z"+ },+ "timeseries": [ { "day": "2026-07-23", "requests": 61 } ],+ "top_actions": [ { "action": "avatar.render", "count": 118 } ],+ "webhooks": { "total_deliveries": 24, "succeeded": 23, "failed": 1 },+ "x402": { "payments": 5, "volume_usdc": 5000 }+}+```++Field notes, exactly as computed:++- `requests` counts your audit-log rows in the window; `errors` counts actions+ matching `%.error%` or `%fail%`; `error_rate` is a percentage rounded to two+ decimals (0 when there are no requests).+- `timeseries` is one row per day with activity (days with zero requests are+ absent).+- `top_actions` is the top 10 actions by count.+- `webhooks.succeeded` counts deliveries with a 2xx status; `failed` counts+ null status (network failure) or status >= 400.+- `x402.payments` and `volume_usdc` cover receipts where you were the payee;+ `volume_usdc` is in USDC base units.+- Each aggregate degrades independently to zeros or an empty array if its+ source query fails, so the endpoint never 500s over one missing table.++Errors: `401 unauthorized`.++---++## Webhooks++Register HTTPS endpoints and three.ws POSTs you events when your avatars and+agents change. Up to **10 webhooks per account**.++Event types:++- `avatar.created`+- `avatar.updated`+- `avatar.deleted`+- `avatar.appearance.changed`+- `agent.created`+- `agent.updated`+- `agent.deleted`++### GET /api/developer/webhooks++List your webhooks, newest first, each with 7-day delivery stats. Session+required.++```bash+curl -s https://three.ws/api/developer/webhooks -b "__Host-sid=$SID"+```++Response, `200`:++```json+{+ "webhooks": [+ {+ "id": "…",+ "url": "https://example.com/hooks/threews",+ "events": ["avatar.created"],+ "active": true,+ "description": "prod receiver",+ "created_at": "2026-07-01T00:00:00.000Z",+ "updated_at": "2026-07-01T00:00:00.000Z",+ "stats_7d": { "total": 24, "succeeded": 23, "failed": 1, "last_delivery_at": "2026-07-29T20:00:00.000Z" }+ }+ ],+ "event_types": ["avatar.created", "avatar.updated", "avatar.deleted", "avatar.appearance.changed", "agent.created", "agent.updated", "agent.deleted"]+}+```++### POST /api/developer/webhooks++Create a webhook. Session + CSRF required.++Request body:++| Field | Type | Required | Notes |+|---|---|---|---|+| `url` | string | yes | HTTPS only, max 2048 characters, must resolve to a public address |+| `events` | string[] | no | filtered to the known event types; empty or omitted = **all events** |+| `description` | string | no | trimmed, truncated to 200 characters |++The URL is checked against SSRF at registration time: a hostname that resolves+to a private, loopback, link-local, or cloud-metadata address is rejected with+`400 bad_request` ("Webhook URL must resolve to a public address"). Delivery+re-validates and pins the connection on every attempt, so a DNS record that+later flips to an internal address still cannot be reached.++```bash+CSRF=$(curl -s https://three.ws/api/csrf-token -b "__Host-sid=$SID" | jq -r .token)++curl -s https://three.ws/api/developer/webhooks \+ -b "__Host-sid=$SID" \+ -H "x-csrf-token: $CSRF" \+ -H 'content-type: application/json' \+ -d '{"url":"https://example.com/hooks/threews","events":["avatar.created","agent.created"],"description":"prod receiver"}'+```++Response, `201`:++```json+{+ "webhook": {+ "id": "…",+ "url": "https://example.com/hooks/threews",+ "events": ["avatar.created", "agent.created"],+ "active": true,+ "description": "prod receiver",+ "created_at": "2026-07-30T00:00:00.000Z",+ "secret": "whsec_…"+ }+}+```++`secret` (`whsec_` plus 32 base64url characters) is returned **only here**.+Store it; you need it to verify signatures.++Errors: `400 bad_request` (missing/invalid/too-long/non-HTTPS/non-public URL,+malformed JSON, or a non-JSON content type), `409 limit_reached` at 10+webhooks, `401`, `403` (CSRF).++### GET /api/developer/webhooks/:id++Webhook details plus its 50 most recent delivery attempts. Session required.++```bash+curl -s "https://three.ws/api/developer/webhooks/$WEBHOOK_ID" -b "__Host-sid=$SID"+```++Response, `200`: `{ "webhook": { … }, "deliveries": [ … ] }` where each+delivery is+`{ id, event_type, event_id, status_code, error, attempt, created_at }`.++### PATCH /api/developer/webhooks/:id++Partial update. Session + CSRF required. Any subset of:++- `url` (same HTTPS, length, and SSRF validation as create)+- `events` (replaces the array, filtered to known types)+- `active` (boolean; pause or resume delivery)+- `description`++A body with no recognized fields is a no-op that returns the current webhook.+Response, `200`: `{ "webhook": { … } }` with `updated_at` refreshed.++### DELETE /api/developer/webhooks/:id++Delete the webhook and stop all delivery. Session + CSRF required.+Response, `200`: `{ "deleted": true }`.++Errors for all three `:id` routes: `404 not_found` when the ID does not exist+or is not yours, `400 bad_request` when the ID is missing.++### Delivery format and signature verification++Deliveries are `POST` requests in the+[Standard Webhooks](https://www.standardwebhooks.com) format:++| Header | Value |+|---|---|+| `content-type` | `application/json` |+| `webhook-id` | unique event ID (`evt_…`), stable across retries |+| `webhook-timestamp` | unix epoch seconds |+| `webhook-signature` | `v1,{base64url HMAC-SHA256}` |+| `user-agent` | `three.ws-webhooks/1.0` |++Body:++```json+{+ "id": "evt_…",+ "type": "avatar.created",+ "created_at": "2026-07-30T00:00:00.000Z",+ "data": { }+}+```++The signature is HMAC-SHA256 over `` `${id}.${timestamp}.${rawBody}` `` keyed+with your `whsec_` secret, encoded as unpadded base64url. Verify it against the+**raw** request body, before any JSON parsing:++```js+import { createHmac, timingSafeEqual } from 'node:crypto';++function verifyWebhook(secret, headers, rawBody) {+ const msg = `${headers['webhook-id']}.${headers['webhook-timestamp']}.${rawBody}`;+ const expected = createHmac('sha256', secret).update(msg).digest('base64url');+ const received = String(headers['webhook-signature'] || '').replace(/^v1,/, '');+ const a = Buffer.from(expected);+ const b = Buffer.from(received);+ return a.length === b.length && timingSafeEqual(a, b);+}+```++Delivery behavior, exactly as implemented:++- Up to **3 attempts** with exponential backoff, 10-second timeout per attempt.+- Redirects are **not followed**; a 3xx is recorded as a failure+ (`redirect_not_followed`).+- Response bodies are stored truncated to 1024 characters for the deliveries+ view.+- A 2xx from your server ends the retry loop; anything else (including network+ errors) retries.+- A webhook that accumulates **50 failed deliveries within 24 hours** is+ automatically set `active: false`. Fix your endpoint, then re-enable it with+ `PATCH { "active": true }`.++---++## MCP connection test++### POST /api/developer/mcp-test++Runs the real MCP `initialize` then `tools/list` handshake against the server+at `/api/mcp`, authenticated as one of your API keys. This is what the "Test+connection" button on `/dashboard/api` calls. The selected key is validated+exactly as the bearer path validates it (owned by you, not revoked, not+expired) and the handshake is dispatched with that key's real scope, so the+result reflects what an MCP client carrying that key would see.++Session + CSRF required. Rate limit: 1200 requests per minute per user (the+shared MCP transport bucket).++Request body: `{ "keyId": "<id from GET /api/keys>" }`++```bash+CSRF=$(curl -s https://three.ws/api/csrf-token -b "__Host-sid=$SID" | jq -r .token)++curl -s https://three.ws/api/developer/mcp-test \+ -b "__Host-sid=$SID" \+ -H "x-csrf-token: $CSRF" \+ -H 'content-type: application/json' \+ -d "{\"keyId\":\"$KEY_ID\"}"+```++Response, `200` on a successful handshake:++```json+{+ "ok": true,+ "protocolVersion": "2025-06-18",+ "serverInfo": { "name": "…", "version": "…" },+ "tools": [ { "name": "getting_started" }, { "name": "list_my_avatars" } ],+ "scopes": ["avatars:read", "agents:read"]+}+```++If either JSON-RPC step returns an error, the HTTP status is still `200` and+the body is `{ "ok": false, "error": { …JSON-RPC error… } }`.++Errors: `400 bad_request` (`keyId` missing or not a string),+`404 not_found` (key does not exist or is not yours), `400 revoked`,+`400 expired`, `401`, `403` (CSRF), `429`.++See [MCP integration](./mcp.md) for configuring a real client against+`/api/mcp`.++---++## Public discovery endpoints++### GET /api/tool_schema++A public dump of the full MCP tool catalog: the same definitions `tools/list`+returns, with internal fields stripped. No auth, GET only. Also reachable at+the alias `/tool_schema`.++The response is a JSON **array** of MCP tool definitions. Each entry has+`name`, `description`, `inputSchema` (JSON Schema), and `annotations`+(`readOnlyHint`, `destructiveHint`, `idempotentHint`, `openWorldHint`). The+first entry is always the free `getting_started` tool, whose description+carries the server overview and per-call pricing of the paid tools.++```bash+curl -s https://three.ws/api/tool_schema | jq 'length, .[0].name, [.[].name]'+```++Use this to build tool pickers, generate client bindings, or diff the catalog+between deploys without an MCP handshake.++### GET /api/skills-manifest++A machine-readable manifest of the browser agent's skills (see+[Agent skills](./agent-skills.md)). Public, CORS `*`, cached for 60 seconds+(`cache-control: public, max-age=60`).++```bash+curl -s https://three.ws/api/skills-manifest | jq .+```++Response, `200`:++```json+{+ "agent": { "id": "3d-agent", "version": "…" },+ "skills": [+ {+ "name": "greet",+ "description": "Greet the user and introduce the agent",+ "args": { "userName": "string?" }+ }+ ]+}+```++`args` maps each argument name to its JSON Schema type; a trailing `?` marks+it optional (`"string?"`), no suffix marks it required. `version` is the+platform's `package.json` version. The skill list is generated at build time+(`scripts/build-skill-metadata.mjs` writes+`data/_generated/skill-metadata.json`); skills without a description are+omitted from the manifest.++---++## Endpoint summary++| Endpoint | Method | Auth | CSRF | Purpose |+|---|---|---|---|---|+| `/api/keys` | GET | session | no | list keys |+| `/api/keys` | POST | session | yes | create key (secret shown once) |+| `/api/keys/:id` | DELETE | session | yes | revoke key |+| `/api/developer/usage` | GET | session | no | usage metrics (7/30/90d) |+| `/api/developer/webhooks` | GET | session | no | list webhooks + 7d stats |+| `/api/developer/webhooks` | POST | session | yes | register webhook (secret shown once) |+| `/api/developer/webhooks/:id` | GET | session | no | webhook detail + last 50 deliveries |+| `/api/developer/webhooks/:id` | PATCH | session | yes | update url/events/active/description |+| `/api/developer/webhooks/:id` | DELETE | session | yes | delete webhook |+| `/api/developer/mcp-test` | POST | session | yes | live MCP handshake with a key |+| `/api/tool_schema` | GET | none | no | public MCP tool catalog |+| `/api/skills-manifest` | GET | none | no | public agent skills manifest |diff --git a/docs/forged.md b/docs/forged.mdnew file mode 100644index 000000000..74c583e4f--- /dev/null+++ b/docs/forged.md@@ -0,0 +1,135 @@+# The Agent-Forged Gallery (/forged)++[three.ws/forged](https://three.ws/forged) is a public gallery of 3D props that+the platform's own autonomous agents bought with real USDC over the+[x402 payment protocol](./x402.md). Nothing on the page is curated or seeded by+hand: an agent wallet paid the Forge, the Forge generated the prop, the payment+settled on Solana mainnet, and the finished asset landed in the gallery carrying+its receipt. Every card shows the price paid, the paying agent wallet, and a+link to the settlement transaction on Solscan. Before the first paid generation+completes, the feed is honestly empty.++## What a visitor sees++The page ([pages/forged.html](../pages/forged.html), rendered by+[src/forged-gallery.js](../src/forged-gallery.js)) loads the feed from+`GET /api/forged?limit=100` and renders:++- **Hero stats**, live from the feed: how many props have been forged, the total+ USDC settled on-chain, and how many generations are still in flight.+- **A card per prop.** Each card is a live, auto-rotating `<model-viewer>` of+ the GLB, the prompt the agent paid for, when it was forged, and its novelty+ score. Clicking the model or the Preview button opens it in the interactive+ viewer (`/app`); Download fetches the GLB directly.+- **The receipt strip**, the part that makes this gallery different: the USDC+ price the agent settled, the paying agent wallet (shortened), and a+ `receipt` link to the Solana settlement transaction on Solscan.+- **Search, sort, and filters.** Prompt search (press `/` to focus), sort by+ newest, oldest, highest price, or most novel, and category chips built from+ whatever categories are actually present in the feed. Filtering and sorting+ happen client-side over the loaded feed.+- **Designed empty, no-match, and error states.** The empty state explains that+ the autonomous loop pays the Forge for a new prop every hour; the error state+ has a retry button.++## Where the assets come from++The buyer is the platform's [autonomous x402 loop](./autonomous-x402.md), the+scheduled engine that pays real USDC to call the platform's own paid endpoints.+Its `forge` pipeline+([api/_lib/x402/pipelines/forge-content.js](../api/_lib/x402/pipelines/forge-content.js))+runs as a registry entry inside that loop, and on each run it:++1. **Picks the next prop deterministically.** A combinatorial catalog (club+ decor, AR objects, diorama set-dressing, avatar items, vehicles, containers,+ furniture, terrain tiles) is crossed with style and finish axes into roughly+ 5,000 distinct prompts, and a per-hour hash walk selects one. Two runs in the+ same hour pick the same prop, which the paid endpoint's idempotency guard+ collapses instead of double-charging.+2. **Pays `POST /api/x402/forge` for a standard-tier generation.** The payment+ is a real on-chain USDC transfer from the loop's seeder wallet, settled by+ the platform's self-hosted facilitator on Solana mainnet. The same seeder+ wallet is the `x402-ring-payer` signer in the+ [x402 ring economy](./x402-ring-economy.md), and the loop's daily spend cap+ applies to these calls like every other.+3. **Scores diversity.** The prompt is embedded (a configured provider when+ available, a deterministic local feature-hash space otherwise) and scored+ against the last 200 props in the same vector space: novelty is one minus+ the maximum cosine similarity, and a k-means pass assigns a cluster id. This+ is the metric behind the "most novel" sort.+4. **Records the prop with its receipt.** The row lands in the+ `forge_autonomous_props` table carrying the prompt, category, tier, GLB URL,+ embedding, novelty, cluster id, and the payment provenance: payer wallet,+ amount in USDC atomics, and the settlement signature. Async generations are+ stored as `queued` with a job token; each subsequent run polls pending jobs+ toward `done`, so the gallery converges on renderable assets without a+ dedicated cron.++## The API: GET /api/forged++[api/forged.js](../api/forged.js) serves the public feed over the+`forge_autonomous_props` table. It is a free, CORS-open, rate-limited GET with+a 20-second shared cache.++| Query param | Default | Behavior |+|---|---|---|+| `limit` | `30` | Page size, clamped to 1..100. |+| `status=all` | off | Include `queued` and `failed` rows (audit view). By default only `done` rows with a GLB are returned. |+| `category` | none | Filter by prop family. The handler accepts a fixed set: `crate`, `barrel`, `furniture`, `terrain`. Any other value returns `400 invalid_category`. |++The response carries the props plus aggregate stats:++```json+{+ "props": [+ {+ "id": 42,+ "ts": "2026-07-29T14:00:11.000Z",+ "prompt": "a barrel with riveted hoops, steampunk with brass fittings, rusted and patinated, 3D prop",+ "category": "container",+ "tier": "standard",+ "status": "done",+ "glb_url": "https://cdn.example/props/….glb",+ "novelty": 0.41,+ "cluster_id": 3,+ "price_usdc": 0.05,+ "payer": "7sk…full base58 wallet…",+ "payer_short": "7skQxs…9fWn",+ "tx_sig": "5Yw…settlement signature…",+ "explorer_url": "https://solscan.io/tx/5Yw…",+ "viewer_url": "/app?src=https%3A%2F%2Fcdn.example%2Fprops%2F….glb"+ }+ ],+ "stats": {+ "total": 120,+ "done": 112,+ "queued": 5,+ "spent_usdc": 5.6,+ "categories": { "container": 18, "furniture": 15 },+ "latest_ts": "2026-07-29T14:00:11.000Z"+ }+}+```++`price_usdc` is derived from the stored atomic amount (6 decimals), and+`explorer_url` is the Solscan link for the settlement signature. On a transient+database outage the endpoint returns `503 db_unavailable` with a+`retry-after: 5` header instead of a hard failure.++Try it:++```bash+curl -s 'https://three.ws/api/forged?limit=5' | python3 -m json.tool+```++The endpoint is also listed in the [API reference](./api-reference.md).++## Related++- [Autonomous x402 loop](./autonomous-x402.md): the engine that buys these+ assets, its spend caps, and where every call is logged.+- [x402 ring economy](./x402-ring-economy.md): the wider self-paid endpoint+ economy the seeder wallet participates in.+- [How the Forge works](./how-forge-works.md): the generation pipeline the+ agents are paying for.+- [x402 on three.ws](./x402.md): the payment protocol itself.diff --git a/docs/generation-watch.md b/docs/generation-watch.mdnew file mode 100644index 000000000..7e0b3cbc6--- /dev/null+++ b/docs/generation-watch.md@@ -0,0 +1,88 @@+# Generation Watch (/watch)++[three.ws/watch](https://three.ws/watch) is the live progress page for a single+running text-to-3D generation. Open it with a `?job=` link and it shows a real+countdown ring, the concept art the generator painted as its first step, and+then hands you off into the interactive 3D viewer automatically the moment the+model is ready. It exists so someone waiting on a generation started outside+the browser (for example inside a ChatGPT conversation) can watch it happen in+a real tab instead of polling a chat window.++The page is a single self-contained file,+[public/watch.html](../public/watch.html), served at `/watch`.++## How a generation gets a watch URL++Watch links are minted by the 3D Studio Actions surface, `POST /api/3d/studio`+([api/3d/studio.js](../api/3d/studio.js)), the REST contract behind the+[three.ws 3D Studio custom GPT](./chatgpt-3d-studio-gpt.md). Fast generations+return `status: "done"` with the model URLs directly and never need a watch+page. When a job cannot finish inside the request window, the response is+`status: "pending"` and carries three handles:++- `job`: the job token (a signed handle or a bare prediction id),+- `poll`: the API path to poll (`/api/3d/studio?job=<id>`),+- `watchUrl`: `https://three.ws/watch?job=<id>&title=<prompt>`.++The GPT hands `watchUrl` to the user; every subsequent pending poll response+repeats it. The optional `title` parameter is the prompt: the page puts it in+the header and the tab title, and carries it through to the viewer so the+finished model opens labeled.++You can build the same link by hand for any valid job token. A missing or+malformed `job` parameter (the page enforces the same handle shape the API+does) lands on the designed empty state, which points to+[three.ws/forge](https://three.ws/forge) instead of erroring.++## What the page shows++The page polls `GET /api/3d/studio?job=<id>` and moves through four states:++- **Waiting.** A countdown ring with the estimated time remaining, updated+ locally at 4 Hz between polls so the timer never freezes. Until the API+ reports a first `etaSeconds` estimate, the ring spins in indeterminate mode+ and the label shows elapsed time ("warming up"); once an estimate arrives the+ ring fills toward completion. The phase line reflects the pipeline's real+ two-step flow: "Painting the concept" while the reference image is being+ generated, then "Sculpting the 3D mesh" once it exists, with the quality tier+ (draft, standard, high) named when known.+- **Concept art.** As soon as the poll response carries `previewImageUrl` (the+ painted reference image, the first step of the text-to-3D pipeline), it fades+ in with the caption "Concept art, now being sculpted into 3D". This is the+ same paint-then-reconstruct flow described in+ [How the Forge works](./how-forge-works.md).+- **Ready.** When the poll returns `status: "done"`, the page shows "opening+ the viewer" and redirects itself into the interactive viewer after a short+ beat, using the API's `viewerUrl` (or building a `/viewer?src=<glb>` link+ from `glbUrl`). A manual link is rendered in case the redirect is blocked.+- **Error.** An upstream failure (`status: "error"`), a stale or malformed+ link (HTTP 400), or a job that produces no viewer link shows an honest error+ with a one-click "Forge it again" path. Generation is free, so retrying+ costs nothing.++Polling is adaptive: the interval scales with the remaining estimate (clamped+between 4 and 10 seconds), a 429 respects the server's `retry_after`, and a+network blip just retries after 6 seconds. If nothing has finished after 40+minutes the page stops itself and says so, rather than spinning forever in a+forgotten tab.++## Relation to background generation++The watch page is a viewport, not the tracker. All job state lives+server-side: the platform tracks every generation to completion whether or not+any tab is watching, finished models land in the creator's gallery, and+unattended completions notify through the bell, push, and email channels. That+machinery is documented in+[Background generation and completion notifications](./forge-background-generation.md).+Closing the watch tab mid-job therefore loses nothing; reopening the same+`?job=` link resumes exactly where the generation actually is.++## Related++- [How the Forge works](./how-forge-works.md): the pipeline behind the+ countdown.+- [Background generation](./forge-background-generation.md): server-side+ tracking, resume, and notifications.+- [The 3D Studio GPT](./chatgpt-3d-studio-gpt.md): the main surface that hands+ out watch links.+- [API reference](./api-reference.md): the full `/api/3d/studio` contract.diff --git a/docs/kol-tracker.md b/docs/kol-tracker.mdnew file mode 100644index 000000000..f7f7a7f33--- /dev/null+++ b/docs/kol-tracker.md@@ -0,0 +1,145 @@+# KOL Tracker: influencers ranked by what their wallets actually did++The KOL Tracker ranks Solana KOLs by realized P&L computed from their own wallets' on-chain trade history. Not screenshots, not self-reported win streaks: the board reads real trades, runs a FIFO cost-basis computation over them, and sorts by the realized USD result. Alongside P&L it shows win rate, traded volume, trade count, and, for the handles an admin has verified actually control the wallet, the X follower count. A big following with a losing wallet is exactly the kind of gap this page exists to expose.++Page: [/tracker](https://three.ws/tracker)++API: `/api/kol/tracker` (the board), with sibling reads `/api/kol/leaderboard`, `/api/kol/trades`, and `/api/kol/wallets` from the same dispatcher.++## Why it exists++Influence and skill are different assets, and only one of them is priced into a follow button. A wallet address cannot exaggerate: every entry and exit is public, timestamped, and attributable. The tracker joins the two records, social reach and on-chain results, into one table so you can see at a glance whose calls are backed by their own money winning. Follower counts are shown only where the wallet-to-handle link has been explicitly verified, and every P&L figure names its source, so the page never renders a number whose provenance it cannot state.++## What the page shows++`pages/tracker.html` is a self-contained module that fetches `/api/kol/tracker?window=<w>&limit=100` and renders one row per wallet:++- **Rank**, with medals for the top three.+- **KOL identity**: avatar, `@handle` (linked to X) when a verified handle is attached, otherwise the curated label, otherwise the shortened wallet address. The wallet address always renders under the name.+- **PnL** for the selected window, green or red. When the figure did not come from our own on-chain computation, a small source tag (for example `(kolscan)`) renders next to it.+- **Followers**, only for verified handles; a wallet with no attached handle shows a blank, never a fabricated count.+- **Volume**, **Win Rate**, and **Trades** for the window.++A segmented control switches the window between 24H, 7D, and 30D (arrow keys work on it), and the column headers relabel to match. Loading renders skeleton rows; an empty tracked list renders a designed empty state; a failed fetch renders an error state. The board never falls back to placeholder rows.++## How ranking works (as coded)++The aggregator is `src/kol/tracker.js` (`getKolTracker`). Per request it:++1. **Builds the wallet universe** by merging two sources. The live universe is the kolscan.io leaderboard for the requested window (`src/kol/leaderboard.js` over `src/kol/kolscan-live.js`: one HTML GET yields all three window boards, priced SOL to USD from the live feed, cached 120 seconds). The curated universe is the admin-maintained list from `src/kol/wallet-store.js` (a bundled `wallets.json` that ships empty by design, merged with R2 imports written by the admin-only import endpoint). Live rows carry numbers; curated records carry identity (label, verified `xHandle`). The merge is by address, so a curated wallet that also ranks live gets both.+2. **Computes on-chain P&L per wallet** with `src/kol/wallet-pnl.js`: real trades for the wallet are fetched server-side, filtered to the window, sorted by time, and run through a FIFO cost-basis engine. Realized P&L is sell proceeds minus FIFO-consumed cost. Win rate is winning closed sells over all closed sells. Volume is the USD value of every trade leg in the window. No synthetic numbers enter this path.+3. **Applies a strict P&L precedence per wallet**, recorded in `pnlSource`: our own FIFO computation wins whenever we have trades for the wallet (`onchain`); otherwise the live kolscan figure for that window (`kolscan`); otherwise whatever the curated record carries (`imported`); otherwise `null`.+4. **Attaches the X profile** (`src/kol/x-profile.js`) only for wallets with an admin-attached handle: follower count, avatar, and verified flag from the real X API, cached 15 minutes per handle. Handles are never inferred or scraped; the only way one enters the list is an admin attaching it at import time after verifying the KOL controls the wallet (a signed message, a public self-disclosure).+5. **Sorts by `pnlUsd` descending, nulls last**, and caps the result at the requested limit (max 100).++If every source is unreachable the tracker returns an empty array and the page shows its empty state. A cron (`api/cron/kol-tracker-refresh.js`, every 10 minutes, Bearer-authenticated with `CRON_SECRET`) prewarms all three windows so the tight X API budget (75 lookups per 15 minutes on the free tier) is never spent inside a visitor's request.++## Where the data comes from++- **On-chain trades, not self-reported numbers.** The `onchain` P&L path computes from the wallet's own trade history; the `kolscan` fallback is itself a board of realized on-chain SOL profit. Nothing on this page is entered by the KOL.+- **kolscan.io** supplies the live wallet universe and the fallback P&L per window. Trader names it publishes are deliberately dropped; the schema stays address-keyed.+- **Helius** enhanced transactions back the per-mint trade feed (`/api/kol/trades`).+- **Birdeye** backs the portfolio proxy (`/api/kol/wallets`).+- **The X API** supplies follower counts and avatars, only for admin-verified handles.++Each integration degrades honestly: a missing key or an upstream outage yields an empty or null field (and, for `/api/kol/trades`, an explicit error when the whole provider is down), never a fabricated or zeroed row that looks like real data.++## API++All reads are public, CORS-open, and IP rate-limited (600 requests per minute per IP; over that returns 429). The dispatcher is `api/kol/[action].js`.++### `GET /api/kol/tracker`++The board behind the page.++| Param | Values | Default |+|---|---|---|+| `window` | `24h`, `7d`, `30d` | `7d` |+| `limit` | 1 to 100 | 100 |++```bash+curl 'https://three.ws/api/kol/tracker?window=7d&limit=25'+```++Response: `{ window, rows }`, sorted by `pnlUsd` descending, nulls last. Each row:++```json+{+ "wallet": "<WALLET_ADDRESS>",+ "label": "curated label or null",+ "xHandle": "verified handle or null",+ "avatarUrl": "X avatar URL or null",+ "verified": false,+ "followerCount": null,+ "pnlUsd": 12345.67,+ "volumeUsd": 98765.43,+ "winRate": 0.62,+ "trades": 41,+ "pnlSource": "onchain",+ "window": "7d"+}+```++`winRate` is a fraction (0 to 1); the page renders it as a percent. `volumeUsd` and `trades` are only populated on the `onchain` path (volume) or on `onchain`/`kolscan` (trades). `pnlSource` is one of `onchain`, `kolscan`, `imported`, or `null`. An invalid `window` returns `400 validation_error`.++### `GET /api/kol/leaderboard`++The raw live board (no curation, no X profiles): address-keyed rows straight from the kolscan-backed source.++```bash+curl 'https://three.ws/api/kol/leaderboard?window=24h&limit=10'+```++Response: `{ items: [{ wallet, pnlSol, pnlUsd, winRate, trades, rank }] }`. Empty when the live source is unreachable, never stale or fabricated.++### `GET /api/kol/trades`++Recent pump.fun buys and sells by the tracked wallets for one mint, via Helius, cached for a few seconds.++```bash+curl 'https://three.ws/api/kol/trades?mint=<MINT_ADDRESS>&limit=20'+```++Response: `{ mint, trades, wallets }` where each trade carries `wallet`, `side`, `amountSol`, `amountToken`, `price`, `signature`, `ts`, `time`, `usd`, `source` (`kol`, `whale`, or `smart-money` from the wallet's tags), and `label`. The `x-kol-source` response header is `helius` when the provider is configured; with no provider key the feed returns an empty list and `x-kol-source: unconfigured`, which is distinct from a configured provider outage (a `502 provider_unavailable` error).++### `GET /api/kol/wallets`++Portfolio snapshot proxy (Birdeye) for up to 20 addresses at once, cached 60 seconds per address. Requires `BIRDEYE_API_KEY` server-side; without it the endpoint returns `503 birdeye_not_configured`.++```bash+curl 'https://three.ws/api/kol/wallets?addresses=<WALLET_ADDRESS>,<WALLET_ADDRESS_2>'+```++Response: `{ data: [{ address, realizedPnl, unrealizedPnl, winRate, totalTrades, topToken }] }`. A wallet whose upstream fetch failed is omitted from `data` rather than rendered as a fake zero-P&L row.++### `POST /api/kol/import-gmgn` (admin only)++Writes the curated tracked-wallet list that the tracker merges in. Accepts `{ rawJson, xHandles }` where `xHandles` is the optional wallet-to-handle map described above: the only path by which a follower count ever attaches to a wallet. Imports persist to R2 and merge with (never blindly replace) the existing list, preserving previously attached handles.++## How it connects to wallet reputation++The tracker answers "who is making money"; the reputation surfaces answer "should this wallet's record earn trust". They meet at the wallet address:++- **`GET /api/intel/wallet/<WALLET_ADDRESS>`** returns one wallet's realized track record from the Smart-Money graph: a 0 to 100 realized score, win rate, average ATH multiple, winners and losers, labels (`smart_money`, `sybil`, `fresh`, and others), and its funder cluster. `computed: false` means no track record exists yet for that address; that is an honest zero, not an error. Any wallet you see on the tracker can be fed straight into it.+- **[Smart Money Radar](./smart-money.md)** is the sibling leaderboard built from graduation outcomes rather than a KOL universe: reputation earned per wallet from which coins actually graduated. The tracker's footer links to it, and the two boards frequently disagree in instructive ways.+- **[Trust primitives](./trust-primitives.md)** wrap the same question for autonomous agents: a paid endpoint that scores any counterparty wallet from real on-chain evidence before an agent transacts with it.++```bash+# Take a wallet from the tracker and pull its reputation record+curl 'https://three.ws/api/intel/wallet/<WALLET_ADDRESS>?network=mainnet'+```++## States and limits++- **Auth.** All tracker reads are public. The import endpoint is admin-only; the refresh cron is Bearer-authenticated with `CRON_SECRET`.+- **Rate limit.** 600 requests per minute per IP on every public read.+- **Windows.** Exactly `24h`, `7d`, `30d`. Anything else is a 400.+- **Follower counts are opt-in by verification.** A wallet with no admin-attached handle ranks normally and simply shows no follower data. Nothing on this page guesses at identity.+- **Provenance is always visible.** Every P&L figure carries `pnlSource`, and the page tags any figure that did not come from our own on-chain computation.+- **Honest degradation everywhere.** Upstream outages produce empty boards, omitted wallets, or explicit errors, never placeholder rows, stale boards presented as fresh, or zeros dressed up as data.++## Related++- [Smart Money Radar](./smart-money.md): reputation earned from graduation outcomes, wallet by wallet+- [Trust primitives](./trust-primitives.md): the paid cross-chain reputation read for autonomous agents+- Pages: [/tracker](https://three.ws/tracker) · [/smart-money](https://three.ws/smart-money) · [/leaderboard](https://three.ws/leaderboard)diff --git a/docs/media-api.md b/docs/media-api.mdnew file mode 100644index 000000000..c3bd0db65--- /dev/null+++ b/docs/media-api.md@@ -0,0 +1,788 @@+# three.ws Media & Render API++Free media endpoints for agents and apps built around three.ws 3D assets:+server-side avatar rendering, runtime GLB optimization, a CORS-open model+proxy, image understanding, speech-to-text, the curated asset libraries, and+the photo-input and mesh-processing front doors. Most endpoints here are+public and keyless; the two that write to an account say so explicitly.++This page is the companion to the [3D API](./3d-api.md), which documents the+core free text-to-3D lane (`/api/3d/generate`), model inspection, and the paid+Forge Pro tiers. Nothing on that page is repeated here: generate a model+there, then render it, optimize it, proxy it, describe it, or save it with the+endpoints below.++Base URL: `https://three.ws`++| Endpoint | Method | Auth | What it does |+|----------|--------|------|--------------|+| [`/api/avatar/render`](#render-an-avatar-as-an-image) | GET | none | Rendered PNG/JPEG/WebP of any public avatar |+| [`/api/render/avatar-clip`](#render-any-glb-posed-and-camera-orbited) | GET, POST | none | Posed, camera-orbited PNG of any GLB |+| [`/api/avatar/optimize`](#optimize-a-glb-at-runtime) | GET | none | Runtime GLB transcoder (LOD, textures, morphs, Draco) |+| [`/api/glb`](#same-origin-glb-proxy) | GET | none | Same-origin GLB proxy with open CORS |+| [`/api/vision`](#image-understanding) | GET, POST | none | Ask a vision model about an image |+| [`/api/asr`](#speech-to-text) | GET, POST | none | Speech-to-text (voice in) |+| [`/api/avatars/library`](#character-library) | GET | none | Paginated manifest of rigged characters |+| [`/api/objects/library`](#object-library) | GET | none | Paginated manifest of CC0 props |+| [`/api/avatars/from-forge`](#save-a-generated-glb-into-your-library) | POST | session or bearer | Save a generated GLB as your avatar |+| [`/api/input-photo`](#photo-to-avatar) | POST | none | Vision-validated photo-to-avatar submission |+| [`/api/input-multiview`](#multi-view-reconstruction) | POST | none | Vision-validated multi-image reconstruction |+| [`/api/forge-segment`](#split-a-glb-into-named-parts) | GET, POST | none | Split a GLB into named parts (async job) |+| [`/api/forge-rembg`](#background-removal) | GET, POST | none | Image background removal (async job) |++---++## Render an avatar as an image++**`GET /api/avatar/render`** returns a rendered PNG, JPEG, or WebP of any+public or unlisted three.ws avatar. Built for `<img>` tags, social cards,+partner integrations, and game engine loaders: point an image tag at the URL+and it just works.++Calling it with **no parameters** returns a self-describing JSON document:+every parameter, the scene presets, and the full pose catalog. That response+is the machine-readable source of truth for this endpoint.++### Query parameters++| Param | Type | Default | Notes |+|-------|------|---------|-------|+| `avatar` | uuid | required | Avatar ID. Omit it to get the self-describing JSON instead. |+| `scene` | enum | `upper-body` | Camera framing: `full-body`, `upper-body`, `portrait`, `headshot`. |+| `size` | integer | `512` | Square dimension in pixels, 64 to 2048. |+| `width` | integer | | Overrides `size` for width (64 to 2048). |+| `height` | integer | | Overrides `size` for height (64 to 2048). |+| `bg` | string | `transparent` | CSS color or `transparent`. |+| `pose` | string | | Pose preset ID. Catalog: `GET /api/render/avatar-clip`. |+| `expression` | json | | URL-encoded ARKit-52 morph map, e.g. `{"mouthSmile":0.6}`. |+| `format` | enum | `png` | `png`, `jpeg`, or `webp`. |+| `quality` | integer | `90` | 1 to 100, for `jpeg`/`webp`. |++### Response++The first request for a given parameter combination renders via headless+chromium + three.js and returns the image bytes directly+(`x-render-cache: miss`, plus `x-render-scene` and `x-render-size` headers).+The result is cached in object storage keyed on avatar ID, the parameter hash,+and the avatar's `updated_at`, so editing the avatar busts the cache+automatically. Subsequent requests answer `302` to the CDN copy+(`x-render-cache: hit`). Both outcomes are correct behind an `<img src>`.++### Errors++| Situation | Response |+|-----------|----------|+| Invalid parameter | `400` with a specific code |+| Avatar does not exist | `404 not_found` |+| Avatar is private | `403 private` (only public or unlisted avatars render) |+| Over 120 renders per 10 minutes per IP | `429` with `Retry-After` |+| Render pipeline failed | `502 render_failed` |++### curl++```bash+# Discover the parameters, scenes, and pose catalog+curl -s https://three.ws/api/avatar/render++# Render a 256px transparent portrait+curl -sL -o portrait.png \+ 'https://three.ws/api/avatar/render?avatar=YOUR_AVATAR_ID&scene=portrait&size=256&bg=transparent'++# Waving, smiling, as WebP+curl -sL -o card.webp \+ 'https://three.ws/api/avatar/render?avatar=YOUR_AVATAR_ID&pose=wave&expression=%7B%22mouthSmile%22%3A0.6%7D&format=webp'+```++---++## Render any GLB, posed and camera-orbited++**`POST /api/render/avatar-clip`** renders a PNG of any public GLB with an+optional pose preset, a free camera orbit, and ARKit-52 facial morphs. Where+`/api/avatar/render` takes a three.ws avatar ID, this endpoint takes a raw GLB+URL, so it works on models that were never saved as avatars.++**`GET /api/render/avatar-clip`** (no body) returns the pose catalog: every+preset's `id`, `label`, and `group` (examples: `tpose`, `apose`, `wave`,+`salute`, `run`, `sit-chair`, `thinker`, `superhero-landing`), plus the+`cameraOrbit` and `background` value ranges. Fetch it once instead of+hardcoding pose IDs.++### Request body (JSON)++| Field | Type | Default | Notes |+|-------|------|---------|-------|+| `glbUrl` | string | required | Public http(s) URL of the GLB, max 10 MB. SSRF-guarded: private hosts are rejected. |+| `width` | integer | `1024` | 64 to 2048. |+| `height` | integer | `1024` | 64 to 2048. |+| `background` | string | `#0a0a0a` | Any CSS color, or `transparent`. |+| `posePresetId` | string | | A pose ID from the GET catalog. Unknown IDs return `400 unknown_pose`. |+| `cameraOrbit` | object | | `{ theta, phi, radius }`. `theta` 0..360 degrees (yaw), `phi` 0..180 degrees (pitch from top, default 80), `radius` in meters or `null` to auto-frame. |+| `expression` | object | | ARKit-52 morph map, e.g. `{ "jawOpen": 0.4, "mouthSmileLeft": 0.6 }`. |++### Response++`200` with `image/png` bytes. Headers report what was rendered:+`x-render-width`, `x-render-height`, `x-render-background`, and, when a pose+was applied, `x-render-pose` and `x-render-pose-label`.++### Errors++| Situation | Response |+|-----------|----------|+| Missing/non-public `glbUrl` | `400 bad_request` |+| Unknown pose preset | `400 unknown_pose` (GET the endpoint for the catalog) |+| Over 60 renders per 10 minutes per IP | `429` with `Retry-After` |+| Fetch or render failed | `502 render_failed` |++### curl++```bash+# Pose catalog+curl -s https://three.ws/api/render/avatar-clip++# Render a rigged model waving, orbited 30 degrees, on transparent+curl -s -X POST https://three.ws/api/render/avatar-clip \+ -H 'content-type: application/json' \+ -d '{+ "glbUrl": "https://three.ws/avatars/cesium-man.glb",+ "posePresetId": "wave",+ "cameraOrbit": { "theta": 30, "phi": 80, "radius": null },+ "background": "transparent"+ }' -o wave.png+```++---++## Optimize a GLB at runtime++**`GET /api/avatar/optimize`** returns a re-encoded variant of a+three.ws-hosted GLB tuned for the caller's hardware budget. The pipeline is+lossless or near-lossless (dedup, prune, weld, texture downscale to WebP), so+one source GLB can serve mobile WebGL, desktop WebGL, and VR runtimes without+per-platform asset duplication.++### Query parameters++Provide exactly one of `src` or `id`; the rest are optional.++| Param | Type | Default | Notes |+|-------|------|---------|-------|+| `src` | url | | Source GLB. Must be on a three.ws-controlled origin (the app origin or the CDN host); anything else is `400 untrusted_source`. |+| `id` | uuid | | A three.ws avatar ID. Only public or unlisted avatars resolve; private ones return `404`. |+| `lod` | enum | `0` | `0` = source, `1` = conservative weld/dedup, `2` = more aggressive weld. |+| `textureSize` | enum | `2048` | Max texture edge: `128`, `256`, `512`, `1024`, or `2048`. Larger textures are downscaled and re-encoded as WebP. |+| `morphs` | enum | `all` | `arkit52` drops every morph target not in the ARKit-52 standard set (plus canonical aliases and visemes); `all` keeps everything. |+| `draco` | flag | off | `draco=1` applies `KHR_draco_mesh_compression`. Smaller bytes, but the client needs a Draco decoder. |++### Response++`200` with `model/gltf-binary` bytes, cached immutably (30 days in the+browser, 1 year at the edge, keyed on the full URL). Headers+`x-three-ws-source-bytes` and `x-three-ws-output-bytes` report the size delta.++### Errors++| Situation | Response |+|-----------|----------|+| Missing `src` and `id`, or invalid `lod`/`textureSize`/`morphs` | `400 invalid_request` |+| `src` not on a three.ws origin | `400 untrusted_source` |+| Avatar/upstream not found | `404 source_not_found` |+| Source over 50 MB | `413 too_large` |+| Upstream fetch failed | `502 upstream_unreachable` |+| Transcode pipeline threw | `500 transcode_failed` |++Requests are rate-limited per IP; a `429` carries `Retry-After`.++### curl++```bash+# Mobile budget: 512px textures, ARKit-52 morphs only, Draco-compressed+curl -sL -o mobile.glb \+ 'https://three.ws/api/avatar/optimize?id=YOUR_AVATAR_ID&textureSize=512&morphs=arkit52&draco=1'++# By source URL, LOD 1+curl -sL -o lite.glb \+ 'https://three.ws/api/avatar/optimize?src=https%3A%2F%2Fthree.ws%2Favatars%2Fcesium-man.glb&lod=1'+```++---++## Same-origin GLB proxy++**`GET /api/glb?src=<url>`** streams any public GLB back with+`access-control-allow-origin: *`. Generated models live on a CDN whose CORS+policy is an origin allowlist, so a `<model-viewer>` embed on a partner site,+a Jupyter/Colab notebook, or a localhost preview cannot fetch them directly.+Routing the bytes through this proxy makes the read work from any origin.+Safe by construction: upstream objects are already public and keyless, and+the fetch runs through the SSRF-hardened fetcher (scheme allowlist, DNS+pinning, private-IP blocklist, redirect re-validation, byte cap, timeout).++### Query parameters++| Param | Type | Notes |+|-------|------|-------|+| `src` | url | Required. Public http(s) URL of a `.glb`. `url=` is accepted as an alias. |++### Response++`200` with `model/gltf-binary` bytes, cached immutably (generated GLBs are+content-addressed, so a given `src` never changes bytes). Max 30 MB, 20 s+upstream timeout, rate-limited per IP.++### Errors++| Situation | Response |+|-----------|----------|+| Missing or non-http(s) `src` | `400 bad_request` |+| Blocked target (`invalid_url`, `scheme_not_allowed`, `private_address`, `host_pin_mismatch`) | `400` with that code |+| Upstream over 30 MB | `413 file_too_large` |+| Upstream fetch failed | `502 fetch_failed` |++### curl++```bash+curl -sL -o model.glb \+ 'https://three.ws/api/glb?src=https%3A%2F%2Fthree.ws%2Favatars%2Fcesium-man.glb'+```++---++## Image understanding++**`POST /api/vision`** asks a vision model a question about an image and+returns plain text. The same capability powers Forge upload checks and+gallery alt text internally; this is the public HTTP surface. Free-first+provider chain with a paid backstop; the response tells you which provider+answered.++**`GET /api/vision`** is a capability probe:+`{ configured, imageTypes }`. Use it to decide whether to offer+describe/critique affordances before uploading anything.++### Request++Two transports:++| Transport | How |+|-----------|-----|+| Raw bytes | Body is the image; `Content-Type` must be `image/jpeg`, `image/png`, `image/webp`, or `image/gif`. Max 12 MB. |+| JSON | `{ "image": "<base64 or data URI>", "imageUrl": "...", "prompt": "...", "maxTokens": 512, "imageType": "image/png" }`. Provide `image` or `imageUrl` (a public https URL; SSRF-guarded). `imageType` labels a bare base64 `image` when it is not a data URI. |++`prompt` and `maxTokens` can also ride as query parameters on either+transport. `prompt` defaults to a concise two-sentence description and is+capped at 2000 characters; `maxTokens` is clamped to 16..2048 (default 512).++Rate limits are per user when signed in (session cookie or bearer token) and+per IP otherwise; signing in raises the budget.++### Response++```json+{ "text": "A low-poly bronze knight in a T-pose, brushed-metal armor...", "provider": "nvidia", "model": "..." }+```++### Errors++| Situation | Response |+|-----------|----------|+| No image in the request | `400 bad_request` |+| Unsupported raw `Content-Type` | `415 unsupported_media_type` |+| Image over 12 MB | `413 payload_too_large` |+| Bad `imageUrl` | `400 invalid_image_url` |+| No vision provider configured | `503 not_configured` |+| All providers failed | `502` with the upstream code |++### curl++```bash+# Capability probe+curl -s https://three.ws/api/vision++# Raw bytes with a custom question+curl -s -X POST 'https://three.ws/api/vision?prompt=What%20object%20is%20this%3F' \+ -H 'content-type: image/png' \+ --data-binary @render.png++# By URL+curl -s -X POST https://three.ws/api/vision \+ -H 'content-type: application/json' \+ -d '{"imageUrl":"https://three.ws/logo.png","prompt":"Describe this image in one sentence."}'+```++---++## Speech-to-text++**`POST /api/asr`** transcribes a spoken utterance. It is the voice-in+companion to `POST /api/tts/speak` (voice out), and exists so users can talk+to an avatar with a real cross-browser recognizer instead of the Chrome-only+`webkitSpeechRecognition`. The lane is NVIDIA Riva ASR; there is deliberately+no paid backstop, so when it is unconfigured clients keep their browser+fallback.++**`GET /api/asr`** is a capability probe:+`{ configured, encodings, sampleRate }`. `sampleRate` is `16000`, the Riva+acoustic-model rate clients should downsample to.++### Request++Two transports, max 8 MB of audio either way:++| Transport | How |+|-----------|-----|+| Raw bytes | Body is the audio; `Content-Type` picks the codec: `audio/wav` (header parsed, rate taken from the file), `audio/pcm` or `audio/L16` (raw 16-bit LE PCM; set `?rate=`), `audio/flac`, `audio/ogg` (Opus). WebM/Opus is rejected with `415`: decode it to PCM/WAV client-side first. |+| JSON | `{ "audio": "<base64>", "format": "wav", "language": "en-US", "sampleRate": 16000, "words": true, "model": "..." }`. `format` is one of `wav`, `pcm`, `flac`, `ogg` (default `wav`). |++Query parameters work on either transport: `language` (BCP-47, default+`en-US`), `rate` (PCM sample rate; defaults to 16000 when the audio does not+declare one), `words=1` (word-level timestamps), `model` (override the Riva+model name).++Rate limits mirror `/api/vision`: per user when signed in, per IP otherwise.++### Response++```json+{ "text": "make the avatar wave", "confidence": 0.94, "language": "en-US", "model": "...", "durationSec": 1.8 }+```++With `words=1` the response adds a `words` array of word-level timestamps.++### Errors++| Situation | Response |+|-----------|----------|+| Unsupported audio `Content-Type` (including WebM) | `415 unsupported_media_type` |+| Audio over 8 MB | `413 payload_too_large` |+| No audio bytes | `400 bad_request` |+| Riva rejected the input | `400 invalid_argument` |+| Lane not configured | `503 not_configured` |+| Upstream failure | `502 provider_error` |++### curl++```bash+# Capability probe+curl -s https://three.ws/api/asr++# Transcribe a WAV with word timestamps+curl -s -X POST 'https://three.ws/api/asr?words=1' \+ -H 'content-type: audio/wav' \+ --data-binary @speech.wav+```++---++## Character library++**`GET /api/avatars/library`** returns the curated rigged character library:+professionally rigged humanoid GLBs (Y Bot, X Bot, Warrok, Remy, zombies,+knights, plus CC0 sets like Quaternius and KayKit). Every GLB carries a+skeleton, skin weights, and textures, so it drops straight into the pose+studio, widget studio, or embed viewer and drives the whole canonical+animation clip library via retargeting. No auth, no key.++The GLBs live on the CDN; this endpoint serves a small manifest whose entries+carry absolute CDN URLs the browser loads directly (CDN CORS allows GET from+web origins).++### Query parameters++Pagination is opt-in and backward compatible:++| Param | Type | Notes |+|-------|------|-------|+| `limit` | integer | 1 to 1000. Omit it entirely to get the whole library in one response. |+| `offset` | integer | Starting index, default 0. Only meaningful with `limit`. |++### Response++```json+{+ "avatars": [+ {+ "name": "y-bot",+ "label": "Y Bot",+ "url": "https://<cdn>/avatars/mixamo/glb/y-bot.glb",+ "thumb": "https://<cdn>/avatars/mixamo/thumbs/y-bot.png",+ "bytes": 3145728,+ "skins": 1,+ "animations": 1,+ "source": "mixamo",+ "license": "Mixamo"+ }+ ],+ "total": 106,+ "generated_at": "2026-07-01T00:00:00.000Z"+}+```++`thumb` is present when a thumbnail has been rendered. With `limit` the+response adds `offset` and `next_offset` (`null` on the last page); `total`+is always the full library size. Before the manifest is staged the endpoint+returns `{ "avatars": [], "total": 0 }`, so feature-detect by emptiness, not+by error handling. Responses are edge-cached for 5 minutes.++### curl++```bash+# Whole library+curl -s https://three.ws/api/avatars/library++# Page of 24+curl -s 'https://three.ws/api/avatars/library?limit=24&offset=0'+```++---++## Object library++**`GET /api/objects/library`** is the same manifest pattern for the CC0 3D+prop library: free, commercial-OK objects (Poly Haven and other CC0 sources)+staged as web-ready GLBs. Identical pagination (`?limit=1..1000`,+`?offset=`), identical empty-until-staged behavior, no auth.++### Response++```json+{+ "objects": [+ {+ "name": "wooden-crate",+ "label": "Wooden Crate",+ "url": "https://<cdn>/objects/polyhaven/glb/wooden-crate.glb",+ "thumb": "https://<cdn>/objects/polyhaven/thumbs/wooden-crate.png",+ "bytes": 1048576,+ "categories": ["props"],+ "tags": ["wood", "container"],+ "license": "CC0",+ "source": "polyhaven"+ }+ ],+ "total": 0,+ "generated_at": "2026-07-01T00:00:00.000Z"+}+```++With `limit`, the response adds `offset` and `next_offset` exactly like the+character library.++### curl++```bash+curl -s 'https://three.ws/api/objects/library?limit=12'+```++---++## Save a generated GLB into your library++**`POST /api/avatars/from-forge`** saves a generated GLB (by URL) straight+into the caller's avatar library, server-side. This is the durable end of the+text-to-3D-avatar pipeline: forge a mesh (see the [3D API](./3d-api.md)), rig+it, then hand the final URL here. Doing the copy server-side sidesteps+cross-origin reads of provider URLs and browser upload caps, and routes+through the same avatar-creation path as a normal upload, so the result is a+first-class avatar with its own agent.++**Auth required**: a signed-in session cookie, or a bearer token carrying the+`avatars:write` scope. Everything else on this page is public; this endpoint+writes to your account.++### Request body (JSON)++| Field | Type | Default | Notes |+|-------|------|---------|-------|+| `glb_url` | string | required | Public https URL of the GLB. SSRF-guarded; max 64 MB. |+| `name` | string | required | Avatar name, 1 to 80 characters. |+| `visibility` | enum | `unlisted` | `public`, `unlisted`, or `private`. |+| `source_prompt` | string | | The prompt that generated it, kept as provenance (max 1000 chars). |+| `rigged` | boolean | | Provenance only. The server inspects the GLB itself for the real rig state; this flag never decides anything. |+| `tags` | string[] | | Up to 20 organizing tags. |++The server fetches the GLB, validates the binary glTF header, copies it into+your storage namespace, registers the avatar, provisions its agent, and, when+the mesh arrived static, queues an auto-rig so the avatar can animate.++### Response++`201` with `{ "avatar": { ... }, "view_url": "https://three.ws/discover/avatar/<id>" }`.++### Errors++| Situation | Response |+|-----------|----------|+| Not signed in / missing scope | `401 unauthorized` |+| Missing `glb_url` or `name` | `400 invalid_request` |+| Non-public or non-https URL | `400 invalid_url` |+| URL did not return a valid GLB | `422 invalid_glb` |+| GLB over 64 MB | `413 payload_too_large` |+| Upstream fetch failed | `502 fetch_failed` |+| Too many saves | `429 rate_limited` with `Retry-After` |++### curl++```bash+curl -s -X POST https://three.ws/api/avatars/from-forge \+ -H 'authorization: Bearer YOUR_TOKEN' \+ -H 'content-type: application/json' \+ -d '{+ "glb_url": "https://three.ws/cdn/forge/anon/a1b2c3d4.glb",+ "name": "Bronze Knight",+ "visibility": "public",+ "source_prompt": "a bronze knight in ornate armor",+ "tags": ["knight", "fantasy"]+ }'+```++---++## Photo to avatar++**`POST /api/input-photo`** is the vision-validated front door for turning a+photo into an avatar. It checks that the image actually contains a face (so a+landscape or a text screenshot fails fast with guidance instead of burning a+generation slot), then submits it to the forge pipeline as an+image-conditioned generation with an avatar-optimized prompt, ready for+auto-rigging. No auth; rate-limited per IP on the generation bucket.++**Privacy is transient by default.** The source photo is never stored in the+creation log unless you set `privacy_opt_in: true`, and when you pass the+`storage_key` from `/api/forge-upload`, the uploaded object is deleted from+storage as soon as the generation job is created. No image bytes are written+to application logs.++### Request body (JSON)++| Field | Type | Default | Notes |+|-------|------|---------|-------|+| `image_url` | string | required | Public https URL of the photo, max 2048 characters. |+| `storage_key` | string | | The storage key returned by `/api/forge-upload`, enabling the transient delete. |+| `privacy_opt_in` | boolean | `false` | `true` keeps the photo as the creation's preview image. |+| `tier` | enum | `standard` | `draft`, `standard`, or `high`. |+| `skip_face_check` | boolean | `false` | Bypass the face-presence gate (for stylized or partial inputs). |++### Response++`200` with the forge job fields (`job_id`, `creation_id`, and the rest of the+standard `/api/forge` submission response) plus:++```json+{+ "mode": "photo_to_avatar",+ "auto_rig": true,+ "privacy_retained": false,+ "privacy_note": "Your photo was processed transiently and was not stored. ..."+}+```++Poll the job on `/api/forge?job=<job_id>` like any forge generation.++### Errors++| Situation | Response |+|-----------|----------|+| Missing/invalid `image_url` | `400 invalid_image_url` |+| No face detected | `422 face_not_detected`, with a `reason` and an `override` hint (`skip_face_check: true`) |+| Generation service unreachable | `502 generation_unreachable` |+| Forge rejected the submission | Forge's own status and error code, passed through |+| Rate limit | `429` with `Retry-After` |++When the vision lane is unconfigured or errors, the face check fails open and+the submission proceeds; forge still validates the image.++### curl++```bash+curl -s -X POST https://three.ws/api/input-photo \+ -H 'content-type: application/json' \+ -d '{"image_url":"https://example.com/selfie.jpg","tier":"standard"}'+```++---++## Multi-view reconstruction++**`POST /api/input-multiview`** accepts 2 to 6 photos of one object from+different angles, validates each with vision (clear subject? in focus? not a+text screenshot?), and submits them to the forge pipeline as a multi-view+reconstruction job. The validation step catches mismatched images and blank+uploads before a generation slot is spent. Same transient-by-default privacy+policy as `/api/input-photo`. No auth; rate-limited per IP.++### Request body (JSON)++| Field | Type | Default | Notes |+|-------|------|---------|-------|+| `image_urls` | string[] | required | 2 to 6 public https URLs, each max 2048 characters. Extras beyond 6 are dropped. |+| `storage_keys` | string[] | | Storage keys from `/api/forge-upload`, deleted after submission unless opted in. |+| `prompt` | string | | Optional guidance text, max 1000 characters. |+| `tier` | enum | `standard` | `draft`, `standard`, or `high`. |+| `privacy_opt_in` | boolean | `false` | `true` keeps the photos as preview images. |+| `skip_validation` | boolean | `false` | Bypass the per-image vision check. |++### Response++`200` with the forge job fields plus a per-image `validation` array,+`privacy_retained`, and `privacy_note`:++```json+{+ "job_id": "f1.eyJ...",+ "validation": [+ { "url": "https://example.com/front.jpg", "index": 0, "ok": true, "subject": "ceramic robot figurine" },+ { "url": "https://example.com/back.jpg", "index": 1, "ok": true, "subject": "ceramic robot figurine" }+ ],+ "privacy_retained": false,+ "privacy_note": "Your photos were processed transiently and were not stored. ..."+}+```++### Errors++| Situation | Response |+|-----------|----------|+| Fewer than 2 usable URLs | `400 too_few_images` |+| One or more images failed validation | `422 invalid_views`, with the full `validation` array (each failure carries an `issue` such as `no_subject`, `text_screenshot`, `too_dark_or_blurry`, or `abstract_or_diagram`, and an actionable `message`) plus an `override` hint (`skip_validation: true`) |+| Generation service unreachable | `502 generation_unreachable` |+| Rate limit | `429` with `Retry-After` |++### curl++```bash+curl -s -X POST https://three.ws/api/input-multiview \+ -H 'content-type: application/json' \+ -d '{+ "image_urls": [+ "https://example.com/owl-front.jpg",+ "https://example.com/owl-side.jpg",+ "https://example.com/owl-back.jpg"+ ],+ "tier": "high"+ }'+```++---++## Split a GLB into named parts++**`POST /api/forge-segment`** splits a 3D model into named, addressable parts+(an async job: submit, then poll). Useful for turning a monolithic generated+mesh into components you can recolor, swap, or animate independently. No+auth; rate-limited per IP.++### Request body (JSON)++| Field | Type | Default | Notes |+|-------|------|---------|-------|+| `mesh_url` | string | required | Public https URL of the GLB. SSRF-validated server-side. |+| `method` | enum | `auto` | `auto`, `connected` (connected components), or `crease` (split at hard edges). |+| `max_parts` | integer | `24` | 2 to 64. |+| `min_part_faces` | integer | `64` | 4 to 100000. Parts smaller than this are merged. |+| `crease_angle` | number | `40` | 5 to 170 degrees, for the `crease` method. |+| `only_part` | string | | Export just this part id or name (e.g. `part_03`). |++### Response++`202` with `{ "job_id": "...", "status": "queued", "method": "auto", "eta_seconds": 30 }`.++**`GET /api/forge-segment?job=<id>`** polls the job:++```json+{+ "job_id": "...",+ "status": "done",+ "result_url": "https://.../segmented.glb",+ "manifest_url": "https://.../parts.json",+ "parts": [ { "...": "one entry per part" } ],+ "part_count": 12,+ "source_faces": 48210,+ "method": "auto",+ "warnings": null,+ "error": null+}+```++Fields are `null` until the stage that produces them completes; on failure+`status` reflects it and `error` carries the reason.++### Errors++| Situation | Response |+|-----------|----------|+| Missing/non-public `mesh_url` | `400 invalid_mesh_url` |+| Malformed `?job=` | `400 invalid_job` (missing entirely: `400 missing_job`) |+| Worker not deployed on this environment | `503 unconfigured` |+| Worker rejected the job | `502 segment_failed` |+| Rate limit | `429` with `Retry-After` |++### curl++```bash+# Submit+curl -s -X POST https://three.ws/api/forge-segment \+ -H 'content-type: application/json' \+ -d '{"mesh_url":"https://three.ws/cdn/forge/anon/a1b2c3d4.glb","method":"auto","max_parts":16}'++# Poll+curl -s 'https://three.ws/api/forge-segment?job=JOB_ID'+```++---++## Background removal++**`POST /api/forge-rembg`** removes the background from an image (an async+job: submit, get `202`, poll). It exists for the forge pipeline (clean+subject cutouts reconstruct better), but it is a general-purpose endpoint. No+auth; rate-limited per IP.++### Request body (JSON)++| Field | Type | Default | Notes |+|-------|------|---------|-------|+| `image_url` | string | required | Public https URL of the image. SSRF-validated server-side. |+| `model` | enum | `rmbg2` | `rmbg2`, `u2net`, `isnet`, `u2net_human_seg`, or `silueta`. |++### Response++`202` with `{ "job_id": "...", "status": "queued", "eta_seconds": 10 }`.++**`GET /api/forge-rembg?job=<id>`** polls the job:++```json+{ "job_id": "...", "status": "done", "result_url": "https://.../cutout.png", "error": null }+```++### Errors++| Situation | Response |+|-----------|----------|+| Missing/non-public `image_url` | `400 invalid_image_url` |+| Malformed `?job=` | `400 invalid_job` (missing entirely: `400 missing_job`) |+| Worker not deployed on this environment | `503 unconfigured` |+| Worker rejected the job | `502 rembg_failed` |+| Rate limit | `429` with `Retry-After` |++### curl++```bash+# Submit+curl -s -X POST https://three.ws/api/forge-rembg \+ -H 'content-type: application/json' \+ -d '{"image_url":"https://example.com/product-shot.jpg","model":"rmbg2"}'++# Poll+curl -s 'https://three.ws/api/forge-rembg?job=JOB_ID'+```++---++## Related++- [3D API](./3d-api.md) - the core free text-to-3D lane, model inspection, and the paid Forge Pro tiers+- [Image to 3D](./image-to-3d.md) - the photo-input reconstruction product these front doors feed+- [Voice Lab](./voice-lab.md) - voice cloning and synthesis, the other half of the avatar voice loop+- [API Reference](./api-reference.md) - the full three.ws HTTP API surfacediff --git a/docs/minted.md b/docs/minted.mdnew file mode 100644index 000000000..533ae293f--- /dev/null+++ b/docs/minted.md@@ -0,0 +1,77 @@+# Minted 3D Assets: the public gallery of on-chain avatars++[three.ws/minted](https://three.ws/minted) is the live, public gallery of every generated or owned avatar that a creator chose to mint as a **Metaplex Core NFT** through three.ws. It is the NFT counterpart of the `/launches` coin directory: real on-chain property, listed the moment it mints. Every card renders the actual model in a live, auto-rotating 3D viewer (not a flat thumbnail), and every asset carries baked provenance and an enforced, capped creator royalty. Minting is always opt-in: the free text-to-3D lane never mints anything on its own.++This doc covers the gallery surface and the mint flow as a user-facing feature. The provenance internals live in their own docs: [content credentials for AI-generated models](provenance.md) (signed credentials, Solana anchoring, the free verify endpoint) and [the three.ws mint mark](mint-mark.md) (the `3ws` address branding on coin launches).++## The gallery++Open [/minted](https://three.ws/minted) with no account and no wallet. What you get:++- **A live 3D card per mint.** Each card is a `<model-viewer>` streaming the asset's GLB, slowly rotating, with the rendered thumbnail as its loading poster. Clicking the model opens it in the full interactive viewer.+- **Royalty chip.** The enforced on-chain creator royalty, as a percentage, on every card.+- **Remix badges.** An asset that names a `parent_mint` (a derivative of another creator's mint) is tagged `remix`; if the parent creator's royalty was actually paid out of the mint fee, the badge upgrades to `remix · royalty paid`.+- **Prompt line.** When the mint carries a generation prompt in its provenance, the card quotes it.+- **Mint link.** Every card links its mint address to Solscan (devnet assets link to the devnet cluster view).+- **Network toggle.** Mainnet is the default feed; a tab switches to devnet, where free test mints land.+- **Counters.** Assets on the page, average royalty, remixes with a paid-out royalty, and the selected network.+- **Continuous feed.** The grid paginates automatically as you scroll, and the top of the feed refreshes every 30 seconds while the tab is visible, so fresh mints appear without a reload.++An empty network shows an honest empty state pointing you at `/forge` to generate a model and at Agent Identity Studio to mint one. There are no synthetic entries.++### The feed API++The gallery reads a free, public, paginated endpoint that anyone (or any agent) can use:++```bash+curl "https://three.ws/api/v1/tokenized/launches?network=mainnet&offset=0&limit=24"+```++- Optional `agent_id=<uuid>` filters to one agent's mints.+- `limit` caps at 100; responses carry `has_more` for pagination.+- Rate-limited to 60 requests/min per IP, with a 15-second CDN cache so polling agents stay current without hammering the database.+- Like every `/api/v1` endpoint, the payload is wrapped in `{ "data": ... }` and the endpoint is discoverable via `GET /api/v1`.++## How a mint works++Minting runs through the `mint_3d_asset` tool on the [3D Studio MCP server](mcp.md). It is priced per call via x402 (USDC); an OAuth bearer token bypasses payment. A creator supplies:++- **The model:** an owned `avatar_id`, or any absolute `glb_url`.+- **The recipient:** an explicit `owner_wallet` (base58), or the OAuth-linked Solana wallet by default.+- **Royalty terms:** `seller_fee_basis_points`, hard-capped at 10% (1000 bps; a higher request is clamped and the response says so), and an optional `royalty_recipient` (defaults to the owner).+- **The network:** `devnet` by default for free testing; `mainnet` is explicit and is a real, disclosed on-chain write.+- **Optional lineage and provenance:** `parent_mint` (this is a remix), plus `prompt`, `generation_model`, and `generation_provider` overrides.++The server then:++1. **Claims an idempotency row before touching the chain.** Repeating a call for the same asset returns the same mint instead of minting twice; a failed attempt can be retried under the same key.+2. **Promotes the media to durable storage.** The GLB and a freshly rendered thumbnail are copied to a permanent first-party key (the NFT media never moves, even if the source avatar is later deleted), and pinned to IPFS when a pinning provider is configured (best-effort; a pin failure never fails the mint).+3. **Builds Metaplex-compliant metadata** with the GLB under `animation_url`, so wallets and marketplaces that render glTF show the live model, and everything else falls back to the rendered image.+4. **Mints the Core asset with an enforced Royalties plugin.** The recipient wallet owns the asset outright; the three.ws collection authority pays the rent and holds update authority (so the platform can curate on-chain metadata, but never move or take the asset).+5. **Records the launch** so the asset appears on `/minted` and in the feed API, with explorer and viewer links in the response.++### Baked provenance++Every mint carries its provenance twice:++- **In the NFT metadata itself:** creator, prompt, generation model and provider, parent lineage, and timestamp travel with the asset wherever it goes.+- **As a signed record on the platform's append-only agent-actions ledger** (when the source avatar has a provisioned agent to sign as): an independently verifiable entry, referenced in the mint response and queryable via the MCP action tools. This write is best-effort and never blocks a mint that already succeeded on-chain.++For how signed credentials, canonical hashing, and on-chain anchoring work under the hood, read [provenance.md](provenance.md). For the `3ws` address mark that brands coin launches, read [mint-mark.md](mint-mark.md).++### Remix royalties: paid the moment a remix mints++Naming another creator's mint as `parent_mint` makes your mint a remix, and that lineage is durable in both the metadata and the launch record. On mainnet, when a real per-call x402 fee was collected for the mint, the parent creator's royalty slice is routed out of that fee as a **real on-chain USDC transfer the moment the mint confirms**, and the settlement (amount, recipient, transaction) comes back in the mint response and shows on the gallery card.++Every non-paying outcome is reported with an honest reason rather than a fake "pending": devnet mints record lineage but settle nothing (the payout wallet holds real mainnet funds only), an OAuth-bypassed call collected no fee to split, a split can fall below the dust floor, or the parent may have no royalty wallet.++## Reading a mint back++The companion MCP tool `get_3d_asset_onchain` resolves any Core mint address to its live state: the current holder and enforced royalty terms read from the chain (authoritative over the platform record), the baked provenance, the GLB and viewer link with a liveness check, and, for assets minted through three.ws, the platform launch record and any remix settlement. It works on any Metaplex Core mint, not just ours.++## Related++- [Verifiable 3D provenance](provenance.md): signed content credentials and free verification for generated models+- [The three.ws mint mark](mint-mark.md): the `3ws` address brand on coin launches+- [MCP servers](mcp.md): the `mint_3d_asset` and `get_3d_asset_onchain` tools+- [Custody you can verify](custody.md): the wallet rails behind agent-held assetsdiff --git a/docs/notifications.md b/docs/notifications.mdnew file mode 100644index 000000000..b8abfb6fa--- /dev/null+++ b/docs/notifications.md@@ -0,0 +1,283 @@+# Notifications: the bell, the /notifications center, and the inbox API++Everything that happens to your work on three.ws (a payment lands, a skill+sells, someone remixes your model, follows you, a quest finishes, a royalty+arrives) becomes a row in one per-user inbox. Two surfaces read that inbox:+the bell in the site header, and the full notification center at+[/notifications](https://three.ws/notifications). This page documents both+surfaces as coded, the category system behind the filter tabs, and the+complete API contract. Where those notifications come from (which features+fire which events) is covered in [The social layer](./social-layer.md#notification-bell);+this page picks up where that one leaves off.++| Piece | Where | Source |+|---|---|---|+| Bell dropdown | The bell button in the header, on every page | [src/notifications.js](../src/notifications.js) |+| Notification center | [/notifications](https://three.ws/notifications) | [pages/notifications.html](../pages/notifications.html), [src/notifications-page.js](../src/notifications-page.js) |+| Preference editor | `/dashboard/settings` | [src/dashboard-next/pages/settings.js](../src/dashboard-next/pages/settings.js) |+| Inbox API | `GET/POST/DELETE /api/notifications/*` | [api/notifications/](../api/notifications/README.md) |++One inbox, two views. The dropdown holds the latest page for a quick glance;+the `/notifications` page adds category tabs, per-row delete, and cursor+pagination for the full history. Both import the same icon, label, link, and+escaping helpers from [src/notifications.js](../src/notifications.js), so a+notification always reads identically in both places.++---++## The notification record++Every row the API returns is++```+{ id, type, payload, read_at, created_at }+```++- `type` is a machine string like `skill_purchased`, `remix`, `follow`,+ `quest_complete`, or `royalty_paid`. The full producing vocabulary is+ `USER_EVENT_TYPES` in [api/_lib/feed.js](../api/_lib/feed.js) plus the types+ written directly by the purchase, forge, withdrawal, and security flows.+- `payload` carries the type-specific details (actor name, skill name, amounts,+ a `link` for click-through). The human-readable sentence is built client-side+ by `notifLabel()`; the click target is resolved by `notifLink()` from+ `payload.link`, then a Solana transaction signature (`payload.tx_signature`,+ linked to its Solscan page), then `payload.agent_id`.+- `read_at` is null until the notification is read; `created_at` orders the+ inbox and doubles as the pagination cursor.++Payload values are other users' text, so both surfaces HTML-escape every+interpolated string, and `notifLink()` only permits same-origin relative paths+or absolute `http(s)` URLs. A hostile payload cannot inject markup or drive+navigation into a `javascript:` URL. Payment amounts denominated in `$THREE`+render with the `$THREE` label; other recognized mints render with their+standard symbol, and an unrecognized mint degrades to a bare number rather+than naming a coin.++## Categories: how the filter tabs group types++The `/notifications` page has eight tabs: **All**, **Sales & earnings**,+**Purchases**, **Social**, **In person**, **Market alerts**, **Creations**,+and **Account**. Each notification type maps to exactly one category; the+mapping (`TYPE_CATEGORY`) lives in+[api/_lib/notify-prefs.js](../api/_lib/notify-prefs.js) and is mirrored in+[src/notifications-page.js](../src/notifications-page.js) for tab filtering.++| Category (tab) | Key | Notification types |+|---|---|---|+| Sales & earnings | `sales` | `skill_purchased`, `asset_purchased`, `sale`, `payment-earned`, `payment_received`, `referral_earned`, `referral_signup`, `referral_reward`, `pump_launch_filled`, `royalty_paid` |+| Purchases | `purchases` | `skill_purchase_confirmed`, `asset_purchase_confirmed`, `skill_gift_received`, `skill_gift_sent` |+| Social | `social` | `remix`, `reply`, `embed`, `mention`, `fork`, `follow`, `dm_received`, `agent_review`, `quest_complete` |+| In person | `irl` | `irl_interaction`, `irl_reply` |+| Market alerts | `alerts` | `pump_alert` |+| Creations | `creations` | `forge_complete`, `forge_failed` |+| Account | `account` | `withdrawal_completed`, `withdrawal_failed`, `payment_mismatch`, `asset_payment_mismatch`, `skill_payment_mismatch`, `security_alert`, `wallet_anomaly_frozen`, plus any type not in the map |++Two details worth knowing:++- **Unmapped types fall back to `account`**, so a newly added notification+ type is never silently undeliverable or unfilterable.+- **Tab filtering is client-side** over the pages already fetched. The API's+ own `?type=` parameter filters server-side by a single exact type (e.g.+ `?type=pump_alert`), not by category.++## How the bell and unread state work++The bell ([src/notifications.js](../src/notifications.js)) is mounted by the+shared nav on every page and is deliberately cheap:++- **Auth-aware.** It reads a local sign-in hint (`3dagent:auth-hint` in+ localStorage). Signed out: no polling at all, the badge stays hidden, and+ opening the panel shows a sign-in prompt instead of an empty inbox.+- **Polling.** Signed in, it fetches `GET /api/notifications?limit=20` every+ 30 seconds, re-polls when the tab regains focus, and pauses while the tab+ is hidden.+- **One fetch per user, not per tab.** All open tabs share the result through+ a localStorage cache plus a BroadcastChannel: whichever tab wins a+ best-effort fetch lock spends the request and broadcasts the payload;+ every other tab reuses it for the poll interval. A new tab seeds its badge+ from the cache instantly without its own request.+- **Backoff.** A 429 from the per-user rate budget starts an exponential+ backoff (doubling from 30 seconds, capped at 5 minutes), so the badge+ self-heals without hammering a drained budget.+- **The badge** shows the server's `unread_count` (rendered as `99+` past 99),+ updates its `aria-label`, and announces changes politely to screen readers.+- **Opening the panel marks everything read.** The dropdown is a glance+ surface: if anything is unread when it opens, it fires+ `POST /api/notifications/read-all` and zeroes the badge. Clicking a single+ row also marks that row read, sends an `opened` funnel beacon to+ `POST /api/notifications/track`, and navigates to the resolved link.+- **Push upsell at the value moment.** While the panel is open (never on page+ load), a one-time banner offers Web Push if it is supported, configured,+ not yet subscribed, and not previously declined. Push plumbing lives in+ [src/push-notifications.js](../src/push-notifications.js) and+ [public/push-sw.js](../public/push-sw.js).++## The notification center: /notifications++[pages/notifications.html](../pages/notifications.html) (served at+`/notifications`, `noindex`) is the overflow surface the dropdown never has+to be: full history, filterable, deletable.++- **Auth wall.** Without the local sign-in hint (or on a 401 from the API)+ the page shows a sign-in wall linking to `/login?next=/notifications`.+- **Category tabs** filter the fetched list client-side per the table above.+ The active tab is reflected with `aria-selected`; each empty category has+ its own designed empty state.+- **Pagination.** Pages of 30 load via the `before` cursor: the Load more+ button passes the last row's `created_at` back to the API and appends the+ result. The button renders only while the API reports `has_more`.+- **Per-row actions.** Clicking a row marks it read, tracks the open, and+ navigates. The delete button on each row removes it permanently+ (`DELETE /api/notifications/:id`), optimistically in the UI and+ fire-and-forget on the wire. Mark all read clears everything at once.+- Unlike the dropdown, the page never auto-marks the whole inbox read on+ open; unread rows stay highlighted until clicked or bulk-cleared.++## API contract++All endpoints require authentication: a session cookie or a bearer credential+(API key / OAuth). Unauthenticated calls answer+`401 { "error": "unauthorized" }`. State-changing routes additionally require+a CSRF token for cookie sessions (fetch one from `GET /api/csrf-token`, echo+it in the `X-CSRF-Token` header); bearer callers are CSRF-exempt, which is+what the examples below use. Every query is scoped to the caller's `user_id`,+so one user can never read, mark, or delete another's notifications. The+same endpoints are exposed as MCP tools by+[packages/notifications-mcp](../packages/notifications-mcp/README.md).++### List the inbox++```+GET /api/notifications?limit=20&type=<type>&before=<iso>+```++`limit` is 1..50 (default 20). `type` filters one exact notification type.+`before` pages past a `created_at` cursor.++```sh+curl -s 'https://three.ws/api/notifications?limit=5' \+ -H 'Authorization: Bearer YOUR_API_KEY'+```++```json+{+ "notifications": [+ {+ "id": "5f3c9c2a-1111-4222-8333-444455556666",+ "type": "remix",+ "payload": { "actor": "mira", "royaltyPaid": true, "royaltyUsd": 0.012, "link": "/viewer?src=..." },+ "read_at": null,+ "created_at": "2026-07-30T09:14:02.511Z"+ }+ ],+ "unread_count": 3,+ "has_more": false+}+```++> Source: [api/notifications/index.js](../api/notifications/index.js).++### Mark one read++```sh+curl -s -X POST \+ 'https://three.ws/api/notifications/5f3c9c2a-1111-4222-8333-444455556666/read' \+ -H 'Authorization: Bearer YOUR_API_KEY'+```++Returns `{ id, read_at }`. Idempotent: an already-read row keeps its original+`read_at`. 404 if the row is not the caller's.++> Source: [api/notifications/[id]/read.js](../api/notifications/%5Bid%5D/read.js).++### Mark everything read++```sh+curl -s -X POST 'https://three.ws/api/notifications/read-all' \+ -H 'Authorization: Bearer YOUR_API_KEY'+```++Returns `{ marked_read: <count> }`.++> Source: [api/notifications/read-all.js](../api/notifications/read-all.js).++### Delete one++```sh+curl -s -X DELETE \+ 'https://three.ws/api/notifications/5f3c9c2a-1111-4222-8333-444455556666' \+ -H 'Authorization: Bearer YOUR_API_KEY'+```++Returns `{ ok: true, id, deleted: true }`; 400 for a non-UUID id, 404 if the+row is not the caller's. Removal is permanent.++> Source: [api/notifications/[id]/index.js](../api/notifications/%5Bid%5D/index.js).++### Track a funnel event++```+POST /api/notifications/track+{ "notification_id": "<uuid>", "channel": "push" | "in_app", "event": "opened" | "returned" }+```++An idempotent analytics beacon closing the sent-to-opened-to-returned loop:+the service worker fires `opened` on a push click, the app fires `returned`+when it boots from a push-sourced open. Session-cookie auth only (no bearer),+CSRF-exempt, deduplicated server-side.++> Source: [api/notifications/track.js](../api/notifications/track.js).++### Preferences++```sh+# Read the resolved category x channel matrix+curl -s 'https://three.ws/api/notifications/preferences' \+ -H 'Authorization: Bearer YOUR_API_KEY'++# Turn push off for the social category+curl -s -X PUT 'https://three.ws/api/notifications/preferences' \+ -H 'Authorization: Bearer YOUR_API_KEY' \+ -H 'content-type: application/json' \+ -d '{ "categories": { "social": { "push": false } } }'+```++GET returns `{ categories, channels, prefs, push: { subscribed_devices } }`:+the seven categories from the table above, the four channels (`in_app`,+`push`, `email`, `telegram`), and the caller's resolved matrix. PUT stores a+sparse override; unknown categories, channels, and keys are dropped, and the+response echoes the re-resolved matrix. The body also accepts+`telegram_chat_id` (digits, settable and clearable) for the Telegram channel.++Delivery gating notes, all enforced in+[api/_lib/notify-prefs.js](../api/_lib/notify-prefs.js):++- Muting `in_app` for a category writes no inbox row at all for it: nothing+ in `unread_count`, nothing in `GET /api/notifications`, and turning it back+ on is not retroactive. The channels are independent, so a muted bell with+ push left on still delivers the OS notification.+- The `account` category's `in_app` channel is locked on. It is the durable+ record of withdrawals and security events, and the fallback bucket for+ unmapped types; the other three channels stay fully mutable.+- A user who never saved gets the defaults, and new categories light up+ automatically without a backfill.++The visual editor for all of this is the Notifications panel in+`/dashboard/settings` ([source](../src/dashboard-next/pages/settings.js)),+one click from the gear icon in both notification surfaces.++> Source: [api/notifications/preferences.js](../api/notifications/preferences.js).+> The endpoint-level README at+> [api/notifications/README.md](../api/notifications/README.md) covers the+> same routes from the operator's side (rate limits, table names, routing).++---++## Related pages++- [The social layer](./social-layer.md): where notification events come from+ and how they connect to the feed, follows, and portfolios.+- [api/notifications/README.md](../api/notifications/README.md): the+ endpoint directory's own reference.+- [packages/notifications-mcp](../packages/notifications-mcp/README.md): the+ same inbox as MCP tools for machine clients.diff --git a/docs/object-library.md b/docs/object-library.mdnew file mode 100644index 000000000..8f2282f52--- /dev/null+++ b/docs/object-library.md@@ -0,0 +1,106 @@+# Object Library: free CC0 3D props for any scene++The Object Library is a free, curated gallery of CC0 3D objects and props: furniture, lighting, electronics, containers, tools, decor. Every object is public domain, free to use commercially with no attribution required. Preview any object live in the browser, place it in your real room with AR, or download the GLB and use it in any engine or tool.++Page: [/objects](https://three.ws/objects) · API: `GET /api/objects/library`+Source: [`pages/objects.html`](../pages/objects.html) · [`src/objects-library.js`](../src/objects-library.js) · [`api/objects/library.js`](../api/objects/library.js)++> This page covers the object gallery and its API. For rigged, animation-ready characters, see the [Character Library](./character-library.md). For how AR placement works on phones and desktops, see [AR & WebXR](./ar.md).++---++## What is in the library++Several hundred CC0 props staged as web-ready GLBs on the R2 CDN, currently sourced from Poly Haven (each entry's `source` field says where it came from). Every entry carries its categories (for the filter chips), free-text tags (searched along with the name), and its file size. The API's `total` field is the authoritative count.++Objects are props, not agents: opening one in the viewer uses object mode, which shows view and modify affordances instead of the agent chat dock.++## Using the gallery++Each card renders the object live in an auto-rotating `<model-viewer>` (with the pre-rendered thumbnail as the poster) and offers three actions:++| Button | Destination | What you get |+|---|---|---|+| **Preview** | `/app#model=<glb-url>&kind=object&title=<name>` | The full three.js [3D viewer](./viewer.md) in object mode (no agent chat; Restyle, AR, and Download affordances instead) |+| **AR** | `/ar/studio?src=<glb-url>&title=<name>` | [AR Studio](./ar-studio.md): place the prop in your real space through the camera (see [AR & WebXR](./ar.md) for how the AR handoff works per device) |+| **Download** | The GLB URL directly | The raw GLB file, CC0, yours to use anywhere |++Gallery controls:++- **Category chips** above the grid filter by category (furniture, lighting, tools, and so on), derived live from the manifest. "All" clears the filter.+- **Search** matches names and tags; press `/` anywhere on the page to focus the search box.+- **Sort** by name (A to Z, Z to A) or by file size (largest or smallest first).+- The whole manifest is fetched once and filtered client-side, so chips, search, and sort are instant.+- Loading shows a skeleton grid; an empty library, an empty search result, and a fetch error each have their own designed state with a recovery action.++## API: `GET /api/objects/library`++Public, no authentication, CORS-open to GET from web origins. The endpoint proxies a small manifest JSON from the R2 CDN (`objects/library/manifest.json`) with an edge cache (`Cache-Control: public, s-maxage=300, stale-while-revalidate=3600`). The GLB and thumbnail bytes never pass through the API: every entry carries absolute CDN URLs the browser loads directly. It mirrors the [Character Library API](./character-library.md) exactly, with `objects` in place of `avatars`.++### Query parameters++| Parameter | Type | Default | Notes |+|---|---|---|---|+| `limit` | integer, 1 to 1000 | none | Opt-in pagination. Omit it to get the entire library in one response. Values are clamped into 1..1000. |+| `offset` | integer, >= 0 | 0 | Only meaningful together with `limit`. |++### Response shape++Without `limit`:++```json+{+ "objects": [ { "...": "entry, see below" } ],+ "total": 511,+ "generated_at": "2026-07-21T13:16:14.305Z"+}+```++With `limit` (and optional `offset`), the response adds `offset` and `next_offset`. `next_offset` is `null` on the last page, and `total` is always the full library size, not the page size.++Each entry in `objects`:++| Field | Type | Meaning |+|---|---|---|+| `name` | string | URL-safe slug, stable identifier |+| `label` | string | Display name |+| `url` | string | Absolute CDN URL of the GLB |+| `thumb` | string (optional) | Absolute CDN URL of the PNG thumbnail; only present when the thumbnail actually rendered, so it is never a broken image link |+| `bytes` | number | GLB file size |+| `categories` | string[] | Categories, used by the gallery's filter chips |+| `tags` | string[] | Free-text tags, searched by the gallery |+| `license` | string | `"CC0"` |+| `source` | string | Origin catalog, e.g. `"polyhaven"` |++Before the manifest is first uploaded, the endpoint returns `{ "objects": [], "total": 0 }` rather than an error, so consumers feature-detect by emptiness.++### Example++```bash+curl -s 'https://three.ws/api/objects/library?limit=2&offset=0'+```++Returns the first two objects plus `total`, `offset`, and `next_offset`, each entry with a directly loadable `url` (GLB) and, when rendered, a `thumb` (PNG).++## Licensing++Every object in the library is CC0 (public domain), and every manifest entry carries `"license": "CC0"`. That means:++- Free for any use, personal or commercial.+- No attribution required (crediting the original authors listed in the source catalogs is appreciated, never required).+- You may download the GLB and use, modify, or redistribute it anywhere, inside or outside three.ws.++## How the library is staged (maintainers)++The gallery and API are read-only consumers of a manifest built by a local pipeline. The GLB bytes live on the R2 CDN; only the manifest index is published:++1. `scripts/fetch-polyhaven-objects.mjs` downloads and converts the source models and writes `public/objects/polyhaven/catalog.json`.+2. `scripts/render-glb-thumbnails.mjs` renders the PNG thumbnails to R2.+3. `scripts/build-object-library.mjs` reads the catalog, keeps only completed models, includes a `thumb` only for thumbnails that actually rendered, and PUTs `objects/library/manifest.json` to R2 (`--dry-run` prints without uploading).++## Related++- [Character Library](./character-library.md): the rigged, animation-ready counterpart to this library.+- [AR & WebXR](./ar.md): the device-by-device AR methods behind the AR button.+- [AR Studio](./ar-studio.md): the `/ar/studio` surface the AR button opens, including multi-object rooms.+- [3D Viewer](./viewer.md): the `/app` engine the Preview button opens in object mode.diff --git a/docs/payment-sessions.md b/docs/payment-sessions.mdnew file mode 100644index 000000000..b54f298df--- /dev/null+++ b/docs/payment-sessions.md@@ -0,0 +1,447 @@+# Payment Sessions++A Payment Session is a platform-managed spend envelope for agents. You fund a+budget from your prepaid credits, receive a bearer token, and hand that token+to an agent (or any script). The agent then calls paid x402 endpoints through+`POST /api/pay/execute` without ever holding a private key: the platform's+Solana wallet signs each payment, and a spend governor enforces your budget,+host allowlist, and per-transaction cap on every call. This is for developers+who want an agent to spend real money inside hard limits, with a full+execution ledger and an unspent-budget refund when the session ends.++The design principle: the agent does not hold a wallet. It proposes spend;+governance enforces policy.++Base URL: `https://three.ws`++---++## How the pieces fit++1. **Credits** are your prepaid balance, denominated in USD. Top up by sending+ SOL or $THREE to the platform deposit wallet, then verifying the transfer+ with `POST /api/credits/deposit`.+2. **A session** locks part of that balance into a budget envelope+ (`POST /api/pay/session`). Creation debits your credits up front and returns+ a one-time bearer token in the form `pss_<session-id>_<random>`. Only an+ HMAC-SHA256 hash of the token is stored; if you lose it, cancel the session+ and create a new one.+3. **Executions** spend the envelope. Each `POST /api/pay/execute` call probes+ the target URL for its 402 challenge, runs the governance checks, reserves+ budget atomically, signs a Solana USDC transfer with the platform payer+ wallet, presents the `X-PAYMENT` header, and records the result in the+ session's execution ledger.+4. **Cancel or expire** to get the rest back. `DELETE /api/pay/session/:id`+ refunds the unspent budget to your credits immediately; a scheduled sweep+ (`/api/cron/payment-session-sweep`, every 5 minutes) does the same for+ sessions that pass their expiry while still active.++## Authentication++The session-management and credits endpoints accept either credential:++- **Browser session cookie** (the normal three.ws login). These endpoints do+ not require a CSRF token.+- **`Authorization: Bearer <token>`** with a three.ws API key (`sk_live_...` /+ `sk_test_...`) or an OAuth access token.++`POST /api/pay/execute` is different: it authenticates with the **session+token itself** (`session_token` in the JSON body). No cookie or API key is+needed, which is the point: the token is a time-bounded spending grant you can+hand to an untrusted agent process.++Rate limits: `GET /api/credits` shares the authenticated-read bucket+(300 requests per 5 minutes per IP). Everything else here shares the strict+auth bucket (50 requests per 10 minutes per IP) and returns 429 with a+`Retry-After` header when exceeded.++---++## Prepaid credits++### `GET /api/credits`++Your balance, recent ledger, where to deposit, and the fixed-price actions+credits can buy.++```bash+curl -s https://three.ws/api/credits \+ -H 'authorization: Bearer sk_live_...'+```++```json+{+ "balance_usd": 12.5,+ "lifetime_deposited_usd": 20,+ "lifetime_spent_usd": 7.5,+ "deposit": {+ "wallet": "<platform deposit address>",+ "network": "mainnet",+ "accepts": ["SOL", "THREE"],+ "three_mint": "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump",+ "three_symbol": "THREE",+ "three_decimals": 6+ },+ "buys": [ { "id": "...", "label": "...", "category": "...", "policy": "...", "usd": 0.05 } ],+ "ledger": [ { "id": "...", "kind": "deposit", "amount_usd": 20, "...": "..." } ],+ "next_cursor": null+}+```++`ledger` is newest-first (25 entries here); each item carries `id`, `kind`+(`deposit`, `refund`, `grant`, `adjust`, or a spend), `amount_usd`,+`balance_after`, `action`, `ref_type`, `ref_id`, `tx_signature`, `asset`,+`asset_amount`, `price_usd`, and `created_at`.++### `POST /api/credits/deposit`++Verify an on-chain transfer into the deposit wallet and credit your balance.+Server-authoritative: the platform confirms the transaction on-chain, requires+that a signer is a Solana wallet linked to your account, and computes the+amount actually received from pre/post balances. Credits land only once the+transaction is finalized.++```bash+curl -s https://three.ws/api/credits/deposit \+ -H 'authorization: Bearer sk_live_...' \+ -H 'content-type: application/json' \+ -d '{ "asset": "SOL", "tx_signature": "<signature>", "network": "mainnet" }'+```++Body fields:++| Field | Type | Notes |+|---|---|---|+| `asset` | string | `"SOL"` or `"THREE"`, required |+| `tx_signature` | string | The Solana transaction signature, required |+| `network` | string | `"mainnet"` (default) or `"devnet"` |++Success:++```json+{+ "ok": true,+ "replay": false,+ "balance_usd": 32.5,+ "credited_usd": 20,+ "usd": 20,+ "asset": "SOL",+ "amount": 0.125,+ "price_usd": 160,+ "tx_signature": "<signature>"+}+```++If the transaction is confirmed but not yet finalized you get a retryable+`{ "ok": false, "pending": true, "status": "awaiting_finalization", ... }`;+poll again in a few seconds. Crediting is idempotent per (signature, asset): a+replay returns `"replay": true` with `credited_usd: 0` instead of+double-crediting.++Error codes: `bad_request` (400), `wallet_not_linked` (403, the transfer was+not signed by a wallet linked to your account), `tx_failed`, `tx_not_found`,+`no_funds_received`, `amount_too_small` (all 422), `price_unavailable` and+`deposit_unavailable` (503).++---++## Creating a session++### `POST /api/pay/session`++```bash+curl -s https://three.ws/api/pay/session \+ -H 'authorization: Bearer sk_live_...' \+ -H 'content-type: application/json' \+ -d '{+ "label": "research agent",+ "budget_usd": 1.00,+ "max_per_tx_usd": 0.01,+ "allowed_hosts": ["three.ws"],+ "expiry_seconds": 86400+ }'+```++Body fields:++| Field | Type | Notes |+|---|---|---|+| `budget_usd` | number | Required. Min $0.001, max $1000. Debited from credits immediately. |+| `label` | string | Optional, trimmed to 120 chars. |+| `max_per_tx_usd` | number | Optional per-payment ceiling, must be above $0.000001. `null` means no cap. |+| `allowed_hosts` | string[] | Optional, max 50 entries, deduplicated. Empty means any host. |+| `agent_id` | string | Optional agent to associate with the session. |+| `network` | string | `"solana"` (default) or `"base"`. Stored on the session; execution settles on Solana (see below). |+| `expiry_seconds` | number | Default 3600. Min 60, max 7776000 (90 days). |+| `metadata` | object | Arbitrary caller metadata, stored and echoed back. |++Response is `201` with the session object and the token, **shown exactly+once**:++```json+{+ "session": {+ "id": "0b2f...",+ "user_id": "...",+ "agent_id": null,+ "label": "research agent",+ "budget_usd": 1,+ "spent_usd": 0,+ "remaining_usd": 1,+ "max_per_tx_usd": 0.01,+ "allowed_hosts": ["three.ws"],+ "network": "solana",+ "status": "active",+ "expires_at": "2026-07-31T00:00:00.000Z",+ "metadata": {},+ "created_at": "2026-07-30T00:00:00.000Z"+ },+ "token": "pss_0b2f..._4f8a...",+ "note": "Store this token securely ..."+}+```++Errors: `402 insufficient_credits` when your balance cannot cover+`budget_usd` (the message includes the required and available amounts), and+`400` with `invalid_budget`, `invalid_ttl`, or `bad_request` for out-of-range+fields.++Session `status` is one of `active`, `exhausted` (budget fully spent),+`cancelled`, or `expired`.++## Inspecting, listing, updating++### `GET /api/pay/session`++Lists your sessions newest-first plus aggregate stats. Query parameters:+`status` (filter by status), `limit` (default 20, max 100), `cursor` (pass the+previous page's `next_cursor`, a `created_at` timestamp).++```json+{+ "items": [ { "id": "...", "status": "active", "...": "..." } ],+ "next_cursor": null,+ "stats": {+ "sessions": { "active": 1, "exhausted": 0, "cancelled": 2, "expired": 0,+ "total_budget_usd": 3, "total_spent_usd": 1.2 },+ "executions": { "settled": 40, "failed": 2, "settled_usd": 1.2, "unique_endpoints": 3 }+ }+}+```++### `GET /api/pay/session/:id`++Returns `{ "session": { ... } }` for a session you own, `404 not_found`+otherwise.++### `GET /api/pay/session/:id/executions`++The payment ledger for one session, newest-first, with `limit` (default 20,+max 100) and `cursor` pagination. Each item:++```json+{+ "id": "...",+ "endpoint_url": "https://three.ws/api/x402/ping",+ "endpoint_host": "three.ws",+ "method": "GET",+ "amount_usd": 0.001,+ "network": "solana",+ "tx_hash": "5Kd...",+ "payer_address": "...",+ "payee_address": "...",+ "status": "settled",+ "error_code": null,+ "duration_ms": 1843,+ "created_at": "2026-07-30T00:01:00.000Z"+}+```++`status` is `settled` or `failed`; failed rows carry an `error_code` (see the+execute error table below).++### `PATCH /api/pay/session/:id`++Update the mutable fields of an **active** session: `label`, `allowed_hosts`,+`max_per_tx_usd` (pass `null` to remove the cap). Budget, network, and expiry+cannot be changed after creation.++```bash+curl -s -X PATCH https://three.ws/api/pay/session/<id> \+ -H 'authorization: Bearer sk_live_...' \+ -H 'content-type: application/json' \+ -d '{ "allowed_hosts": ["three.ws", "api.example.com"] }'+```++Returns `{ "session": { ... } }`. Errors: `400 nothing_to_update` when no+recognized field is present, `404 not_found` when the session is missing, not+yours, or no longer active.++### `DELETE /api/pay/session/:id`++Cancels an `active` or `exhausted` session and refunds the unspent budget to+your credit balance. The refund is idempotent per session.++```json+{ "cancelled": true, "session_id": "0b2f...", "refunded_usd": 0.85 }+```++`404 not_found` if the session does not exist, is not yours, or is already+cancelled or expired. Expired sessions are refunded automatically by the+sweep, so there is nothing left to cancel.++---++## Spending a session++### `POST /api/pay/execute`++Executes one x402 payment against any public https endpoint, using the session+token as the only credential.++Body fields:++| Field | Type | Notes |+|---|---|---|+| `session_token` | string | Required. The `pss_...` token from session creation. |+| `url` | string | Required. Public https endpoint to call. Private and non-public addresses are rejected. |+| `method` | string | `"GET"` (default) or `"POST"`. Anything else is treated as GET. |+| `body` | object or string | Optional JSON body, sent when `method` is POST. |+| `idempotency_key` | string | Optional but recommended. Recorded with the execution; the executions table is unique on it, so duplicate submissions of the same key collapse to a single recorded execution. |++What happens, in order:++1. **Token check.** The token is verified against its stored hash.+2. **Probe.** The endpoint is fetched (SSRF-guarded, 20 s timeout, redirects+ not followed). If it responds with anything other than 402, you get the+ response back with `"paid": false` and the session is not touched.+3. **Accept selection.** From the 402 challenge's `accepts[]`, the platform+ picks a Solana USDC accept (the challenge must offer network `solana...`,+ asset USDC, and a `feePayer` in `extra`). Sessions created with+ `network: "base"` store that preference, but execute settles on Solana+ only; a challenge with no Solana option fails with `no_solana_accept`.+4. **Governance.** Five checks in order: session is active, not expired, host+ is in the allowlist (exact hostname or a subdomain of an allowed host),+ amount is within `max_per_tx_usd`, and remaining budget covers the amount.+ The budget reservation is a single atomic SQL update, so concurrent calls+ can never collectively overspend a session; when two racing calls both fit+ individually but not together, exactly one wins and the other gets+ `insufficient_budget`.+5. **Sign and pay.** The platform Solana payer wallet signs a USDC transfer+ matching the accept and re-requests the endpoint with the `X-PAYMENT`+ header. The service's fee payer covers the transaction fee; your budget is+ charged only the payment amount.+6. **Record.** The execution lands in the session ledger with the settlement+ transaction hash (read from the endpoint's `x-payment-response` header)+ and a Solscan explorer link. On a pre-settlement rejection (the endpoint+ answers 402 again), the reservation is rolled back and your budget is+ restored.++```bash+curl -s https://three.ws/api/pay/execute \+ -H 'content-type: application/json' \+ -d '{+ "session_token": "pss_0b2f..._4f8a...",+ "url": "https://three.ws/api/x402/rate-limit-probe",+ "method": "POST",+ "body": { "endpoint": "/api/x402/forge" },+ "idempotency_key": "probe-2026-07-30-001"+ }'+```++Success:++```json+{+ "ok": true,+ "paid": true,+ "result": { "remaining_calls": 412, "reset_at": "...", "cooldown_active": false },+ "payment": {+ "session_id": "0b2f...",+ "amount_usd": 0.001,+ "network": "solana",+ "payer": "...",+ "pay_to": "...",+ "tx_hash": "5Kd...",+ "explorer": "https://solscan.io/tx/5Kd..."+ },+ "session": { "id": "0b2f...", "spent_usd": 0.001, "remaining_usd": 0.999 },+ "duration_ms": 1843+}+```++Free endpoint (no 402 challenge):++```json+{ "ok": true, "paid": false, "note": "Endpoint served response without a 402 ...", "status": 200, "result": { "...": "..." } }+```++### Execute error codes++| HTTP | Code | Meaning | Budget |+|---|---|---|---|+| 400 | `missing_token`, `missing_url`, `invalid_url` | Request is malformed or the URL is not a public https endpoint. | untouched |+| 400 | `blocked_url` | The target resolves to a private or unreachable address. | untouched |+| 401 | `invalid_token` | Token is malformed, unknown, or does not match its stored hash. | untouched |+| 403 | `session_inactive`, `session_expired` | Session is exhausted, cancelled, or past its expiry. | untouched |+| 403 | `allowlist_blocked` | Target host is not in the session's allowlist. `detail` carries the host and the allowlist. | untouched |+| 402 | `per_tx_exceeded` | The endpoint's price exceeds `max_per_tx_usd`. `detail` carries `amount_usd` and `cap_usd`. | untouched |+| 402 | `insufficient_budget` | Remaining budget cannot cover the price. `detail` carries `need_usd` and `remaining_usd`. | untouched |+| 402 | `payment_rejected` | The service rejected the payment before settlement. | rolled back |+| 422 | `no_solana_accept`, `unsupported_asset`, `missing_fee_payer` | The challenge offers no payable Solana USDC option. | untouched |+| 502 | `endpoint_unreachable`, `invalid_challenge` | Could not reach the endpoint or parse its challenge. | untouched |+| 502 | `build_failed` | Building the Solana transaction failed. | rolled back |+| 502 | `settle_uncertain` | Network failure after signing: chain state unknown. Do not retry immediately; check the session executions and wallet activity first. | kept reserved |+| 502 | `upstream_error` | The endpoint returned a non-402 error after payment. Check wallet activity before retrying. | kept reserved |+| 503 | `wallet_unconfigured` | The platform payer wallet is not configured. | rolled back |++The two "kept reserved" cases are deliberate: funds may have moved on-chain,+so the platform refuses to silently restore budget it cannot prove was+unspent. Both are recorded as `failed` executions with the matching+`error_code`.++---++## Full walkthrough++```bash+BASE=https://three.ws+AUTH='authorization: Bearer sk_live_...'++# 0. Check your credit balance (top up first via POST /api/credits/deposit if empty)+curl -s $BASE/api/credits -H "$AUTH" | jq '{balance_usd, deposit}'++# 1. Create a $0.50 session, capped at $0.01 per call, three.ws only, 24 h+CREATE=$(curl -s $BASE/api/pay/session -H "$AUTH" -H 'content-type: application/json' -d '{+ "label": "walkthrough",+ "budget_usd": 0.50,+ "max_per_tx_usd": 0.01,+ "allowed_hosts": ["three.ws"],+ "expiry_seconds": 86400+}')+TOKEN=$(echo "$CREATE" | jq -r .token)+SID=$(echo "$CREATE" | jq -r .session.id)++# 2. Spend it: pay a $0.001 x402 endpoint (no auth header needed, the token is the credential)+curl -s $BASE/api/pay/execute -H 'content-type: application/json' -d '{+ "session_token": "'$TOKEN'",+ "url": "'$BASE'/api/x402/rate-limit-probe",+ "method": "POST",+ "body": { "endpoint": "/api/x402/forge" },+ "idempotency_key": "walkthrough-1"+}' | jq '{paid, payment, session}'++# 3. Inspect the session and its execution ledger+curl -s $BASE/api/pay/session/$SID -H "$AUTH" | jq .session+curl -s $BASE/api/pay/session/$SID/executions -H "$AUTH" | jq .items++# 4. Cancel and refund the unspent budget back to credits+curl -s -X DELETE $BASE/api/pay/session/$SID -H "$AUTH" | jq .+curl -s $BASE/api/credits -H "$AUTH" | jq .balance_usd+```++## Related++- [x402 Protocol](./x402.md): the challenge / verify / settle mechanics behind every paid call.+- [x402 Buyer Client](./x402-buyer.md): paying x402 endpoints from your own wallet instead of a session.+- [x402 Developer Tools](./x402-dev-tools.md): free echo / debug / receipt-verification tools for debugging a paid call.diff --git a/docs/reasoning-ledger.md b/docs/reasoning-ledger.mdnew file mode 100644index 000000000..d56e59646--- /dev/null+++ b/docs/reasoning-ledger.md@@ -0,0 +1,80 @@+# The Reasoning Ledger: hash-chained agent decisions you can audit++Every consequential call a three.ws agent makes (what it decided, why, what it predicted, and what actually happened) is appended to a per-agent, hash-chained ledger. The decision is committed at the moment it is made; the outcome is reconciled later against real on-chain data and stored separately, so a record can never be rewritten to flatter the agent. Being wrong is exactly as visible as being right: honesty is the trust signal.++Browse it at [three.ws/ledger](https://three.ws/ledger). The page is per-agent (`/ledger/<agentId>`, or `/reasoning-ledger?agent=<id>`): a filterable decision timeline, a transparent reputation score with a "how is this computed" drill-down, a calibration chart, and a verification badge that re-checks the chain and its on-chain anchor on demand.++## What a ledger entry contains++Each entry in `agent_decisions` commits, at decision time:++- `seq`: the entry's 1-based position in the agent's chain+- `kind`: what sort of decision (e.g. `snipe`, `optimize`)+- `subject_ref` / `action_ref`: what the decision was about (a token mint, a strategy id) and the concrete action it produced (a position id)+- `inputs`: the evidence in front of the agent (trigger, firewall verdict and score, price impact, size, model thesis)+- `rationale`: a plain-language explanation of why+- `prediction`: a falsifiable claim (direction, basis, metric)+- `confidence`: 0 to 1, self-rated and later scored against reality+- `network` and `decided_at`+- `prev_hash` and `entry_hash`: the chain links (below)++The outcome lives in a separate table, `decision_outcomes`, written only when ground truth arrives: what was observed (realized P&L in SOL and percent, the sell signature, the exit reason), `was_correct`, and when it was reconciled. Reconciled entries on the page show a right/wrong chip, the exact P&L, and an explorer link to the on-chain proof.++## How the hash chain makes tampering evident++The chain construction lives in `api/_lib/reasoning-ledger.js`:++- Each agent's chain starts from a **genesis hash bound to that agent's id** (`threews-reasoning-ledger:v1:<agentId>`), so one agent's history cannot be spliced onto another's.+- Every entry is serialized to a **canonical form**: object keys sorted recursively, confidence at fixed precision, timestamps normalized, so the hash is reproducible after a database round-trip.+- `entry_hash = sha256(prev_hash + separator + canonical(entry))`. Each entry commits to the one before it, so the head hash commits to the entire history.+- **Only decision-time fields are hashed, never the outcome.** Reconciling a decision cannot alter its hash, and neither can anyone "fixing" a bad call after the fact.++The consequences, each detectable and pinpointed to a specific `seq`:++- Editing any committed field breaks that entry's own hash.+- Deleting or inserting an entry breaks the next entry's `prev_hash` link (or leaves a sequence gap).+- Rewriting the whole chain produces a new head, which no longer matches the head committed on-chain.++That last check is the anchor: on a schedule, each agent's current chain head is written to Solana as a signed SPL-Memo transaction (kind `threews.ledger.v1`, recorded in `ledger_anchors`). Because the head commits to the whole prefix, anchoring one hash is a tamper proof for the entire history up to that point. Anchoring is best-effort by contract: without a funded attester key the commitment is recorded locally as pending, and the chain's cryptographic tamper-evidence holds regardless; only the independent on-chain timestamp is deferred.++## Verifying a ledger yourself++```bash+curl "https://three.ws/api/ledger/verify/<agentId>"+```++Public, no account. The verifier trusts **no stored hash**: it recomputes every `entry_hash` from the committed fields, checks every `prev_hash` link and the sequence, then compares the recomputed head against the latest on-chain anchor. Statuses:++- `verified`: chain intact and the head matches the on-chain anchor (the response includes the anchor transaction and explorer link)+- `verified_unanchored`: chain intact, on-chain commitment still pending+- `verification_failed`: a tamper or inconsistency was found; `chain.broken_at` names the exact entry and `chain.reason` says what broke+- `empty`: no decisions recorded yet++The ledger page runs this same check and renders it as the verification badge; clicking it re-verifies live.++The timeline itself is public too:++```bash+curl "https://three.ws/api/ledger/<agentId>?limit=50&kind=snipe&q=firewall"+```++It returns the agent, the reputation breakdown, the latest anchor summary, and the paginated decisions with outcomes (`before=<seq>` pages older entries).++## Who writes entries++There is a single write path, `recordDecision`, and it is a chokepoint by design: appends are idempotent per real-world action (a handler that fires twice records once) and concurrency-safe when claiming the next chain slot. Today's writers, as coded:++- **The [Agent Sniper](agent-sniper.md) executor** appends a `snipe` entry the moment a buy settles: trigger, firewall verdict, price impact, committed size, the buy signature, and (for LLM-judged arms) the model's thesis and confidence.+- **The sniper optimizer cron** appends an `optimize` entry whenever it auto-tunes a strategy from realized outcomes, so the self-tuning loop's own decisions are auditable next to the trades that drove them.+- **The reconcile cron** (`api/cron/reconcile-decisions`) writes no decisions; it closes the loop. When a linked position settles on-chain, it records the outcome against the sell signature (idempotently, so re-runs never double-count), then anchors each agent's advanced chain head, and raises an ops alert if a sizeable track record's hit rate collapses.++Any subsystem that makes a consequential agent decision can adopt the same write path; the page's filters already anticipate more kinds than the sniper pipeline emits today.++## The reputation score is explainable, not a black box++The headline score (0 to 100) is derived only from reconciled outcomes, and the API returns the full formula next to the number: 50% hit rate, 30% calibration (1 minus expected calibration error: do 80%-confidence calls hit about 80% of the time?), 20% realized P&L squashed to a 0-1 range, regressed toward neutral until the agent has 20 reconciled decisions. Every component ships with its raw value, weight, and contribution, and the calibration chart plots predicted confidence against actual hit rate per band.++## Related++- [Agent Sniper](agent-sniper.md): the pipeline that writes `snipe` entries, with a live case-study ledger+- [Custody you can verify](custody.md): the same provable-not-promised approach applied to the wallets these decisions spend fromdiff --git a/docs/timeline.md b/docs/timeline.mdnew file mode 100644index 000000000..0d1f992d8--- /dev/null+++ b/docs/timeline.md@@ -0,0 +1,125 @@+# The Story So Far: the 3D history timeline++`/timeline` tells three.ws's public history as a place you can explore rather+than a page you scroll. Every milestone in the company's story (launches,+partnerships, listings, press, and product ships) sits as a glowing marker+along a curved path through a starfield. You can orbit the whole scene in+360°, walk the path end to end behind an animated guide, or jump around from+a synced scrubber at the bottom. All of it is driven by one static data file,+[`data/timeline.json`](../data/timeline.json); beyond that single fetch,+everything runs client-side in [`src/timeline.js`](../src/timeline.js).++## What it shows++- **The path.** Milestones are laid out chronologically along a gentle+ S-curve (a Catmull-Rom spline, re-parametrized by arc length so marker+ spacing and walk speed stay even through the turns), 6.4 m apart, over a+ dim ground plane and a ~1,400-point starfield.+- **Markers.** Each event is a small faceted sphere colored by its category.+ Its size, and the height of the translucent light beam rising from it,+ scale with the event's `importance` (1 to 5), so the big moments read as+ big from across the scene. A floating label above each beam shows the+ event's title and date.+- **Categories.** The data file defines six (Launch, Partnership, Milestone,+ Listing, Press, Product), each with its own color. The colors carry through+ the markers, the scrubber ticks, the filter chips, and the detail panel+ badge.+- **The guide.** The site's default rigged avatar (`/avatars/default.glb`,+ served from [`public/avatars/`](../public/avatars)) stands on the path at+ tour-guide scale, playing the idle clip from the shared animation library+ ([`src/animation-manager.js`](../src/animation-manager.js) plus the+ manifest at [`public/animations/manifest.json`](../public/animations/manifest.json)).+ In Walk mode it leads the way. If the avatar or manifest fails to load, the+ timeline simply continues without a visible guide; it never breaks the+ scene.+- **The detail panel.** Selecting any milestone opens a side panel (a bottom+ sheet on mobile) with the category badge, date, title, plain-language+ summary, a "Read the source" link when the event has one, and a+ "Milestone i of N" counter.++## How to navigate++Two modes, switched from the pill bar at the top:++- **360° Orbit** (the default). Drag to look around; the camera orbits with+ damping, auto-rotating slowly until your first drag (auto-rotate is off+ entirely under `prefers-reduced-motion`). Zoom is clamped between 4 m and+ 60 m and the camera cannot dip below the ground. Click or tap any marker to+ select it: the camera glides its orbit point over to that marker while+ preserving your current viewing angle, so you are never yanked out of a+ free look.+- **Walk the path.** A chase camera sits just above and behind the current+ point on the path, looking down the path ahead, and eases from milestone to+ milestone (about 0.95 s per move). The guide avatar walks the path in front+ of the camera, always facing forward along the curve.++Around both modes:++- **Scrubber** (bottom bar): one tick per milestone, colored by category.+ Click a tick to jump straight to that event; the active tick lifts,+ auto-scrolls into view, and the label above reads "n / N · date".+- **Prev / next** (the ‹ and › buttons) step through milestones. Stepping+ wraps around at either end and skips any category you have filtered out.+- **Auto-play** (▶) runs the tour: it switches to Walk mode and advances one+ milestone every 2.6 s (0.9 s under reduced motion), stopping on its own at+ the last visible milestone. Dragging the scene, clicking a tick, stepping,+ or pressing an arrow key pauses it.+- **Keyboard**: Arrow Right / Arrow Left step, Space toggles auto-play,+ Escape closes the detail panel.+- **Category filter chips** (top bar) toggle each category. Filtered-out+ categories dim to near-invisible in the scene and in the scrubber, their+ markers stop responding to clicks, and stepping and auto-play skip them.++## Fallbacks and states++- **No WebGL**: the exact same events render as a plain, accessible,+ chronological list (date, title, summary, source link), with a one-line+ note explaining why the 3D scene is not showing.+- **Reduced motion**: no auto-rotate, camera moves become effectively+ instant, and auto-play steps briskly instead of gliding.+- **Loading and errors**: a spinner while the data loads; a failed fetch+ shows a designed error state with a Retry button.++## Adding a milestone++Append an object to the `events` array in+[`data/timeline.json`](../data/timeline.json), keeping the array in+chronological order (markers are laid out in array order, not re-sorted).+There is no build step: the file is fetched at runtime from+`/data/timeline.json`.++```json+{+ "id": "2026-07-25-openai-select-partner",+ "date": "2026-07-25",+ "title": "Named an OpenAI Select Partner",+ "category": "partnership",+ "summary": "One or two plain-language sentences shown in the detail panel and the accessible fallback list.",+ "source_url": "https://three.ws/openai",+ "importance": 3+}+```++Field by field, as consumed by [`src/timeline.js`](../src/timeline.js):++| Field | Rules |+| --- | --- |+| `id` | Unique slug; the convention is date-prefixed (`YYYY-MM-DD-short-name`). |+| `date` | `YYYY-MM-DD`. Displayed verbatim in the label, the panel, the scrubber, and the fallback list. |+| `title` | Keep it short: the floating 3D label truncates past 42 characters. |+| `category` | Must be a key of the top-level `categories` map. It drives the marker color, the panel badge, and which filter chip controls the event. A key missing from the map renders permanently dimmed and unclickable, so if you introduce a new category, add it to `categories` (with a `label` and a `color`) in the same change; the chip appears automatically. |+| `summary` | Plain text, one or two sentences. Rendered escaped in the panel and fallback list. |+| `source_url` | A fetchable third-party URL, or `null` when the only source is the X post history. `null` hides the "Read the source" link. |+| `importance` | Integer 1 to 5. Scales the marker size and beam height; it has no other effect. |++## Code map++| Piece | Location |+| --- | --- |+| Page shell (header, boot spinner, fallback styles) | [`pages/timeline.html`](../pages/timeline.html) |+| Scene, controls, UI, fallback rendering | [`src/timeline.js`](../src/timeline.js) |+| Milestone data | [`data/timeline.json`](../data/timeline.json) |+| Guide avatar + animation runtime | [`public/avatars/default.glb`](../public/avatars/default.glb), [`src/animation-manager.js`](../src/animation-manager.js), [`public/animations/manifest.json`](../public/animations/manifest.json) |++Routing: `vercel.json` rewrites `/timeline` to the page in production (the+server reads that route table on boot).diff --git a/prompts/README.md b/prompts/README.mdindex 94a6c4ed5..c4175492d 100644--- a/prompts/README.md+++ b/prompts/README.md@@ -13,7 +13,6 @@ Internal work-order packs for Claude agents. Each subdirectory is a campaign: a| Directory | What it is ||---|---|-| [agent-briefs/](agent-briefs/) | Multi-agent program briefs (design system, 3D world, world-online), each with a program overview and its own progress log. || [bnb-chain/](bnb-chain/) | BNB Chain campaign: payments and gasless-rail work orders with a verified-facts context file. || [fable-audit/](fable-audit/) | One work order per finding from the 2026-07-11 deep audit, with severity, exact defect location, fix, and verification. || [gcp-credits/](gcp-credits/) | Prompt pack for the GCP credit program: GPU worker deploys, catalog and animation seeding. |@@ -24,7 +23,7 @@ Internal work-order packs for Claude agents. Each subdirectory is a campaign: a| [store-submissions/](store-submissions/) | Prompts for listing three.ws MCP tools across Claude and OpenAI marketplaces and MCP registries. `_generated/` holds submission evidence. || [user-value/](user-value/) | User-facing platform features: creator profiles, activity feed, social graph, notifications, discovery search, leaderboard, onboarding. |-Fully completed campaigns are removed from this directory once every work order is verified shipped (x402-catalog and x402-overhaul were retired 2026-07-28); their packs, progress logs, and evidence remain readable in git history. Open items they still carried were re-homed into [../ISSUES.md](../ISSUES.md).+Fully completed campaigns are removed from this directory once every work order is verified shipped (x402-catalog and x402-overhaul were retired 2026-07-28; agent-briefs, whose world-online program shipped through Phase 3, was retired 2026-07-30); their packs, progress logs, and evidence remain readable in git history. Open items they still carried were re-homed into [../ISSUES.md](../ISSUES.md).## Runtime consumptiondiff --git a/prompts/agent-briefs/W-world-online/PORT-CHECKLIST.md b/prompts/agent-briefs/W-world-online/PORT-CHECKLIST.mddeleted file mode 100644index b11592e23..000000000--- a/prompts/agent-briefs/W-world-online/PORT-CHECKLIST.md+++ /dev/null@@ -1,397 +0,0 @@-# Port Checklist — bring `/walk` + `world.three.ws` systems into `/play`--> Companion to [W00-program-overview.md](W00-program-overview.md). This is the concrete,-> dependency-ordered work list for closing the gap between `/play` (the isometric Coin-> Communities plaza) and the two richer surfaces we already run: `/walk` (in-repo three.js +-> Rapier + Colyseus) and `world.three.ws` (hosted Hyperfy).->-> **Reuse-first is mandatory.** Almost everything below already exists in the repo and is-> wired into `/walk` only — or is built but orphaned. The job is to *lift and wire*, not-> reinvent. Do not switch engines. Do not build a second world client.-------## Ground truth (verified in-repo, 2026-06-11)--- `/play` = [src/game/coincommunities.js](../../../src/game/coincommunities.js) (2289 LOC).- Renders a **flat `PlaneGeometry` plaza**, `WORLD_RADIUS = 58`- ([coincommunities.js:59](../../../src/game/coincommunities.js#L59)), a **single fixed- `PerspectiveCamera`** ([:413](../../../src/game/coincommunities.js#L413)), and **zero- physics** (`grep` for `rapier|PhysicsWorld` → 0 hits).-- `/walk` = [src/walk.js](../../../src/walk.js) (3696 LOC). Has Rapier physics, heightfield- terrain, a 4-mode camera system, friends/presence, and AR.-- **Both `/play` and `/walk` already join the SAME authoritative room** — `walk_world`- (`WalkRoom`). `/play` via [community-net.js](../../../src/game/community-net.js), `/walk`- via [walk-net.js](../../../src/walk-net.js). **Multiplayer is NOT a gap** — the netcode is- shared. Every item below is a **client-side render/physics/UX** port.-- The server already carries vehicle constants (`VEHICLE_WORLD_RADIUS_M`, max-step, max-speed)- in [WalkRoom.js](../../../multiplayer/src/rooms/WalkRoom.js) — driving is partly server-ready.--### Already-in-repo assets to lift (do not rewrite)--> **Re-verified 2026-07-10.** The table below was accurate at the 2026-06-11 ground-truth-> pass but drifted as later sessions shipped Phase 1/2 and quietly wired the three-> "orphaned" modules without updating this row. Trust `grep`, not this table, when in doubt-> — that drift is exactly what sent an earlier session in this program down a dead-end-> re-research path before it re-verified importers directly.--| System | File | Status today |-|---|---|---|-| Rapier wrapper + kinematic character controller | [src/physics/physics-world.js](../../../src/physics/physics-world.js) | **wired into `/play`** (Phase 1, `_initPhysics()` in `coincommunities.js`) |-| Heightfield terrain (shared mesh + collider source) | [src/game/terrain.js](../../../src/game/terrain.js) | **superseded in `/play`** by the district's static-box colliders (see Phase 1 note) — `/walk` still uses the heightfield directly |-| 4-mode camera (follow/cinematic/firstperson/topdown) | [src/walk.js:466-520](../../../src/walk.js#L466-L520) | **wired into `/play`** (`_camModes`, `C` cycles) — still inline in both files, never extracted to a shared module |-| Friends / presence panel | [src/game/friends-panel.js](../../../src/game/friends-panel.js) | **wired into `/play`** 2026-07-10 (P4.2 — see below) + `/walk` + `friends.js` |-| Client vehicle manager (Rapier raycast vehicle) | [src/game/vehicles.js](../../../src/game/vehicles.js) | **wired into `/play`** (Phase 2, `VehicleManager` import in `coincommunities.js`) |-| Day/night cycle | [src/game/day-night.js](../../../src/game/day-night.js) | **wired into `/play`** (imported by `src/agent-screen-world.js`, driven by `src/shared/world-clock.js`) |-| Activities/minigame loop | [src/game/play-activities.js](../../../src/game/play-activities.js) | **wired into `/play`** (P4.1 — `PlayActivities` constructed, ticked, disposed in `coincommunities.js`; F-key chop/mine/cook/pickupRod) |-| Generic world persistence (Postgres index + R2 blob) | [api/world/[action].js](../../../api/world/[action].js), `api/_lib/world-store.js` | live API, **`/play` still doesn't use it** — real gap, see P3.1 |-------## Phase 1 — Physical world foundation (unblocks the most; do first) — SHIPPED 2026-07-08--Maps to **W01**. Goal: `/play` stops being a flat clamped disc and becomes a real 3D space-with gravity, collision, a drivable district, and a free camera. Pure lift from `/walk`.--- [x] **P1.1 — Mount `PhysicsWorld` in `coincommunities.js`.** Done, with one adaptation: by- the time this landed, `district.js` + `world-zones.js` already existed (built in an earlier- session, tagged "W01" in their own headers, but never wired in) as the intended drivable-city- answer for this brief — so physics mounts a flat `addGround()` + the district's building- colliders (`addStaticBox` per `district.colliders`) rather than a second heightfield. Rapier- boots once in the constructor (`_initPhysics()`, memoized like `/walk`'s `initRapier()`), the- kinematic character controller persists across coin switches, `_stepLocal` feeds it- camera-relative displacement + integrated gravity every frame, and `physics.step(dt)` runs- right after in `_loop()` (move-before-step, per physics-world.js's contract). Falls back to- the old direct-mutation path until Rapier's WASM resolves.-- [x] **P1.2 — Real ground collision for the plaza+district.** Superseded by the district- answer above: `terrain.js`'s rolling-hill heightfield is still `/walk`'s ground (unchanged);- `/play`'s Downtown plaza + district streets are flat by design (asphalt/sidewalks), so a flat- `addGround()` matches the rendered geometry exactly instead of fighting it with hills.-- [x] **P1.3 — Raise/replace the 58 m clamp.** Movement now clamps to the square- `WORLD_BOUND`/`DISTRICT` from [world-zones.js](../../../src/game/world-zones.js)- (`clampToBounds`, half=200) instead of the old `WORLD_RADIUS` disc (58, kept only as the- Downtown plaza's *visual* radius for dressing/build-placement/NPC-roam, unrelated to movement- now). This already matches `WalkRoom`'s own `WORLD_HALF_M`/`WORLD_BOUND_M` server clamp- one-for-one — no server change needed.-- [x] **P1.4 — Extract the camera-mode system into a shared module.** Done as- [src/game/camera-modes.js](../../../src/game/camera-modes.js): `CAMERA_MODES`,- `CAMERA_MODE_LABELS`, `CAMERA_MODE_FOV`, the pure `computeCameraForMode()` math, and a- `createCameraModeController()` stateful wrapper (cycling, localStorage persistence, cross-fade- transition). Fully wired into `coincommunities.js` (press **C** to cycle; 'follow' reproduces- the original fixed orbit exactly). `walk.js` was intentionally left on its own inline- controller wiring (haptics/session-save/DOM-indicator are walk-specific) — a follow-up can- point it at the shared constants/math if it's worth the risk on that much larger file.-- [x] **P1.5 — Wire the orphaned day/night cycle.** `createDayNightCycle(env, district)` now- runs every frame in `_tickEnv`, driven by the same deterministic `worldClock(Date.now())`- used by `/agent-screen`'s ambient stage — zero network sync, every client agrees on the sky.- `district.setNight(k)` brings up building windows + streetlamps at dusk for free (the hook- was already built into `day-night.js`, just never called).--**Phase 1 done when:** an avatar in `/play` is stopped by real colliders (not a disc clamp) —-verified end-to-end against a local Colyseus room: a district building blocks a straight-line-walk a few metres short of its wall — can switch all four camera modes (verified via keyboard +-screenshot), the world has a day/night sky driving real light/fog values, and every client in a-`?coin=` world computes the identical district + sky from the same seed/clock. Real Rapier +-real district + real day/night — no mocks. Next: **W02** (vehicles) can now assume a live-`PhysicsWorld` + character controller + district colliders to enter/exit a car against.-------## Phase 2 — Vehicles & driving — SHIPPED 2026-07-08--Maps to **W02**. Depends on Phase 1 (needs the Rapier world + terrain colliders).--- [x] **P2.1 — Wire the orphaned client `VehicleManager`.**- [src/game/vehicles.js](../../../src/game/vehicles.js) is imported and instantiated in- `coincommunities.js` (`this.vehicles = new VehicleManager({ host: this })`); it spawns the- server-seeded fleet (`VEHICLE_SPAWNS` in `multiplayer/src/vehicles.js` — 6 cars across 4 types:- coupe/sedan/pickup/buggy) and gates enter/exit on `VEHICLE_ENTER_RANGE_M` proximity, contextual- **F** to take the wheel / tap-to-enter on touch.-- [x] **P2.2 — Network vehicle state through `WalkRoom`.** `WalkRoom.js` seeds the fleet- (`_seedVehicles`), handles `venter`/`vexit`/`vsync` (rate-limited via the same `_actionOk` gate- every other handler uses, teleport/speed-hack clamped in `_applyVehicleTransform`), and the- `Vehicle` schema (`multiplayer/src/schemas.js`) auto-replicates to every `/play` client via- `CommunityNet` (`vehicleAdd`/`vehicleChange`/`vehicleRemove`/`vehicle` ack events). Remote- vehicles render + interpolate via [src/game/vehicle-mesh.js](../../../src/game/vehicle-mesh.js).-- [x] **P2.3 — Driving camera + HUD.** The follow camera (P1.4's camera-modes module) hands off- to a chase view on entry (`camDist` pulled out to 11m+) and re-centers behind the car's heading- each frame; a dedicated speedometer + Exit button + touch pedal/steering cluster- (`.veh-hud`/`.veh-speedo` in `vehicles.js`) shows live km/h and brake-light state. This is a- self-contained overlay rather than a merge into `WorldHudSystem`- ([src/game/hud/world-hud.js](../../../src/game/hud/world-hud.js)) — functionally complete, but- folding it into that shared system remains a legitimate follow-up if the HUD grows more panels.--**Real bug found + fixed during verification:** the raycast vehicle controller-(`createVehicle` in [src/physics/physics-world.js](../../../src/physics/physics-world.js)) was-correct, but 3 of the 4 vehicle types' `suspension.rest` values in-[multiplayer/src/vehicles.js](../../../multiplayer/src/vehicles.js) left too little clearance-between the chassis collider and the wheel-contact line for their chassis height — the hull-itself rested on/against the ground and its own friction pinned the car almost dead still-regardless of engine force (sedan and pickup: ~0.00 m/s after 3s of full throttle even at 10x-their spec'd engine force; coupe: crawled at 0.6 m/s). Root-caused with a standalone real-Rapier-repro (no browser, no game loop — immune to frame-rate starvation) at-[scripts/verify-w02-physics-core.mjs](../../../scripts/verify-w02-physics-core.mjs).-Fixed by raising `suspension.rest` (coupe 0.32→0.4, sedan 0.36→0.5, pickup 0.42→0.6; buggy was-already fine at 0.46) — all four types now accelerate, steer, and are stopped by real wall-collision correctly.--**Phase 2 done when:** a player walks up to a car, presses to enter, drives it across terrain-with collision, a second browser sees the car move smoothly, and exit returns to on-foot. —-**Verified for real, twice:**-1. A standalone real-Rapier physics repro (no browser/network — immune to shared-box CPU- contention): [scripts/verify-w02-physics-core.mjs](../../../scripts/verify-w02-physics-core.mjs)- — real acceleration on open ground, a real wall stopping the car (not tunnelling, not a- bounds-clamp teleport), real steering-induced lateral displacement, and the handbrake- arresting speed. All passing against the production `createVehicle`/`vehicleSpec` code.-2. A full two-Chromium-context Playwright run against a live Vite dev server + a freshly-started- Colyseus `WalkRoom` (no mocked physics, no mocked network):- [scripts/verify-w02-vehicles.mjs](../../../scripts/verify-w02-vehicles.mjs) — Player A- joins, Rapier boots, the 6-vehicle fleet syncs, A walks to a parked car under real on-foot- Rapier movement, presses F, the server grants the seat, the driving HUD appears, Player B's- independent client sees the `driver` field flip to A's sessionId and sees the car's replicated- mesh actually move in lock-step with A's throttle input, A exits, and B sees it parked again —- zero console errors/warnings on either client. (Environment note: this shared box runs many- concurrent agent build/dev/test processes — load average routinely exceeds its core count —- which starves headless Chromium's frame rate; the script's wall-clock timeouts were widened- accordingly. This affects wall-clock budget only, not the pass/fail physics or networking- assertions.)-------## W04 — Economy & money — SHIPPED 2026-07-08--Maps to [W04-economy-and-money.md](W04-economy-and-money.md) (brief written alongside this-change — the file didn't exist yet when this work started). Independent of Phases 1–2 above-(no vehicle/physics dependency) — cash, a bank/ATM, general-store vendors, and the `$THREE`-boutique bridge.--- [x] **General store.** `WalkRoom` now handles `storeReq`/`storeBuy`/`storeSell` against the- already-built price tables in `multiplayer/src/shop.js` (found labeled "(W04)" but never- wired). A "General Store" NPC sits at each `vendor` spawn point `world-zones.js` had reserved;- walk up, press E, buy tools/consumables with cash or sell gathered goods — every trade priced- and validated server-side, never a client-supplied number.-- [x] **Bank/ATM.** `WalkRoom` now handles `bank` (deposit/withdraw), calling `economy.js`'s- already-built `bankTransfer()` (found with a `// W04 extends` comment, never called from- anywhere). A "Bank Teller" NPC sits at a new `atm` spawn point on the Downtown plaza. Banked- cash survives a death drop — the risk/reward point of using it.-- [x] **`$THREE` bridge (the boutique).** Premium in-game cosmetics- (`multiplayer/src/cosmetics-catalog.js`) unlock via a real on-chain `$THREE` payment: the- player's connected Solana wallet signs one transaction- (`multiplayer/src/game-token.js#buildTokenPurchase`, found in a section literally headed- "generic fixed-amount purchases (W04 $THREE boutique)" and never called), split between the- holder-rewards pool and the treasury; the server re-reads the **confirmed** transaction from- RPC (`verifyTokenPurchase`) before granting anything. Wired into the wardrobe panel's- previously-inert "Locked" cards (`play-systems.js`) rather than a new NPC — a shop for what- you're already wearing.-- [x] **Evaluated and deliberately not reused:** the separate R21–25 avatar-shop/x402 rail- (`api/_lib/cosmetics.js` / `cosmetics-economy.js` / `api/x402/cosmetic-purchase.js`) sells a- different catalog in USDC for a standalone character-creator surface — see the brief's "Ground- truth" section for why building a second on-chain path on top of it would have been the- parallel payment stack the program overview warns against.--**Done when:** a player walks to the general store, buys and sells for real cash (server-echoed-purse), walks to the ATM, deposits/withdraws (server-echoed bank balance), and can spend a real,-on-chain `$THREE` payment on a premium cosmetic that appears equipped moments later. Verified-end to end — real Rapier-driven walk-up, a real freshly-started `WalkRoom`, real server-side-cash mutations, and a real devnet Solana settlement (mint, airdrop, sign, broadcast, RPC-re-verify) for the on-chain leg; see the brief for the exact verification runs.-------## W03 — Character & avatar customization — SHIPPED 2026-07-08--Maps to **W03** (avatar creator + selfie→3D + wardrobe). No dependency on W01/W02. Unlike-W01/W02, no `Wxx` brief file existed yet when this pass started — the program README/W00-referenced `W03-character-avatar-customization.md` but it was never written. Filed as-[W03-character-avatar-customization.md](W03-character-avatar-customization.md) as part of this-pass, documenting the (extensive) reused infra below plus what was actually added.--**Ground truth found (most of this brief already existed and was already wired into `/play`):**-the lobby's full **Create your avatar** flow (design-from-scratch/selfie via `AvatarCreator` +-the real Avaturn selfie→3D SDK, `.glb` upload, or the full Avatar Studio sculptor — see-`src/game/coincommunities-ui.js` `_openCreate()`), a real x402-settled **cosmetics shop**-(`cosmetics-shop.js` → `/api/cosmetics/catalog` → `/api/x402/cosmetic-purchase`), and a real-server-authoritative **wardrobe/equip** system (`cosmetics-wardrobe.js` →-`WalkRoom` `equip-cosmetic` → persisted profile) were all already shipped, all real (no-mocks), and already reachable from the HUD.--**Real gap found and closed:** cosmetics customization existed only behind a HUD menu button —-no physical presence in the world, unlike every other economy interaction in `/play` (which is-NPC-fronted).--- [x] **Boutique NPCs.** `src/game/npc/npc-catalog.js` now seats **Roux · Tailor**- (`boutique-se`, opens the Shop) and **Nell · Fitting Room** (`boutique-nw`, opens the- Wardrobe) via `spawnsOfType('boutique')` — no hardcoded duplicate coordinates. `world-zones.js`- had already reserved the original `vendor-ne`/`vendor-sw` stalls for this kind of thing- ("consumed by economy/shop briefs"), but the concurrent W04 pass claimed those two for its- general-store clerks — resolved by giving the boutique its own `type: 'boutique'` pair,- mirrored onto the plaza's other diagonal (`(44,44)`/`(-44,-44)`) so nothing stands on top of- anything else. Both NPCs use the same data-driven `Npc`/`WorldLife` engine every other- townsperson uses (proximity prompt, press E, `onInteract`) — zero new wiring beyond the- catalog entries.-- [x] **`world.openShop`/`world.openWardrobe` callbacks.** `coincommunities.js` passes these- into the `WorldLife` `world` config (bound to the existing `_toggleShop()`/`_toggleWardrobe()`- methods the HUD buttons already call), so the boutique NPCs and the HUD open the identical- real panels — one system, two entry points.-- [x] **Docs.** [docs/character-studio.md](../../../docs/character-studio.md) gained a- "Character customization in `/play` (World Online)" section mapping the full flow (lobby- creation → shop → wardrobe → boutique NPCs) for a reader with zero prior context — this area- had no `/play`-specific documentation before.--**Gaps identified but intentionally NOT closed this pass (documented, not silently dropped):**-- Premium cosmetics remain USDC-only on this rail, deliberately separate from the in-world cash- economy and from W04's own on-chain `$THREE` boutique bridge (see the W04 entry above) — three- distinct currencies already exist by design; unifying them is a product decision above this- brief's scope, not an oversight.-- Deep body/face/hair sliders (Avatar Studio) are reachable only via "Advanced studio" in a new- tab, not embedded in the `/play` canvas — a deliberate choice (a heavy sculpting iframe- competing with the game's WebGL canvas for GPU/CPU is a worse experience than a tab hop), not- an oversight. Revisit only if there's a concrete UX complaint.-- The lobby's selfie flow (Avaturn SDK, fast/stylized/game-ready) is intentionally lighter than- the standalone `/create/selfie` pipeline (photorealistic, 3-shot guided capture) — different- products for different needs (fast in-game vs. photorealistic showcase), not a regression.--**W03 done when:** a new player can design or scan an avatar into `/play` with zero sign-in-friction, and once in the world can walk up to a physical storefront (not just a menu) to-browse and equip real, server-persisted cosmetics. **Verified for real** against a local Vite-dev server + a freshly-started Colyseus `WalkRoom` (no mocked physics, no mocked catalog, no-mocked SDK) with Playwright:-[scripts/verify-w03-boutique.mjs](../../../scripts/verify-w03-boutique.mjs) — the lobby's-"Design your avatar" card opens `AvatarCreator`, which fires a real network request to-`avaturn.*` (the SDK is genuinely wired, not a stub); the player joins the `$THREE` world over a-real Colyseus session; both boutique NPCs are present in `worldLife.npcs`; real on-foot-Rapier-driven movement (camera-relative WASD, ~62 m) reaches Roux · Tailor, the "E · Browse the-wardrobe" prompt appears, pressing E opens the real `CosmeticsShop` panel rendering real catalog-cards fetched from `/api/cosmetics/catalog`; the Fitting Room leg confirms Nell opens the real-`CosmeticsWardrobe` panel via the identical `onInteract` → `world.openWardrobe()` path — zero-unexpected console errors/warnings.--## W07 — Combat & weapons — SHIPPED 2026-07-08--Maps to [W07-combat-and-weapons.md](W07-combat-and-weapons.md). Depends on W01 (physics,-district bounds). Independent of W02–W06.--- [x] **Mob AI + PvE.** `multiplayer/src/combat-handlers.js` (new) seeds a difficulty- gradient of roaming mobs into the three named `DANGER_ZONES` and ticks their AI every- 200ms — idle, chase, or swing at the nearest live player, clamped so a chase never- leaves its home zone (the town stays lawful by construction). Killing one grants- XP/gold and spills a lootable tombstone.-- [x] **`attack`/`loot` intents wired into `WalkRoom`.** Both were fully designed- (`combat.js`, `items.js` WEAPONS/MOB_STATS/LOOT_TABLES, `world-features.js`- DANGER_ZONES) and completely unreachable — `grep` for the combat helpers in- `WalkRoom.js` hit only the import line. `registerCombatHandlers`/`seedMobs`/- `tickMobs`/`tickHeat` now wire it in, mirroring `activities.js`'s split exactly.-- [x] **Safe/danger zone gating, for real.** Attacking is rejected server-side outside a- `DANGER_ZONES` circle — not just visually signposted.-- [x] **Wanted/heat meter.** PvP raises the attacker's heat (`combat.addHeat`), decaying- faster in town; the public star count rides on `Player.heat` (already in schemas.js,- never populated before this).-- [x] **Death, tombstones, respawn.** A kill (mob or player) calls `killPlayer`:- `dropCarried` spills a tombstone, `player.dead=true` flags the downed state on the- shared schema (a `move` from a dead player is now rejected server-side — a real bug- found while wiring this in), and a 5.5s timer respawns at `SPAWN_POINT` via- `reviveProfile`.-- [x] **Client vitals HUD.** `src/game/hud/world-hud.js` — fully built, dormant, never- imported — is now mounted by the new `src/game/combat-system.js`, feeding- `setHealth`/`setArmor`/`setWanted` (this brief) and `setCash`/`setBanked`/minimap- viewer (closing the same dormant-HUD gap for W04's money readout as a side effect).-- [x] **Mob rendering reuses W08's already-built (but dormant) `MobSystem`.** `src/game/npc/mobs.js`- was already written against a `window.twsCombat` contract ("when W07 ships, mobs light- up with zero changes here" — confirmed true). Rather than ship a second, competing mob- renderer, `combat-system.js` **is** that contract: it installs `window.twsCombat` before- `WorldLife` constructs `MobSystem` and feeds it this module's own per-frame-interpolated,- server-authoritative positions. `MOB_TINT` in `mobs.js` gained the real W07 kinds- (goblin/ogre/troll/dummy) alongside its original placeholders.-- [x] **Tombstones, danger-zone ground, hit feedback, death overlay, wanted nameplate- badge.** All new in `combat-system.js` + a small `RemotePlayer` extension in- `coincommunities.js` (a downed peer tilts flat and dims — an honest static pose, not a- fabricated ragdoll; a wanted peer's nameplate carries a star badge).--**Real gap found and closed in passing:** `src/game/items.js` (client display/glyph-registry) was missing `bat`/`pistol`/`bow`/`ammo`/`arrow`/`vest` — the server already had-icons for all of them; the client would have rendered a bare first-letter fallback.--**Phase done when:** a player equips a weapon, walks into a named danger zone (attacking-is rejected outside one), kills a PvE mob and loots its tombstone, damages a second-player (raising wanted heat, visible on both the HUD and the victim's nameplate), and a-kill drops the victim's carried valuables + auto-respawns them in town at full health —-all real Rapier-driven movement, a real freshly-started `WalkRoom`, zero mocked combat-math. Verified end-to-end with two independent Chromium contexts against a live server:-[scripts/verify-w07-combat.mjs](../../../scripts/verify-w07-combat.mjs).------------## Phase 3 — Persistent, buildable world (the Hyperfy parity items)--Maps to **W01 persistence + Hyperfy's build/upload/persistence model**. These are the things-`world.three.ws` has that neither `/play` nor `/walk` fully has yet.--- [ ] **P3.1 — Persist the coin-world build through the existing world store.** `/play` already- has limited prop building (`WorldObjects`/`PropGhost`, capped to 12 m). Route saves/loads- through the live [api/world/[action].js](../../../api/world/[action].js) +- `api/_lib/world-store.js` (Postgres index + R2 blob, optimistic-concurrency etags), keyed by- coin mint as `worldId`. This is the Hyperfy "save every 30s" pattern, already half-built here.-- [ ] **P3.2 — Lift the build-radius cap.** With persistence + permissions- (`world-store.canWriteWorld`), expand beyond the 12 m `clearMaxRadius`- ([coincommunities.js:298](../../../src/game/coincommunities.js#L298)) so holders can build a- real place, governed by the per-world permission model rather than a hard cap.-- [ ] **P3.3 — Player asset uploads (GLB).** Hyperfy lets players upload GLB/VRM. We already- have [src/game/avatar-upload.js](../../../src/game/avatar-upload.js) and an R2 pipeline —- extend it to world props, size-limited like Hyperfy's `PUBLIC_MAX_UPLOAD_SIZE`. Validate and- sanitize server-side before serving.-- [ ] **P3.4 — (stretch) VRM avatar support.** Hyperfy is VRM-native; we're GLB-native. Evaluate- adding a VRM loader path alongside GLB in the avatar pipeline. Lower priority — only if a- clear holder demand exists. Do **not** block Phases 1–2 on it.--**Phase 3 done when:** a holder builds in their coin world, reloads the page, and the build is-still there; a second visitor sees the same persisted build; permissions stop non-owners from-overwriting it.-------## Phase 4 — Living-world & social parity--Maps to **W08/W09**. `/play` already has NPCs (`WorldLife`), voice, cosmetics — these add the-`/walk` social surface and the orphaned activities loop.--- [x] **P4.1 — Wire the orphaned activities/minigame loop.** SHIPPED (undated — found already- complete 2026-07-10). `PlayActivities` is constructed/ticked/disposed in `coincommunities.js`- and bound to the `F` key (chop/mine/cook/pickupRod), sharing the vehicle-interact/fish- priority chain.-- [x] **P4.2 — Port the friends/presence panel.** SHIPPED 2026-07-10. `FriendsPanel` mounts in a- right-docked drawer (`_openFriends`/`_closeFriends` in `coincommunities.js`), toggled by the- `J` hotkey or the HUD `Friends` button (unread badge, `aria-expanded`), closed with `Esc`.- The real gap this closed: `community-net.js` never carried a signed presence ticket into the- `walk_world` join and never forwarded the server's `social` message — so every `/play` player- showed **Offline** to their friends and live DMs were silently dropped, even though the panel- itself and the server-side `socialHub` registration were both already built. Fixed at the net- layer (`getPresence` option + `social` → `_emit`), not just the UI. See- `tests/play-friends-presence.test.js` for the regression coverage.-- [x] **P4.3 — Minimap.** SHIPPED (undated — found already complete 2026-07-10).- `WorldHudSystem` (`src/game/hud/world-hud.js`) owns a rotating `Minimap`- (`src/game/hud/minimap.js`) with compass + live blips, range widening while driving.-------## Cross-cutting rules (from CLAUDE.md — apply to every item)--- **No mocks, no stubs, no TODOs, no fake loading.** Real Rapier, real terrain, real- `walk_world` netcode, real R2/Postgres persistence.-- **$THREE is the only coin.** Worlds are keyed by arbitrary user-supplied mints at runtime- (the generic plumbing exception) — never hardcode or surface any non-`$THREE` mint.-- **Every state designed:** loading skeleton, empty world, physics-init failure, asset-upload- rejection, save conflict (409 etag) — all handled and actionable.-- **Definition of done per item:** `npm run dev`, exercise in a real browser at 320/768/1440,- zero console errors, Network tab shows real `walk_world` + `api/world` traffic, `npm test`- green, `git diff` self-reviewed.-- **Changelog:** each phase that ships a user-visible change gets a `data/changelog.json` entry- (tags: `feature`/`improvement`), per CLAUDE.md.--## Suggested order--`P1.1 → P1.2 → P1.3 → P1.4 → P1.5` (foundation) → `P2.x` (vehicles) → `P3.1 → P3.2 → P3.3`-(persistence/build) → `P4.x` (social). All of Phase 1, 2, and 4 are now shipped (see the-checkboxes above) — **Phase 3 (persistence/build parity) is the only remaining phase** and the-next place to pick up this program.diff --git a/prompts/agent-briefs/W-world-online/W00-program-overview.md b/prompts/agent-briefs/W-world-online/W00-program-overview.mddeleted file mode 100644index 3eaf19c15..000000000--- a/prompts/agent-briefs/W-world-online/W00-program-overview.md+++ /dev/null@@ -1,157 +0,0 @@-# W00 — World Online: program overview & shared architecture (READ FIRST)--> Every agent picking up a `Wxx` brief in this folder MUST read this file first. It is the-> shared context the individual briefs assume. Do not re-decide the stack, the coin rules,-> or the networking pattern — they are settled here.-------## North Star--Turn `/play` from a charming 60-meter plaza into a **GTA Online–class, high-quality 3D-multiplayer world**: a persistent, drivable open world with a real in-game economy, jobs &-missions, activities/minigames, combat, deep avatar customization, and living NPCs — all-wallet-native to `$THREE`.--**Explicitly NOT isometric.** Kintara (kintara.gg) is the *feature* reference for the-economy/quest/loop ideas, but the *fidelity* bar is GTA Online / high-end third-person 3D.-We render full 3D avatars, third-person camera, real physics, real vehicles.--The quality bar from `CLAUDE.md` stands: ship complete, polished, real-data features that a-room of senior engineers would respect. No mocks, no stubs, no TODOs, no fake loading.-------## Two existing assets you MUST mine before writing anything--1. **`world.three.ws`** — our own already-built, nicely-polished 3D world framework (hosted- on Google Cloud). It is the single richest source of proven patterns we have. Before- building any `Wxx` feature, **open `world.three.ws`, exercise the relevant system, read- its client code (view-source / network tab / its served JS bundles), and PORT what- already works** instead of reinventing it. If a system there is better than what `/play`- has, lift it. Treat it as a first-class dependency, not inspiration.--2. **The in-repo `/play` + `/walk` foundation** — we already run the exact stack a- GTA-style world needs, in production:- - **Rendering:** three.js (GLTF/GLB avatars, instanced voxels, world env/biomes).- - **Physics:** Rapier (`@dimforge/rapier3d`) — `/walk` already has a reusable- `PhysicsWorld` + kinematic character controller + heightfield (see memory- `walk-physics-rapier`). This is the base for character collision AND vehicles.- - **Multiplayer:** Colyseus — `multiplayer/src/rooms/WalkRoom.js` is an authoritative- room with per-coin world instances, movement validation, chat, emotes, voice (WebRTC),- and an **off-schema economy** (fishing, inventory, XP). This is the spine everything- networked hangs off.--**Reuse-first is a hard rule for this program.** We do not switch engines and we do not-build a second world client. We extend three.js + Rapier + Colyseus + the WalkRoom, and we-port from `world.three.ws`.-------## Approved package allowlist (don't reinvent these)--Use these; do not hand-roll equivalents. Adding anything outside this list requires a one-line-justification in your brief's PR.--| Need | Package / repo | Notes |-|------|----------------|-------|-| Rendering | `three` | Already the foundation. |-| Physics (chars, vehicles, props) | `@dimforge/rapier3d` | Already in `/walk`. Has a built-in **raycast vehicle controller** — that is our driving model. |-| Authoritative multiplayer | `colyseus` / `@colyseus/schema` | Already in `multiplayer/`. Extend WalkRoom or add sibling rooms. |-| Fast world collision / raycast | `three-mesh-bvh` | For large static world meshes (streets, buildings). |-| NPC navigation | `three-pathfinding` (donmccurdy) | Navmesh for pedestrians, traffic, quest NPCs, mob AI. |-| Customizable full-body avatars | A third-party full-body avatar SDK + our existing GLB/VRM pipeline + `/scan` selfie→3D | We already load GLB/VRM and have a selfie→3D pipeline (memory `scan-to-3d-pipeline`). The SDK adds a wardrobe. |-| Character animation | three.js `AnimationMixer` + Mixamo clips (already wired in `avatar-rig.js`) | Reuse the emote/anim manifest system. |-| Reference architecture (vehicles + ECS netcode) | [iErcann/Notblox](https://github.com/iErcann/Notblox) | three.js + Node + Rapier + ECS, cars/city/players, GTA/Roblox-like. **Read it for patterns; do not fork wholesale.** |--We deliberately do NOT adopt a different engine (PlayCanvas, Babylon, Needle, Hyperfy, etc.).-We already have a working three.js+Rapier+Colyseus world; switching engines would be exactly-the wheel-reinvention the user asked us to avoid.-------## The networking pattern every gameplay feature follows (off-schema economy)--This is how `/play` already does fishing/inventory/XP, and how EVERY new server-authoritative-mechanic in this program must be built. Do not invent a second pattern.--- **Synced world state** (positions, blocks, who's present) lives in the Colyseus- `WalkState` schema and auto-replicates to all clients.-- **Private/per-player state** (inventory, cash, XP, quests, vehicle ownership) lives- **off-schema** in server-side `Map`s on the room (`this.econ`, etc.), persisted per-account- (wallet when the gate is on, else guest id). Peers never see it.-- **Flow:** client sends an intent message (`this.net.send('mine')`) → server handler- validates (tool/range/cooldown/space) → rolls authoritatively → mutates off-schema state →- replies to that one client with targeted `notice` / `inv` / `xpgain` / `levelup` messages →- client renders toast + HUD. **The client is pure UI; the server is the authority.**-- **Template to copy:** `multiplayer/src/rooms/WalkRoom.js` `_handleFish` (the canonical- example) + `multiplayer/src/economy.js` + `multiplayer/src/items.js` +- `multiplayer/src/world-features.js`, and the client side in `src/game/play-systems.js`.--Each brief that adds a mechanic must: add world feature(s)/spawn data, add the server-message handler(s), add item/data tables, add client UI + 3D feedback, and persist.--**Anti-cheat baseline:** never trust a client-sent position, balance, hit, or reward. Validate-range, cooldown, ownership, and inventory space server-side every time. Rate-limit every new-message type like the existing handlers do.-------## The world structure we're building on--- One **mainland** + one isolated world instance **per `$THREE`/coin community** (and a- gated **Holders** tier per coin). Keep this model. "Districts" within a world are zones,- not new Colyseus rooms, unless a brief says otherwise.-- The flagship `$THREE` town is the showcase world — land new flagship features there first- (e.g. the Agent Exchange NPCs already live only there).-- Builds persist per-world via `blockStore` (Redis/memory). Any new persistent world state- (vehicles parked, properties owned, quest progress) follows the same per-world/per-account- persistence discipline.-------## Coin rule — absolute (from CLAUDE.md)--**`$THREE` is the ONLY coin. CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`.** Never name,-add, or reference any other token anywhere — not even ones we've launched. In-game spendable-currency is **"cash"/"gold"** (a game resource, not a token) — that's fine and encouraged. The-only on-chain token that may ever appear is `$THREE`. Test/fixture mints use `$THREE` or an-obviously-synthetic placeholder.-------## Definition of done (applies to every brief)--Inherit the full `CLAUDE.md` "Definition of done" + "Self-review protocol". In addition:--- Dev server run, feature exercised in a real browser, **no console errors/warnings**.-- Server-authoritative: cheating the mechanic from the client console fails.-- Every new networked action is rate-limited and validated server-side.-- Reuses `world.three.ws` patterns and the existing off-schema architecture — reviewer can- see what was ported vs newly written, and why anything new was necessary.-- Loading/empty/error/populated states all designed; mobile (touch/joystick) works.-- Run the **completionist** subagent over changed files; fix everything it flags.-- Do not push unless the user asks; when they do, `git push threews main` — the only push- target per CLAUDE.md. Never push/pull/fetch/merge `threeD` (retired mirror, diverged history).-------## Brief index & dependency order--Build roughly in this order; later briefs assume earlier foundations.--| Brief | Feature | Depends on |-|-------|---------|------------|-| **W01** | Open-world foundation (drivable streamed world, physics, day/night) | — |-| **W02** | Vehicles & driving (Rapier raycast vehicle, enter/exit, networked) | W01 |-| **W03** | Character & avatar customization (avatar creator + selfie→3D + wardrobe) | — |-| **W04** | Economy & money (cash, bank/ATM, sell/buy vendors, `$THREE` sink/faucet) | — |-| **W05** | Jobs, missions & heists (data-driven quest engine, solo + co-op) | W04 |-| **W06** | Activities & minigames (gather/craft loop, races, arcade) | W04 (W02 for races) |-| **W07** | Combat & weapons (server-authoritative, health/armor, wanted, safe zones) | W01 |-| **W08** | NPCs & world life (vendors, traffic, pedestrians, quest-givers, mob AI) | W01 |-| **W09** | Social & crews (crews, friend instances, profiles, minimap/waypoints) | — |-| **W10** | HUD, interaction menu & game-feel polish (GTA-style HUD, cameras) | W01 |--Each `Wxx` file is self-contained enough for one agent to own end-to-end, but all share this-overview. When in doubt, re-read this file.diff --git a/prompts/gcp-credits/04-gpu-workers-deploy.md b/prompts/gcp-credits/04-gpu-workers-deploy.mddeleted file mode 100644index ada530135..000000000--- a/prompts/gcp-credits/04-gpu-workers-deploy.md+++ /dev/null@@ -1,103 +0,0 @@-# 04 — Deploy the GPU worker fleet to Cloud Run (self-hosted 3D stack)--## Mission--Deploy the already-written GPU model workers to Cloud Run on our GCP credits and flip the forge-router's self-host backends live: TRELLIS (text/image→3D), Hunyuan3D, TripoSG/TripoSR, UniRig-(auto-rigging), and text2motion. Outcome: the paid forge lane stops paying Replicate (≈100%-margin during the credit window), the free lane stops being throttled by hosted NVIDIA NIM's-rate limits, image→3D opens up on the free lane (hosted NIM preview rejects user images; our-own TRELLIS accepts them), and prompt 05 gets a firehose for catalog seeding. Everything-reverts by unsetting env URLs.--## Prerequisites--- Prompt 01 ran: project set, Cloud Run/Cloud Build/Storage APIs enabled, `gcloud` authed.-- GPU quota: check `nvidia-l4` quota in the target region (`us-central1` unless the existing- buckets/scripts say otherwise). File an increase immediately if < 4 GPUs — it can take days;- deploy what fits now and document the pending ask.--## Context (from prior code audit; re-verify everything against the tree)--- Workers, each with `main.py` + `Dockerfile` + `cloudbuild.yaml` targeting Cloud Run L4- (`--gpu=1 --gpu-type=nvidia-l4`, min-instances 0):- `workers/model-trellis/` (TRELLIS-image-large), `workers/model-hunyuan3d/`,- `workers/model-triposg/`, `workers/model-triposr/`, `workers/unirig/` (VAST UniRig —- skeleton + skinning + ARKit-52 blendshapes; also `rig_glb.py`), `workers/model-text2motion/`.- Deploy helpers in `workers/deploy/*.sh`; docs in `workers/README.md`, `workers/deploy/README.md`.-- Model weights staged in GCS bucket `three-ws-model-weights`; intermediate output to- `three-ws-avatar-reconstructions`. Durable public assets stay on Cloudflare R2 (`api/_lib/r2.js`)- — do not move asset storage to GCS.-- Shared auth between Vercel and workers: bearer `GCP_RECONSTRUCTION_KEY`.-- The router already has the code paths: `api/forge.js` (~2000 lines; lane routing) with- backends `trellis_selfhost`, `hunyuan3d`, `triposg`; health-aware routing + cold-start ETA in- `api/_lib/forge-lane-health.js` / `api/_lib/provider-health.js`; scale limits in- `api/_lib/forge-scale.js`. Rigging goes through `api/_providers/gcp.js`- (`GCP_RECONSTRUCTION_URL`, `/rig`) and `api/_lib/auto-rig.js`. Direct NIM-protocol path:- `api/nim-forge.js` (`NIM_TRELLIS_URL`/`MODEL_TRELLIS_URL`).-- Env URLs the router reads (verify exact names in code): `MODEL_TRELLIS_URL`,- `GCP_HUNYUAN3D_URL`, `GCP_TRIPOSG_URL`, `GCP_RECONSTRUCTION_URL`, `GCP_TEXT2MOTION_URL`.--## Tasks--1. **Pre-flight per worker.** Read each worker's README/cloudbuild/deploy script. Confirm the- weights it expects exist in `three-ws-model-weights` (stage them if missing — the deploy- scripts or READMEs describe how). Fix anything stale (base image, CUDA version pins) —- these were written a while ago; a build that fails on today's Cloud Build gets fixed, not- skipped.-2. **Deploy all six** via `gcloud builds submit` / the deploy scripts. Generate and set a strong- `GCP_RECONSTRUCTION_KEY` (Cloud Run env + Vercel env). Configuration decisions:- - Region: co-locate with the weights bucket.- - **min-instances 1 for `model-trellis` and `unirig`** during the credit window (cold-start- on L4 + model load is brutal; instances are ~free on credits). min-instances 0 for the- rest. Document per-service settings.- - Concurrency/timeouts per the worker READMEs; requests can run minutes — set Cloud Run- timeout ≥ 900s where the code expects it.-3. **Health.** Curl each service's health endpoint directly, then confirm the platform's lane- health (`forge-lane-health.js` / provider-health) registers them once env URLs are set.-4. **Wire Vercel env** (preview first): all five URL vars + `GCP_RECONSTRUCTION_KEY`. Confirm- `api/forge.js` routing actually selects self-host backends — read the routing logic; if- selection needs a flag or priority tweak to prefer self-host over Replicate/hosted-NIM,- make that change **behind `FORGE_SELFHOST_PRIMARY=1`** with fallthrough to today's ladder on- error, same fail-safe philosophy as the whole program.-5. **End-to-end verification (all five paths, real requests, definition of done):**- - Text→3D free lane → self-hosted TRELLIS → GLB lands in R2, viewable via the viewer link.- - Image→3D with a real input image (the thing hosted NIM couldn't do) → GLB.- - Paid-lane `mesh_forge`-style chain (reference image → reconstruction) → GLB, with logs- proving **Replicate was not called**.- - Rig: send a generated GLB through `/rig` (UniRig) → animation-ready GLB; load it and- confirm the skeleton drives the canonical clips (`src/glb-canonicalize.js` path).- - text2motion: one text→motion generation → clip JSON.- Record latency (cold + warm) for each in the runbook.-6. **Scale limits.** Revisit `forge-scale.js` ceilings that exist to protect the hosted-NIM- free allocation: with self-host primary, raise the free-lane hourly/global ceilings to what- the deployed GPU count sustains (compute it from measured per-asset latency; show the math).- Keep abuse/per-IP limits intact. Flag-gate the raised limits with the same- `FORGE_SELFHOST_PRIMARY` so revert restores today's ceilings.-7. **Cost note.** Compute $/asset from measured latency × L4 Cloud Run pricing; write it into- `docs/gcp-credits.md` (prompt 08 needs it for the keep/kill decision at expiry).--## Guardrails--- Fallback ladder stays: self-host error → hosted NIM / Replicate / HF exactly as today.-- Don't commit any Cloud Build artifacts or `api/` files mangled by tooling — beware the known- trap: `npx vercel build` overwrites `api/*.js` in place; check `head -1` of changed api files- for `__defProp` before committing.-- R2 remains the asset store. GCS is weights/intermediates only.--## Acceptance criteria--- [ ] All six services deployed, healthy, and reachable with the bearer key.-- [ ] All five E2E paths verified with real outputs (GLBs/clips inspected, not just 200s).-- [ ] Replicate absent from paid-lane logs when `FORGE_SELFHOST_PRIMARY=1`.-- [ ] Raised free-lane limits computed and flag-gated.-- [ ] Latency + $/asset table in `docs/gcp-credits.md`; per-service Cloud Run config documented.-- [ ] Flags/URLs unset ⇒ today's behavior (spot-check one path).-- [ ] `npm test` green; `git diff` reviewed.--## Wrap-up--Changelog entry when this hits production (users notice: image→3D on free lane, faster/looser-limits) — plain-language, per CLAUDE.md. Update `STRUCTURE.md` only if a new surface/dir landed.-Commit explicit paths, push `threews` (the only push target). Report: what's live, GPU quota-state, cost table, and the env flips for production.diff --git a/prompts/gcp-credits/README.md b/prompts/gcp-credits/README.mdindex ba271372d..579620562 100644--- a/prompts/gcp-credits/README.md+++ b/prompts/gcp-credits/README.md@@ -11,7 +11,7 @@ acceptance criteria all pass.| 1 | `01-gcp-foundation.md` | — | — (run first, alone) || 2 | `02-vertex-claude-provider.md` | 01 | 03, 04 || 3 | `03-imagen-activation.md` | 01 | 02, 04 |-| 4 | `04-gpu-workers-deploy.md` | 01 | 02, 03 |+| 4 | `04-gpu-workers-deploy.md` (retired 2026-07-30, verified shipped: six workers + flag-gated routing + cost docs; rig lane shipped as `workers/rig`/model-rig replacing the unirig stub) | 01 | 02, 03 || 5 | `05-catalog-animation-seeding.md` | 04 | 06, 07 || 6 | `06-vanity-inventory.md` | 01 | 05, 07 || 7 | `07-spend-observability.md` | 01 (best after 02–04) | 05, 06 |diff --git a/prompts/quality-bar/09-realism-eval-harness.md b/prompts/quality-bar/09-realism-eval-harness.mddeleted file mode 100644index 29ab717d6..000000000--- a/prompts/quality-bar/09-realism-eval-harness.md+++ /dev/null@@ -1,54 +0,0 @@-# 09: Realism eval harness (measure it or it regresses)--Read `prompts/quality-bar/_shared.md` first. Its operating clause applies: finish 100%, never ask.--## Mission--Build the measurement loop the whole campaign hangs on: a fixed benchmark of prompts, an-automated generate-render-score pipeline using Vertex Gemini vision as judge, and a dashboard-so "did quality go up" is a number, not a vibe. Everything runs on GCP credits.--## Tasks--1. **Benchmark set.** `data/quality-bench/prompts.json`: 20 fixed prompts spanning people- (portrait, full body), animals, food, vehicles, tools, furniture, architecture, nature,- fantasy, and 3 image→3D cases (fixed CC0 reference photos stored alongside). Each entry:- id, prompt, subject class, what realism failure to watch for (plastic skin, melted text,- blob geometry).-2. **Runner.** `scripts/quality-bench.mjs`: for a given lane/tier (or all), fire each prompt- through the REAL `/api/forge` path, poll to GLB, render 3 canonical views (reuse the- headless screenshot harness from the og-image work), and score each view with Vertex- Gemini (`gemini-2.5-pro` vision): photorealism 1-10, geometry integrity 1-10, texture- fidelity 1-10, prompt adherence 1-10, one-line critique. Judge prompt must include the- subject-class failure watchlist. Persist runs to `data/quality-bench/runs/` as JSON- (append-only, one file per run, committed).-3. **Anti-gaming rules.** The judge sees only rendered images, never the prompt-enhancement- text; temperature 0; each image scored twice and averaged; keep the judge prompt in the- repo so scores are comparable across runs.-4. **Dashboard.** A page (internal path is fine, e.g. `/quality-bench`, added to- `data/pages.json` only if made public) rendering the run history: score trends per lane and- subject class, worst-5 gallery with critiques, side-by-side of any two runs. Real fetch of- the committed run JSON, designed states per the platform bar.-5. **Regression gate.** A weekly Cloud Scheduler job runs the bench on the primary lanes and- posts a summary line into the run log; `scripts/quality-bench.mjs --compare latest,previous`- exits nonzero on a >1.0 mean drop so any agent can check for regressions before/after a- forge change. Document that check in the forge docs so future swarm prompts adopt it.-6. **First real runs.** Execute the bench on every live lane at standard and high tiers. This- baseline is the campaign's before picture; later prompts cite it.--## Definition of done--- Bench set, runner, dashboard, scheduler job all live; baseline runs committed.-- Runner is idempotent and resumable (a crashed run resumes, never double-spends).-- README in `data/quality-bench/` explaining how to run, read, and extend it.-- Changelog entry only if the dashboard is public; otherwise internal (no entry).--## Anticipated blockers, pre-answered--- Cost math: 20 prompts x 3 views x 2 scorings is 120 vision calls per lane-tier, trivially- within credits; GPU time dominates and is approved. Do not sample down.-- A lane down mid-run: record the failure as a scored zero with reason, continue; the runner- never aborts a whole run for one lane.-- Judge self-preference drift: scores are comparative over time on fixed inputs; note model- version (`modelVersion` from the response) in each run file so a Gemini upgrade is visible- in the data.diff --git a/prompts/quality-bar/README.md b/prompts/quality-bar/README.mdindex 15716da8c..bde9ee34a 100644--- a/prompts/quality-bar/README.md+++ b/prompts/quality-bar/README.md@@ -27,7 +27,7 @@ measured so it cannot regress (09), with humans as the hardest special case (10)| 06 | 06-forge-ux-flow.md | /forge flagship experience | best after 01, 05 || 07 | 07-design-system-sweep.md | Tokens, states, microinteractions sitewide | none || 08 | 08-mobile-performance.md | Mobile excellence, GLB compression | best after 05 |-| 09 | 09-realism-eval-harness.md | Benchmark + Gemini judge + regression gate | run EARLY for the baseline |+| 09 | 09-realism-eval-harness.md (retired 2026-07-30, verified shipped) | Benchmark + Gemini judge + regression gate | run EARLY for the baseline || 10 | 10-avatar-likeness-irl-people.md | IRL people: likeness, hands, rig, AR | best after 02, 04 |Run 09 first (baseline), then 01/04/05/07 in parallel (no dependencies), 02/03 as quota lands,diff --git a/prompts/roadmap/00-README.md b/prompts/roadmap/00-README.mdindex 9503930a6..131263ab9 100644--- a/prompts/roadmap/00-README.md+++ b/prompts/roadmap/00-README.md@@ -73,7 +73,7 @@ splatting, PBR/restyle, scene layout, Solana minting, embed/OG. Each roadmap pro7. `07-new-input-modalities.md` — sketch→3D, photo→avatar, multi-image→3D, voice→scene. New on-ramps into generation.### Track 3 — New ways to create & use (3D + crypto + AI)-8. `08-crypto-native-creation.md` — mint generated 3D as on-chain assets with signed provenance; token-gated/premium generation via x402; $THREE utility; royalties.+8. `08-crypto-native-creation.md` (retired 2026-07-30, all five tasks verified shipped, see git history): mint generated 3D as on-chain assets with signed provenance; token-gated/premium generation via x402; $THREE utility; royalties.9. `09-creator-marketplace-remix.md` — gallery, remix, discovery, creator profiles, leaderboards (build on the Loom gallery + launches feed).10. `10-agent-native-3d-and-embed.md` — MCP tools + agents that autonomously create and use 3D; embeddable/social distribution so the platform spreads.diff --git a/prompts/roadmap/08-crypto-native-creation.md b/prompts/roadmap/08-crypto-native-creation.mddeleted file mode 100644index c61b6c813..000000000--- a/prompts/roadmap/08-crypto-native-creation.md+++ /dev/null@@ -1,33 +0,0 @@-# Prompt 08 — Crypto-native creation: mint, provenance, gating, royalties (new)--> Paste into a fresh Claude Code chat. Follow CLAUDE.md + `prompts/roadmap/00-README.md`. Run `npm run gate` before and after.--## Context-Crypto rails already exist: `contracts/` (ERC-8004 identity, skill-license SPL NFTs, agent-invocation), `packages/provenance-mcp/` (append-only signed on-chain-verifiable action log), the launches feed (`/api/pump/launches`, `pump_agent_mints`), and x402 (USDC + $THREE) settlement. Connect these to 3D creation so assets become ownable, provable, and monetizable.--## Objective-Let creators turn a generated 3D asset into an **owned, provenance-backed, optionally-monetized** on-chain asset — using $THREE + USDC only.--## Tasks (new, additive; reuse existing contracts/rails)-1. **Signed provenance for every asset.** On generation, write a signed provenance record (creator, prompt, parent lineage, model hash, timestamp) via `provenance-mcp`. Verifiable, append-only. This underpins authenticity for everything below.-2. **Mint generated 3D on-chain.** A creator opt-in to mint an asset as an SPL NFT (reuse the skill-license SPL NFT pattern as the reference implementation) referencing the GLB + provenance. Real mint on the existing chain config; clear cost disclosure; never auto-mint.-3. **Token-gated / premium generation.** Add optional gating where premium tiers, higher quality, or exclusive styles require $THREE holdings or an x402 payment. Generic, runtime-supplied gating — $THREE is the only coin referenced; USDC for settlement. The free TRELLIS lane stays free and ungated.-4. **Royalties on remix.** When someone mints/derives from another creator's published asset, route a royalty split to the original via x402 (align with prompt 06/09 lineage). Real settlement, real split math, hard caps.-5. **Launches integration.** Surface minted/created 3D assets in the existing launches/agent-profile records pattern (the product-feature directories CLAUDE.md explicitly allows). Do not hardcode or promote any non-$THREE mint.--## Non-negotiables-- **$THREE is the only coin** referenced anywhere in code, copy, or metadata. USDC is settlement only. No other token, ever. `grep` to prove it.-- Minting/payments are opt-in with disclosure; no surprise on-chain writes. Spend/mint caps enforced.-- Reuse existing contracts/programs; do not deploy a parallel system without justification.--## Verification-- Generate → write provenance → (opt-in) mint an SPL NFT on the configured chain; paste the on-chain reference. Verify provenance is queryable.-- A gated premium generation requires $THREE/x402 and the free lane stays free.-- A remix mint routes a real royalty split (paste settlement ref); caps enforced.-- `grep -ri` for any non-$THREE token across changed files → zero. `npm run gate` green. Changelog + `npm run build:pages`.--## Definition of done-- Provenance on every asset; opt-in on-chain minting; opt-in $THREE/x402 gating with a free lane preserved; remix royalties with caps — all real, all $THREE-only.--## Hand-off-Report the provenance format, mint flow + on-chain refs, gating model, and royalty logic. Commit/push only if asked; `git push threews main` is the only push target.diff --git a/prompts/robinhood-chain/00-INDEX.md b/prompts/robinhood-chain/00-INDEX.mdindex ea61042d2..7b665a1a2 100644--- a/prompts/robinhood-chain/00-INDEX.md+++ b/prompts/robinhood-chain/00-INDEX.md@@ -20,7 +20,7 @@ independent and can run concurrently. Every agent reads `_shared.md` first, then| [03-sdk-advanced-wrapper.md](03-sdk-advanced-wrapper.md) | Advanced toolkit (`hoodkit`) | `robinhood/hoodkit/` || [04-market-data-api.md](04-market-data-api.md) | Hosted market-data API + x402 | `robinhood/hood-api/` || [05-x402-usdg-rail.md](05-x402-usdg-rail.md) | x402 USDG middleware + facilitator | `robinhood/hood402/` |-| [06-mcp-servers.md](06-mcp-servers.md) | MCP servers (data + trading) | `robinhood/hood-mcp/` |+| 06-mcp-servers.md (retired 2026-07-30, verified shipped: [email protected] on npm, 13/13 tests green; owner residuals: faucet-funded swap hash, GitHub Pages enable) | MCP servers (data + trading) | `robinhood/hood-mcp/` || [11-toolkit-cli.md](11-toolkit-cli.md) | CLI toolkit (`hood-cli`) | `robinhood/hood-cli/` || [14-wallet-connect-kit.md](14-wallet-connect-kit.md) | Wallet & onboarding kit (`hood-connect`) | `robinhood/hood-connect/` || [15-tokenlist.md](15-tokenlist.md) | Canonical token list (`hood-tokenlist`) | `robinhood/hood-tokenlist/` |diff --git a/prompts/robinhood-chain/06-mcp-servers.md b/prompts/robinhood-chain/06-mcp-servers.mddeleted file mode 100644index 0fbab48b4..000000000--- a/prompts/robinhood-chain/06-mcp-servers.md+++ /dev/null@@ -1,51 +0,0 @@-# 06 — MCP servers: `hood-mcp` (chain data + trading for AI agents)--Read `prompts/robinhood-chain/_shared.md` first. Requires Wave 1 core SDK-(`file:../robinhood-chain-sdk`).--## Mission-Build `robinhood/hood-mcp/` — production MCP servers for Robinhood Chain. Robinhood's own MCP-covers only their US brokerage; the chain itself has just two 0-star read-only hobby MCPs.-Ours is the productized one: full data surface + a guarded trading surface. npm `hood-mcp`-(fallbacks: `hoodchain-mcp`, `robinhood-chain-mcp-server`).--## Deliverables — two servers, one package--1. **`hood-mcp` (data server, zero-config, read-only)** — stdio + streamable-HTTP transports,- built on `@modelcontextprotocol/sdk` (use the current SDK — check npm for the latest major):- - `list_stock_tokens`, `get_stock_quote` (Chainlink + DEX price + premium),- `get_portfolio` (multiplier-correct), `get_coin` / `list_trending_coins`,- `get_recent_launches`, `watch_launches` (streamable), `get_chain_stats`,- `search_token` (symbol/name/address via registry + Blockscout).- - Every tool: precise JSON schema, one-line description an LLM can route on, real error- messages. No API key required — public RPC default, `ALCHEMY_KEY` env optional.-2. **`hood-mcp/trading` (wallet server, explicitly opt-in)** — separate entry point, requires- `ROBINHOOD_CHAIN_PRIVATE_KEY` + `HOOD_MCP_ENABLE_TRADING=1`:- - `get_swap_quote`, `execute_swap` (memecoins; Stock Token buys additionally require- `HOOD_MCP_ACKNOWLEDGE_ELIGIBILITY=1` per `_shared.md`), `transfer_usdg`, `get_my_portfolio`.- - Hard spend caps via `HOOD_MCP_MAX_SPEND_USDG` (per-call and per-session), every mutating- tool returns the simulation result and requires a `confirm: true` argument round-trip.-3. **Registry listings** — prepare (don't submit) the metadata for the MCP registries the- ecosystem actually uses (modelcontextprotocol registry `server.json`, Smithery config), plus- Claude Desktop / Claude Code / Cursor install snippets in the README — exact, tested JSON.-4. **Optional x402 monetization seam** — if `robinhood/hood402` exists when you run, add a- config flag that paywalls the expensive data tools (history, firehose) using its middleware- on the HTTP transport; otherwise leave a documented seam. Free tools stay free either way.--## Requirements-- Vitest: tool-schema validation tests + a scripted MCP client (SDK's client) exercising every- tool for real: data tools against mainnet, trading tools against testnet 46630 with faucet- funds — a REAL `execute_swap` round-trip (simulate → confirm → receipt) with tx hash pasted- (if faucet funding is still owner-blocked, prove through simulation and say so plainly).-- `docs/` static site per `_shared.md`: landing shows a real Claude Code session transcript- (run it yourself with the local server via `claude mcp add`) doing "what's AAPL trading at- on-chain and what's the premium?" — the answer with live numbers is the screenshot. Install- matrix (Claude Code / Desktop / Cursor / any stdio client), tool reference, safety model page.-- README: 60-second install per client, both servers, env table, safety model.--## Done checklist-- [ ] Every tool exercised by the scripted client with real outputs in the report.-- [ ] Real testnet swap through the trading server (hash in report) or explicit funding-blocked- status with simulation evidence. Spend-cap + confirm-gate tests green.-- [ ] Claude Code session actually run against the local build; transcript captured for docs.-- [ ] `npm pack` clean; registry metadata validates; report lists owner actions (registry submissions).diff --git a/prompts/user-value/00-INDEX.md b/prompts/user-value/00-INDEX.mdindex 129c02fdf..e685ae176 100644--- a/prompts/user-value/00-INDEX.md+++ b/prompts/user-value/00-INDEX.md@@ -7,7 +7,7 @@ user *return*. Every agent reads `_shared.md` first, then its prompt. Run orderwaves consume earlier waves' output. Within a wave, prompts are independent and can runconcurrently.-> DO NOT DELETE PROMPT FILES — even after their work ships. Only the owner removes prompts.+> Retirement follows the policy in [../README.md](../README.md): a work order is deleted only after its deliverables are verified shipped in the codebase and inbound code references are rewritten. Partial or blocked work orders stay.## Wave 1 — foundation (run first, alone)| Prompt | Feature | Touches |diff --git a/prompts/user-value/02-activity-feed.md b/prompts/user-value/02-activity-feed.mddeleted file mode 100644index 2a609f08c..000000000--- a/prompts/user-value/02-activity-feed.md+++ /dev/null@@ -1,51 +0,0 @@-# 02 — Real activity feed--Read `prompts/user-value/_shared.md` first. It is binding. Depends on wave 1-(`01-creator-profile.md`) for the creation-aggregation endpoint — read what it shipped before-starting.--## Why this matters--`pages/community.html` is a static card-link grid with no dynamic content. `pages/feed.html`-exists but its data source needs verification — it may be a genuine half-built start. Neither-gives a user a reason to check back: "what happened since I was last here?" This is the single-biggest lever for daily-return behavior identified in the audit.--## Mission--Turn `feed.html` into a real, live activity feed of platform creation events, and turn-`community.html` from a static link grid into a page that surfaces that activity.--## Tasks--1. **Audit `pages/feed.html` fully** — read all 381 lines, trace what API it calls (if any), and- determine whether it's dead, partially wired, or fully wired to fake/empty data. Report this- precisely before changing anything.-2. **Audit `api/remix-feed.js` fully** (196 lines) — it's an existing remix/creation feed- backend. Determine what events it already emits and whether it can be the feed's data source- directly, or needs extending to cover more event types (new forges, new dioramas, new- launches, new avatars — not just remixes).-3. **Build/extend the feed endpoint** to emit a real, paginated, reverse-chronological stream of- platform events: creation (forge/diorama/restyle), launch, remix, and (once wave 2's- `03-social-graph.md` ships — coordinate via a shared event shape, don't block on it) follow- events. Each event: actor (linking to their profile per `01-creator-profile.md`), action,- target (linking to the live asset), timestamp.-4. **Wire `feed.html`** to render this stream: infinite scroll or paginated, real-time-ish- (poll or SSE — match whatever real-time pattern already exists elsewhere in the codebase,- e.g. check `src/social/` or `/play` presence code before inventing a new one).-5. **Rebuild `community.html`** from a static grid into a genuine community page: a trending/- recent activity module (reuses the feed endpoint), plus whatever the static grid currently- links to that's still worth keeping (audit its existing links before deleting them).-6. **Filters.** At minimum: all activity vs. "people I follow" (stub gracefully if wave 2's- social graph hasn't shipped yet — build the filter UI, no-op it to "all" with a visible note- in the report, not a broken feature).--## Done checklist--- [ ] `feed.html` renders real events from real platform activity, verified by triggering a- real creation (e.g. forge a test model) and confirming it appears in the feed within a- reasonable delay.-- [ ] `community.html` no longer static — shows live data.-- [ ] Every event in the feed links to both the actor's profile and the created asset.-- [ ] Designed empty state for a feed with zero events for a new/quiet account.-- [ ] Report exactly what `feed.html`'s prior state was (dead/partial/wired) and what changed.diff --git a/prompts/user-value/04-notifications.md b/prompts/user-value/04-notifications.mddeleted file mode 100644index a346081de..000000000--- a/prompts/user-value/04-notifications.md+++ /dev/null@@ -1,51 +0,0 @@-# 04 — Notification center--Read `prompts/user-value/_shared.md` first. It is binding. Can run concurrently with wave 2-siblings; consumes event shapes documented by `02-activity-feed.md` and `03-social-graph.md` if-they've shipped, otherwise define the shape yourself and note it in your report.--## Why this matters--DMs, remixes, royalty payouts, and quest completions already happen server-side with zero way-for a user to learn about them without polling every page manually. `notifications` doesn't-appear anywhere in `data/pages.json`. This is a pure retention gap: real value already being-created (someone remixed your model, you earned a royalty) is currently invisible.--## Mission--Ship a real notification system: a bell/inbox UI reachable from every logged-in page, backed by-a real notification store, populated by real platform events.--## Tasks--1. **Audit existing event sources.** Find every place the platform already knows something- notification-worthy happened but doesn't tell the user: remix events (`api/remix-feed.js`),- royalty payouts, DM receipt (`src/friends.js`/`src/social/`), quest/leaderboard milestones,- coin launch fills, follow events (from `03-social-graph.md`). List them precisely in your- report before building.-2. **Storage.** A `notifications` table/API: recipient, type, actor, target, read/unread state,- created_at. Check for an existing partial implementation before creating a new table — search- for `notification` across `api/` and any `.sql`/migration files first.-3. **Write path.** Wire each real event source from task 1 to insert a notification. Don't build- a generic "emit anything" bus if the codebase has no event bus already — direct inserts at- the point each event already happens are fine and simpler.-4. **Read path + UI.** A bell icon with unread count in the site's persistent nav (find the- shared header/nav component — do not duplicate it per-page), opening a dropdown or dedicated- `pages/notifications.html` listing recent notifications, each linking to its target (the- remix, the DM thread, the profile that followed you). Mark-as-read on view/click.-5. **Delivery cadence.** In-app is required. If the codebase already has an email or push- channel wired anywhere (check for existing transactional email usage), route high-value- notification types (royalty payout, remix) through it too — don't build a new delivery- channel from scratch if this is a nice-to-have without existing infra; note the gap in your- report instead.-6. **Preferences.** At minimum a per-type mute toggle so notification volume doesn't become- noise — store it, respect it in the write path.--## Done checklist--- [ ] Triggering a real event (e.g. a real remix, a real follow from `03-social-graph.md`)- produces a real notification visible in the bell UI within a reasonable delay.-- [ ] Unread count is accurate and clears on read.-- [ ] `pages/notifications.html` (or equivalent) registered in `data/pages.json`.-- [ ] Mute preference persists and is respected.-- [ ] Report which event sources from task 1 got wired and which didn't (with reasons).diff --git a/public/README.md b/public/README.mdnew file mode 100644index 000000000..b77c93deb--- /dev/null+++ b/public/README.md@@ -0,0 +1,18 @@+# public/++Vite's static asset root. Everything here is copied verbatim into `dist/` at build time (`npm run build`) and served by production exactly as-is: no bundling, no hashing, no transformation. That is the difference from [../pages/](../pages/README.md), whose HTML files are Vite build inputs that get processed, and from [../src/](../src/README.md), which holds the bundled application modules.++## What belongs here++- **Static pages that must ship byte-for-byte.** Some standalone pages live here instead of `pages/` because they need to bypass the bundler (for example `watch.html`, `404.html`, `500.html`, `agent-passport.html`, and the `cookbook/` notebook page). They still need a `vercel.json` rewrite to get a clean URL; see the routing walkthrough in [../pages/README.md](../pages/README.md).+- **Brand and platform assets**: `brand/` (logo marks, press assets), icons, Open Graph images.+- **Prebuilt vendor bundles and loose page scripts** that pages reference with plain `<script src>` tags rather than module imports.+- **Data-like static directories** consumed at runtime: `animations/`, `avatars/`, `accessories/`, `badges/`, plus the generated changelog outputs (`changelog.json`, `changelog.xml`, and the rendered pages under `changelog/`).+- **Per-surface asset folders** (`admin/`, `assistant/`, `concierge/`, `dashboard-next/`, ...) holding CSS and media for their matching pages.++## Rules++- Nothing here is processed, so nothing here can use bare module imports, TypeScript, or anything a browser cannot run directly.+- A file placed here is public the moment it deploys. No secrets, no drafts, no scratch output.+- Generated artifacts (for example the changelog feeds under `changelog/` written by `npm run build:pages`) are regenerated by their build steps; edit the source, not the output.+- Adding a new user-facing page? Prefer `pages/` unless it genuinely must skip the bundler, and register it in `data/pages.json` either way.diff --git a/scripts/embed-gate-e2e-demo.mjs b/scripts/embed-gate-e2e-demo.mjsindex 30f7d6d02..5cc27cae6 100644--- a/scripts/embed-gate-e2e-demo.mjs+++ b/scripts/embed-gate-e2e-demo.mjs@@ -1,4 +1,5 @@-// One-off evidence script for prompts/store-submissions/18-token-gated-3d-embeds.md —+// One-off evidence script for the store-submissions campaign, prompt 18+// (token-gated 3D embeds; retired, see git history).// NOT part of the shipped feature. Drives the REAL api/embed/gate-create.js,// api/embed/gate-verify.js, and api/embed/resolve.js handlers (as real Node// request/response objects, not mocks) against the real dev database and realdiff --git a/scripts/rh-lobby-click-e2e.mjs b/scripts/rh-lobby-click-e2e.mjsindex 65a955675..dc87ed266 100644--- a/scripts/rh-lobby-click-e2e.mjs+++ b/scripts/rh-lobby-click-e2e.mjs@@ -1,4 +1,5 @@-// One-off evidence script for prompts/robinhood-chain/13-threews-play.md —+// One-off evidence script for the robinhood-chain campaign, work order 13+// (three.ws /play integration; retired, see git history). Covers the// full user journey: /worlds lobby -> Robinhood Chain tab -> click a real// coin card -> lands on /play with the coin-flavored biome active.diff --git a/scripts/rh-play-e2e-demo.mjs b/scripts/rh-play-e2e-demo.mjsindex 2591aeabd..37b1dca86 100644--- a/scripts/rh-play-e2e-demo.mjs+++ b/scripts/rh-play-e2e-demo.mjs@@ -1,4 +1,5 @@-// One-off evidence script for prompts/robinhood-chain/13-threews-play.md.+// One-off evidence script for the robinhood-chain campaign, work order 13+// (three.ws /play integration; retired, see git history).// Drives a real headless Chromium against the local server/index.mjs (built// dist/ + real api/** handlers, no mocks) to verify the Robinhood Chain /play// integration end to end: the /worlds lobby renders the Robinhood Chain tab,diff --git a/scripts/verify-w04-boutique-setup.mjs b/scripts/verify-w04-boutique-setup.mjsindex 2195e30a6..a06126b28 100644--- a/scripts/verify-w04-boutique-setup.mjs+++ b/scripts/verify-w04-boutique-setup.mjs@@ -5,8 +5,9 @@// boutique-affordable balance to it, and writes the fixture (keys + env) to// disk for the server + Playwright runs to consume.//-// Targets a local `solana-test-validator` (started separately — see-// PORT-CHECKLIST/W04 brief) rather than the public devnet faucet: the public+// Targets a local `solana-test-validator` (started separately; see the+// W-world-online program's W04 brief and port checklist in git history)+// rather than the public devnet faucet: the public// faucet is globally rate-limited ("airdrop limit today / faucet has run// dry" — hit repeatedly during this verification, unrelated to this box) and// a shared box running many concurrent agents makes that worse. A localdiff --git a/src/README.md b/src/README.mdindex 8a720273b..fe02ce5e3 100644--- a/src/README.md+++ b/src/README.md@@ -1,8 +1,59 @@-# Source Code+# src/-This directory contains the main source code for the 3D-Agent application.+Frontend source for three.ws: roughly 600 flat ES modules plus 60+ subsystem directories, built by Vite into the static site (`npm run build`) and the embeddable `agent-3d` library (`npm run build:lib`). Every page under [../pages/](../pages/README.md) loads one or more entry modules from here; [../vite.config.js](../vite.config.js) declares those entries explicitly.-## Structure+## How this directory is organized-The source code is organized into the following directories:-...+The convention is one module per page surface, named after the route it powers, living flat at the root of `src/`. A page named `pages/tracker.html` loads `src/tracker.js`; its styles, when not inline, sit next to it as `tracker.css`. When a surface outgrows a single file it graduates into a subdirectory of the same name (`src/agora/`, `src/scene-studio/`, `src/mission-control/`).++Related surfaces share a filename prefix, so the flat listing reads as clusters. The largest:++| Prefix | What it covers |+|---|---|+| `agent-screen-*` | The live agent screen: casting stage, control handoff, diary, treasury HUD, reputation, world view. Doc: [agent screen control](../docs/agent-screen-control.md). |+| `agent-skills-*` | The skills system UI: catalog, editor, A2A wiring. Doc: [agent skills](../docs/agent-skills.md). |+| `agent-*` (rest) | Agent surfaces: detail pages, editing, memory, naming, wallets, embeds, identities. |+| `walk-companion-*`, `walk-embed-*` | The corner companion and its third-party embed build. Doc: [the agent shell](../docs/agent-shell.md). |+| `avatar-studio-*` | Avatar Studio page modules. Doc: [avatar studio](../docs/avatar-studio.md). |+| `admin-*` | Internal control panels served under `/admin/*`. |+| `ui-juice-*` | The shared game-feel animation library. Doc: [ui-juice](../docs/ui-juice.md). |+| markets (`radar`, `screener`, `signals`, `watchlist`, `yields`, `stablecoins`, ...) | The trading and market-data surfaces. Doc: [trading surfaces](../docs/trading-surfaces.md). |++## Subsystem directories++The subdirectories hold multi-module subsystems. The ones you will touch most:++- `lib/` and `shared/`: cross-surface utilities (sanitized Markdown, toasts, fuzzy search, retry, caches). Import from here instead of hand-rolling; the catalog is in [shared utilities](../docs/shared-utilities.md).+- `components/`: reusable DOM components used across pages.+- `shell/`: the persistent agent shell (header, command palette, companion) that survives navigation on shell-enabled pages.+- `three/`, `loaders/`, `procedural/`, `physics/`: the Three.js rendering stack, glTF/GLB loading, procedural animation (gaze, foot placement), and physics.+- `viewer/`, `widget/`, `widgets/`: the standalone model viewer and embeddable widgets.+- `solana/`, `eth/`, `bnb/`, `onchain/`, `wallet/`: chain integrations. Solana is the home chain; EVM directories are secondary surfaces.+- `pump/`, `launchpad/`, `mint/`: coin launch surfaces over the platform's own launch records.+- `studio/`, `scene-studio/`, `forge-studio/`, `editor/`: the creation studios.+- `agora/`, `city/`, `play/`, `game/`: the 3D worlds.+- `auth/`, `permissions/`, `proof-of-custody/`: sign-in, permission model, custody verification.+- `pages/`: page-level orchestration modules that do not fit the flat convention.++## Two build targets++`vite.config.js` builds two targets from this tree, controlled by `TARGET`:++- `TARGET=app` (default, `npm run build`): the full site into `dist/`.+- `TARGET=lib` (`npm run build:lib`): `dist-lib/agent-3d.js`, the ES module + UMD bundle third-party sites load for `<agent-3d>` embeds.++Code that ships in the lib target must stay compatible with old embedded WebViews; see the polyfill note at the top of `vite.config.js` before using new runtime APIs.++## Conventions++- Vanilla ES modules. No framework. DOM APIs and Three.js directly.+- One surface, one entry module, named after its route.+- Heavy dependencies are lazy-loaded with dynamic `import()` so first paint stays fast.+- Animation and rig logic lives in `glb-canonicalize.js` and `animation-retarget.js`: any humanoid rig is mapped to the canonical bone set, never a hardcoded rig allowlist.+- Before adding a utility, check `lib/`, `shared/`, and [shared utilities](../docs/shared-utilities.md) for an existing one.++## Related reading++- [STRUCTURE.md](../STRUCTURE.md): maps every product surface to its directory.+- [pages/README.md](../pages/README.md): how a page HTML file becomes a live route (Vite input + route table + registry).+- [docs/architecture.md](../docs/architecture.md): the full system picture.diff --git a/src/bnb-latency.js b/src/bnb-latency.jsindex 4282b06ec..1f14291ff 100644--- a/src/bnb-latency.js+++ b/src/bnb-latency.js@@ -5,7 +5,7 @@// on every tick. No hardcoded "0.45s" anywhere in this file: every number// on screen traces back to the most recent successful probe.//-// See prompts/bnb-chain/17-latency-proof-page.md and 00-CONTEXT.md (verified+// See the bnb-chain campaign, work order 17 (latency proof page; retired, see git history), and 00-CONTEXT.md (verified// fact #3 — 0.45s blocks live; never claim BEP-670's 250ms target).import { escapeHtml as esc, timeAgo } from './shared/coin-format.js';diff --git a/src/bnb.js b/src/bnb.jsindex 344147660..fcdefa9c9 100644--- a/src/bnb.js+++ b/src/bnb.js@@ -5,7 +5,7 @@// probing the real route/API on this deployment. No hardcoded live/coming-soon// flags: a card lights up the moment its check target starts resolving.//-// See prompts/bnb-chain/19-bnb-hub-page.md and 00-CONTEXT.md (verified/refuted+// See the bnb-chain campaign, work order 19 (BNB hub page; retired, see git history), and 00-CONTEXT.md (verified/refuted// claims list — every sentence on this page traces back to that list).import { escapeHtml as esc, timeAgo } from './shared/coin-format.js';diff --git a/src/game/camera-modes.js b/src/game/camera-modes.jsindex 945ce9a14..7b5f8d5ac 100644--- a/src/game/camera-modes.js+++ b/src/game/camera-modes.js@@ -1,7 +1,7 @@// Camera modes — a shared 4-mode chase camera (follow / cinematic / firstperson// / topdown), extracted from `/walk` (W01: open-world foundation) so `/play`// gets the same camera system instead of a second, divergent implementation.-// See prompts/agent-briefs/W-world-online/PORT-CHECKLIST.md P1.4.+// See the W-world-online program port checklist, item P1.4 (retired; see git history).//// `computeCameraForMode()` is the pure per-frame pose math (no allocation// beyond a shared scratch, no side effects) — both `walk.js` anddiff --git a/tests/api/activity-feed.test.js b/tests/api/activity-feed.test.jsindex dca8183b4..f87f5f4b3 100644--- a/tests/api/activity-feed.test.js+++ b/tests/api/activity-feed.test.js@@ -1,6 +1,7 @@// Unit tests for the merge/render logic of GET /api/users/me/feed, covering// both the scope=all (platform-wide, no-auth) path and the scope=following-// (personal, auth-required) path added by prompts/user-value/02-activity-feed.md,+// (personal, auth-required) path added by the user-value campaign, work order 02+// (activity feed; retired, see git history),// across every event kind the endpoint emits: avatar, agent, coin, model,// world, restyle, follow (see tests/api/users-follow.test.js for the// follow-graph-specific contract this file deliberately leaves alone).diff --git a/tests/api/notifications-center.test.js b/tests/api/notifications-center.test.jsindex 36169a181..fd27befe2 100644--- a/tests/api/notifications-center.test.js+++ b/tests/api/notifications-center.test.js@@ -1,5 +1,5 @@// Unit tests for the notification center's read path-// (prompts/user-value/04-notifications.md task 4):+// (user-value campaign, work order 04 task 4; retired, see git history):// GET /api/notifications -> api/notifications/index.js// POST /api/notifications/read-all -> api/notifications/read-all.js//diff --git a/tests/api/notify-in-app-gate.test.js b/tests/api/notify-in-app-gate.test.jsindex d326d9e17..cc16cb7a0 100644--- a/tests/api/notify-in-app-gate.test.js+++ b/tests/api/notify-in-app-gate.test.js@@ -4,7 +4,7 @@// rendered a per-category `in_app` toggle, but the bell row used to be inserted// unconditionally, so muting a category did nothing: the notification still// landed in the inbox and still counted toward unread. These tests pin the fix-// from prompts/user-value/04-notifications.md task 6 ("store it, respect it in+// from the user-value campaign, work order 04 task 6 ("store it, respect it in// the write path"): the `user_notifications` insert is gated on// channelEnabled(prefs, type, 'in_app'), independently of every other channel.//diff --git a/tests/api/users-follow.test.js b/tests/api/users-follow.test.jsindex 2fbb99a35..e3bc18c35 100644--- a/tests/api/users-follow.test.js+++ b/tests/api/users-follow.test.js@@ -207,9 +207,9 @@ describe('GET /api/users/:username/follows', () => {});// GET /api/users/me/feed?scope=following is the "people I follow" activity-// filter that 02-activity-feed.md's mission depends on — and it's under active-// concurrent development by that prompt's agent (its query set and response-// shape changed shape mid-session while this file was being written). We only+// filter that the user-value campaign's work order 02 (activity feed; shipped+// and retired, see git history) depended on. Its query set and response shape+// changed mid-session while this file was being written, so we only// assert the follow-graph-specific contract here: default scope requires auth,// and the zero-following case degrades to an empty (never a crashed) feed. The// merge/render logic for avatars/agents/coins/models/worlds/follows itself isdiff --git a/tests/bnb-hub-helpers.test.js b/tests/bnb-hub-helpers.test.jsindex b06888df9..6d1bc1ff5 100644--- a/tests/bnb-hub-helpers.test.js+++ b/tests/bnb-hub-helpers.test.js@@ -1,6 +1,6 @@// Pure helpers behind the /bnb hub page: block-time formatting and the// track-availability gating that decides "live" vs "coming soon" per card.-// See prompts/bnb-chain/19-bnb-hub-page.md — "Pure helpers (stat formatting,+// See the bnb-chain campaign, work order 19 (BNB hub page; retired, see git history): "Pure helpers (stat formatting,// track-availability gating) in tests/".import { describe, expect, it } from 'vitest';diff --git a/tests/bnb-latency-helpers.test.js b/tests/bnb-latency-helpers.test.jsindex 903339ac5..1322130b9 100644--- a/tests/bnb-latency-helpers.test.js+++ b/tests/bnb-latency-helpers.test.js@@ -1,7 +1,7 @@// Pure helpers behind the /bnb-latency live block-race page: interval// averaging from raw block timestamps, lane state derivation, sparkline bar// normalization, and the honest measured-vs-measured speedup ratio. See-// prompts/bnb-chain/17-latency-proof-page.md — "Pure interval-averaging ++// the bnb-chain campaign, work order 17 (latency proof page; retired, see git history): "Pure interval-averaging +// sparkline math in tests/ (feed block timestamps → correct rolling// average)".diff --git a/tests/bnb-vault-fsm.test.js b/tests/bnb-vault-fsm.test.jsindex 82395870e..8942333f9 100644--- a/tests/bnb-vault-fsm.test.js+++ b/tests/bnb-vault-fsm.test.js@@ -2,7 +2,7 @@// backing the /vault page (prompt 12). No DOM, no network: every branch of// deriveListingState/nextFlowStep is exercised table-style so the UI's// buy → settle → unlock progression is provably correct independent of-// mounting the page. See prompts/bnb-chain/12-vault-ui.md's "Tests" section.+// mounting the page. See the bnb-chain campaign, work order 12's (vault UI; retired, see git history) "Tests" section.import { describe, it, expect } from 'vitest';import { deriveListingState, nextFlowStep, formatBnbAtomic, truncateAddress, pollDelayMs, SALE_STATUS, FLOW_STEPS } from '../src/vault-fsm.js';