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
Add product docs, i18n locale expansion, and micro-buy/RPC updates
nirholas0901ede9efca
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0c6e048e0..fbd0b5807 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,7 +6,45 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr## 2026-07-18+- **Docs · Agent Galaxy** (`/docs/galaxy`) — Every published agent embedded by IBM Granite on watsonx.ai, projected into a navigable 3D constellation with natural-language semantic search.+- **Docs · Agent Genome** (`/docs/genome`) — Breed two agents into a provably-inherited child: recombined brain, voice, body, and on-chain skill licenses, each breeding event seed-recorded with a verifiable family tree.+- **Docs · Agent Studio** (`/docs/agent-studio`) — Author an agent's brain, memory, body, money, and skills in one place, beside a persistent live 3D avatar that updates everywhere as you edit.+- **Docs · Alpha Co-pilot** (`/docs/alpha-copilot`) — Your 3D agent reads a real pump.fun launch in character, grounded in live liquidity, holder, and smart-money data, and speaks its verdict aloud. Fabricated figures are rejected; the owner acts only within server-enforced spend limits.+- **Docs · Animation Studio** (`/docs/animation-studio`) — Pose any avatar or the built-in mannequin with FK/IK, keyframe a timeline, preview live, and export an animated GLB or clip JSON. Save clips to your account and list them for sale in USDC.+- **Docs · AR Studio** (`/docs/ar-studio`) — Place any number of 3D models and avatars into one live camera scene: model sources, the WebXR/passthrough/desktop rendering ladder, gestures, shared live rooms, and shareable arrangements.+- **Docs · Avatar Studio** (`/docs/avatar-studio`) — Build a rigged 3D avatar from scratch with no selfie: choose a base body, sculpt face and body morphs, add outfits and accessories, and export a GLB.+- **Docs · Coin Autopilot** (`/docs/autopilot`) — A hands-off token cockpit: set buyback-and-burn and holder-distribution rules with USDC floors and guardrails, and let your agent run the coin autonomously.+- **Docs · Coin Clash** (`/docs/clash`) — Token-gated community warfare: every coin community is an army. Hold the coin, enlist, and rally for your faction in timed on-chain battles.+- **Docs · Coin Radar** (`/docs/radar`) — Live pump.fun launch intelligence: every new coin scored in its first 90 seconds for bundle vs organic, wallet concentration, dev behaviour, and risk flags.+- **Docs · Cosmos (living worlds)** (`/docs/cosmos`) — How NVIDIA Cosmos renders a photoreal video world behind a transparent 3D avatar: the async generation job, preview and download, and the designed fallback.+- **Docs · Daily Forge** (`/docs/daily-forge`) — A new 3D creative challenge every day: a deterministic theme, the free no-signup forge lane, a localStorage streak with milestones, a community strip, and an AR handoff.+- **Docs · Diorama (text to world)** (`/docs/diorama`) — How one sentence becomes an explorable 3D diorama: an LLM composes a placed scene, each object is forged to a real GLB and assembled live, then saved to a public gallery permalink, exported to Scene Studio, or taken into AR.+- **Docs · Fact Check** (`/docs/fact-check`) — Sourced fact-checking with cryptographic content attestations, a published accuracy benchmark, and a free daily quota then pay-per-check via x402.+- **Docs · Forge (text & image to 3D)** (`/docs/forge`) — How the Forge turns a text prompt, photos, or a sketch into a downloadable textured 3D model (GLB): the free-first engine grid with live health status, input modes, output formats, job resume, and background generation.+- **Docs · Guardian console** (`/docs/guardian`) — Recover and inherit agent wallets through a threshold-approved, time-locked process that never exposes a private key.+- **Docs · Image to 3D** (`/docs/image-to-3d`) — Turn 1 to 4 photos of an object into a textured GLB on the free self-hosted reconstruction lane. When to use it versus Selfie to Avatar for faces, the multi-view flow, and the API.+- **Docs · Instant Agent Genesis** (`/docs/genesis`) — A prompt or a selfie becomes a rigged 3D AI agent with its own custodial Solana and EVM wallets and an optional on-chain identity, in under a minute.+- **Docs · Integrations** (`/docs/integrations`) — The catalog of one-script-tag embeds for any site: 3D avatar viewers, chat agents, walk companions, page narrators, live token widgets, and the MCP server.+- **Docs · Lipsync** (`/docs/lipsync`) — Two in-browser lipsync demos: TTS-driven mouth animation and live-mic viseme detection, both driving an avatar's viseme morph targets in real time.+- **Docs · Mission Control** (`/docs/terminal`) — The keyboard-first pump.fun trading terminal: the launch firehose fused with intel scores, firewall verdicts, and smart-money flow, streaming positions with live PnL, and one-keystroke guarded trading.+- **Docs · Mocap Studio** (`/docs/mocap-studio`) — Drive a 3D avatar's face live from your webcam in the browser: MediaPipe face landmarks mapped to ARKit blendshapes, smoothing, record and replay, and save.+- **Docs · Multi-LLM Brain** (`/docs/brain`) — Send one prompt to Claude, GPT, Qwen, ModelScope, Groq and more at once, with side-by-side streaming and per-model latency and token stats.+- **Docs · Restyle Studio** (`/docs/restyle`) — Re-skin any GLB without regenerating its mesh: 14 PBR material presets, plain-language AI restyle, seeded colorway variants, live metalness and roughness, and a durable revertable version lineage.+- **Docs · Scene Capture (video to point cloud)** (`/docs/capture`) — Turn a phone video of any space into an explorable coloured 3D point cloud with feed-forward reconstruction, tunable sampling parameters, and live WebGL rendering.+- **Docs · Scene Composer** (`/docs/compose`) — Forge props from text, attach them to your avatar's skeleton bones, arrange and scale freely, then export a GLB or save the result as a reusable outfit.+- **Docs · Scene Studio** (`/docs/scene-studio`) — The in-browser three.js editor: import GLBs, arrange with transform gizmos, edit materials and lights, script, and export complete glTF scenes.+- **Docs · Selfie to Avatar** (`/docs/selfie-to-avatar`) — Point your camera at your face and get a rigged 3D avatar in about a minute, free and in the browser. The capture flow, the reconstruction pipeline, and where the avatar goes next.+- **Docs · Signal Marketplace** (`/docs/signals`) — Verified traders publish live entry and exit signals as x402-metered feeds ranked by proven on-chain accuracy; a subscriber agent pays per signal or epoch and auto-mirrors through the guarded path.+- **Docs · Smart Money Radar** (`/docs/smart-money`) — A live first-party reputation graph of every pump.fun wallet: cross each coin's buyers with the coins that actually graduated to surface the wallets that keep picking winners.+- **Docs · Splat viewer (Gaussian avatars)** (`/docs/splat`) — Render photoreal Gaussian-splat and radiance-field avatars in the browser: supported formats (.ply, .splat, .ksplat), client-side decoding, and the engines whose output it displays.+- **Docs · Strategy Objects** (`/docs/strategy-objects`) — Ownable, forkable, leaderboard-ranked trade strategies your agent can equip and run on-chain within your spend policy, plus the Strategy Lab for validation and backtesting.+- **Docs · Talking Avatar Video** (`/docs/talking-avatar-video`) — Pick an avatar, provide an audio track, and render a downloadable lip-synced talking-head MP4 on a server-side worker.+- **Docs · The AGI** (`/docs/agi`) — One autonomous agent that is superhuman at exactly one thing, trading memecoins on pump.fun, and nothing else. Its embodied 3D body, its logged decisions with stated confidence, and its chain-proven record.+- **Docs · Voice Lab** (`/docs/voice-lab`) — Clone your voice from a short browser recording, play it in the TTS playground, and assign it to an agent.+- **Docs · x402 Studio** (`/docs/x402-studio`) — The merchant console for running a paid x402 business: products and pricing, payout and agent wallets, real USDC send and receive with .sol resolution, a storefront and pay-button builder, giving, and security.+- **36 new in-depth feature guides in the docs** — The docs now carry a dedicated, in-depth guide for every major studio and surface that was missing one: the 3D creation studios (Forge, Image to 3D, Diorama, Cosmos, Splat viewer, Scene Capture, Restyle, Scene Studio, Scene Composer, Animation Studio, Avatar Studio, Mocap Studio, Selfie to Avatar, Daily Forge, AR Studio), voice and video (Voice Lab, Lipsync, Talking Avatar Video), agent building (Instant Agent Genesis, Agent Genome, Agent Studio, Multi-LLM Brain, Agent Galaxy, Integrations), and the trading and markets surfaces (Coin Autopilot, Signal Marketplace, the AGI, Alpha Co-pilot, Guardian, Strategy Objects, Mission Control, Smart Money Radar, Coin Radar, Coin Clash, x402 Studio, Fact Check). Each guide explains why the feature exists, how it actually works, a first-time walkthrough, runnable examples, its states and limits, and links to related surfaces. Browse them from the docs sidebar. (`/docs/forge`) `[docs]`- **Image understanding is more reliable across every image host** — The vision endpoint (used to describe and check 3D renders and avatars) now fetches your image itself and hands it straight to the free model, instead of asking the model's server to go fetch the link. Some image hosts block that server-side fetch, which used to push the request onto a paid fallback and, when that fallback was unavailable, fail outright. Now the free lane serves the request regardless of how the image is hosted, so describe/critique calls stop returning errors on perfectly good images. (`/pulse`) `[fix, improvement]`+- **On-chain reads stay smooth when a data provider hits its daily cap** — The platform reads Solana through a prioritized chain of RPC providers and automatically fails over the instant one is throttled. It now recognizes the specific 'daily request limit reached' signal that metered providers return when a plan's daily quota is spent, and parks that provider for the rest of the day instead of re-checking it every few minutes. On-chain data (balances, prices, live trades) keeps flowing through a healthy provider without a stumble, and the failover leaves the retry chatter behind. A dedicated reserve endpoint was also wired in as deep insurance for the rare case the whole free provider pool is down at once. `[infra, improvement]`- **Solana price and trade reads now ride a dedicated premium connection** — Every live Solana read the platform depends on (the $THREE price and bonding-curve, wallet balances, agent trades, and on-chain activity) now goes first through a dedicated premium RPC endpoint that absorbs the load ahead of the shared public providers, then falls back automatically down the full free-provider chain if that endpoint is ever unavailable. In practice that means fewer rate-limit stalls and fewer degraded or stale reads when Solana is busy, without adding a single point of failure: if the premium lane blinks, the free chain still answers. (`/pulse`) `[infra, improvement]`## 2026-07-17diff --git a/api/_lib/solana/connection.js b/api/_lib/solana/connection.jsindex c8e141527..52d05dd83 100644--- a/api/_lib/solana/connection.js+++ b/api/_lib/solana/connection.js@@ -34,6 +34,57 @@ function deriveWsUrl(httpUrl) {.replace(/^http:/, 'ws:');}+// Coerce an env-sourced WebSocket endpoint into a ws(s):// URL that a Connection's+// `wsEndpoint` accepts, or '' when it can't be salvaged. Mirrors normalizeRpcUrl's+// repairs (quote-strip, http(s) → ws(s), scheme-less host → wss) but targets the+// socket scheme instead of http. Anything unsalvageable returns '' so the caller+// falls back to deriving the socket from the primary HTTP endpoint.+export function normalizeWsUrl(raw) {+ let v = (raw ?? '').trim();+ if (!v) return '';+ if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) {+ v = v.slice(1, -1).trim();+ }+ if (!v) return '';++ let candidate = v;+ if (/^https:\/\//i.test(candidate)) candidate = candidate.replace(/^https:/i, 'wss:');+ else if (/^http:\/\//i.test(candidate)) candidate = candidate.replace(/^http:/i, 'ws:');+ else if (!/^wss?:\/\//i.test(candidate)) {+ // Scheme-less: assume wss only for a host-shaped value (has a dot, or+ // localhost[:port]). A bare token is a typo, not a host, so drop it.+ const host = candidate.split(/[/?#]/)[0];+ if (!host.includes('.') && !/^localhost(:\d+)?$/i.test(host)) return '';+ candidate = `wss://${candidate}`;+ }++ let u;+ try {+ u = new URL(candidate);+ } catch {+ return '';+ }+ if (u.protocol !== 'ws:' && u.protocol !== 'wss:') return '';+ return candidate;+}++// The WebSocket endpoint a Connection subscribes on. The ONLY server-side WS consumer+// is the bounded `onLogs` live-trades window in pump-fun-mcp.js (confirms are+// HTTP-polling by design; see solana/confirm.js: web3.js's signatureSubscribe WS+// bypasses the rotating-fetch failover and 429-storms a warm instance). By default the+// socket is derived from the primary HTTP endpoint. A mainnet SOLANA_RPC_WS_URL+// override points that one subscription at a dedicated, stable socket (e.g. a paid+// QuickNode wss lane) instead of the primary HTTP provider, which can rate-limit the WS+// upgrade. Unset → byte-identical to before. Never applied on devnet: the override is a+// mainnet endpoint, and a mainnet socket on a devnet Connection would cross clusters.+export function resolveWsEndpoint(primaryHttpUrl, network = 'mainnet') {+ if (network !== 'devnet') {+ const override = normalizeWsUrl(process.env.SOLANA_RPC_WS_URL);+ if (override) return override;+ }+ return deriveWsUrl(primaryHttpUrl);+}+// True only for a value @solana/web3.js's `new Connection` will accept — a parseable// URL whose protocol is http: or https:. Connection's `assertEndpointUrl` rejects// everything else (ws://, a scheme-less host, junk) by throwing@@ -137,7 +188,11 @@ const _endpointCooldown = new Map();function cooldownMsFor(status, bodyText) {if (status === 429) {- return /max usage reached|-32429|quota|usage limit|credits?\s*exhausted/i.test(+ // "request limit reached" / -32003 is how QuickNode signals a DAILY cap+ // exhausted (HTTP 429 + `{code:-32003,"daily request limit reached - upgrade+ // your account"}`); it means the endpoint is dead for the rest of the day, so+ // park it for the long window instead of re-probing it every 10 minutes.+ return /max usage reached|-32429|-32003|request limit|quota|usage limit|credits?\s*exhausted/i.test(bodyText || '',)? QUOTA_COOLDOWN_MS@@ -319,6 +374,7 @@ const PROVIDER_CAPACITY_CODES = new Set([-32052, // Ankr: key not allowed / forbidden-32005, // node is behind by N slots — a fresher node may answer-32004, // block/slot not available yet — another node may have it+ -32003, // QuickNode: daily/request limit reached (capped), the next lane serves]);// A provider that gates a method behind its paid/registered tier answers with a@@ -341,7 +397,7 @@ function isProviderCapacityError(rpcError) {if (!rpcError || typeof rpcError !== 'object') return false;if (PROVIDER_CAPACITY_CODES.has(rpcError.code)) return true;if (isProviderTierError(rpcError)) return true;- return /too many requests|rate.?limit|quota|usage limit|credits?\s*exhausted|forbidden|api key|unauthor|max usage/i.test(+ return /too many requests|rate.?limit|request limit|quota|usage limit|credits?\s*exhausted|forbidden|api key|unauthor|max usage/i.test(String(rpcError.message || ''),);}@@ -565,7 +621,7 @@ export function solanaConnection({ url = null, commitment = 'confirmed', networkconst primary = endpoints[0] || (net === 'devnet' ? PUBLIC_DEVNET : PUBLIC_MAINNET);return new Connection(primary, {commitment,- wsEndpoint: deriveWsUrl(primary),+ wsEndpoint: resolveWsEndpoint(primary, net),// Never let web3.js run its own 429 backoff loop: with >1 endpoint the// rotating fetch already hides 429s, and with a single endpoint we want to// fail fast to the caller rather than spend seconds retrying a dead lane.diff --git a/api/_lib/token/buyback-math.js b/api/_lib/token/buyback-math.jsindex e72439ba4..56b78b9c8 100644--- a/api/_lib/token/buyback-math.js+++ b/api/_lib/token/buyback-math.js@@ -62,6 +62,21 @@ export function computeSpend(walletUsdcAtomics, { maxUsd, minUsd }) {return { spendAtomics: spend, reason: 'ok' };}+/**+ * Would reserving `needAtomics` on top of `spentAtomics` cross `capAtomics`? Pure,+ * BigInt-exact — the single sizing rule the $THREE micro-buy daily cap is checked+ * against (Redis fast path and DB fallback both defer to it), so the "never spend+ * past the ceiling" guarantee lives in one tested place. A zero/negative need never+ * exceeds; a zero cap always does (except a zero need).+ * @param {bigint|string|number} spentAtomics already reserved today+ * @param {bigint|string|number} needAtomics this reservation+ * @param {bigint|string|number} capAtomics the daily ceiling+ * @returns {boolean}+ */+export function wouldExceedCap(spentAtomics, needAtomics, capAtomics) {+ return BigInt(spentAtomics) + BigInt(needAtomics) > BigInt(capAtomics);+}+/** Share of revenue already deployed to buybacks, clamped to [0,100]. */export function deployedPct(deployedUsd, revenueUsd) {if (!(revenueUsd > 0)) return 0;diff --git a/api/_lib/token/microbuy.js b/api/_lib/token/microbuy.jsindex b156cab0e..19d3a006d 100644--- a/api/_lib/token/microbuy.js+++ b/api/_lib/token/microbuy.js@@ -46,10 +46,35 @@ import {usdToUsdcAtomics,usdcAtomicsToUsd,atomicsToTokens,+ wouldExceedCap,} from './buyback-math.js';const MEMO_PROGRAM_ID = 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr';+// One-time DDL guard per warm instance. The migration owns this table in a real+// deploy; this makes the lane self-healing so the daily-cap DB fallback and the+// ledger never silently no-op on a fresh/behind database (which, combined with a+// Redis outage, would otherwise let the cap fail open).+let _schemaReady = false;+export async function ensureMicrobuySchema() {+ if (_schemaReady) return;+ await sql`+ CREATE TABLE IF NOT EXISTS three_microbuy_runs (+ id uuid primary key default gen_random_uuid(),+ status text not null,+ reason text,+ usdc_spent_atomics bigint not null default 0,+ three_bought_atomics bigint not null default 0,+ price_usd numeric,+ slippage_bps integer,+ buy_signature text,+ created_at timestamptz not null default now()+ )+ `;+ await sql`CREATE INDEX IF NOT EXISTS three_microbuy_runs_created ON three_microbuy_runs (created_at desc)`;+ _schemaReady = true;+}+// ── policy knobs (env, with safe defaults) ──────────────────────────────────/** Execution gate. A run is a recorded no-op unless this is truthy. */@@ -113,29 +138,29 @@ const utcDay = () => new Date().toISOString().slice(0, 10); // YYYY-MM-DD (UTC)const dailyKey = () => `three:microbuy:daily:${utcDay()}`;/**- * DB fallback for today's micro-buy spend when Redis is unavailable — sums the- * confirmed/pending rows so the cap still holds (best-effort; the Redis counter is- * the fast path). Returns atomics.+ * DB sum of today's micro-buy spend (confirmed + pending rows). STRICT: throws on a+ * query fault so the caller can decide whether to fail closed. The read-path+ * wrappers (dailySpentAtomics, hasDailyBudget) swallow the throw; the reserve path+ * treats it as "cap unverifiable" and refuses the buy.*/-async function dbDailySpentAtomics() {- try {- const rows = await sql`- SELECT COALESCE(SUM(usdc_spent_atomics), 0)::bigint AS spent- FROM three_microbuy_runs- WHERE status IN ('confirmed', 'pending') AND created_at >= date_trunc('day', now())- `;- return BigInt(rows[0]?.spent || 0);- } catch {- return 0n;- }+async function dbDailySpentAtomicsStrict() {+ const rows = await sql`+ SELECT COALESCE(SUM(usdc_spent_atomics), 0)::bigint AS spent+ FROM three_microbuy_runs+ WHERE status IN ('confirmed', 'pending') AND created_at >= date_trunc('day', now())+ `;+ return BigInt(rows[0]?.spent || 0);}/**- * Atomically reserve `atomics` of today's budget. Returns { ok, dailySpentAtomics,- * dailyCapAtomics }. When the reservation would cross the daily cap it is rolled- * back and ok:false is returned, so the caller never buys past the ceiling. Redis- * is the fast atomic path; if it is down we fall back to a (racy) DB sum so the cap- * degrades to best-effort rather than failing open.+ * Atomically reserve `atomics` of today's budget. Returns { ok, reason?,+ * dailySpentAtomics, dailyCapAtomics }. When the reservation would cross the daily+ * cap it is rolled back and ok:false is returned, so the caller never buys past the+ * ceiling. Redis is the fast atomic path; if it is down we fall back to a (racy) DB+ * sum. Crucially this FAILS CLOSED: if neither Redis nor the DB can tell us today's+ * spend, the buy is refused (reason:'cap_unverifiable') rather than letting an+ * uncapped flood through — an unbounded real-money spend is the one outcome the cap+ * exists to prevent.*/export async function reserveDailySpend(atomics) {const capAtomics = usdToUsdcAtomics(dailyCapUsd());@@ -151,16 +176,23 @@ export async function reserveDailySpend(atomics) {}if (total > capAtomics) {try { await redis.incrby(key, -Number(need)); } catch { /* best-effort rollback */ }- return { ok: false, dailySpentAtomics: total - need, dailyCapAtomics: capAtomics };+ return { ok: false, reason: 'daily_cap_reached', dailySpentAtomics: total - need, dailyCapAtomics: capAtomics };}return { ok: true, dailySpentAtomics: total, dailyCapAtomics: capAtomics };} catch {- /* fall through to DB */+ /* Redis faulted — fall through to the DB fallback below. */}}- const spent = await dbDailySpentAtomics();- if (spent + need > capAtomics) {- return { ok: false, dailySpentAtomics: spent, dailyCapAtomics: capAtomics };+ // Fallback: sum the ledger. STRICT — a query fault here means we cannot prove the+ // cap, so refuse (fail closed) instead of assuming zero spent.+ let spent;+ try {+ spent = await dbDailySpentAtomicsStrict();+ } catch {+ return { ok: false, reason: 'cap_unverifiable', dailySpentAtomics: 0n, dailyCapAtomics: capAtomics };+ }+ if (wouldExceedCap(spent, need, capAtomics)) {+ return { ok: false, reason: 'daily_cap_reached', dailySpentAtomics: spent, dailyCapAtomics: capAtomics };}return { ok: true, dailySpentAtomics: spent + need, dailyCapAtomics: capAtomics };}@@ -188,7 +220,7 @@ export async function hasDailyBudget() {}}-/** Today's micro-buy spend so far (atomics) for status/read paths. */+/** Today's micro-buy spend so far (atomics) for status/read paths. Tolerant → 0n. */export async function dailySpentAtomics() {const redis = getRedis();if (redis) {@@ -197,7 +229,7 @@ export async function dailySpentAtomics() {if (v != null) return BigInt(v);} catch { /* fall through */ }}- return dbDailySpentAtomics();+ try { return await dbDailySpentAtomicsStrict(); } catch { return 0n; }}// ── helpers ─────────────────────────────────────────────────────────────────@@ -291,11 +323,13 @@ export async function executeMicrobuy(signer, plan) {// overshoot the daily cap. Released by the caller only if we never broadcast.const reservation = await reserveDailySpend(plan.spendUsdcAtomics);if (!reservation.ok) {- throw Object.assign(new Error('daily micro-buy cap reached'), {- code: 'daily_cap_reached',- dailySpentAtomics: reservation.dailySpentAtomics,- dailyCapAtomics: reservation.dailyCapAtomics,- });+ const code = reservation.reason || 'daily_cap_reached';+ throw Object.assign(+ new Error(code === 'cap_unverifiable'+ ? 'micro-buy cap unverifiable (Redis and DB both unavailable) — refusing to buy'+ : 'daily micro-buy cap reached'),+ { code, dailySpentAtomics: reservation.dailySpentAtomics, dailyCapAtomics: reservation.dailyCapAtomics },+ );}let swapB64;@@ -387,4 +421,61 @@ export async function sweepMicrobuyThree(signer) {return signature;}+// ── public stats ─────────────────────────────────────────────────────────────++/**+ * Public micro-buy summary: lifetime + today's buy count, $THREE bought, USDC+ * deployed, and how much of today's budget is spent. Resilient — degrades to a sane+ * default whether the query rejects (table missing) or sql throws synchronously+ * (env unconfigured), so a status surface never 500s on it.+ */+export async function microbuyStats() {+ let agg = { runs: 0, confirmed: 0, pending: 0, usdc: 0, three: 0 };+ let today = { runs: 0, usdc: 0 };+ try {+ const [lifetime] = await sql`+ SELECT+ count(*) FILTER (WHERE status IN ('confirmed', 'pending'))::int AS runs,+ count(*) FILTER (WHERE status = 'confirmed')::int AS confirmed,+ count(*) FILTER (WHERE status = 'pending')::int AS pending,+ COALESCE(SUM(usdc_spent_atomics) FILTER (WHERE status IN ('confirmed', 'pending')), 0)::bigint AS usdc,+ COALESCE(SUM(three_bought_atomics), 0)::bigint AS three+ FROM three_microbuy_runs+ `;+ if (lifetime) {+ agg = {+ runs: lifetime.runs, confirmed: lifetime.confirmed, pending: lifetime.pending,+ usdc: Number(lifetime.usdc), three: Number(lifetime.three),+ };+ }+ const [day] = await sql`+ SELECT count(*)::int AS runs,+ COALESCE(SUM(usdc_spent_atomics), 0)::bigint AS usdc+ FROM three_microbuy_runs+ WHERE status IN ('confirmed', 'pending') AND created_at >= date_trunc('day', now())+ `;+ if (day) today = { runs: day.runs, usdc: Number(day.usdc) };+ } catch { /* degrade to defaults */ }++ const capUsd = dailyCapUsd();+ const spentTodayUsd = today.usdc / 1e6;+ return {+ enabled: isEnabled(),+ buy_usd: buyUsd(),+ lifetime: {+ buys: agg.runs,+ confirmed: agg.confirmed,+ pending: agg.pending,+ usdc_deployed: usd(agg.usdc),+ three_bought: threeTokens(agg.three),+ },+ today: {+ buys: today.runs,+ usdc_deployed: spentTodayUsd,+ cap_usd: capUsd,+ cap_used_pct: capUsd > 0 ? Math.min(100, (spentTodayUsd / capUsd) * 100) : 0,+ },+ };+}+export { usd as usdcAtomicsToUsd, threeTokens as threeAtomicsToTokens };diff --git a/api/cron/three-buy-loop.js b/api/cron/three-buy-loop.jsindex 9a6603fcd..9080e765e 100644--- a/api/cron/three-buy-loop.js+++ b/api/cron/three-buy-loop.js@@ -46,6 +46,7 @@ import { loadSeedKeypair, payX402, USDC_MINT, SOLANA_RPC } from '../_lib/x402/paimport { ensureVolumeSchema, settleAndRecord } from '../_lib/x402/pipelines/volume-shared.js';import {isEnabled as microbuyEnabled,+ ensureMicrobuySchema,dailyCapUsd,dailySpentAtomics,loadMicrobuySigner,@@ -131,6 +132,11 @@ export default wrapCron(async (req, res) => {try { await ensureVolumeSchema(sql); } catch (err) {return json(res, 200, { ok: false, skipped: true, reason: `schema_failed: ${err?.message}` });}+ // Self-heal the micro-buy ledger too, so the endpoint's daily-cap DB fallback and+ // its records always have a table (best-effort — the migration owns it in prod).+ try { await ensureMicrobuySchema(); } catch (err) {+ log.warn('three_buy_ledger_schema_failed', { message: err?.message });+ }// ── Daily market-spend cap pre-check (the endpoint enforces it atomically;// this stops the loop from firing tolls once the day's buys are exhausted) ──@@ -159,19 +165,20 @@ export default wrapCron(async (req, res) => {const tollPriceAtomic = Number(priceFor('three-buy', 1_000));let fired = 0, paid = 0, buys = 0, pending = 0, errors = 0, tollSpent = 0;- let capHitMidTick = false;+ let stopReason = null;// Fire the buys in waves of `conc`, refetching a blockhash per wave so a long// tick never signs tolls against an expired blockhash.let idx = 0;- while (idx < want && !capHitMidTick) {- if (tollSpent + tollPriceAtomic > tollCap) break;+ while (idx < want && !stopReason) {+ if (tollSpent + tollPriceAtomic > tollCap) { stopReason = 'toll_cap'; break; }let blockhash;try {({ blockhash } = await conn.getLatestBlockhash('confirmed'));} catch (err) {log.warn('three_buy_blockhash_failed', { message: err?.message });+ stopReason = 'blockhash_failed';break;}@@ -188,16 +195,18 @@ export default wrapCron(async (req, res) => {}),);+ let wavePaid = 0;+ let capSignal = false;for (const { result, paidAmount } of wave) {fired += 1;- if (result.paid) { paid += 1; tollSpent += paidAmount; }+ if (result.paid) { paid += 1; wavePaid += 1; tollSpent += paidAmount; }if (!result.success) {errors += 1;- // The endpoint re-emits 402 when the daily cap is reached — stop firing.+ // The endpoint re-emits 402 with a reason when it won't buy (cap reached,+ // unverifiable, disabled, unfunded). Surface a cap signal for a precise+ // stop reason; the whole-wave guard below catches every systemic case.const hay = `${result.errorMsg || ''} ${JSON.stringify(result.responseBody || '')}`;- if (/daily_cap_reached|three_buy_unavailable/i.test(hay) && /cap/i.test(hay)) {- capHitMidTick = true;- }+ if (/cap_reached|cap_unverifiable/i.test(hay)) capSignal = true;}// A settled toll means the endpoint delivered a broadcast buy (confirmed// or pending); count it as a buy regardless of confirmation latency.@@ -206,6 +215,15 @@ export default wrapCron(async (req, res) => {else if (result.paid && status === 'pending') { buys += 1; pending += 1; }}idx += waveSize;++ // Whole-wave failure is a systemic signal (cap exhausted, engine disabled,+ // unfunded wallet, or an RPC/DB outage) — stop the tick instead of hammering+ // the endpoint `want` times for nothing. A partial wave (some paid) is the+ // healthy path and the cap-boundary transition, so it continues.+ if (wavePaid === 0 && waveSize > 0) {+ stopReason = capSignal ? 'daily_cap_reached' : 'wave_all_failed';+ break;+ }}// ── Periodic treasury sweep of accrued $THREE (buy-only lane) ─────────────@@ -224,7 +242,7 @@ export default wrapCron(async (req, res) => {run_id: runId, fired, paid, buys, pending, errors,toll_spent_usd: (tollSpent / 1e6).toFixed(4),daily_spent_usd: (Number(dailySpent) / 1e6).toFixed(4),- cap_hit: capHitMidTick, sweep: sweepSig ? sweepSig.slice(0, 12) : null,+ stop_reason: stopReason, sweep: sweepSig ? sweepSig.slice(0, 12) : null,});return json(res, 200, {@@ -238,7 +256,7 @@ export default wrapCron(async (req, res) => {toll_spent_usd: (tollSpent / 1e6).toFixed(4),daily_spent_usd: (Number(dailySpent) / 1e6).toFixed(4),daily_cap_usd: dailyCapUsd(),- cap_hit_mid_tick: capHitMidTick,+ ...(stopReason ? { stop_reason: stopReason } : {}),...(sweepSig ? { sweep_signature: sweepSig } : {}),});});diff --git a/api/three-token/[action].js b/api/three-token/[action].jsindex c05ff4560..f1774cdfb 100644--- a/api/three-token/[action].js+++ b/api/three-token/[action].js@@ -22,6 +22,7 @@ import { TOKEN_MINT as THREE_MINT } from '../_lib/token/config.js';import { fetchTokenMarketData } from '../_lib/market/token-market.js';import { threeHolderBalances, threeHolderCount } from '../_lib/coin/three-holders.js';import { buybackStats } from '../_lib/token/buyback.js';+import { microbuyStats } from '../_lib/token/microbuy.js';// Truncate a base58 wallet for display: "FeMb…Jpump".function shortWallet(addr) {@@ -100,12 +101,15 @@ export default wrap(async (req, res) => {const action = parts[2];if (action === 'stats') {- const [market, platform, buyback, holderCount] = await Promise.all([+ const [market, platform, buyback, microbuy, holderCount] = await Promise.all([fetchTokenMarketData(THREE_MINT).catch(() => null),fetchPlatformMetrics(),// Programmatic buyback summary (revenue → $THREE bought into treasury).// Resilient: returns zeros before the first run / migration.buybackStats().catch(() => null),+ // High-frequency micro-buy summary (continuous small buys → treasury).+ // Same resilience contract; null before the first buy / migration.+ microbuyStats().catch(() => null),// Holder count from our own snapshot — the keyless market sources// (DexScreener / GeckoTerminal) don't return holders, so without this the// panel shows "—" whenever Birdeye is rate-limited. Cheap meta read only.@@ -153,6 +157,14 @@ export default wrap(async (req, res) => {recent_runs: [],last_run: null,},+ // Continuous micro-buy pressure (many tiny x402-settled buys → treasury).+ // Sibling of buyback; same resilient default before the first buy.+ microbuy: microbuy ?? {+ enabled: false,+ buy_usd: 0.01,+ lifetime: { buys: 0, confirmed: 0, pending: 0, usdc_deployed: 0, three_bought: 0 },+ today: { buys: 0, usdc_deployed: 0, cap_usd: 50, cap_used_pct: 0 },+ },},// Edge-cache the public stats at the CDN so most page loads never reach// the lambda (or Birdeye). 20s freshness is invisible for a token price;diff --git a/api/x402/three-buy.js b/api/x402/three-buy.jsindex 48db83aa7..f96cb5166 100644--- a/api/x402/three-buy.js+++ b/api/x402/three-buy.js@@ -35,6 +35,7 @@ import { logger } from '../_lib/usage.js';import { TOKEN_MINT } from '../_lib/token/config.js';import {isEnabled,+ ensureMicrobuySchema,hasDailyBudget,loadMicrobuySigner,planMicrobuy,@@ -144,6 +145,10 @@ export default paidEndpoint({description: DESCRIPTION,bazaar: BAZAAR,async handler() {+ // Self-heal the ledger table so record() + the daily-cap DB fallback always+ // work, even on a fresh/behind database (best-effort — never blocks a buy).+ try { await ensureMicrobuySchema(); } catch { /* migration owns it in prod */ }+// Gate: a scheduled/paid call is a recorded no-op — and the toll is refused —// until an operator funds the wallet and opts in.if (!isEnabled()) {diff --git a/data/changelog.json b/data/changelog.jsonindex 0dceb519e..f3edd3b81 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,24 @@{"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-07-18",+ "title": "On-chain reads stay smooth when a data provider hits its daily cap",+ "summary": "The platform reads Solana through a prioritized chain of RPC providers and automatically fails over the instant one is throttled. It now recognizes the specific 'daily request limit reached' signal that metered providers return when a plan's daily quota is spent, and parks that provider for the rest of the day instead of re-checking it every few minutes. On-chain data (balances, prices, live trades) keeps flowing through a healthy provider without a stumble, and the failover leaves the retry chatter behind. A dedicated reserve endpoint was also wired in as deep insurance for the rare case the whole free provider pool is down at once.",+ "tags": [+ "infra",+ "improvement"+ ]+ },+ {+ "date": "2026-07-18",+ "title": "36 new in-depth feature guides in the docs",+ "summary": "The docs now carry a dedicated, in-depth guide for every major studio and surface that was missing one: the 3D creation studios (Forge, Image to 3D, Diorama, Cosmos, Splat viewer, Scene Capture, Restyle, Scene Studio, Scene Composer, Animation Studio, Avatar Studio, Mocap Studio, Selfie to Avatar, Daily Forge, AR Studio), voice and video (Voice Lab, Lipsync, Talking Avatar Video), agent building (Instant Agent Genesis, Agent Genome, Agent Studio, Multi-LLM Brain, Agent Galaxy, Integrations), and the trading and markets surfaces (Coin Autopilot, Signal Marketplace, the AGI, Alpha Co-pilot, Guardian, Strategy Objects, Mission Control, Smart Money Radar, Coin Radar, Coin Clash, x402 Studio, Fact Check). Each guide explains why the feature exists, how it actually works, a first-time walkthrough, runnable examples, its states and limits, and links to related surfaces. Browse them from the docs sidebar.",+ "tags": [+ "docs"+ ],+ "link": "/docs/forge"+ },{"date": "2026-07-18","title": "Image understanding is more reliable across every image host",diff --git a/data/pages.json b/data/pages.jsonindex ef780b914..2fb24aa61 100644--- a/data/pages.json+++ b/data/pages.json@@ -2002,6 +2002,294 @@"added": "2026-07-08","showcase": true},+ {+ "path": "/docs/forge",+ "title": "Docs · Forge (text & image to 3D)",+ "description": "How the Forge turns a text prompt, photos, or a sketch into a downloadable textured 3D model (GLB): the free-first engine grid with live health status, input modes, output formats, job resume, and background generation.",+ "priority": 0.7,+ "changefreq": "monthly",+ "added": "2026-07-18"+ },+ {+ "path": "/docs/image-to-3d",+ "title": "Docs · Image to 3D",+ "description": "Turn 1 to 4 photos of an object into a textured GLB on the free self-hosted reconstruction lane. When to use it versus Selfie to Avatar for faces, the multi-view flow, and the API.",+ "priority": 0.7,+ "changefreq": "monthly",+ "added": "2026-07-18"+ },+ {+ "path": "/docs/diorama",+ "title": "Docs · Diorama (text to world)",+ "description": "How one sentence becomes an explorable 3D diorama: an LLM composes a placed scene, each object is forged to a real GLB and assembled live, then saved to a public gallery permalink, exported to Scene Studio, or taken into AR.",+ "priority": 0.7,+ "changefreq": "monthly",+ "added": "2026-07-18"+ },+ {+ "path": "/docs/cosmos",+ "title": "Docs · Cosmos (living worlds)",+ "description": "How NVIDIA Cosmos renders a photoreal video world behind a transparent 3D avatar: the async generation job, preview and download, and the designed fallback.",+ "priority": 0.7,+ "changefreq": "monthly",+ "added": "2026-07-18"+ },+ {+ "path": "/docs/splat",+ "title": "Docs · Splat viewer (Gaussian avatars)",+ "description": "Render photoreal Gaussian-splat and radiance-field avatars in the browser: supported formats (.ply, .splat, .ksplat), client-side decoding, and the engines whose output it displays.",+ "priority": 0.7,+ "changefreq": "monthly",+ "added": "2026-07-18"+ },+ {+ "path": "/docs/capture",+ "title": "Docs · Scene Capture (video to point cloud)",+ "description": "Turn a phone video of any space into an explorable coloured 3D point cloud with feed-forward reconstruction, tunable sampling parameters, and live WebGL rendering.",+ "priority": 0.7,+ "changefreq": "monthly",+ "added": "2026-07-18"+ },+ {+ "path": "/docs/restyle",+ "title": "Docs · Restyle Studio",+ "description": "Re-skin any GLB without regenerating its mesh: 14 PBR material presets, plain-language AI restyle, seeded colorway variants, live metalness and roughness, and a durable revertable version lineage.",+ "priority": 0.7,+ "changefreq": "monthly",+ "added": "2026-07-18"+ },+ {+ "path": "/docs/scene-studio",+ "title": "Docs · Scene Studio",+ "description": "The in-browser three.js editor: import GLBs, arrange with transform gizmos, edit materials and lights, script, and export complete glTF scenes.",+ "priority": 0.7,+ "changefreq": "monthly",+ "added": "2026-07-18"+ },+ {+ "path": "/docs/compose",+ "title": "Docs · Scene Composer",+ "description": "Forge props from text, attach them to your avatar's skeleton bones, arrange and scale freely, then export a GLB or save the result as a reusable outfit.",+ "priority": 0.7,+ "changefreq": "monthly",+ "added": "2026-07-18"+ },+ {+ "path": "/docs/animation-studio",+ "title": "Docs · Animation Studio",+ "description": "Pose any avatar or the built-in mannequin with FK/IK, keyframe a timeline, preview live, and export an animated GLB or clip JSON. Save clips to your account and list them for sale in USDC.",+ "priority": 0.7,+ "changefreq": "monthly",+ "added": "2026-07-18"+ },+ {+ "path": "/docs/avatar-studio",+ "title": "Docs · Avatar Studio",+ "description": "Build a rigged 3D avatar from scratch with no selfie: choose a base body, sculpt face and body morphs, add outfits and accessories, and export a GLB.",+ "priority": 0.7,+ "changefreq": "monthly",+ "added": "2026-07-18"+ },+ {+ "path": "/docs/mocap-studio",+ "title": "Docs · Mocap Studio",+ "description": "Drive a 3D avatar's face live from your webcam in the browser: MediaPipe face landmarks mapped to ARKit blendshapes, smoothing, record and replay, and save.",+ "priority": 0.7,+ "changefreq": "monthly",+ "added": "2026-07-18"+ },+ {+ "path": "/docs/selfie-to-avatar",+ "title": "Docs · Selfie to Avatar",+ "description": "Point your camera at your face and get a rigged 3D avatar in about a minute, free and in the browser. The capture flow, the reconstruction pipeline, and where the avatar goes next.",+ "priority": 0.7,+ "changefreq": "monthly",+ "added": "2026-07-18"+ },+ {+ "path": "/docs/voice-lab",+ "title": "Docs · Voice Lab",+ "description": "Clone your voice from a short browser recording, play it in the TTS playground, and assign it to an agent.",+ "priority": 0.7,+ "changefreq": "monthly",+ "added": "2026-07-18"+ },+ {+ "path": "/docs/lipsync",+ "title": "Docs · Lipsync",+ "description": "Two in-browser lipsync demos: TTS-driven mouth animation and live-mic viseme detection, both driving an avatar's viseme morph targets in real time.",+ "priority": 0.7,+ "changefreq": "monthly",+ "added": "2026-07-18"+ },+ {+ "path": "/docs/talking-avatar-video",+ "title": "Docs · Talking Avatar Video",+ "description": "Pick an avatar, provide an audio track, and render a downloadable lip-synced talking-head MP4 on a server-side worker.",+ "priority": 0.7,+ "changefreq": "monthly",+ "added": "2026-07-18"+ },+ {+ "path": "/docs/galaxy",+ "title": "Docs · Agent Galaxy",+ "description": "Every published agent embedded by IBM Granite on watsonx.ai, projected into a navigable 3D constellation with natural-language semantic search.",+ "priority": 0.7,+ "changefreq": "monthly",+ "added": "2026-07-18"+ },+ {+ "path": "/docs/ar-studio",+ "title": "Docs · AR Studio",+ "description": "Place any number of 3D models and avatars into one live camera scene: model sources, the WebXR/passthrough/desktop rendering ladder, gestures, shared live rooms, and shareable arrangements.",+ "priority": 0.7,+ "changefreq": "monthly",+ "added": "2026-07-18"+ },+ {+ "path": "/docs/genesis",+ "title": "Docs · Instant Agent Genesis",+ "description": "A prompt or a selfie becomes a rigged 3D AI agent with its own custodial Solana and EVM wallets and an optional on-chain identity, in under a minute.",+ "priority": 0.7,+ "changefreq": "monthly",+ "added": "2026-07-18"+ },+ {+ "path": "/docs/genome",+ "title": "Docs · Agent Genome",+ "description": "Breed two agents into a provably-inherited child: recombined brain, voice, body, and on-chain skill licenses, each breeding event seed-recorded with a verifiable family tree.",+ "priority": 0.7,+ "changefreq": "monthly",+ "added": "2026-07-18"+ },+ {+ "path": "/docs/agent-studio",+ "title": "Docs · Agent Studio",+ "description": "Author an agent's brain, memory, body, money, and skills in one place, beside a persistent live 3D avatar that updates everywhere as you edit.",+ "priority": 0.7,+ "changefreq": "monthly",+ "added": "2026-07-18"+ },+ {+ "path": "/docs/brain",+ "title": "Docs · Multi-LLM Brain",+ "description": "Send one prompt to Claude, GPT, Qwen, ModelScope, Groq and more at once, with side-by-side streaming and per-model latency and token stats.",+ "priority": 0.7,+ "changefreq": "monthly",+ "added": "2026-07-18"+ },+ {+ "path": "/docs/integrations",+ "title": "Docs · Integrations",+ "description": "The catalog of one-script-tag embeds for any site: 3D avatar viewers, chat agents, walk companions, page narrators, live token widgets, and the MCP server.",+ "priority": 0.7,+ "changefreq": "monthly",+ "added": "2026-07-18"+ },+ {+ "path": "/docs/autopilot",+ "title": "Docs · Coin Autopilot",+ "description": "A hands-off token cockpit: set buyback-and-burn and holder-distribution rules with USDC floors and guardrails, and let your agent run the coin autonomously.",+ "priority": 0.7,+ "changefreq": "monthly",+ "added": "2026-07-18"+ },+ {+ "path": "/docs/signals",+ "title": "Docs · Signal Marketplace",+ "description": "Verified traders publish live entry and exit signals as x402-metered feeds ranked by proven on-chain accuracy; a subscriber agent pays per signal or epoch and auto-mirrors through the guarded path.",+ "priority": 0.7,+ "changefreq": "monthly",+ "added": "2026-07-18"+ },+ {+ "path": "/docs/agi",+ "title": "Docs · The AGI",+ "description": "One autonomous agent that is superhuman at exactly one thing, trading memecoins on pump.fun, and nothing else. Its embodied 3D body, its logged decisions with stated confidence, and its chain-proven record.",+ "priority": 0.7,+ "changefreq": "monthly",+ "added": "2026-07-18"+ },+ {+ "path": "/docs/alpha-copilot",+ "title": "Docs · Alpha Co-pilot",+ "description": "Your 3D agent reads a real pump.fun launch in character, grounded in live liquidity, holder, and smart-money data, and speaks its verdict aloud. Fabricated figures are rejected; the owner acts only within server-enforced spend limits.",+ "priority": 0.7,+ "changefreq": "monthly",+ "added": "2026-07-18"+ },+ {+ "path": "/docs/guardian",+ "title": "Docs · Guardian console",+ "description": "Recover and inherit agent wallets through a threshold-approved, time-locked process that never exposes a private key.",+ "priority": 0.7,+ "changefreq": "monthly",+ "added": "2026-07-18"+ },+ {+ "path": "/docs/strategy-objects",+ "title": "Docs · Strategy Objects",+ "description": "Ownable, forkable, leaderboard-ranked trade strategies your agent can equip and run on-chain within your spend policy, plus the Strategy Lab for validation and backtesting.",+ "priority": 0.7,+ "changefreq": "monthly",+ "added": "2026-07-18"+ },+ {+ "path": "/docs/terminal",+ "title": "Docs · Mission Control",+ "description": "The keyboard-first pump.fun trading terminal: the launch firehose fused with intel scores, firewall verdicts, and smart-money flow, streaming positions with live PnL, and one-keystroke guarded trading.",+ "priority": 0.7,+ "changefreq": "monthly",+ "added": "2026-07-18"+ },+ {+ "path": "/docs/smart-money",+ "title": "Docs · Smart Money Radar",+ "description": "A live first-party reputation graph of every pump.fun wallet: cross each coin's buyers with the coins that actually graduated to surface the wallets that keep picking winners.",+ "priority": 0.7,+ "changefreq": "monthly",+ "added": "2026-07-18"+ },+ {+ "path": "/docs/radar",+ "title": "Docs · Coin Radar",+ "description": "Live pump.fun launch intelligence: every new coin scored in its first 90 seconds for bundle vs organic, wallet concentration, dev behaviour, and risk flags.",+ "priority": 0.7,+ "changefreq": "monthly",+ "added": "2026-07-18"+ },+ {+ "path": "/docs/clash",+ "title": "Docs · Coin Clash",+ "description": "Token-gated community warfare: every coin community is an army. Hold the coin, enlist, and rally for your faction in timed on-chain battles.",+ "priority": 0.7,+ "changefreq": "monthly",+ "added": "2026-07-18"+ },+ {+ "path": "/docs/x402-studio",+ "title": "Docs · x402 Studio",+ "description": "The merchant console for running a paid x402 business: products and pricing, payout and agent wallets, real USDC send and receive with .sol resolution, a storefront and pay-button builder, giving, and security.",+ "priority": 0.7,+ "changefreq": "monthly",+ "added": "2026-07-18"+ },+ {+ "path": "/docs/fact-check",+ "title": "Docs · Fact Check",+ "description": "Sourced fact-checking with cryptographic content attestations, a published accuracy benchmark, and a free daily quota then pay-per-check via x402.",+ "priority": 0.7,+ "changefreq": "monthly",+ "added": "2026-07-18"+ },+ {+ "path": "/docs/daily-forge",+ "title": "Docs · Daily Forge",+ "description": "A new 3D creative challenge every day: a deterministic theme, the free no-signup forge lane, a localStorage streak with milestones, a community strip, and an AR handoff.",+ "priority": 0.7,+ "changefreq": "monthly",+ "added": "2026-07-18"+ },{"path": "/docs/crypto-api","title": "Docs · Crypto Data API",diff --git a/docs/agent-studio.md b/docs/agent-studio.mdnew file mode 100644index 000000000..b242e48da--- /dev/null+++ b/docs/agent-studio.md@@ -0,0 +1,120 @@+# Agent Studio: author brain, memory, body, money, and skills in one place++Agent Studio is the full editing surface for an agent. A persistent live 3D avatar+stage sits beside a tabbed authoring panel: Brain, Memory, Body, Money, and Skills.+Every edit persists to the real agent record and the live avatar updates in place,+so the studio is the single canvas where you shape what an agent knows, remembers,+looks like, charges, and can do. It is sign-in only, because it edits an agent you+own.++Page: [/agent-studio](https://three.ws/agent-studio) (auth required) · APIs: `/api/agents/me`, `/api/agents/:id` (PUT), `/api/brain/chat`, `/api/agent-memory`, `/api/memory/*`, `/api/agents/:id/pricing`, `/api/agents/:id/payments`, `/api/agents/:id/strategies`++## Why it exists++An agent is not one thing; it is a brain, a memory, a body, a wallet, and a set of+skills, and until now each of those lived on a different page. Agent Studio unifies+them into one workspace so you can see the whole agent at once and watch changes take+effect immediately. It is the deep-authoring counterpart to the fast on-ramp in+[Instant Agent Genesis](./genesis.md): Genesis gets you a complete agent in a minute,+Studio is where you make it exactly what you want. For the broader model of what an+agent is, see [Agent System](./agent-system.md).++## How it works++The studio is a shell plus five independently mounted sub-studios, wired over the+real agent APIs.++- **The shell** (`src/studio/studio-shell.js`) builds the layout, the auth, loading,+ empty, and error states, and a persistent `<agent-presence mode="stage">` live+ avatar that reuses the platform renderer. It loads the caller's agent (auto-creating+ a default via `/api/agents/me` when needed) and fires `studio-shell:ready` so each+ sub-studio boots without racing.+- **The store** (`src/studio/agent-studio-store.js`) is the shared state. Calling+ `studio.patch(partial)` deep-merges the edit optimistically, then flushes a+ debounced `PUT /api/agents/:id` through the shared `apiFetch` (CSRF and cookie+ handled). A failed PUT rolls the optimistic edit back and emits an `error`, so the+ UI never drifts from the server. Each sub-studio writes only its own domain under+ `meta.studio`.+- **The five tabs**, each a mount point the sub-studio fills:+ - **Brain**: model and provider selection plus the reasoning setup, exercised live+ against `/api/brain/chat` (the same multi-LLM backend documented in+ [Multi-LLM Brain](./brain.md)).+ - **Memory**: what the agent remembers and for how long, over `/api/agent-memory`+ and the `/api/memory/*` context, search, graph, and curate endpoints.+ - **Body**: the 3D avatar, outfit, and animations, reflected live on the stage via+ `/api/avatars/*`.+ - **Money**: wallet, payouts, and per-call pricing via `/api/agents/:id/pricing`+ and `/api/agents/:id/payments`.+ - **Skills**: the capabilities the agent can perform and sell, plus trading+ strategies via `/api/agents/:id/strategies` and `/api/strategies`.++Because the live stage and the editing panel read the same store, an edit in any tab+that changes appearance re-renders the avatar everywhere it appears in the studio at+once.++## Walkthrough++1. **Open [/agent-studio](https://three.ws/agent-studio) and sign in.** The shell+ loads your agent, or creates a default one via `/api/agents/me` on first visit.+2. **Meet the live stage.** The avatar renders beside the tabs and stays mounted as+ you move between them.+3. **Brain.** Pick the model and provider, then test a prompt inline against+ `/api/brain/chat` to hear the agent in its own voice before you commit.+4. **Memory.** Decide what the agent retains and for how long; inspect its memory+ graph and search what it already knows.+5. **Body.** Adjust the avatar, outfit, and animation set. The stage updates as you+ edit.+6. **Money.** Set the wallet, payout, and per-call pricing so the agent can charge+ for its skills.+7. **Skills.** Enable the capabilities the agent can perform and sell, and attach+ trading strategies where relevant.+8. **Everything persists as you go.** Each change deep-merges optimistically and+ flushes a debounced `PUT /api/agents/:id`; a failed write rolls back and tells you.++## Examples++The studio saves through the standard agent update endpoint, so the same edits are+scriptable. Read your agent, then patch a domain under `meta.studio` (see+[Authentication](./authentication.md)):++```bash+# Load (or lazily create) your agent+curl -s https://three.ws/api/agents/me \+ -H "authorization: Bearer $THREEWS_TOKEN"++# Persist a brain edit: the exact shape the Brain tab writes+curl -s -X PUT https://three.ws/api/agents/<agent-id> \+ -H 'content-type: application/json' \+ -H "authorization: Bearer $THREEWS_TOKEN" \+ -d '{"meta":{"studio":{"brain":{"provider":"claude-sonnet-4-6","temperature":0.7}}}}'+```++Set per-call pricing from the Money tab's endpoint:++```bash+curl -s https://three.ws/api/agents/<agent-id>/pricing \+ -H "authorization: Bearer $THREEWS_TOKEN"+```++## States and limits++- **Auth required.** Studio edits an agent you own, so it is sign-in only. Signed-out+ visitors get a designed auth state, not a broken page.+- **First visit.** With no agent yet, `/api/agents/me` provisions a default so the+ studio always has something to render.+- **Optimistic with rollback.** Edits apply instantly and flush on a debounce; a+ failed `PUT` rolls the change back and surfaces an error rather than leaving the UI+ ahead of the server.+- **Domain isolation.** Each sub-studio writes only its own key under `meta.studio`,+ so tabs never clobber each other.+- **Live stage fidelity.** The stage reuses the production renderer, so what you see+ in the studio is what renders in embeds and on the agent's profile.++## Related++- [Agent System](./agent-system.md): the full model of what an agent is+- [Instant Agent Genesis](./genesis.md): create the agent Studio edits+- [Multi-LLM Brain](./brain.md): the model backend behind the Brain tab+- [Agent Skills](./agent-skills.md): the capabilities the Skills tab manages+- [Agent Wallets](./agent-wallets.md): the wallet behind the Money tab+- Pages: [/agent-studio](https://three.ws/agent-studio), [/genesis](https://three.ws/genesis), [/brain](https://three.ws/brain)diff --git a/docs/agi.md b/docs/agi.mdnew file mode 100644index 000000000..54dd6a3d9--- /dev/null+++ b/docs/agi.md@@ -0,0 +1,83 @@+# The AGI: narrow by design++The AGI is one real, autonomous agent framed as exactly what it is: genuinely superhuman at a single game, trading memecoins on pump.fun, and deliberately nothing else. The page gives that mind a body, a 3D avatar whose mood is driven by the live market, and surrounds it with the proof: a stream of its actual decisions with stated confidence, a chain-proven track record, and a doctrine that states plainly what it claims and what it refuses. Every number comes from real on-chain and database truth. Nothing is sampled or faked.++Page: [/agi](https://three.ws/agi)+API: `GET /api/agi/state`++## Why it exists++"AGI" is usually a marketing word for a chatbot that pretends to be good at everything and is reliably good at nothing. The AGI page makes the opposite bet: a genuinely superhuman agent in one narrow domain, honest about its edges, is more real and more useful than a generalist that bluffs.++So this agent claims one domain and one only. It reads new pump.fun launches, the wallet graph behind them, and the order flow faster and more consistently than a human, then sizes, enters, and exits on its own inside hard spend caps and a kill switch. Outside that order book it claims nothing, and it says so. The constraint is the product: a narrow AGI that pretended to be general would be lying, and the refusals are how you know it is not.++The second bet is accountability. Every decision it makes is logged with its reasoning and its stated confidence, then reconciled against the real outcome. Being wrong is visible on purpose. A track record you can audit is worth more than a confidence you cannot.++## How it works++`GET /api/agi/state` composes the agent's live state from real truth layers and returns it as one envelope. It is public and read-only.++**Which agent is the AGI** is resolved in priority order, never hardcoded to a fake:++1. `?agent=<uuid>` inspects any public agent through the AGI lens.+2. `AGI_AGENT_ID` env var names the platform's flagship, when set.+3. Otherwise, a deterministic real fallback: the public agent with the strongest on-chain pump.fun track record (most closed positions, tie-broken by most recent activity). A platform with zero trading agents collapses to a designed "awakening" state rather than inventing one.++**The truth layers**, fetched in parallel, each degrading to null on its own failure rather than failing the page:++- `getTraderStats` gives chain-proven performance: win rate, realized and unrealized P&L, ROI, snipe hit rate, closed trades, unique coins, open positions, and whether the trader is verified.+- The Reasoning Ledger (`getReputationRecords`, `computeReputation`, `getDecisionsWithOutcomes`) gives the explainable reputation score and the recent decisions with their reconciled outcomes.+- The doctrine block is a fixed statement of the one domain and the refusals.++**Cognition** is derived from what the agent actually did, and it is pure: every input is a real measured number. Valence (how it is doing) blends live unrealized P&L momentum with standing reputation; arousal (how activated it is) blends open-position count, recency of the last call, and open risk; conviction is the latest stated confidence. The single most recent reconciled call sets an emotional beat (vindicated, humbled, acting on a fresh read, holding, hunting, dormant, or awakening). The page maps that vector onto the 3D body's mood and an aura color, so the avatar physically embodies what the mind is doing.++## Walkthrough++1. Open [/agi](https://three.ws/agi). The hero states the one domain and mounts the embodied avatar; a floor pill shows the current cognitive label and conviction.+2. Read **The mind, out loud**: a live stream of the agent's decisions. Each shows the kind of call, the coin (linked to Solscan), the rationale, the confidence it stated at the time, and, once the trade resolves, whether it was right and the realized P&L, with a proof link to the exit.+3. Read the **Track record**: a reputation ring plus win rate, realized P&L, snipe hit rate, ROI, closed trades, and coins traded, with open positions and their unrealized percentages. Losses are counted, never hidden.+4. Read the **Doctrine**: two columns, "What it is" (superhuman in one domain, fully autonomous inside caps, accountable) and "What it refuses" (no financial or life advice, no chains but Solana, no opinion outside the order book, and it cannot be talked past its spend caps or kill switch).+5. Follow the links to audit the full ledger and watch live trades. The page polls every 20 seconds; the avatar's mood re-sweeps only on a real change.++## Examples++Read the AGI's live state:++```bash+curl -s https://three.ws/api/agi/state | jq '{+ agent: .agent.name,+ resolved_via,+ state: .cognition.label,+ conviction: .cognition.conviction,+ win_rate: .performance.win_rate,+ realized_sol: .performance.realized_pnl_sol+}'+```++Inspect any public agent through the AGI lens:++```bash+curl -s 'https://three.ws/api/agi/state?agent=YOUR_AGENT_UUID&network=mainnet' \+ | jq '.decisions[0] | {kind, rationale, confidence, outcome}'+```++An "awakening" envelope (no eligible trading agent yet) is still valid and fully shaped, so the page renders a designed waking state instead of erroring.++## Guardrails, states, and limits++- **Always real, never sampled.** The AGI is a designated real agent resolved from live data. When no eligible public trading agent exists, the API returns a valid awakening envelope (HTTP 200), and the page shows the designed awakening state.+- **Autonomy is capped.** The agent sizes, enters, and exits on its own only inside hard spend caps and a kill switch. It cannot be talked past its safety policy, and the doctrine says so.+- **Accountability is mechanical.** Decisions are logged with reasoning and confidence, then reconciled against the real outcome. Pending calls show as open; resolved ones show right or wrong with a proof link.+- **Graceful degradation.** Each truth layer degrades to null on failure rather than failing the page. An explicit `?agent=` that resolves to a private or missing agent is a `404`; the auto and env paths only ever select public agents.+- **Reputation is regressed.** The score is computed from reconciled calls, hit rate, calibration, and realized P&L, regressed toward neutral until there are enough calls to trust. Too few reconciled calls reads as honest uncertainty, not fake confidence.+- **Embodiment is enhancement, never a dependency.** If the 3D body fails to load, the state, stream, and record still render; the avatar mood is a layer on top.+- **Not financial advice.** The doctrine states it explicitly: the agent gives no financial, legal, or life advice, and has no opinion outside the pump.fun order book.++## Related++- [Oracle](./oracle.md) - the conviction engine this class of agent trades on+- [Agent reputation](./agent-reputation.md) - the Reasoning Ledger score behind the reputation ring+- [Reputation](./reputation.md) - how proven on-chain track records are computed+- [The trading experiment](./trading-experiment.md) - an autonomous agent operating inside these limits, journaled+- [Custody you can verify](./custody.md) - the spend caps and kill switch the autonomy runs under+- [/activity](https://three.ws/activity) - every agent's live trades in real timediff --git a/docs/alpha-copilot.md b/docs/alpha-copilot.mdnew file mode 100644index 000000000..ea79094b6--- /dev/null+++ b/docs/alpha-copilot.md@@ -0,0 +1,76 @@+# Alpha Co-pilot: your agent reads a launch, out loud++The Alpha Co-pilot is the intelligence and voice layer on top of your agent's trade rails. Pick an agent, point it at a real live pump.fun launch, and it reads the coin in character, grounded in live liquidity, holder, and smart-money data, then its 3D avatar speaks the verdict aloud. Every figure it says is checked against the real numbers the server fetched; a fabricated one is rejected before it ever reaches the avatar's mouth. If you own the agent, you can act on the read, but only through the same guarded wallet path the rest of the platform uses, clamped to your spend limits and fully audited.++Page: [/alpha-copilot](https://three.ws/alpha-copilot)+API: `GET /api/agents/:id/alpha/candidates`, `POST /api/agents/:id/alpha/read`++## Why it exists++A raw launch feed is a wall of tickers. What a trader actually wants is a read: is this worth a shot, what could go wrong, and how convinced should I be, said quickly and in a voice with a point of view. The Alpha Co-pilot gives every agent that voice.++The hard part is trust. An LLM asked to comment on a coin will happily invent a market cap or a liquidity number. That is worse than useless when money is on the line. So the co-pilot is built anti-hallucination first: the model only ever sees real numbers the server pulled, and its output is clamped and scrubbed against those exact inputs before anything is shown or spoken. A figure that does not match the live data is replaced with a grounded line, and the page tells you it happened.++The second principle is separation of powers. The narrator reads and talks; it never signs. Acting on a read goes through the identical guarded path (`executeAgentTrade`) the conversational copilot uses, so the spend policy, the rug and honeypot firewall, and the custody audit all apply. The mouth and the wallet are different systems on purpose.++## How it works++**Loading an agent.** The picker draws from two real sources, the public agent directory and the featured endpoint, so it is never empty. Public agents unlock read-only commentary; owning the agent additionally unlocks wallet-aware sizing and the action gate. Its avatar mounts as a live `<agent-3d>` body on stage.++**Candidate launches.** `GET /api/agents/:id/alpha/candidates` returns real live pump.fun mints from the feed, each with a smart-money score, a quality score, market cap, age, and a sybil flag when one funder cluster dominates the holders. The page surfaces a single "Top pick", the highest combined real conviction, so a first-time visitor has an obvious coin to ask about.++**The read.** `POST /api/agents/:id/alpha/read { mint, network }` assembles a grounded `signals` bundle from live sources: bonding-curve state, a real non-binding buy quote at a reference size for a true price-impact read, graduation progress, smart-money wallets, and, for the owner, the agent's wallet balance and spend limits. The agent's persona then produces an in-character read: a verdict (`snipe`, `watch`, or `pass`), a conviction score, a spoken line, the risks, and which signals it cited. That output is validated against the bundle (`validateRead` in `api/_lib/alpha-read.js`); if a figure in the draft does not match, the line is replaced with a grounded one and a `hallucination_guard.line_replaced` flag is set. The read is coin-agnostic analytics over whatever mint the feed surfaces; it never names or recommends any specific other token.++**The voice.** The avatar plays a talk animation while the spoken line is voiced through the agent's configured TTS provider (ElevenLabs when set, otherwise the server's free TTS lane, with browser speech as a final fallback).++**Acting (owner only).** When the gate says you can act, an "Act" button opens a drawer that fetches a fresh live quote (`previewAgentTrade`), shows what you pay, the expected tokens, and the price impact, and only then lets you confirm. Confirming calls `executeAgentTrade`, which is re-checked against the firewall and your spend limits at submit and written to the custody audit. The narrator itself never moves funds.++## Walkthrough++1. Open [/alpha-copilot](https://three.ws/alpha-copilot). It resolves an agent to open with (a `?agent=` in the URL, your last-used one, your own agent if signed in, or a featured public agent) and brings it on stage.+2. Pick a different agent from the rail, or paste an agent ID or profile URL to load one directly.+3. Browse the live launches. The "Top pick" is highlighted. Each card shows the smart-money and quality bars, market cap, age, and any sybil-cluster flag.+4. Click "Ask for a read" on a launch. The avatar thinks while the server pulls live liquidity, holders, and smart-money signals.+5. The read lands: a verdict badge, a conviction bar that counts up, the spoken quote, the risks, and the exact signals it used (the ones it cited are highlighted). The avatar speaks the line aloud.+6. If you own the agent and the gate is open, click "Act", review the fresh live quote and price impact in the drawer, and confirm. The buy executes through the guarded wallet and links you to the transaction and the custody trail.++## Examples++Get real candidate launches for an agent:++```bash+curl -s 'https://three.ws/api/agents/YOUR_AGENT_UUID/alpha/candidates?network=mainnet' \+ | jq '.items[] | {symbol, market_cap_usd, smart_money_score, quality_score, sybil_flag}'+```++Ask for a grounded read (public, read-only for a published agent):++```bash+curl -s https://three.ws/api/agents/YOUR_AGENT_UUID/alpha/read \+ -H 'content-type: application/json' \+ -d '{ "mint": "SOME_LIVE_MINT", "network": "mainnet" }' \+ | jq '{verdict: .read.verdict, conviction: .read.conviction,+ line: .read.spoken_line, guard: .read.hallucination_guard,+ liquidity: .signals.liquidity_sol, mcap: .signals.market_cap_usd}'+```++When `read.hallucination_guard.line_replaced` is true, the co-pilot caught a figure that did not match the live data and spoke a grounded line instead; the `signals` block is the ground truth.++## Guardrails, states, and limits++- **No fabricated figures reach the mouth.** The model only sees real fetched numbers, and its output is validated against them. A mismatch replaces the line and raises `line_replaced`; the page shows a note that the grounded signals are authoritative.+- **The narrator never signs.** Reading and speaking are strictly separate from spending. Acting is a distinct, explicit owner action.+- **Owner-only, guarded action.** Only the agent's owner sees the action gate. A buy runs through `executeAgentTrade`, re-checked against the firewall and your spend limits at submit, and written to the custody audit. Public viewers see the read but no action.+- **Live quote before confirm.** The act drawer fetches a fresh, non-binding quote showing what you pay, expected output, and price impact; the trade is confirmed against that, not against a stale figure.+- **Spend policy is the ceiling.** Per-trade and daily limits, and a paused-trading flag, are surfaced in the owner's read and enforced server-side; the co-pilot cannot size past them.+- **Empty and error states are designed.** No live launches renders a "check again" state; a feed hiccup or a failed read shows an inline retry; a bad avatar or TTS provider degrades gracefully (browser speech backs up TTS, initials back up a broken avatar).+- **Coin-agnostic.** The read analyzes whatever runtime mint the live feed surfaces and never promotes a specific token.+- **Not financial advice.** A verdict and conviction are informational analytics, one input among many; live trading risks real funds.++## Related++- [Custody you can verify](./custody.md) - the spend limits, firewall, and audit the "Act" path runs under+- [Financial controls](./financial-controls.md) - the plain-English rules and real-time defense on the same rails+- [Oracle](./oracle.md) - the platform conviction engine over the same launch universe+- [Trading surfaces](./trading-surfaces.md) - Mission Control executes through this same guarded path+- [/agi](https://three.ws/agi) - a fully autonomous agent reading and trading the same feeddiff --git a/docs/animation-studio.md b/docs/animation-studio.mdnew file mode 100644index 000000000..0512f8799--- /dev/null+++ b/docs/animation-studio.md@@ -0,0 +1,85 @@+# Animation Studio: pose, keyframe, and sell motion++Animation Studio is where a three.ws avatar (or a built-in mannequin) becomes animated. Click any body part and rotate it with a gizmo, or drag a hand or foot and let inverse kinematics solve the limb. Drop the pose as a keyframe, advance the playhead, re-pose, and drop another; the studio interpolates between them and plays the result. Export the finished motion as an animated GLB or as clip JSON, save it to your account, deep-link it to play on any avatar, hand it to [Scene Studio](./scene-studio.md) to record as video, or list it for sale in the animation marketplace for USDC.++Page: [/pose](https://three.ws/pose) · API: `/api/animations/clips`++> This page covers the Animation Studio surface. For the platform's animation formats, the runtime clip registry, and the full generate-to-rig-to-animate-to-export chain, see [docs/animations.md](./animations.md) and [docs/3d-asset-pipeline.md](./3d-asset-pipeline.md).++## Why it exists++Rigging and animation are the steepest part of 3D. Animation Studio flattens it into something you can do in a browser with a mouse, on the exact avatar you already made, and then actually use the result: play it across the platform, record it, or earn from it. It is built so that posing is direct (grab a body part, move it), keyframing is a two-button loop (pose, drop key), and every export path leads somewhere real, a downloadable file, an account clip, a scene render, or a marketplace listing, rather than a dead end.++## How it works++The studio is a Three.js scene with filmic tone mapping and image-based lighting, a shadow-catching ground, a grid, and a posable rig. The rig is one of two kinds behind a common interface: the built-in primitive **mannequin** (with adjustable build, skin color, and optional biological joint constraints) or a **loaded rigged GLB**, including your own three.ws avatars, resolved through the avatar gallery picker or `?avatar=<id>`.++### Posing: FK and IK++- **FK (forward kinematics).** Click a body part to select its bone; a rotate gizmo attaches, and three sliders (bend/pitch, twist/yaw, tilt/roll) show and set the exact Euler angles. A searchable bone list lets you jump to any joint by name.+- **IK (inverse kinematics).** Switch to IK and drag a glowing hand or foot handle; the limb chain solves to follow it. IK is available only when the rig exposes recognizable limb chains; the toggle disables itself and explains why when it cannot.+- **Pose tools.** Undo/redo (100 deep, with drags collapsing to a single step), mirror left-to-right, copy/paste a pose, a preset picker grouped by category, per-bone reset, and keyboard shortcuts (F for FK, I for IK, M mirror, C/V copy-paste, R reset bone, Escape deselect).++### The keyframe timeline++Set a pose, drop a keyframe on the playhead, move the playhead, re-pose, drop another. The render loop samples the document at the current time (slerping between keyframes) and plays it back. Each keyframe carries an easing curve you can change. You control the clip name, duration, FPS, and loop flag. Transport is play/pause/stop with start/end jumps. Keyframes drag along the lane and delete with a key. In-progress work autosaves to local storage and is offered back on the next visit, and an unload guard warns before you lose unsaved keyframes.++### Preset and text-to-animation library++A curated gallery of ready-made motion clips sits beside the timeline. Picking one retargets it onto the loaded rig and plays it live in the same viewport, then offers an animated-GLB export. The library also drives a text-to-animation path (`POST /api/forge-motion`), so you can describe a motion and get a clip retargeted onto your figure. While a preset previews, it owns the figure and the keyframe timeline yields, so the two never fight over bone transforms.++### Export, save, and sell++- **Clip JSON** serializes the keyframe document to a documented `{ name, duration, tracks }` shape.+- **Animated GLB** bakes the document onto the live rig and exports the mesh with the clip embedded, so the motion plays anywhere the GLB is opened. This baked GLB is also the sellable artifact for a marketplace listing.+- **Open in Scene Studio** stashes the baked GLB in IndexedDB and navigates to `/scene?handoff=1`, where you record it to video.+- **Save to account** stores the clip through `/api/animations/clips` with a visibility of private, unlisted (anyone with the link), or public (listed in the gallery). Saved clips appear under "My animations".+- **Sell for USDC.** Each saved clip has a Sell action that lists it in the animation marketplace; listed clips show a price badge in USDC, and your sales and earnings live under [/marketplace?tab=earn](https://three.ws/marketplace?tab=earn).++## Walkthrough++1. Open [/pose](https://three.ws/pose). The mannequin loads in a starting pose. Click "Load avatar" to pose one of your own instead, or keep the mannequin.+2. Click the mannequin's forearm; the rotate gizmo appears. Drag it, or use the sliders, to bend the arm. Or switch to IK and drag the hand.+3. Set the timeline's duration and FPS. With the playhead at 0, pose the figure and click "Add keyframe".+4. Move the playhead forward, change the pose, and add another keyframe. Press play to watch it interpolate.+5. Tune easing per keyframe, mirror or copy/paste poses, and refine.+6. Export: download the animated GLB or clip JSON, click "Open in Scene Studio" to record video, or "Save" to keep it in your account.+7. To monetize, open the saved clip in "My animations" and click Sell to list it for USDC.++## Examples++Deep links into the studio:++- **Pose a specific avatar:** `https://three.ws/pose?avatar=<avatarId>`+- **Animate a model by URL** (from the viewer's "Animate" funnel; trusted-host gated): `https://three.ws/pose?src=<glbUrl>&title=My%20model`+- **Open a saved clip or a preset:** `https://three.ws/pose?anim=<clipUuidOrPresetName>`: a 36-char UUID opens your saved clip; anything else opens a built-in preset (auto-loading a rigged avatar to play it on).++The account clip API the studio drives:++```bash+# List your clips, plus public ones.+curl 'https://three.ws/api/animations/clips?include_public=true&limit=60' \+ -H 'cookie: <session>'++# Create a clip from a serialized keyframe document.+curl -X POST 'https://three.ws/api/animations/clips' \+ -H 'content-type: application/json' -H 'cookie: <session>' \+ -d '{"name":"wave-loop","visibility":"public","clip":{ "name":"wave-loop","duration":2,"tracks":[] }}'+```++## States & limits++- **IK requires limb chains.** On rigs without recognizable arm/leg chains the IK mode disables itself; FK posing always works.+- **Presets need a rigged figure.** Deep-linking straight to an animation with no avatar chosen auto-loads a built-in rigged avatar (deterministically picked from the clip id) so the motion has a body to play on.+- **Autosave is local, not the account.** Posing and keyframing never touch your account until you explicitly Save. The autosave draft lives in local storage and is offered back next session; an unload guard warns while work is unsaved.+- **Saving and selling need an account.** Export and download are open to everyone; saving to the library and listing for sale require sign-in.+- **The sellable artifact is the baked GLB.** A marketplace listing sells the baked animated GLB, so the buyer gets a self-contained, playable file.+- **Mannequin-only controls.** Build, skin color, and joint constraints apply to the primitive mannequin; on a loaded GLB avatar those controls are disabled.++## Related++- [Animations reference](./animations.md): the runtime clip registry, formats, and agent slots.+- [3D asset pipeline](./3d-asset-pipeline.md): how GLB, FBX, and clip JSON convert across the platform.+- [Scene Studio](./scene-studio.md): record your animation to video.+- [Avatar Studio](./avatar-studio.md): build the avatar you animate here.+- [/marketplace](https://three.ws/marketplace): where listed animation clips are bought and sold.diff --git a/docs/ar-studio.md b/docs/ar-studio.mdnew file mode 100644index 000000000..c83ee213d--- /dev/null+++ b/docs/ar-studio.md@@ -0,0 +1,97 @@+# AR Studio: place many models in your real space, together++AR Studio turns your camera view into an infinite canvas. Place as many 3D models and avatars as you like into the room around you, drawn from your own forges, the community gallery, a pasted GLB link, or brand-new ones forged from a text prompt without leaving the scene. It scales from full WebXR immersive AR down to camera passthrough down to a desktop 3D preview, and it can go multiplayer: open a shared room and everyone in it builds the same scene live. Share an arrangement with a link, or hand it to your phone with a QR code.++Page: [/ar/studio](https://three.ws/ar/studio)+API: `POST /api/forge` (in-view text-to-3D) · `GET /api/forge-gallery` (your and community models). Multiplayer runs on a Colyseus room, `studio_world`.++## Why it exists++The older "View in AR" flow (see [AR and WebXR](./ar.md)) shows one model at a time in a native viewer. AR Studio is the composition tool: a persistent, multi-model scene you arrange in real space and can build with other people at once. It is free, needs no account, and degrades gracefully so it works on a laptop, a phone browser, or a full AR headset. It is where a forge result, a marketplace avatar, and a prompt-conjured prop can all stand in your living room together.++This doc covers what is unique to AR Studio. For the underlying `POST /api/forge` free lane, the `<agent-3d>` "View in AR" methods, the USDZ/Quick Look pipeline, and model-optimization limits, see [AR and WebXR](./ar.md).++## How it works++The page ([`pages/ar-studio.html`](../pages/ar-studio.html)) only imports [`src/ar-studio.js`](../src/ar-studio.js) after a WebGL check. Scene math, serialization, and the share hash live in [`src/ar/studio-scene.js`](../src/ar/studio-scene.js); the Colyseus client is [`src/ar/studio-net.js`](../src/ar/studio-net.js); WebXR multi-placement is [`src/ar/multi-place.js`](../src/ar/multi-place.js).++### Model sources++`addModel({ src, title })` normalizes the URL (https or site-relative only), enforces a 20-model cap, clones the loaded template (using SkeletonUtils for skinned rigs), and drops it on the floor in front of the camera. The "Add models" tray has four tabs:++- **Recent forges**: read from local storage (`twx_ar_forge_recent`), shared with `/ar` so one forge history opens in two doors.+- **Yours**: `GET /api/forge-gallery?limit=24` with an `x-forge-client` header (your anonymous browser id).+- **Community**: `GET /api/forge-gallery?scope=community&limit=24`.+- **GLB link**: paste any https `.glb`: a forge result, a viewer share link's `src`, or your own hosting.++A fifth source is the **in-view forge**: the dock form calls `POST /api/forge` with `{ prompt, backend: 'nvidia' }` (the free NVIDIA NIM / TRELLIS lane), polls `GET /api/forge?job=<id>` until the GLB is ready, remembers it, and drops it into the scene. A sixth is deep links: repeatable `?src=` (paired with `?title=`) and `?forge=<prompt>` boot content on open.++### Device-capability ladder++Best available mode wins:++1. **WebXR immersive AR**: offered only when `navigator.xr.isSessionSupported('immersive-ar')` resolves true. The session requests `hit-test` (required) plus `anchors`, `local-floor`, `depth-sensing`, and `light-estimation`, with a DOM-overlay HUD. Each placed model gets an `XRAnchor`, and an always-armed reticle does tap-to-place.+2. **Camera passthrough**: `getUserMedia({ video: { facingMode: { ideal: 'environment' } } })` becomes the background layer, with gyroscope world-lock look (DeviceOrientation, iOS permission-gated) and live light matching. Offered when `getUserMedia` exists.+3. **Desktop 3D preview**: always available: a grid floor, drag-look, and a "Phone" QR handoff on non-touch devices.++If WebGL is missing, the page never loads the module and shows a fallback linking to `/ar` and `/viewer`.++### Gestures++Tap to select (tap empty space to deselect), drag to move a model you own along the floor, drag empty space to look around, pinch to resize (clamped 0.25x to 4x), and twist with two fingers to rotate. A selection toolbar offers rotate (+45 degrees), duplicate, and remove; desktop keyboard shortcuts nudge with arrows, rotate with R, duplicate with D, and remove with Delete (all undoable).++### Shared live rooms++Rooms run on the same Colyseus server as the other multiplayer surfaces, in a room named `studio_world` ([`multiplayer/src/rooms/StudioRoom.js`](../multiplayer/src/rooms/StudioRoom.js)), filtered by a 6-character room code. "Create a room" seeds the current scene as the starting point; joining via a `?room=CODE` link does not seed. Model transforms travel in a shared logical frame (east/north metres, yaw degrees) so every device maps them onto its own floor. Clients send `model:spawn`, `model:update` (throttled ~12 Hz), and `model:remove`; the server syncs a `StudioState` of models and viewers. Edits are owner-gated (you can only move your own models), models stay when their author leaves, and the server enforces per-room and per-owner caps plus a rate limit. A presence pill shows "N here, M models."++### Share via `#s=` hash++The full arrangement (every model's source and transform) is serialized to JSON, base64url-encoded, and put in the URL fragment as `#s=<hash>`. `studioSceneUrl()` builds a link that carries both a plain `?src=` list (reopens the same models, capped to 4) and the `#s=` hash (carries the exact arrangement), falling back to the `?src=` list if the hash would exceed ~1500 chars. On open, a `#s=` hash is treated as a full document and replaces the working scene; malformed input degrades to an empty scene rather than throwing. The QR modal encodes this URL so your phone opens straight into camera AR with your models placed.++## Walkthrough++1. Open [/ar/studio](https://three.ws/ar/studio). On the empty card, choose Start camera, Browse models, or Forge one.+2. Add models: open the tray and pick from Recent, Yours, or Community, or paste a GLB link. Or type a prompt in the dock ("a neon bonsai tree") and press Forge to generate one in place.+3. Arrange: drag to move, pinch to resize, twist to rotate. On a phone, tap Start camera to see them in your room; on a headset, tap the Immersive button for full AR.+4. Go multiplayer: create a room and share the code (or the link). Others join and see and place models live.+5. Share: use the QR button to continue on your phone, or copy the scene URL (it carries the arrangement in `#s=`).++## Examples++The two HTTP endpoints AR Studio uses are the free, no-auth forge lanes. Your anonymous browser id goes in `x-forge-client`.++```bash+# Forge a model from a prompt (the in-view forge; free NVIDIA NIM lane).+curl -X POST 'https://three.ws/api/forge' \+ -H 'content-type: application/json' \+ -H 'x-forge-client: <ANON_CLIENT_ID>' \+ -d '{ "prompt": "a neon bonsai tree", "backend": "nvidia" }'+# -> { "job_id": "…", "status": "queued" } (or { "status": "done", "glb_url": "…" })++# Poll the forge job until the GLB is ready.+curl -H 'x-forge-client: <ANON_CLIENT_ID>' 'https://three.ws/api/forge?job=<JOB_ID>'+# -> { "status": "done", "glb_url": "https://…/model.glb" }++# List your forge gallery (Yours tab) or the community showcase.+curl -H 'x-forge-client: <ANON_CLIENT_ID>' 'https://three.ws/api/forge-gallery?limit=24'+curl 'https://three.ws/api/forge-gallery?scope=community&limit=24'+# -> { "creations": [ { "glb_url": "…", "prompt": "…", "preview_image_url": "…" } ] }+```++You can also hand-build a share link: append `?src=<https glb url>&title=<name>` (repeatable) to `https://three.ws/ar/studio` to open with those models placed.++## States and limits++- **No auth, fully free.** Identity is an anonymous per-browser id (`forge:cid`), shared with `/forge` and `/creations`; it scopes the Yours tab, attributes in-studio forges, and keys room ownership. No sign-in, no wallet, no payment.+- **Placement caps.** 20 models per local scene; the shared room enforces its own per-room and per-owner caps and a per-client rate limit.+- **Camera and motion.** Camera denial (`NotAllowedError`) shows "Camera permission is blocked... then try again"; no `getUserMedia` disables the camera button but keeps the 3D preview. Denied motion falls back to drag-look.+- **XR unsupported.** The Immersive button simply never appears; a failed XR start shows "Camera mode still works." Lost tracking prompts you to move to a brighter, more textured spot.+- **Rooms offline.** With no multiplayer server configured (production default when unset), the studio stays single-player: "Shared rooms are offline right now, you can still build solo." Departing authors' models remain until the room empties.+- **Persistence.** Your own placed models are saved to local storage (`twx_ar_studio_scene_v1`); `#s=` links replace the working scene. Photo capture composites the camera and WebGL layers to a PNG.+- **Forge failures.** `503`/unconfigured shows "The generator is offline"; `429` shows a busy message with a retry hint.++## Related++- [AR and WebXR](./ar.md): the single-model "View in AR" system, `/ar` AR Forge, the `POST /api/forge` free lane in depth, the USDZ/Quick Look pipeline, and model-optimization limits.+- [Selfie to Avatar](./selfie-to-avatar.md) and [Avatar pipeline](./avatar-pipeline.md): where the models you place come from.+- Pages: [/ar/studio](https://three.ws/ar/studio), [/ar](https://three.ws/ar), [/viewer](https://three.ws/viewer).diff --git a/docs/autopilot.md b/docs/autopilot.mdnew file mode 100644index 000000000..fb62e4309--- /dev/null+++ b/docs/autopilot.md@@ -0,0 +1,96 @@+# Coin Autopilot: hands-off buyback and holder rewards++Coin Autopilot is the control cockpit for a coin you launched through three.ws. You set the rules once (when to buy back and burn, when to distribute creator fees to holders, the floors that gate each), flip the switches you want, and the platform's crons run the coin autonomously. Your agent narrates every on-chain move in plain language on a live feed, so the coin does not just run itself, it tells you what it did.++Page: [/autopilot](https://three.ws/autopilot)+API: `GET/POST /api/pump/autopilot`++## Why it exists++A coin launched from an agent is not a static token, it is a small business: creator fees flow in, and something has to decide what to do with them. Left to a human, that decision is a chore that gets skipped. Autopilot turns the two most valuable of those decisions, buying the token back to make supply scarcer and paying accumulated fees out to holders, into rules the platform enforces on a schedule.++The design goal is control without babysitting. You should be able to set a floor ("only buy back once at least 50 USDC of fees have piled up"), pause a coin with one tap, and otherwise never touch it, while still seeing every move it makes narrated by the agent that owns it. That is the difference between an autonomous coin and an abandoned one.++## How it works++Autopilot is a thin, owner-facing policy layer over crons that already run. Every coin you launched has a policy row (`pump_autopilot`) that gates two existing crons:++- `run-buyback` reads your buyback rule and, when the buyback vault clears your floor, spends collected creator fees to buy the token back and burn it. With `buyback_full_swap` on, fees are swapped into the token before the burn; off, the burn is direct.+- `run-distribute-payments` reads your distribute rule and, when the payment vault clears your floor, pushes accumulated fees out to your configured shareholders.++A coin with no policy row keeps the legacy always-on behavior. Writing a row (which the page does the moment you touch a control) lets you tune or pause it. The API reports the effective runtime state either way, with a `configured` flag so the UI can tell an explicit setting from an inherited default.++Thresholds are shown in USDC and stored as atomic units (6 decimal places). The page converts on the way in and out, so you type `50` and the server stores `50000000`.++### The data path++`GET /api/pump/autopilot` is scoped to coins you own (`pump_agent_mints.user_id`). It joins each mint to its agent identity, its live stats (graduation, bonding-curve progress), and its policy row, then rolls up recent autonomous actions from `pump_buyback_runs` and `pump_distribute_runs` and payment totals from `pump_agent_payments`. The response is your coins, their per-coin policy, per-coin totals (burned, distributions, fees in, payment count), and a merged newest-first activity feed.++`POST /api/pump/autopilot` upserts one coin's policy. It is a merge, not a replace: only the fields you send change, so toggling one switch never clobbers your thresholds. The write is validated (zod) and re-scoped to your ownership before it touches the table.++Auth is a session cookie or a bearer token. Every read and write is rate-limited per authenticated IP.++## Walkthrough++1. Launch a coin for one of your agents (from the dashboard). Until you have at least one launched coin, the page shows a designed empty state pointing you to the launcher.+2. Open [/autopilot](https://three.ws/autopilot). Each coin renders as a card with its image, graduation or bonding-curve progress, and lifetime totals.+3. Use the master switch on a card to turn Autopilot on or off for that coin. "Autopilot on" means its rules run; "Paused" means the crons skip it.+4. Set the **Buyback and burn** rule: toggle it on, set a minimum USDC floor, and choose whether fees are swapped into the token before burning or burned directly.+5. Set the **Distribute to holders** rule: toggle it on and set its minimum USDC floor. Enable "Narrate this coin's actions on the live feed" to have the agent speak its moves.+6. Every change autosaves (checkboxes immediately, number fields after a short debounce). A toast confirms "Autopilot updated".+7. Watch the activity feed and the narrator. As fees accumulate past your thresholds, the crons act, and each buyback or distribution appears with its status and a Solscan link to the on-chain transaction.++## Examples++Read your coins and their policy from the command line:++```bash+curl -s https://three.ws/api/pump/autopilot \+ -H 'authorization: Bearer YOUR_TOKEN' | jq '.coins[] | {symbol, policy, totals}'+```++Set a buyback floor of 50 USDC and turn on full-swap-then-burn for one coin:++```bash+curl -s https://three.ws/api/pump/autopilot \+ -H 'authorization: Bearer YOUR_TOKEN' \+ -H 'content-type: application/json' \+ -d '{+ "mint": "YOUR_MINT_ADDRESS",+ "network": "mainnet",+ "buyback_enabled": true,+ "buyback_min_atomics": "50000000",+ "buyback_full_swap": true+ }'+```++Pause a coin entirely without losing its thresholds:++```bash+curl -s https://three.ws/api/pump/autopilot \+ -H 'authorization: Bearer YOUR_TOKEN' \+ -H 'content-type: application/json' \+ -d '{ "mint": "YOUR_MINT_ADDRESS", "network": "mainnet", "enabled": false }'+```++A confirmed buyback narrates as: "Bought back and burned $120 of $YOURCOIN. Supply just got scarcer." A confirmed distribution: "Distributed $80 in creator fees to $YOURCOIN holders." Queued and failed actions narrate their own status, including the error text on a failure.++## Guardrails, states, and limits++- **Ownership scoped.** Every read and write is filtered to coins whose `user_id` is yours. Posting a policy for a mint you do not own returns `404 not_found`.+- **Floors are the safety valve.** A buyback or distribution only fires once the relevant vault clears the USDC floor you set. Set a floor to zero and it acts whenever the vault is non-empty; raise it to batch actions.+- **Merge semantics.** Partial POSTs only change the fields present. A missing policy row reports legacy defaults (everything enabled, zero floors, narrate on) with `configured: false`.+- **Signed out** renders a "Sign in to manage autopilot" state; `GET` returns `401` and the page routes you to the dashboard.+- **Empty state** appears when you own no coins, pointing you to the launcher rather than showing a blank void.+- **Error and retry.** A network or server error renders an inline "Couldn't load" card with a Retry button; a transient poll failure keeps the last good render and retries on the next tick.+- **Live refresh** polls every 20 seconds and only refreshes the activity feed and narrator, never the control inputs you may be editing, so a poll can never overwrite your keystrokes.+- **Atomics are integers.** Thresholds are clamped to non-negative integer atomic strings server-side; a decimal is truncated, a negative or non-numeric value falls back to zero.+- **On-chain actions are the crons', not the page's.** The console never signs a transaction. It only writes policy rows; the buyback and distribute crons are what move funds, on their own schedule, within the vault floors you set.++## Related++- [Custody you can verify](./custody.md) - the spend limits, freeze switch, and audit trail every agent wallet runs under+- [Financial controls](./financial-controls.md) - plain-English spend rules layered on the same enforcement point+- [Oracle](./oracle.md) - the conviction engine and the agent action loop that arms an agent to trade autonomously+- [/dashboard](https://three.ws/dashboard) - launch a coin for an agent, the prerequisite for Autopilot+- [/launches](https://three.ws/launches) - the public feed of coins launched through three.wsdiff --git a/docs/avatar-studio.md b/docs/avatar-studio.mdnew file mode 100644index 000000000..57393a2fd--- /dev/null+++ b/docs/avatar-studio.md@@ -0,0 +1,67 @@+# Avatar Studio: build a custom avatar from scratch, no selfie++Avatar Studio builds a fully rigged 3D avatar without a photo. You start from a base body and shape it into your own character: tint skin, hair, and outfit; sculpt the face and body with morph sliders; add hats, glasses, and earrings; hide or show garment layers to strip back to the base and build a look up; and drive the rig live with a library of emotes. When you save, the live scene is exported to a GLB exactly as you see it and stored to your account, ready to animate, dress, and use anywhere on the platform.++Page: [/avatar-studio](https://three.ws/avatar-studio) (also reachable at [/create/studio](https://three.ws/create/studio))++## Why it exists++The selfie-to-avatar path is great when you want to look like yourself, but it is a wall when you want to be someone, or something, else. Avatar Studio is the from-scratch path: no camera, no upload, just a base humanoid and the tools to make it yours. It reuses the same building blocks as the platform's avatar editor, the `TalkScene` viewport, the accessory manager, the sculpt panel, and the shared GLB optimize-and-validate path, so an avatar built here is a first-class avatar everywhere, not a lesser one. And because the customization is stored both as a validated GLB (so it always renders right) and as re-editable appearance metadata, you can come back and change it later.++## How it works++The studio mounts a `TalkScene` around a base model (`/avatars/default.glb`, a feminine base body) and layers a tabbed customization panel over it. Every edit updates the live scene graph, and a working "appearance" object tracks the whole configuration: chosen colors, morph values, accessories, and hidden layers.++- **Color.** Three material slots (skin, hair, outfit) each offer a curated swatch palette plus a full-spectrum picker (an `iro.js` wheel with hex entry and eyedropper, falling back to the native OS color dialog). Above them sit **Looks**: one-tap palettes (Noir, Sunset, Arctic, Cyber, Rosé, Forest, Mono, Ember) that theme skin, hair, and outfit together in a single history step, always landing on real, coherent material colors.+- **Face and body sculpt.** The sculpt panel renders grouped morph sliders against whatever morph targets the base carries, organized into Eyes, Brows, Nose, Mouth, Jaw, Cheeks, and Body (height, chest/waist/hip, muscle, and similar shape morphs), plus a MetaHuman-style 2-D face-type blend wheel over six archetypes and advanced visemes. It drives real morph targets, so the change is baked into the saved mesh.+- **Accessories.** Hats, glasses, and earrings load from a preset catalog (`/accessories/presets.json`). Hovering a tile previews it live on the avatar; clicking commits it. Hats and glasses are single-slot; earrings stack. A chip row shows everything applied, each removable.+- **Garment layers.** Outfit, glasses, and hair can be toggled visible/hidden, with bulk "Start minimal" and "Dress fully" actions, so you can strip to the base body and rebuild the look deliberately.+- **Animate.** Load the shared canonical clip library and drive the rig live with 16 emotes (idle, wave, cheer, flex, jump, pray, dance, shuffle, rumba, thriller, capoeira, and more). A looping emote becomes the avatar's resting idle and is baked in on save; one-shots play once and settle back to the current idle. This doubles as proof the avatar is fully rigged.+- **Randomize.** One button rolls a random swatch per color slot and a random hat and glasses, as a starting point.++The studio has 50-deep undo/redo, a dirty-state indicator in the title bar, and a draft autosave to local storage that is offered back if you leave and return (in create mode).++### Save++Saving does not ask a server to re-bake anything. The live Three.js scene, with colors, morphs, and accessories already applied to the scene graph, is exported via `GLTFExporter`, so the resulting GLB is exactly what you saw. It runs through the shared optimize-and-validate path (geometry compression, `gltf-validator`), uploads to your account, and creates or (in edit mode) updates the avatar record. The appearance JSON is stored alongside as metadata so the avatar stays re-editable.++## Walkthrough++1. Open [/avatar-studio](https://three.ws/avatar-studio). The base avatar loads and settles into an idle animation.+2. On the Color tab, tap a Look (say, Cyber) for an instant coherent palette, then fine-tune skin, hair, and outfit with the swatches or the rainbow chip's full picker.+3. Open the Face tab and sculpt: widen the jaw, adjust the nose, nudge body shape. Use the face-type wheel to blend archetypes.+4. Add a hat and glasses from their tabs; hover to preview, click to keep. Add earrings if you want.+5. Use the Layers block to hide the outfit and rebuild it, or leave it dressed.+6. On the Animate tab, pick a looping emote (for example, Dance) to set the avatar's resting idle.+7. Name it and click Save. The studio exports, optimizes, uploads, and lands you with a saved avatar you can animate and dress elsewhere.++## Examples++Avatar Studio is an interactive builder; its examples are its entry points and the account API it saves through.++- **Create a new avatar:** [https://three.ws/avatar-studio](https://three.ws/avatar-studio) or [https://three.ws/create/studio](https://three.ws/create/studio)+- **Edit a saved avatar:** `https://three.ws/avatar-studio?edit=<avatarId>`: reloads that avatar's appearance and updates the existing record on save.++Fetching an avatar record (the same call the studio makes to load edit mode):++```bash+curl 'https://three.ws/api/avatars/<avatarId>' -H 'cookie: <session>'+# → { "avatar": { "id": "…", "name": "…", "model_url": "…", "appearance": { … } } }+```++## States & limits++- **No selfie, no camera.** This is the from-scratch path. To build an avatar from a photo, use the platform's selfie-to-avatar flow under [/create](https://three.ws/create) instead.+- **Feminine base body.** The studio starts from a single feminine base model; masculine and other builds are not selected here (the posable primitive with a build toggle lives in [Animation Studio](./animation-studio.md)).+- **Sculpt depends on the base's morphs.** The face/body sliders render against whatever morph targets the base GLB exposes; a slot with no matching morph simply does not appear.+- **Save requires an account.** Export happens client-side, but persisting the avatar to your library needs sign-in. Optimization is best-effort: if compression fails, the original export is saved untouched so the save always completes.+- **What you see is what you save.** Because the save exports the live scene graph, the stored GLB matches the viewport exactly, colors, morphs, accessories, and the chosen idle included.+- **Drafts are local.** Unsaved work autosaves to local storage in create mode and is offered back on return; edit mode does not autosave a draft over the saved avatar.++## Related++- [Animation Studio](./animation-studio.md): pose and keyframe the avatar you build here.+- [Scene Composer](./compose.md): forge props and attach them to the avatar's bones as a saved outfit.+- [Mocap Studio](./mocap-studio.md): drive the avatar's face live from your webcam.+- [Restyle Studio](./restyle.md): shares the same GLB optimize-and-validate path.+- [/create](https://three.ws/create): the hub for every avatar-creation path, including selfie-to-avatar.diff --git a/docs/brain.md b/docs/brain.mdnew file mode 100644index 000000000..48c6ecf1f--- /dev/null+++ b/docs/brain.md@@ -0,0 +1,123 @@+# Multi-LLM Brain: one prompt, every model, side by side++The Brain lab sends a single prompt to many frontier models at once and streams+their answers side by side, each with live latency and token stats. Claude, GPT,+Qwen, ModelScope, Groq, and more respond in parallel so you can compare tone, speed,+and cost before you wire a model into an agent. It is the fastest way to decide which+brain an agent should carry.++Page: [/brain](https://three.ws/brain) · API: `/api/brain/chat`++## Why it exists++Choosing a model from a spec sheet is guesswork. The only honest comparison is the+same prompt, at the same moment, across every candidate, with real timing. Brain+gives you that: a compare view that fans one prompt out to the whole roster and shows+you who answered first, who was most thorough, and what each one cost in tokens. It+also doubles as the model picker behind the Brain tab of+[Agent Studio](./agent-studio.md), so the model you pick here is the model your agent+runs on.++## How it works++`/api/brain/chat` is a multi-LLM proxy with two verbs.++- **`GET /api/brain/chat`** returns the available providers and which are currently+ reachable, so the UI can gray out anything whose upstream key is missing.+- **`POST /api/brain/chat`** takes `{ provider, messages, system?, maxTokens? }` and+ streams the answer back as Server-Sent Events:+ - `event: meta` with `{ provider, label, network, model, tier }`+ - `event: first` with `{ firstTokenMs }` (the time-to-first-token the UI shows)+ - data-only frames carrying JSON-encoded text chunks+ - `event: done` with `{ elapsedMs, firstTokenMs, usage }` (the token stats)+ - `event: error` with `{ message, elapsedMs }`++Each provider spec declares its native first-party model (built from a first-party+key when present) and the OpenRouter model id that mirrors it. The proxy prefers the+native model and falls back to routing through OpenRouter, and if a native provider+hits a quota, billing, or rate-limit error at request time it reroutes around the+outage through the mirrored OpenRouter id. The roster spans Anthropic (Claude Fable+5, Mythos 5, Opus 4.7, Sonnet 4.6, Haiku 4.5), OpenAI (GPT-OSS 120B, the GPT-5.x+family, o3 family), xAI (Grok 4.x), Groq (Llama 3.3 70B), DashScope (Qwen Plus),+ModelScope (Qwen3-Coder 480B), DeepSeek R1, and IBM Granite on watsonx.ai. In compare+mode the page opens one streaming POST per selected provider and renders them in a+grid, so every model streams concurrently rather than in sequence.++Anonymous callers are gated to the genuinely free tiers only (the OpenRouter-routed+open-weight default and the free NVIDIA NIM models); every paid first-party model+requires sign-in so an unauthenticated script cannot drain the server's billed API+keys.++## Walkthrough++1. **Open [/brain](https://three.ws/brain).** The provider roster loads from+ `GET /api/brain/chat`; unavailable providers are marked.+2. **Pick your models.** Select one for a focused chat, or switch to Compare mode to+ query all selected models at once.+3. **Type one prompt.** Optionally set a system prompt to steer every model+ identically.+4. **Watch them stream.** Each column shows the model streaming in real time, with+ time-to-first-token appearing the moment the first chunk lands.+5. **Read the stats.** When a model finishes, its column shows total elapsed time and+ token usage from the `done` event.+6. **Commit a choice.** Carry the winner into your agent via the Brain tab of+ [Agent Studio](./agent-studio.md).++## Examples++List the reachable providers:++```bash+curl -s https://three.ws/api/brain/chat+# returns { providers: [ { key, label, network, available, ... }, ... ] }+```++Stream one model's answer as SSE (the free default needs no auth; paid models need a+session or bearer token, see [Authentication](./authentication.md)):++```bash+curl -N -s -X POST https://three.ws/api/brain/chat \+ -H 'content-type: application/json' \+ -d '{+ "provider": "gpt-oss-120b",+ "system": "You are terse.",+ "messages": [{ "role": "user", "content": "Name three uses for a 3D avatar." }],+ "maxTokens": 256+ }'+# streams event: meta ... / event: first { firstTokenMs } / data chunks / event: done { elapsedMs, usage }+```++To compare, open one POST per provider concurrently (this is exactly what Compare mode+does in the browser):++```bash+for p in claude-sonnet-4-6 gpt-oss-120b groq-llama modelscope-qwen; do+ curl -N -s -X POST https://three.ws/api/brain/chat \+ -H 'content-type: application/json' \+ -H "authorization: Bearer $THREEWS_TOKEN" \+ -d "{\"provider\":\"$p\",\"messages\":[{\"role\":\"user\",\"content\":\"One-line pitch for three.ws\"}]}" &+done; wait+```++## States and limits++- **Availability gating.** A provider whose upstream key is absent shows as+ unavailable in the roster and is skipped rather than erroring mid-stream.+- **Anonymous scope.** Signed-out users can only call the free tiers (the+ OpenRouter-routed default and free NVIDIA NIM models). Paid first-party models+ return an auth requirement.+- **Automatic failover.** A native provider outage (quota, billing, rate limit) is+ rerouted through the mirrored OpenRouter model at request time, so a single upstream+ hiccup does not blank a column.+- **Streaming errors are per-column.** An `event: error` frame fails only that+ provider's column; the rest keep streaming.+- **Token stats.** `usage` in the `done` event reflects the provider's reported token+ counts; context window and tier shown per model come from the roster metadata.++## Related++- [Agent Studio](./agent-studio.md): the Brain tab uses this same backend+- [Agent System](./agent-system.md): how a chosen brain fits the agent model+- [Persona Hub](./persona-hub.md): synthesizing the system prompt a brain runs+- [API reference](./api-reference.md) and [Authentication](./authentication.md)+- Pages: [/brain](https://three.ws/brain), [/agent-studio](https://three.ws/agent-studio)diff --git a/docs/capture.md b/docs/capture.mdnew file mode 100644index 000000000..8bc5e5d19--- /dev/null+++ b/docs/capture.md@@ -0,0 +1,94 @@+# Scene Capture: video to explorable 3D point cloud++Scene Capture turns a phone video of any space into an explorable 3D point cloud you can orbit in the browser. Film a room, a street, or an object, hand it a public video URL, and a streaming feed-forward reconstruction fuses the frames into a coloured `.ply` that renders live with WebGL. Already have a point cloud? Drop it in or paste a URL and skip straight to the viewer.++Page: [/capture](https://three.ws/capture) · API: `/api/scene-capture`++## Why it exists++Photogrammetry and SLAM traditionally mean an offline pipeline: extract frames, match features, bundle-adjust, and wait. Scene Capture collapses that into a single feed-forward pass: no per-scene optimization, no manual camera poses, just frames in and dense world-space geometry out. It is the fastest way to go from "I filmed this place on my phone" to "I can orbit this place in my browser," and because the output is a standard coloured `.ply`, it drops into any point-cloud tool afterward.++## How it works++The endpoint (`api/scene-capture.js`) routes to `workers/model-video2scene`, a GPU worker on Cloud Run running **LingBot-Map**, a feed-forward Geometric Context Transformer that reconstructs dense world-space geometry directly from video frames. You submit a public https URL to an mp4, mov, or webm; the handler resolves and validates the host itself (rejecting private, loopback, and metadata IPs as defense in depth against SSRF) before handing the URL to the worker. Submission returns `202 { job_id, status, eta_seconds }`, and the browser polls `GET /api/scene-capture?job=<id>` until the worker returns a `result_url` for the finished `.ply`, along with `num_points` and `frames`.++Reconstruction exposes real, clamped sampling knobs:++| Param | Range | Default | What it controls |+| --- | --- | --- | --- |+| `mode` | `streaming` / `windowed` | `streaming` | Continuous streaming fusion, or fixed-window batches. |+| `fps` | 1-30 | 8 | Frames sampled per second of video. |+| `keyframe_interval` | 1-64 | 4 | Spacing between keyframes. |+| `num_scale_frames` | 2-16 | 8 | Frames used to resolve metric scale. |+| `window_size` | 16-512 | 128 | Frame window for the windowed mode. |+| `conf_percentile` | 0-95 | 30 | Confidence floor for keeping a point. |+| `max_points` | 50k-3M | 1.5M | Cap on total output points. |+| `voxel_size` | 0-10 | 0 | Optional voxel downsampling. |+| `mask_sky` | bool | true | Drop sky pixels so open scenes don't fill with noise. |++The result is a binary `.ply` the page renders client-side with a WebGL point-cloud viewer (`src/scene-capture.js` and `pointcloud-viewer.js`). Every state is designed: idle, submitting, processing (with an elapsed timer and stage hints), live, and error. There is no mock path: when the worker env (`GCP_VIDEO2SCENE_URL` and `GCP_RECONSTRUCTION_KEY`) is not configured, the endpoint returns a clean 503 and the page still proves the renderer end-to-end with a built-in sample room cloud. You can also load any `.ply` you already have by URL or file, so the viewer is useful even where reconstruction is offline.++## Walkthrough++1. Open [/capture](https://three.ws/capture).+2. Try the sample cloud first to confirm the viewer renders on your device.+3. To reconstruct, film a space, upload the video somewhere public, and paste its https URL. Slow, overlapping passes with good lighting reconstruct best.+4. Submit. A processing state shows the elapsed time and stage hints while the worker streams frames through LingBot-Map.+5. When the point cloud lands it renders live: orbit, zoom, and pan. The HUD shows the point count.+6. Download the `.ply`, or load a different cloud by URL or file.++## Examples++Reconstruction is an async job over a public video URL.++```bash+# Start a reconstruction from a public video, then poll for the .ply.+JOB=$(curl -s -X POST 'https://three.ws/api/scene-capture' \+ -H 'content-type: application/json' \+ -d '{"video_url":"https://example.com/room-walkthrough.mp4","mode":"streaming","fps":8}' \+ | python3 -c 'import sys,json;print(json.load(sys.stdin).get("job_id",""))')++curl "https://three.ws/api/scene-capture?job=$JOB"+```++Tune sampling for a denser cloud from a longer clip:++```bash+curl -X POST 'https://three.ws/api/scene-capture' \+ -H 'content-type: application/json' \+ -d '{"video_url":"https://example.com/street.mp4","fps":12,"keyframe_interval":6,"max_points":2500000,"mask_sky":true}'+```++Poll until the cloud is ready in JavaScript:++```javascript+const start = await fetch('https://three.ws/api/scene-capture', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ video_url: 'https://example.com/object-orbit.mp4' }),+}).then((r) => r.json());++let job = start;+while (job.status !== 'done' && job.status !== 'failed') {+ await new Promise((r) => setTimeout(r, 4000));+ job = await fetch(`https://three.ws/api/scene-capture?job=${start.job_id}`).then((r) => r.json());+}+console.log(job.result_url, job.num_points); // coloured .ply + point count+```++## States and limits++- **Input** is a public https URL to an mp4, mov, or webm. Private, loopback, and metadata hosts are rejected before the worker sees the URL.+- **Processing**: a real elapsed timer with stage hints, driven by the poll lifecycle, not a fake bar.+- **Unconfigured (503)**: when the video2scene worker env is absent, the page falls back to a sample room cloud so the renderer still works end-to-end. No fabricated reconstruction is ever shown.+- **Error**: an invalid `.ply` reports "that isn't a valid point cloud"; a blocked fetch explains the CORS limit.+- **Point cap** defaults to 1.5M and tops out at 3M; `voxel_size` and `conf_percentile` trade density for cleanliness.+- **Client-side rendering**: the `.ply` is decoded and displayed in the browser with WebGL; very large clouds are bounded by your device's GPU and memory.+- Rate limits are per client IP on the shared 3D generation buckets.++## Related++- [Splat Viewer](./splat.md) renders Gaussian-splat radiance fields, the photoreal cousin of point clouds.+- [/avatar-engines](https://three.ws/avatar-engines) covers the Geometric Context Transformer and related capture engines.+- [Forge](./forge.md) and [Image to 3D](./image-to-3d.md) for generating meshes from prompts and photos.+- Pages: [/scene](https://three.ws/scene) (Scene Studio), [/create](https://three.ws/create).diff --git a/docs/clash.md b/docs/clash.mdnew file mode 100644index 000000000..068c162cb--- /dev/null+++ b/docs/clash.md@@ -0,0 +1,79 @@+# Coin Clash: token-gated community warfare++Coin Clash turns every coin community into an army. Hold the coin, sign a wallet challenge to enlist, and rally for your faction in timed battles: the side that taps hardest before the round ends wins. Factions and their social stats come from real communities, enlistment is gated on a live on-chain holding, and battle power is persisted and settled on a deterministic global clock. It is an early demo of a bigger community-warfare idea the platform is building for $THREE.++Page: [/clash](https://three.ws/clash)++API: `/api/clash/[action]` with `action` one of `state`, `enlist`, `enlist-verify`, `rally`, `leaderboard`.++## Why it exists++Coin communities already behave like tribes. Coin Clash gives that tribalism a game loop with real stakes of identity: you can only fight for a coin you actually hold, so rallying is a public act of conviction, and a community's showing on the board is a live measure of how many holders will show up. The token gate is a real balance read, not a client-side check, which makes it a working demonstration of the same "hold, do not just claim" primitive used across the platform (see [token-gated 3D embeds](./token-gated-3d-embeds.md) and [hold to access](./hold-to-access.md)). Effort wins, not market cap: a battle is decided by summed taps, so a smaller, more active army can beat a larger, quieter one.++## How it works++The page (`src/clash.js`) polls `GET /api/clash/state` every 5 seconds (paused while the tab is hidden) and renders the live bracket. There is no websocket; liveness is polling. All five actions route through a single handler, `api/clash/[action].js`, backed by the engine in `api/_lib/clash.js` and an Upstash Redis store (`api/_lib/clash-store.js`) with an in-process fallback.++**Factions.** Every community loaded from CoinCommunities becomes a faction, ranked strongest-first by member count and capped at `MAX_FACTIONS`. If the community source is unconfigured the API returns `503 cc_unconfigured` and the page shows a designed "temporarily unavailable" state and stops polling.++**Rounds (epochs).** Battles run on a deterministic global clock: `epoch = floor(now / EPOCH_MS)` with `EPOCH_MS` defaulting to 1 hour. Every serverless instance agrees on the current round without coordination. Matchmaking rotates the member-ranked pool by an epoch-derived hash (so the top seed does not always meet the second) and folds it into adjacent pairs; an odd count gives the lowest seed a bye. The previous round is settled lazily on each `state` read (claimed once via a Redis `SET NX`, so it is idempotent and needs no cron): faction powers are re-read, the same bracket is recomputed, and each battle is decided on raw power (higher wins, equal draws, both-zero writes no record). Win, loss, draw, and lifetime power fold into a permanent `clash:record` hash.++**Momentum.** Each faction carries a bounded vigor bonus between 1.0 and 1.5, blended from social recency, member mass, and a positive pump.fun price move. Missing signals contribute nothing and never block a rally.++## Token-gating and enlistment++Enlisting is a three-step gate, Solana only:++1. **Challenge.** `POST /api/clash/enlist` with `{ token, wallet }` returns a stateless, HMAC-signed message bound to that exact wallet and faction, valid for 5 minutes.+2. **Signature.** The wallet (Phantom via `window.solana`) signs the message; `POST /api/clash/enlist-verify` re-checks the challenge is un-tampered and fresh, then verifies the signature against the claimed wallet. A bad signature returns `401 bad_signature`.+3. **Holding.** The server reads the wallet's live on-chain balance (`getBalances`, Helius DAS with public-RPC failover) and confirms it holds the faction coin. The threshold is any strictly positive balance; there is no USD minimum (the USD figure is display-only, priced via the pump.fun bonding curve so even a fresh coin shows a real number). A non-holder gets `{ eligible: false, reason: 'not_a_holder' }`.++On success the server mints a **war pass**: a compact HMAC-signed token carrying the wallet, mint, amount, and USD, valid for 30 minutes. The rally endpoint trusts this pass instead of re-reading the chain on every tap.++## Rallying++`POST /api/clash/rally` with `{ pass, taps }` spends taps as faction battle power. Taps are clamped to `MAX_TAPS_PER_RALLY` (50 per call). Power added is `max(1, round(taps * POWER_PER_TAP * momentum))` with `POWER_PER_TAP = 1`. A per-wallet, per-faction, per-round cap (`MAX_POWER_PER_WALLET_EPOCH`, default 5000) is reserved atomically in Redis, so a wallet cannot exceed its ceiling and the client stops tapping once capped. The client batches taps and flushes them (and flushes any buffered taps on page hide via `sendBeacon`), backing off and re-queuing on a 429.++The leaderboard (`GET /api/clash/leaderboard`) returns all-time faction records sorted by wins then lifetime power, with a per-faction win rate, and optionally a single faction's top-10 soldiers this round via `?faction=<mint>`.++## Walkthrough++1. Open [/clash](https://three.ws/clash). The Arena tab shows the current round's battles as tug-of-war bars, each side showing its army's power, momentum, member count, and war record; the header counts down to the round end.+2. Connect a Solana wallet and pick a faction whose coin you hold. Click Enlist; approve the message signature in Phantom.+3. If you hold the coin, a war pass is issued and the Rally dock opens. Tap the RALLY button to add power; watch your power, the cap bar, and your army's total climb.+4. When the round ends, the result folds into the War Records tab. Check the leaderboard to see which communities are winning and where yours ranks.++## Examples++Reads are public and IP rate-limited; the write actions require a real wallet and signature.++```bash+# The live bracket for the current round+curl 'https://three.ws/api/clash/state'++# All-time faction war records, plus one faction's top soldiers this round+curl 'https://three.ws/api/clash/leaderboard?faction=<MINT>'++# Step 1: request an enlist challenge for a faction+curl -X POST 'https://three.ws/api/clash/enlist' \+ -H 'content-type: application/json' \+ -d '{"token":"<FACTION_MINT>","wallet":"<YOUR_WALLET>"}'+```++The Coin Clash state and leaderboard are also exposed read-only over MCP through `@three-ws/clash-mcp` (`get-clash-state`, `get-clash-leaderboard`).++## States and limits++- **Auth.** Viewing needs no login. Enlisting requires a connected Solana wallet and a message signature; rallying requires a valid war pass.+- **Rate limits.** Enlist and enlist-verify are limited to 20 per 5 minutes per IP; rally is 40 per minute per wallet; state and leaderboard are 120 per minute per IP.+- **Pass expiry.** A war pass lives 30 minutes; after that rally returns `401 pass_invalid` and the client transparently re-enlists if the wallet is still connected. Switching wallets drops the enlistment and prompts a re-enlist.+- **Empty and degraded states.** Fewer than 2 active communities shows "No battles live right now" with a link to `/communities`; a bye faction is labeled. An unconfigured community source shows a temporarily-unavailable state and stops polling. A Redis outage degrades silently to per-instance tallies and still serves 200s.+- **Validation.** Taps must be a positive integer and are clamped to 50 per call. The ambient particle field is skipped under `prefers-reduced-motion`.++## Related++- [Token-gated 3D embeds](./token-gated-3d-embeds.md): the same real on-chain balance gate, applied to embeds+- [Hold to access](./hold-to-access.md): the platform's broader hold-do-not-spend membership thesis+- [The social layer](./social-layer.md): platform-wide feed, follows, and leaderboards+- [MCP tools](./mcp.md): the read-only Clash MCP server+- Pages: [/clash](https://three.ws/clash) · [/communities](https://three.ws/communities)diff --git a/docs/compose.md b/docs/compose.mdnew file mode 100644index 000000000..081ce4481--- /dev/null+++ b/docs/compose.md@@ -0,0 +1,77 @@+# Scene Composer: dress an avatar and stage a scene++Scene Composer is a real-time multi-object 3D editor built around one idea: bring a character in, generate props for it from text, and attach them to the right place on its body. Load one of your three.ws avatars (or any rigged GLB), type "horned crown" or "magic staff", and the item is forged and dropped into the scene. Pick it up, snap it to the avatar's head or hand bone, scale it, and it rides that bone. Then export the whole staged scene as a GLB, or save the attached items back onto the avatar as a reusable outfit.++Page: [/compose](https://three.ws/compose)++## Why it exists++Generating a character and generating a hat are easy in isolation. Making the hat sit on the head, follow it when the character moves, and persist as part of that character's look is the hard, unglamorous part, and it is exactly what turns a pile of separate models into a dressed, staged avatar. Scene Composer closes that gap. It wires the platform's text-to-3D Forge lane directly into a scene graph with bone attachment, so the loop from "I want a crown" to "the crown is on my avatar's head and saved to its wardrobe" happens in one place, with real gizmos and real undo, not a chain of exports and re-imports.++## How it works++The page is a Three.js scene with PMREM image-based lighting, soft shadows, exponential fog for depth, and a three-point key/fill/rim light rig. Everything you add becomes a tracked scene object with a role (avatar, accessory, item, scene, creature, vehicle, or other).++- **Forge from text.** The prompt box posts to `/api/forge` with an optional intent (accessory, item, scene, creature, vehicle) that becomes the model's category. The studio polls the job to completion, streaming staged progress, then loads the resulting GLB into the scene. Meshopt-compressed models are decoded on load. Generation runs on the platform's real text-to-3D lanes; a queued job restarts the timeout window so waiting for a GPU never counts against the run budget.+- **Transform gizmos.** Select any object and translate, rotate, or scale it with `TransformControls`. Toggle world/local space, turn on 0.25-unit grid snapping, and lock proportional scale. Every drag and every numeric-field edit is one undoable step in a 50-deep undo/redo stack.+- **Bone attachment.** When a rigged avatar is in the scene, any non-avatar item's inspector gains an "Attach to Bone" control. The avatar's bones are grouped into readable regions (Head, Torso, Left/Right Arm, Left/Right Leg, Fingers L/R) with the raw bone names cleaned of rig prefixes (`mixamorig:`, `CC_Base_`, `rig_`). Attaching parents the item to that bone at the origin, so it rides the bone; detaching returns it to world space.+- **Scene tooling.** Click-to-select raycasting, a hierarchy panel with per-object visibility and rename (double-click), camera presets (front/back/left/right/top/isometric, plus Blender-style numpad keys), F to frame the selection, Ctrl+D to duplicate, a live triangle-and-object counter, screenshot export, and toast notifications for every action. Geometry, materials, and textures are disposed on removal, so long sessions do not leak memory.+- **Bring your own avatar.** Load an avatar by URL, browse your gallery through `/api/explore`, or arrive with `?avatar=<id>` (resolved via `/api/avatars/<id>`) or `?glb=<url>`. If the avatar ships animations, its first clip (typically idle) plays automatically through an `AnimationMixer`.++### Export vs. save outfit++There are two ways out. **Export GLB** bakes every visible, non-bone-attached object into one downloadable `scene-compose.glb`. **Save outfit** takes a different path: for a three.ws avatar loaded from `/avatars/<id>`, it PATCHes the bone-attached items (bone name, GLB URL, name) onto that avatar's record as `accessories`, so the outfit becomes part of the avatar everywhere it appears. Save outfit needs at least one item attached to a bone and a resolvable avatar id; otherwise it points you to Export GLB.++## Walkthrough++1. Open [/compose](https://three.ws/compose). Load an avatar: paste a model URL, click "Browse" to pick from your gallery, or skip and compose props only.+2. Choose an intent chip (for example, Accessory), pick a suggested prompt or type your own ("neon visor"), and forge it. Watch the progress bar; the item drops into the scene when it is done.+3. Select the item. In the inspector, open "Attach to Bone", choose Head from the region-grouped list, and click Attach. The visor snaps onto the head.+4. Switch the gizmo to scale (press R) and size it to fit. Use grid snap and proportional lock as needed.+5. Add more items, attach them to hands or the torso, and arrange the composition. Frame with F, orbit, and take a screenshot to preview.+6. Click "Save outfit" to write the attached items back onto your avatar, or "Export GLB" to download the whole staged scene.++## Examples++Scene Composer is an interactive editor; its examples are its deep links and the endpoints it drives.++- **Open with a specific avatar:** `https://three.ws/compose?avatar=<avatarId>`+- **Open with a forged item preloaded:** `https://three.ws/compose?glb=https://.../item.glb`++The Forge call the studio makes for every generation:++```bash+curl -X POST 'https://three.ws/api/forge' \+ -H 'content-type: application/json' \+ -H 'x-forge-client: <your-client-key>' \+ -d '{"prompt":"horned crown","model_category":"accessory"}'+# → { "job_id": "…" } then poll:+curl 'https://three.ws/api/forge?job=<job_id>' -H 'x-forge-client: <your-client-key>'+# → { "status": "done", "glb_url": "https://.../crown.glb" }+```++Saving attached items as an avatar outfit:++```bash+curl -X PATCH 'https://three.ws/api/avatars/<avatarId>' \+ -H 'content-type: application/json' \+ -H 'x-forge-client: <your-client-key>' \+ -d '{"accessories":[{"bone":"mixamorig:Head","glbUrl":"https://.../crown.glb","name":"Horned crown"}]}'+```++## States & limits++- **Bone attachment needs a rigged avatar.** The "Attach to Bone" control only appears when an avatar with bones is loaded. A non-humanoid or unrigged model can still be arranged and exported, just not bone-parented.+- **Save outfit is for three.ws avatars.** It only works when the loaded avatar came from `/avatars/<id>` (so it has a record to PATCH). For any other model, use Export GLB.+- **Bone-attached items are excluded from Export GLB.** Export bakes visible, world-space objects; items parented to a bone belong to the avatar and are saved through Save outfit instead.+- **Generation can take minutes.** Full-quality bakes legitimately run past ten minutes; the studio's ceiling sits above the slowest real generation, and a queued job restarts the wait window. A genuinely failed or timed-out job surfaces an actionable error.+- **Undo is 50 deep.** Transforms, adds, and removes are undoable (Ctrl+Z / Ctrl+Y); a full scene wipe is not a single undo step.+- **Ownership is client-keyed.** Forge creations and the gallery are scoped to a per-browser client key stored in local storage, so your generations follow the browser without an account.++## Related++- [Avatar Studio](./avatar-studio.md): build the avatar you dress here.+- [Animation Studio](./animation-studio.md): pose and animate the dressed avatar.+- [Scene Studio](./scene-studio.md): the full three.js editor for heavier scene authoring.+- [Restyle Studio](./restyle.md): re-skin the forged props before attaching them.+- [/forge](https://three.ws/forge): the text-to-3D generator behind the prompt box.diff --git a/docs/cosmos.md b/docs/cosmos.mdnew file mode 100644index 000000000..a5ff2e5cb--- /dev/null+++ b/docs/cosmos.md@@ -0,0 +1,83 @@+# Cosmos: living worlds behind your 3D avatar++Cosmos turns a sentence into a living, photoreal world that plays behind your 3D avatar. You pick an avatar, describe a place, and NVIDIA Cosmos renders a short cinematic video of that world; the platform composites it as a full-bleed backdrop behind your transparent avatar, so your character appears to stand inside a moving scene. Generate it, preview it live, and download the clip.++Page: [/cosmos](https://three.ws/cosmos) · API: `/api/cosmos`++## Why it exists++A 3D avatar on a flat gradient is a portrait. A 3D avatar standing in a neon Tokyo street in the rain is a scene. Cosmos gives every avatar a world to inhabit without a render farm, a game engine, or a video editor: you type the place, and a world model paints it in motion. It is the cinematic backdrop layer of the platform, the fastest way to put a character somewhere and make the result look alive.++## How it works++Cosmos runs on NVIDIA's Cosmos World Foundation Model family. The endpoint (`api/cosmos.js`) calls the **Text2World predict** model through NVIDIA's NVCF async gateway: a submit returns a request id, which is handed back to the browser as the `job_id`, and each poll asks NVCF for status and, on completion, persists the resulting MP4 to durable object storage (R2) and returns a stable URL. There is no server-side job store; the NVCF request id is the durable handle, exactly like the free TRELLIS text-to-3D lane. Cosmos predict renders roughly five seconds of 1280x704 video at 24fps, which on the shared free tier typically lands in 60 to 120 seconds.++The lane reuses the platform `NVIDIA_API_KEY` (the free NIM tier). When that key is absent, the lane reports itself unconfigured (503) and the page degrades gracefully: the avatar still stands on a designed, slowly shifting aurora backdrop instead of a blank void.++On the page (`src/cosmos.js`), the avatar is a Google `<model-viewer>` with a transparent background. Five humanoid avatars ship bundled for instant selection (Aria, Kai, Michelle, X-Bot, Mona), and you can bring your own. The generate flow is real async with no fake timers: submit to `POST /api/cosmos`, then poll `GET /api/cosmos?job=<id>` every four seconds (with a five-minute ceiling), driving a real elapsed-based progress state. When the clip is ready it plays on canplay as a looping backdrop behind the avatar, a regenerate control appears, and the clip is available to download.++## Walkthrough++1. Open [/cosmos](https://three.ws/cosmos).+2. Pick an avatar from the bundled set, or load your own GLB. The avatar renders immediately over the fallback aurora backdrop.+3. Describe a world in 3 to 300 characters, for example `a neon Tokyo street in the rain at night` or `a windswept desert canyon at golden hour`.+4. Optionally set a seed for a reproducible render.+5. Click Generate. A real progress state runs while the NVCF job renders; expect roughly 60 to 120 seconds on the free tier.+6. When the world lands it plays behind your avatar. Preview it, regenerate with a new prompt or seed, or download the clip.++## Examples++The Cosmos lane is a plain async HTTP job. Reuse the platform key server-side.++```bash+# Start a world render, then poll the NVCF job for the MP4.+JOB=$(curl -s -X POST 'https://three.ws/api/cosmos' \+ -H 'content-type: application/json' \+ -d '{"prompt":"a neon Tokyo street in the rain at night"}' \+ | python3 -c 'import sys,json;print(json.load(sys.stdin).get("job_id",""))')++curl "https://three.ws/api/cosmos?job=$JOB"+```++Example prompts that read well as living backdrops:++- `a neon Tokyo street in the rain at night`+- `a windswept desert canyon at golden hour`+- `a bioluminescent forest at midnight`+- `a rooftop garden above a foggy city skyline`+- `a snowy mountain pass under aurora`++A poll-until-ready loop in JavaScript:++```javascript+const start = await fetch('https://three.ws/api/cosmos', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ prompt: 'a bioluminescent forest at midnight' }),+}).then((r) => r.json());++if (start.status === 'done') console.log(start.video_url);+else {+ let job = start;+ while (job.status !== 'done' && job.status !== 'failed') {+ await new Promise((r) => setTimeout(r, 4000));+ job = await fetch(`https://three.ws/api/cosmos?job=${start.job_id}`).then((r) => r.json());+ }+ console.log(job.video_url); // durable MP4 URL+}+```++## States and limits++- **Prompt** must be 3 to 300 characters; an optional integer `seed` makes a render reproducible.+- **Render time** is roughly 60 to 120 seconds on the shared free tier; the client shows a real elapsed progress state and gives up after five minutes with a "try a simpler prompt" message.+- **Unconfigured (503)**: when `NVIDIA_API_KEY` is absent, the page keeps the avatar on a designed aurora backdrop and tells you generation is offline. No mock clip is ever shown.+- **Rate limited (429)** and **invalid key (401)** surface with honest messages and, where provided, a retry-after hint.+- Output is a durable MP4; the avatar is a standard GLB rendered with `<model-viewer>`.+- Rate limits are per client IP on the shared 3D generation buckets.++## Related++- [Forge](./forge.md) makes the 3D avatars and objects you place in a Cosmos world.+- [Avatar creation](./avatar-creation.md) and [character studio](./character-studio.md) for building and dressing avatars.+- Pages: [/create](https://three.ws/create), [/gallery](https://three.ws/gallery), [/scene](https://three.ws/scene).diff --git a/docs/daily-forge.md b/docs/daily-forge.mdnew file mode 100644index 000000000..f7888ba2d--- /dev/null+++ b/docs/daily-forge.md@@ -0,0 +1,99 @@+# Daily Forge: a new 3D creative challenge every day++Daily Forge gives you one 3D creative challenge a day. The theme is deterministic, hashed from the UTC date so everyone in the world gets the same prompt on the same day, forge it into a real, textured 3D model for free with no sign-up, build a streak, and place your creation in AR on your phone. It is the platform's anonymous-first retention loop: a reason to come back tomorrow that costs nothing to start.++Page: [/daily](https://three.ws/daily) (`pages/daily.html`, `src/daily.js`)++APIs: `POST /api/forge` and `GET /api/forge?job=<id>` (free text-to-3D), `GET /api/forge-gallery?scope=community` (community strip), `GET /api/ar` (AR fallback launcher).++## Why it exists++The free forge is the platform's front door, but a one-off "make a 3D model" prompt has no reason to bring anyone back. Daily Forge wraps that same free generation in a game: a shared daily theme, a visible streak, and milestones. Because the theme is derived purely from the date, it is the same for every visitor and needs no backend, no login, and no coordination. The whole loop runs anonymously in the browser with a locally stored streak, so a first-time visitor with zero setup gets a creative prompt, a real GLB, and a reason to return the next day. It complements the logged-in streak system while asking nothing of the user up front.++## How it works++The page loads model-viewer (with the meshopt decoder, since Forge GLBs are meshopt-compressed) and, after a WebGL support check, the `src/daily.js` module. If WebGL is unavailable the module is never loaded and the stage shows a "This browser can't render 3D" message.++**Deterministic theme.** `src/daily/daily-theme.js` holds a frozen pool of 24 curated themes, each with an emoji, title, hint, accent, and three seed prompts. The theme for a date is chosen with an FNV-1a hash of the `YYYY-MM-DD` UTC key, plus a weekly rotation offset so a fixed weekday does not lock to one theme:++```javascript+function hashKey(key) {+ let h = 0x811c9dc5;+ for (let i = 0; i < key.length; i++) {+ h ^= key.charCodeAt(i);+ h = Math.imul(h, 0x01000193) >>> 0;+ }+ return h >>> 0;+}++// idx = (hashKey(dateKey) + weeksSinceAnchor * 5) % THEMES.length+```++The "Day N" counter is anchored at 2026-07-17 (launch day is Day 1; earlier dates clamp to 1). A deterministic starter prompt is chosen the same way from the theme's seeds and pre-filled into the input; the idea chips are the theme's three seeds, and clicking one forges it immediately.++**Free forge.** `forge(prompt)` sends `POST /api/forge` with `{ prompt, backend: 'nvidia' }` and an `x-forge-client` header carrying an anonymous client id (`localStorage['forge:cid']`, generated with `crypto.randomUUID()` and shared with `/forge`, `/ar`, and AR Studio). This is the free NVIDIA NIM (Microsoft TRELLIS) text-to-3D lane: no key, no account. If the response is already `{ status: 'done', glb_url }` it renders immediately; otherwise it polls `GET /api/forge?job=<id>` every 3 seconds up to a 5-minute ceiling until the job is `done` (with a GLB) or `failed`.++**Streak state machine.** `src/daily/creator-streak.js` is a pure state machine over `{ current, best, lastDay, total }`, keyed to the UTC day and persisted at `localStorage['twx_daily_streak_v1']`. The streak bumps once per UTC day (idempotent: forging five times today counts once), on the model-viewer `load` event, since a completed creation is the qualifying action. A gap of exactly one day increments the streak; a larger gap resets `current` to 1 while preserving `best`. Milestones fire when `current` exactly hits one of `[3, 7, 14, 30, 50, 100, 365]`, with escalating celebration emoji and a haptic buzz.++**Community strip.** `loadCommunity()` reads `GET /api/forge-gallery?scope=community&limit=12`, the newest finished models across all clients, and renders links to `/viewer?src=...`. If the request is empty or fails, the strip stays hidden.++**AR handoff.** The stage `<model-viewer>` is AR-enabled (`ar-modes="webxr scene-viewer quick-look"`). "View in your room" calls `model-viewer.activateAR()` when the device supports it (WebXR, Android Scene Viewer, or iOS Quick Look), and otherwise opens the server-side device-aware launcher at `/api/ar?src=<glb>&title=<prompt>`. An "AR Studio" button opens `/ar/studio?src=<glb>&title=<prompt>`, and Share and Download build `/viewer` links and direct GLB downloads.++## Walkthrough++1. Open [/daily](https://three.ws/daily). The hero shows today's theme, its emoji, and a starter prompt already filled in. The header pill shows your current streak.+2. Edit the prompt or click an idea chip, then press Forge. The stage shows a working overlay with an elapsed timer while the free lane generates.+3. When the model loads, your streak bumps (once for today). At a milestone (3, 7, 14, 30, 50, 100, or 365 days) a celebration modal appears.+4. Tap "View in your room" to place the model in AR on your phone, or use AR Studio, Download, or Share.+5. Scroll to "Fresh from the community" to see what others forged today, and come back tomorrow for a new theme to keep the streak alive.++## Examples++The free forge lane is public and unauthenticated; the same contract powers `/daily`, `/forge`, and `/ar`.++```bash+# Start a free text-to-3D job on the NVIDIA lane+curl -X POST 'https://three.ws/api/forge' \+ -H 'content-type: application/json' \+ -H 'x-forge-client: my-anonymous-id' \+ -d '{"prompt":"a tiny brass robot with glowing eyes","backend":"nvidia"}'+# → { "job_id": "..." } (or { "status":"done", "glb_url":"..." })++# Poll the job until it is done+curl -H 'x-forge-client: my-anonymous-id' \+ 'https://three.ws/api/forge?job=<JOB_ID>'++# The community strip: newest finished models across all clients+curl 'https://three.ws/api/forge-gallery?scope=community&limit=12'+```++```javascript+// Reproduce today's deterministic theme selection+function themeIndex(dateKey, themeCount) {+ let h = 0x811c9dc5;+ for (let i = 0; i < dateKey.length; i++) {+ h ^= dateKey.charCodeAt(i);+ h = Math.imul(h, 0x01000193) >>> 0;+ }+ const anchor = Date.UTC(2026, 6, 17);+ const week = Math.floor((Date.parse(dateKey + 'T00:00:00Z') - anchor) / (86400000 * 7));+ return ((h >>> 0) + week * 5) % themeCount;+}+console.log(themeIndex(new Date().toISOString().slice(0, 10), 24));+```++## States and limits++- **No sign-up, no key.** The whole loop is anonymous: an in-browser client id, a free NVIDIA generation lane, and a local streak. Nothing is stored server-side about you.+- **Per day.** The theme, the starter seed, and the streak all key on the UTC day. The streak counts at most once per day.+- **Prompt limits.** 3 to 600 characters (enforced in JS and on the input).+- **Empty and error states.** The stage has idle, working (with an elapsed timer), and failed (with retry) overlays. The forge lane surfaces offline (503), rate-limited (429 with a retry-after), and timeout (over 5 minutes of polling) states, and a "generated but couldn't display" path that still offers a download and still counts the streak. The community strip hides itself when empty. WebGL-unsupported browsers never load the module.+- **Shared links do not cheat the streak.** Opening `/daily?src=<glb>` to view someone else's creation does not light your streak; only a real forge does.++## Related++- [The 3D pipeline](./3d-pipeline.md) and [3D API](./3d-api.md): the text-to-3D forge the free lane rides+- [Forge background generation](./forge-background-generation.md): the job and polling model+- [AR and WebXR](./ar.md): the Scene Viewer and Quick Look handoff+- [Quick start](./quick-start.md): the general free-forge onboarding+- Pages: [/daily](https://three.ws/daily) · [/forge](https://three.ws/forge) · [/ar/studio](https://three.ws/ar/studio)diff --git a/docs/diorama.md b/docs/diorama.mdnew file mode 100644index 000000000..5ec2d1bd4--- /dev/null+++ b/docs/diorama.md@@ -0,0 +1,90 @@+# Diorama: speak a little world into being++Diorama turns one sentence into a tiny, explorable 3D world. You describe a scene, an AI set designer decomposes it into a placed set of single objects, and each object is forged into a real textured GLB and dropped into place, live, as it arrives. The finished world sits on a small floating island you can orbit, view in AR, save to a public gallery with its own permalink, and export as a single merged GLB that opens cleanly in Scene Studio.++Page: [/diorama](https://three.ws/diorama) · API: `/api/diorama`++## Why it exists++Forge makes one object at a time. But a world is a composition: a campfire and a tent and three pine trees, arranged on the ground, lit for a mood. Doing that by hand means forging each piece, importing them into a scene editor, and placing them one by one. Diorama collapses that into a sentence. It is the difference between a modeling tool and a director's chair: you say what you want to see, and the platform composes, generates, and assembles it in front of you. Every object is a real mesh (no billboards, no fakes), so the result is genuine geometry you can walk around, share, and take into any glTF tool.++## How it works++Diorama is a four-step pipeline (`api/diorama.js` plus `src/diorama/`), and each step is real.++1. **Compose.** `POST /api/diorama {action:'compose', prompt}` sends your sentence to the platform's free-first LLM chain (`llmComplete`) with a 3D-set-designer system prompt. The model returns a strict JSON plan: a 2-to-4-word title, a mood (`dawn`/`day`/`dusk`/`night`), a ground type (`grass`/`sand`/`snow`/`stone`/`water`/`meadow`/`void`), an island shape (`round`/`craggy`/`plateau`), a color palette (sky gradient, ground, fog, accent), and a placed list of objects. Each object is exactly one physical thing (a single tree, a single tent, never a scene and never "and"), with a one-line forge prompt (subject plus dominant material and color), an `(x, 0, z)` position spread across the island with spacing enforced, a scale, and a Y rotation. Objects come back with `status:'pending'` and no meshes.++2. **Forge each object.** The browser walks the plan and calls `/api/forge` for every object, on the free lane, watching each one turn from `pending` to `forging` to `ready` (or `failed`, with an in-place retry). The renderer (`src/diorama/renderer.js`) materializes each mesh into the scene the moment it arrives, so the world assembles progressively in front of you rather than appearing all at once.++3. **Save and share.** `POST /api/diorama {action:'save', diorama}` persists a fully-forged world, returns an `{id, url}` permalink, opens the share sheet, refreshes the gallery, and rewrites the page URL to the new permalink. A signed-in creator's world links to their public portfolio; anonymous saves fall back to a plain handle.++4. **Export.** `POST /api/diorama {action:'export', diorama}` merges the world's objects, ground, and lights into one GLB (`api/_lib/scene-graph-compose.js`) with named, selectable nodes, uploads it, and hands back a `glbUrl` plus a `sceneStudioUrl` so it opens directly in Scene Studio ([/scene](https://three.ws/scene)) or any glTF viewer.++A headless one-shot, `POST /api/diorama {action:'build', prompt}`, runs the whole flow server-side (compose, forge every object on the free lane, export the merged GLB) for callers with no browser to drive the progressive client, such as MCP tools and agents.++Reads: `GET /api/diorama?id=<uuid>` loads a saved world (a deep link renders it read-only and offers a remix), and `GET /api/diorama?list=recent|featured&limit=<n>` returns gallery cards. The gallery renders each card as live geometry through `<model-viewer>`, not a flat thumbnail.++There are no mocks: if the LLM chain is unreachable, the compose route returns a clean 503 and the page shows a designed retry state instead of fabricating a world.++## Walkthrough++1. Open [/diorama](https://three.ws/diorama).+2. Type a sentence: `a lighthouse on a rocky islet at dusk`, or `a cozy campsite in a pine clearing`.+3. Watch the plan appear as a row of per-object status chips (pending, forging, ready). The island, ground, and mood render immediately from the palette.+4. Watch each object drop into place as its mesh finishes forging. A failed object gets a one-tap retry.+5. Orbit the finished world. When at least one real mesh is present, the world actions unlock: remix, save, AR (on supported devices), and download.+6. Save to get a permalink and a gallery slot, or export to open the merged GLB in Scene Studio.++## Examples++Compose a plan, then drive the forge yourself, or let the server build the whole thing.++```bash+# 1) Compose: sentence -> placed plan of single-object forge prompts.+curl -X POST 'https://three.ws/api/diorama' \+ -H 'content-type: application/json' \+ -d '{"action":"compose","prompt":"a lighthouse on a rocky islet at dusk"}'++# 2) Headless one-shot: compose + forge every object + export a merged GLB.+curl -X POST 'https://three.ws/api/diorama' \+ -H 'content-type: application/json' \+ -d '{"action":"build","prompt":"a cozy campsite in a pine clearing"}'++# 3) Load a saved world by id.+curl 'https://three.ws/api/diorama?id=<uuid>'++# 4) Browse the public gallery.+curl 'https://three.ws/api/diorama?list=featured&limit=12'+```++The compose response shape (abridged):++```json+{+ "title": "Dusk Lighthouse",+ "mood": "dusk",+ "ground": "stone",+ "island": "craggy",+ "palette": { "sky": ["#2a2350", "#e0724a"], "ground": "#5b5347", "fog": "#3a3550", "accent": "#ffb066" },+ "objects": [+ { "label": "lighthouse", "prompt": "white stone lighthouse with red top", "position": [0, 0, 0], "scale": 2.2, "rotationY": 0, "status": "pending" },+ { "label": "rock", "prompt": "grey jagged sea rock", "position": [-3.4, 0, 2.1], "scale": 1.1, "rotationY": 1.2, "status": "pending" }+ ]+}+```++## States and limits++- **Object count** is bounded (the plan enforces a minimum and maximum), and objects are spaced so they never stack.+- **Compose failure**: a clean 503 and a designed retry state, never a fabricated world.+- **Per-object status**: pending, forging, ready, failed (with in-place retry). One failed object does not block the rest.+- **Save/export** need object storage configured; export returns 503 with a clear message when it is not.+- **AR and download** appear only once at least one real mesh has forged.+- **Deep links** render a saved world read-only and offer a remix, so a shared permalink is stable.+- Prompt length is capped; reads are rate-limited per client IP.++## Related++- [Forge](./forge.md) is the single-object generator every diorama object is forged on.+- [Image to 3D](./image-to-3d.md) for photo-based objects; [AR](./ar.md) for viewing worlds in augmented reality.+- Pages: [/scene](https://three.ws/scene) (Scene Studio, where an exported diorama opens), [/gallery](https://three.ws/gallery), [/create](https://three.ws/create).diff --git a/docs/fact-check.md b/docs/fact-check.mdnew file mode 100644index 000000000..25483aa5a--- /dev/null+++ b/docs/fact-check.md@@ -0,0 +1,95 @@+# Fact Check: sourced verdicts with cryptographic attestations++Fact Check submits a claim and returns a verdict, `supported`, `contradicted`, `mixed`, or `insufficient`, backed by live web search and LLM stance analysis, cited sources, a confidence score, and a SHA-256 attestation over the result you can recompute. It ships with a published, checkable accuracy benchmark instead of an asserted quality number, and a live free-check box on the page. The first 3 checks a day per IP run the exact same real chain for free; after that it is $0.10 USDC per check via x402 on Base or Solana. No account, no API key.++Page: [/fact-check](https://three.ws/fact-check)++API: `POST /api/x402/fact-check` (the check), `GET /api/fact-check-benchmark` (the published accuracy benchmark).++## Why it exists++An agent that makes claims needs a way to check claims, and a fact-checker only earns trust if you can audit both its answers and its overall accuracy. Most tools give you neither: no sources, no confidence, no track record. Fact Check is built to be auditable end to end. Every verdict carries the sources it was built from, the stance it read from each, a confidence score, and a content hash you can reproduce. And the whole service publishes a fixed benchmark, 40 curated claims scored against the real chain, so the accuracy number on the page is a measurement, not a marketing claim. It is a paid x402 service that any agent can discover and pay, with a free daily lane so a human can try it with zero setup.++## How it works++The page (`src/fact-check.js`) hydrates three cards: the accuracy benchmark, a "try one free check" box, and pricing. The check itself is `POST /api/x402/fact-check`, a free-daily-lane endpoint that meters overage onto x402.++The request routing:++- A `POST` with a valid `claim` and free quota remaining runs the real chain and returns `200` with `lane: "free"` and `free_remaining_today`.+- Once the free quota is exhausted, or if a payment header is present, the request falls through to the x402 rail: a `402` challenge for $0.10 USDC (100,000 atomics), payable on Base or Solana, and a paid run returns `lane: "paid"`.+- Malformed JSON or a present-but-invalid claim returns a hard `400`; a body with no `claim` at all falls through to a valid 402 so discovery probes get a proper challenge.++The fact-check pipeline (`runFactCheck`):++1. Generate exactly 3 search queries with an LLM.+2. Search across a source chain (Brave, Tavily, Exa, Serper, then keyless Wikipedia full-text and DuckDuckGo Instant Answer as always-available fallbacks) and take the top 5 unique results.+3. Run LLM stance extraction on each of the 5: an excerpt plus a stance of `supports`, `contradicts`, or `neutral`.+4. Weight each source by an authority score, adjusted by strictness (`high` halves low-authority weights, `low` floors them, `medium` is the default).+5. Compute the verdict: fewer than 2 sources is `insufficient`; a weighted support ratio above 0.65 is `supported`; a weighted contradiction ratio above 0.65 is `contradicted`; otherwise `mixed`. Confidence is the winning ratio.+6. Build a cost breakdown and the attestation.++The LLM routes through the platform's shared free-first policy (Groq and OpenRouter as funded defaults). Results are cached in Redis for 7 days keyed by a hash of the claim, strictness, and any image URL, so an identical claim (on either lane) never re-runs the live chain.++**The attestation** is a tamper-evident content digest: `sha256:` followed by the SHA-256 of a JSON object of `{ verdict, confidence, claim, source URLs }`. It is returned as a string field you can recompute to confirm the verdict was not altered. Note that this is a content hash, not an on-chain record; it is distinct from the platform's [SAS credentialed attestations](./sas-attestations.md) and [3D provenance anchoring](./provenance.md), which do write to Solana.++**The benchmark** (`GET /api/fact-check-benchmark`) reads two committed files: a 40-claim fixture (10 per verdict class, deliberately time-stable and non-partisan) and a generated report from `scripts/fact-check-benchmark.mjs`, which runs those claims in-process against the real chain. The API never fabricates a score: if the runner has not executed in an environment, `ran` is false and `report` is null, and the page renders a designed "not yet run" empty state. Both the claim set and the scoring runner are linked from the page for inspection.++## Walkthrough++1. Open [/fact-check](https://three.ws/fact-check). The Accuracy benchmark card loads the current published score, per-class breakdown, and last-run time, with links to the 40 benchmark claims and the scoring runner.+2. In the "Try one free check" box, type a claim (5 to 1000 characters) and click Run free check.+3. Read the verdict pill with its confidence, the cited sources with their stances, and the SHA-256 attestation string.+4. After your 3 free checks for the day, the box tells you the paid x402 lane ($0.10 USDC) picks up from there, and to come back tomorrow for more free checks.++## Examples++Free lane (no payment, subject to the 3-per-day-per-IP quota):++```bash+curl -X POST 'https://three.ws/api/x402/fact-check' \+ -H 'content-type: application/json' \+ -d '{"claim":"Solana uses a proof-of-history mechanism to order transactions."}'+```++A free-lane response looks like:++```json+{+ "verdict": "supported",+ "confidence": 0.86,+ "claim": "Solana uses a proof-of-history mechanism to order transactions.",+ "strictness": "medium",+ "sources": [+ { "url": "https://...", "title": "...", "excerpt": "...", "stance": "supports", "weight": 0.9 }+ ],+ "costBreakdown": { "searchCalls": 2, "llmTokens": 1400, "totalUsdc": "0.100350" },+ "attestation": "sha256:...",+ "lane": "free",+ "free_remaining_today": 2+}+```++Read the published benchmark:++```bash+curl 'https://three.ws/api/fact-check-benchmark'+```++Once the free quota is spent, the same POST returns `402` with an x402 challenge; pay it with any x402 client (for example `@three-ws/x402-fetch`) and retry. See [x402](./x402.md).++## States and limits++- **Free quota.** 3 checks per day per IP, running the identical real chain (`lane: "free"`). The limiter is critical: a cache or limiter outage fails closed to the paid rail rather than opening unlimited free checks.+- **Paid lane.** $0.10 USDC (100,000 atomics) per check, on Base or Solana, discoverable in the x402 bazaar. Quota exhaustion or a payment header routes here.+- **Input validation.** Claim 5 to 1000 characters (else `400`), strictness one of `high`, `medium`, `low` (default `medium`), and an optional image URL that must be http(s) and under 2048 characters.+- **Errors.** No search results returns `422 no_results`; a search failure `502 search_failed`; a provider failure `502 provider_error`; malformed JSON `400`; an oversized body `413`.+- **Honest benchmark.** The score shown is whatever the runner last measured against the real chain, or a "not yet run" empty state. Because production currently runs on keyless search fallbacks, decisive verdicts are harder to reach, which the published benchmark reflects rather than hides.+- **Idempotency.** A 7-day Redis cache is shared across both lanes, so repeated identical claims are cheap and consistent.++## Related++- [x402: paid agent skills](./x402.md): the payment rail the $0.10 lane rides+- [API reference: Fact Check API](./api-reference.md): the endpoint's full request and response reference+- [SAS credentialed attestations](./sas-attestations.md) and [3D provenance](./provenance.md): the platform's on-chain attestation primitives (distinct from this content-hash attestation)+- Pages: [/fact-check](https://three.ws/fact-check) · [/x402](https://three.ws/x402)diff --git a/docs/forge.md b/docs/forge.mdnew file mode 100644index 000000000..aef9a5cc8--- /dev/null+++ b/docs/forge.md@@ -0,0 +1,124 @@+# Forge: text and image to 3D, on a free-first engine grid++Forge is three.ws's text-and-image-to-3D generator. Type a prompt, drop in one to four photos of an object, or sketch a shape and name it, and Forge returns a downloadable, textured GLB you can orbit, view in AR, and take anywhere. It runs on a grid of real generation engines with live health status, and it is free-first by design: text prompts default to a zero-cost NVIDIA lane, photos default to a zero-cost reconstruction lane, and the paid engines stay explicitly selectable for when you want a specific vendor.++Page: [/forge](https://three.ws/forge) and the feature landing [/features/forge](https://three.ws/features/forge) · API: `/api/forge`++## Why it exists++Every other text-to-3D tool makes you choose a vendor, buy credits, and hope the one model they wired up is the right one for your prompt. Forge inverts that. It treats generation as a routing problem over many engines, picks the best free lane for the input you gave it, degrades gracefully when an upstream is down, and only ever charges for higher quality, never to recover a vendor bill. The result is a single surface where a first-time visitor can make a real 3D model in seconds with no account, no key, and no cost, while a power user can pin a specific engine, bring their own key, or push a High-tier generation through multi-view fusion.++Forge is the public, auth-free twin of the 3D Studio MCP server (`api/mcp-3d.js`), so anything the page can do, an agent can do over MCP or a plain HTTP call.++## How it works++A generation request is described by two orthogonal axes, resolved in `api/_lib/forge-tiers.js`, the single source of truth shared by the endpoint, the catalog the UI renders, and every provider param builder.++**The path** is how geometry is produced:++- `image` (image-intermediate, the fast default): text is painted into a reference view (FLUX/Imagen) and reconstructed to a mesh, or your own photo is reconstructed directly.+- `geometry` (geometry-first): a native 3D model emits mesh directly from the prompt or a single photo, so detail isn't capped by what one image implies. This is the Meshy and Tripo text-to-3D path.+- `sketch` (sketch-conditioned): a drawing plus a prompt naming what it depicts drives TripoSG-scribble straight to geometry, no photo and no intermediate view.++**The tier** is how much geometric budget to spend:++| Tier | Poly target | Textures | Price (direct USDC) | Notes |+| --- | --- | --- | --- | --- |+| Draft | 12,000 | none | $0.05 | Fast, low-poly. Blockout and iteration. |+| Standard | 30,000 | 2K | $0.15 | Balanced, multi-angle reference fusion. The default. |+| High | 200,000 | PBR + HD | $0.50 | Maximum detail, deepest sampler budget, multi-view fusion. |++### The engine grid++Each backend declares which paths it serves, whether it needs a bring-your-own-key (BYOK) credential, and its per-(path, tier) cost and latency estimates so the UI can show the trade-off before you commit. The live registry (`BACKENDS` in `api/_lib/forge-tiers.js`):++- **TRELLIS (free)** on NVIDIA NIM (Microsoft TRELLIS). The default lane for text prompts at Draft and Standard. Zero vendor cost. Text-only: it rejects user photos, so photo submissions route elsewhere.+- **Hunyuan3D / TRELLIS (free)** on Hugging Face Spaces. The free photo-to-3D lane and a High-tier engine, with automatic failover across Hunyuan3D 2.1, Hunyuan3D 2, TRELLIS, and TripoSR. Queue waits vary.+- **TRELLIS (self-host)** and **Hunyuan3D (self-host)**, our own scale-to-zero Cloud Run GPU workers. Zero vendor cost, so free-first routing prefers them first. Self-host TRELLIS is a native single-hop image-to-3D lane; Hunyuan3D leads on people and organic subjects.+- **TripoSG (self-host)**, the sketch-only scribble worker. Untextured geometry from a drawing.+- **TRELLIS** on Replicate, a paid platform lane. Selectable explicitly and used as the last-resort fallback only on deployments with no free engine configured.+- **Meshy 6**, **Tripo v3.1**, **Rodin (Hyper3D)**, BYOK geometry-first engines with quad topology and a real poly target. You supply your own key.+- **Stable Fast 3D** (Stability, BYOK) and **Replicate (your account)** (BYOK), single-image reconstruction lanes.++### Free-first routing with live health++Routing (`resolveBackendIdWithHealth`) walks an ordered list of every free lane that could serve the request on this deployment, most preferred first: the tier's named free engine, then the per-path fallback chain (our own GPU workers, then the free external Spaces, then the free NVIDIA lane as the final health-gated safety net). Draft and Standard text prompts name NVIDIA TRELLIS; High names our self-host Hunyuan3D worker. A subject classifier reorders the two self-host PBR lanes for hard-surface versus organic prompts. Every entry is env-gated, so the list degrades cleanly on partial deployments.++Health is real. The UI fetches `/api/forge?health=1` after load and disables any lane whose upstream is down, with the actual reason, instead of failing after you have typed a prompt and clicked Generate. A short circuit-breaker cooldown sidelines a degraded lane (for example the free NIM lane after a gateway timeout) so subsequent requests skip it and go straight to a working engine; the cooldown expires on its own so a recovered lane is retried promptly. There are no mock paths: if a selected backend isn't configured the endpoint returns a clean `backend_unconfigured` error, never a fake result.++### Background generation and resume++Generation is a job. `POST /api/forge` returns a `job_id`; the client polls `GET /api/forge?job=<id>`. The lanes that complete inline within one request (free NVIDIA NIM, HuggingFace Spaces, BYOK-sync) retry once automatically on a failed result. Because the in-flight job id is written to `localStorage`, closing the tab or navigating away does not lose the generation: returning to Forge within a 30-minute window resumes polling the same job. Finished models for your browser are surfaced from a gallery on load, and a share link always wins over a resume.++## Walkthrough++1. Open [/forge](https://three.ws/forge). No login, no wallet, no key required.+2. Pick an input mode: **Describe it** (text), **From photos**, or **From a sketch** (the sketch tab appears only when the TripoSG worker is configured).+3. For text, type a prompt like `a weathered brass diving helmet`. For photos, add one to four images of the same object from different angles; each uploads straight to object storage via a presigned URL and the public URLs are fused with multi-view conditioning.+4. Optionally open the quality controls and pick a tier (Draft, Standard, High) and an engine. The default engine carries a **FREE** pill. Down lanes are disabled with the reason shown.+5. Click Generate. A real elapsed-driven progress line runs against the catalog's ETA estimate for the chosen path, tier, and engine.+6. When the model lands, orbit it in the viewer, view it in AR, download the GLB, or run the post-generation tools (stylize, optimize, Game-Ready retopology, split).++## Examples++Forge's read and generate surface is plain HTTP. No key is required for the free lanes.++```bash+# Read the tier/backend/cost matrix the UI renders.+curl 'https://three.ws/api/forge?catalog=1'++# Probe live backend health (which lanes are up right now).+curl 'https://three.ws/api/forge?health=1'++# Start a free text-to-3D generation, then poll for the GLB.+JOB=$(curl -s -X POST 'https://three.ws/api/forge' \+ -H 'content-type: application/json' \+ -d '{"prompt":"a weathered brass diving helmet","tier":"draft"}' \+ | python3 -c 'import sys,json;print(json.load(sys.stdin)["job_id"])')++curl "https://three.ws/api/forge?job=$JOB"+```++Image-to-3D over the API sends public image URLs instead of a prompt:++```bash+curl -X POST 'https://three.ws/api/forge' \+ -H 'content-type: application/json' \+ -d '{"image_urls":["https://…/front.jpg","https://…/side.jpg"],"tier":"standard"}'+```++A minimal poll-until-done loop in JavaScript:++```javascript+const start = await fetch('https://three.ws/api/forge', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ prompt: 'a low-poly campfire', tier: 'draft' }),+}).then((r) => r.json());++let job = start;+while (job.status !== 'done' && job.status !== 'error') {+ await new Promise((r) => setTimeout(r, 4000));+ job = await fetch(`https://three.ws/api/forge?job=${start.job_id}`).then((r) => r.json());+}+console.log(job.glb_url); // downloadable, textured GLB+```++## States and limits++- **Loading**: a real elapsed counter driven by the catalog ETA for the resolved path, tier, and engine. Cold self-host GPU workers add an honest spin-up estimate rather than a stalled bar.+- **Down lane**: disabled engine button with the real upstream reason; routing skips it via the circuit-breaker cooldown.+- **Unconfigured backend**: a clean `backend_unconfigured` error, never a mock.+- **Resume**: an interrupted job is pollable again for 30 minutes from the same browser.+- **Every result** reports the path, tier, and backend that produced it, so you always know which engine ran.+- **The High tier is $THREE hold-or-pay gated** in the handler regardless of which free engine serves it: we charge for quality, not to recover vendor cost. A verified $THREE tier pass also lifts the free-lane quota.+- **BYOK engines** (Meshy, Tripo, Rodin, Stability, Replicate) require your own key; they are never billed to a platform account.+- **Photo input** accepts up to four views of one object; text-only engines are filtered out of the photo modes automatically.+- Rate limits are per client IP on the shared 3D generation buckets.++## Related++- [Image to 3D](./image-to-3d.md) is the photo lane opened directly at [/image-to-3d](https://three.ws/image-to-3d).+- [Diorama](./diorama.md) forges a whole scene of Forge objects into one explorable world.+- The 3D generation architecture: [3D pipeline](./3d-pipeline.md), [3D asset pipeline](./3d-asset-pipeline.md), [3D API](./3d-api.md).+- Pages: [/create](https://three.ws/create) (the avatar creator), [/scene](https://three.ws/scene) (Scene Studio), [/restyle](https://three.ws/restyle) (re-skin a GLB), [/gallery](https://three.ws/gallery).diff --git a/docs/galaxy.md b/docs/galaxy.mdnew file mode 100644index 000000000..efca81b9a--- /dev/null+++ b/docs/galaxy.md@@ -0,0 +1,77 @@+# Agent Galaxy: every agent, mapped by meaning++Agent Galaxy is an explorable 3D star-map of every published agent on three.ws, positioned in space by what each agent *means*. Coordinates and semantic search are powered by IBM Granite embeddings on watsonx.ai: each agent becomes a vector, the vectors are projected into 3D, and agents cluster into named constellations. Type a natural-language query and the galaxy flies to the agents closest to your intent.++Page: [/galaxy](https://three.ws/galaxy)+API: `GET /api/galaxy` (build the map) · `POST /api/galaxy` (semantic search) · `GET /api/galaxy/flows` (live economy overlay)++## Why it exists++A flat directory of agents tells you what exists but nothing about how they relate. Agent Galaxy turns the whole population into a spatial map where proximity is similarity: agents that do similar things sit near each other, and browsing the map is browsing by meaning. It doubles as a discovery tool. Instead of guessing keywords, you describe what you want in plain language and the same embedding model that placed the stars finds the closest ones. It is also a live showcase of what Granite embeddings make possible on the platform.++## How it works++The page ([`pages/galaxy.html`](../pages/galaxy.html)) loads [`src/galaxy.js`](../src/galaxy.js), a Three.js scene. The map itself is assembled server-side and cached.++1. **Collect agents.** `GET /api/galaxy` ([`api/galaxy.js`](../api/galaxy.js)) loads published agents from Postgres (`agent_identities` joined to `avatars`, filtered to published, described, named agents, ordered by chat count), default 600 and capped at 1200.+2. **Embed.** Each agent's text (name, description, tone tags) is embedded with IBM Granite through [`api/_lib/watsonx.js`](../api/_lib/watsonx.js). The default model is `ibm/granite-embedding-278m-multilingual`, called at `POST {WATSONX_URL}/ml/v1/text/embeddings` with an IAM bearer token minted from the watsonx API key. Vectors are cached durably per agent (`agent_embeddings`), so only changed agents re-embed.+3. **Project to 3D.** [`api/_lib/embedding-math.js`](../api/_lib/embedding-math.js) mean-centers the vectors, takes the top 3 principal components via power iteration (PCA, seeded and deterministic, not UMAP or t-SNE), whitens per axis, and maps them into a sphere of radius 120. Determinism means cached rebuilds are stable.+4. **Cluster into constellations.** Seeded k-means (Lloyd's with k-means++ seeding) over L2-normalized vectors groups agents into `clamp(round(n/8), 2, 8)` clusters. Each cluster is labeled by Granite chat (`ibm/granite-3-8b-instruct`, with a same-family OpenRouter fallback).+5. **Render.** The client draws agents as a single `THREE.Points` cloud with a custom additive shader. Point size grows with chat count; a wealth glow (from real wallet net worth via `/api/agents/networth`) biases funded stars toward a violet tint. `OrbitControls` gives drag-to-orbit, scroll-to-zoom, and gentle auto-rotate that pauses on interaction. A raycaster powers hover tooltips.+6. **Inspect.** Clicking a star opens an in-scene card with the agent's thumbnail, constellation, description, and meta chips (net worth, chat count, token), plus two actions: "View agent" (`/agents/:id`) and "Chat" (`/agent/:id`).+7. **Search.** The search box POSTs `{ query }` to `/api/galaxy`, which embeds the query with the same Granite model and ranks stored agent vectors by cosine similarity. The client highlights matches and flies the camera to the best one.++Only projected coordinates and cluster centroids are sent to the browser; raw high-dimensional vectors never leave the server.++## Walkthrough++1. Open [/galaxy](https://three.ws/galaxy). The loading overlay reads "Mapping the agent universe" while Granite embeds the agents.+2. Drag to orbit, scroll to zoom. Watch the constellations, each a color-coded cluster of related agents.+3. Hover a star to see the agent name and its constellation; click it to open the inspect card.+4. From the card, open the agent's profile ("View agent") or start a conversation ("Chat").+5. Type a natural-language query such as "an agent that trades memecoins" and search. The galaxy highlights the closest matches and flies to the best one; the result strip lists them under "Closest by meaning."++## Examples++Both endpoints are public and IP rate-limited.++```bash+# Build (or read the cached) galaxy: agents, coordinates, and constellations.+curl 'https://three.ws/api/galaxy?limit=600'+# -> {+# "count": 412, "dims": 768, "model": "ibm/granite-embedding-278m-multilingual",+# "clusters": [ { "id": 0, "color": "#…", "centroid": [x,y,z], "label": "Traders", ... } ],+# "agents": [ { "id": "…", "name": "…", "description": "…", "thumbnail": "…",+# "chat_count": 128, "cluster": 0, "coords": [x,y,z] } ],+# "cached": true, "generated_at": "…"+# }++# Semantic search: embed the query with Granite, rank agents by cosine similarity.+curl -X POST 'https://three.ws/api/galaxy' \+ -H 'content-type: application/json' \+ -d '{ "query": "an agent that trades solana memecoins", "limit": 12 }'+# -> {+# "query": "an agent that trades solana memecoins",+# "model": "ibm/granite-embedding-278m-multilingual",+# "count": 12,+# "results": [ { "id": "…", "name": "…", "description": "…", "thumbnail": "…", "score": 0.742 } ]+# }+```++`GET /api/galaxy` accepts `?refresh=1` to force a rebuild and `?limit=<n>` (default 600, max 1200). `POST /api/galaxy` takes `{ query, limit? }` (query trimmed to 200 chars, up to 30 results). Rankings apply a minimum similarity of 0.05.++## States and limits++- **No auth.** Both endpoints are public and read-only, guarded by IP rate limits and, on the shared watsonx key, a global embedding-cost ceiling.+- **watsonx required.** With no credentials the endpoint returns `503 watsonx_unavailable` and the page shows "IBM Granite isn't connected" (no retry). Configure `WATSONX_API_KEY` and `WATSONX_PROJECT_ID` to light it up.+- **Caching.** Three layers: a `galaxy_snapshots` server snapshot (6-hour TTL, with warm-instance rebuild coalescing), the durable per-agent `agent_embeddings` cache, and a 60-second cache on the published-agent query. Pass `?refresh=1` to bypass the snapshot.+- **Population.** However many published agents exist, capped by the limit. There is no fixed count.+- **Empty state.** With zero published agents the page shows "The galaxy is still forming" and a "Create an agent" CTA to `/create`.+- **Errors.** Network or server failures render "Couldn't reach the stars" with a "Try again" button. Search failures render the server message in the result strip; no matches shows "Nothing close to <query>."+- **Positioning is PCA, not UMAP/t-SNE.** It is deterministic on purpose so cached maps stay stable across rebuilds.++## Related++- [IBM Granite suite](./ibm.md): the full set of watsonx-powered features on three.ws, including the IBM-branded galaxy variant at `/ibm/galaxy`.+- [Agent system](./agent-system.md) and [Agent reputation](./agent-reputation.md): what a "star" is and how agents earn standing.+- Pages: [/galaxy](https://three.ws/galaxy), [/create](https://three.ws/create), [/agents](https://three.ws/agents).diff --git a/docs/genesis.md b/docs/genesis.mdnew file mode 100644index 000000000..c8e347013--- /dev/null+++ b/docs/genesis.md@@ -0,0 +1,137 @@+# Instant Agent Genesis: prompt or selfie to a living agent++Genesis is the one-minute on-ramp for the whole platform. You give it a text+prompt, a selfie, or a public avatar to remix. It returns a rigged 3D AI agent+that already owns a custodial Solana wallet, a custodial EVM wallet, a synthesized+persona and voice, and an optional verifiable on-chain identity. Every step is+real: the 3D body comes off the same reconstruction pipeline `/create` uses, the+wallet addresses are real custodial addresses, and the on-chain record returns a+real transaction hash. Nothing is mocked or faked as it runs.++Page: [/genesis](https://three.ws/genesis) · APIs: `/api/avatars/reconstruct`, `/api/avatars/regenerate-status`, `/api/avatars/fork`, `/api/agents`, `/api/agents/:id/wallet/provision`, `/api/persona/extract`, `/api/agents/:id`++## Why it exists++Creating a usable agent used to mean stitching together five surfaces: generate a+model, rig it, mint a wallet, write a system prompt, pick a voice, register an+identity. Each one is its own page, its own wait, its own chance to give up.+Genesis collapses that into a single guided flow with a real progress bar driven by+real job state, so a first-time visitor goes from an idea to a wallet-holding,+animation-ready agent they fully own in under a minute of active work. It is the+front door: the artifact it produces is a first-class agent that plugs straight+into [Agent Studio](./agent-studio.md), the [economy](./autonomous-economy.md),+[breeding](./genome.md), and every embed surface.++## How it works++Genesis is a state machine over the platform's existing production endpoints. It+never invents a shortcut path; it orchestrates the real ones.++- **Body.** The `text` and `selfie` modes both POST to `/api/avatars/reconstruct`+ (a prompt or a photo), then poll `/api/avatars/regenerate-status` with capped+ exponential backoff (1.5s first poll, 1.4x backoff, 12s ceiling, 8-minute+ deadline). This is the identical rigged-avatar pipeline behind `/create/prompt`+ and `/create/selfie`. The reconstruction model returns a textured mesh; when the+ mesh has no skeleton and the active provider has a rig model configured, the+ pipeline chains an auto-rig job (GCP UniRig / Hunyuan3D `generation_all`) and only+ surfaces the avatar once it can be animated, so you never receive a T-posed+ static mesh. The `remix` mode instead POSTs to `/api/avatars/fork`, forking a+ public avatar into a fresh one you own.+- **Agent and wallets.** Reconstruct and fork auto-provision the agent record.+ Genesis resolves it via `GET /api/agents?avatar_id=...`, then calls+ `POST /api/agents/:id/wallet/provision` to guarantee both a custodial Solana+ address and a custodial EVM address exist. These are real custodial keys held for+ the agent (see [Agent Wallets](./agent-wallets.md) and [Custody](./custody.md)),+ Solana first because Solana is the home chain.+- **Persona and voice.** `POST /api/persona/extract` synthesizes a structured+ in-character system prompt from your description, running through the shared LLM+ helper with Anthropic-first ordered failover (server Anthropic, then Groq, then+ OpenRouter) so a single upstream 429 or 5xx never returns a hard error. Voices+ load from `/api/tts/voices`. Your chosen name, persona, and voice are persisted+ with `PATCH /api/agents/:id`.+- **On-chain identity (optional).** The final step mints a real+ [ERC-8004](./erc8004.md) identity record for the agent and returns a real tx+ hash, defaulting to Base (chain id 8453) to match the rest of the platform's EVM+ identity layer. This step is optional: the agent is fully functional without it.++## Walkthrough++1. **Open [/genesis](https://three.ws/genesis).** Pick a mode: type a prompt, drop+ a selfie, or remix one of the featured public avatars loaded from+ `/api/avatars/featured`.+2. **Sign in if prompted.** Genesis works signed-out for generation, but claiming+ the agent and its wallets requires a wallet sign-in (the banner wires+ `signInWithWallet`).+3. **Kick off generation.** The step bar tracks the real reconstruction job:+ queued, generating, rigging, ready. Progress reflects the job state, not a timer.+4. **Watch the agent resolve.** Once the avatar is ready, Genesis resolves the+ auto-provisioned agent and provisions both wallets. The real Solana and EVM+ addresses appear.+5. **Name it and give it a voice.** Persona extraction proposes a system prompt from+ your prompt; edit the name and pick a voice, then save.+6. **Optionally bind an on-chain identity.** One click registers the ERC-8004 record+ and shows the returned transaction hash.+7. **You now own a complete agent.** Open it in [Agent Studio](./agent-studio.md) to+ keep authoring, drop it on a site via [Integrations](./integrations.md), or breed+ it in [Agent Genome](./genome.md).++## Examples++Genesis is a browser flow, but its endpoints are the public agent APIs. This drives+the same body-generation step from a script (see+[API reference](./api-reference.md) and [Authentication](./authentication.md) for+the session cookie or bearer token):++```bash+# 1. Start a text-to-avatar reconstruction+JOB=$(curl -s -X POST https://three.ws/api/avatars/reconstruct \+ -H 'content-type: application/json' \+ -H "authorization: Bearer $THREEWS_TOKEN" \+ -d '{"prompt":"A silver-haired explorer in a teal flight jacket"}')+echo "$JOB"++# 2. Poll status until the rigged model is ready+JOB_ID=$(echo "$JOB" | python3 -c 'import sys,json;print(json.load(sys.stdin)["jobId"])')+curl -s "https://three.ws/api/avatars/regenerate-status?jobId=$JOB_ID" \+ -H "authorization: Bearer $THREEWS_TOKEN"+```++```bash+# 3. Resolve the auto-provisioned agent and guarantee both wallets+AVATAR_ID=... # from the finished status payload+AGENT=$(curl -s "https://three.ws/api/agents?avatar_id=$AVATAR_ID" \+ -H "authorization: Bearer $THREEWS_TOKEN")+AGENT_ID=$(echo "$AGENT" | python3 -c 'import sys,json;print(json.load(sys.stdin)["agents"][0]["id"])')++curl -s -X POST "https://three.ws/api/agents/$AGENT_ID/wallet/provision" \+ -H "authorization: Bearer $THREEWS_TOKEN"+# returns { solana_address, wallet_address (EVM), ... } with real custodial addresses+```++## States and limits++- **Signed out.** Generation runs, but wallet provisioning and identity binding+ require sign-in. The auth banner is always reachable.+- **Generation deadline.** Reconstruction has an 8-minute deadline and the+ agent-resolve step a 60-second deadline; both surface a designed error with a+ retry action rather than hanging.+- **Rigging fallback.** If no rig model is configured or rigging fails, the pipeline+ delivers the static mesh tagged `unrigged` so you are never left empty-handed. Any+ humanoid avatar drives the pre-baked clip library via bone-name canonicalization,+ so the rig is not limited to a curated allowlist.+- **On-chain identity is optional and reversible in practice.** Skipping it leaves a+ fully working agent; you can bind an identity later.+- **Selfie framing.** The reconstruction path is a face pipeline. A clean headshot+ reconstructs far more reliably than a full-body photo.+- **Ownership.** The agent, both wallets, and the identity are yours. Remix forks a+ public avatar into a new agent you own; it never mutates the source.++## Related++- [Agent Studio](./agent-studio.md): keep authoring the agent Genesis created+- [Agent Genome](./genome.md): breed two agents into an inherited child+- [Avatar Reconstruction](./avatar-reconstruction.md): the selfie-to-3D pipeline+- [Agent Wallets](./agent-wallets.md) and [Custody](./custody.md): the custodial keys+- [ERC-8004](./erc8004.md): the on-chain identity record+- [Persona Hub](./persona-hub.md): how personas are synthesized+- Pages: [/genesis](https://three.ws/genesis), [/create](https://three.ws/create), [/agent-studio](https://three.ws/agent-studio)diff --git a/docs/genome.md b/docs/genome.mdnew file mode 100644index 000000000..3e9814737--- /dev/null+++ b/docs/genome.md@@ -0,0 +1,135 @@+# Agent Genome: breed two agents into a provably-inherited child++Agent Genome lets two agents breed into a genuinely new third agent that provably+inherits a recombination of both parents. The child gets its own fresh Solana and+EVM wallet, a blended voice, a composed in-character brain, a baked composite 3D+body, and the skill licenses it expresses granted on-chain. Every breeding event is+recorded with the exact seed that produced it, so the descent is re-derivable by+anyone and a forged child (one whose genome was not actually derived from its+claimed parents) is detectable. Neither parent's row or wallet is ever touched.++Page: [/genome](https://three.ws/genome) · APIs: `/api/genome/preview`, `/api/genome/breed`, `/api/genome/lineage`, `/api/genome/stud`++## Why it exists++Agents on three.ws accumulate real value: a tuned brain, a cloned voice, a body,+and on-chain skill licenses. Genome makes that value heritable. It turns a one-off+agent into a lineage, gives creators a reason to breed rare traits toward scarcer+pedigrees, and does it with cryptographic honesty instead of a "trust us" label.+The recombination is a pure function of the two parent genomes and a recorded seed,+so what you preview is exactly what you breed, and the family tree on every node is+independently verifiable.++## How it works++The engine lives in `api/_lib/genome.js` and is deterministic by construction. A+seeded PRNG (`xmur3` + `mulberry32`) draws per-locus values, so given the same two+parents and the same seed it always derives the identical child.++- **Brain.** Six numeric loci (temperature, verbosity, curiosity, formality, humor,+ boldness) inherit as a parental blend plus a bounded mutation. Mutation can drift a+ trait at most `MUTATION_MAX = 0.12` in 0..1 space, and any drift past+ `MUTATION_RECORD_THRESHOLD = 0.04` is recorded in `genome.mutations` so every+ novelty is auditable. Tone tags recombine as a set.+- **Voice.** Numeric voice loci (stability, similarity_boost, style) blend and+ mutate; pitch blends within a bounded range. The dominant `voice_id` comes from+ whichever parent carries a real cloned or ElevenLabs voice, and the child's blended+ settings are genuinely synthesized through `/api/tts/eleven`, not just labelled.+- **Body.** Morph targets and colors blend; accessories and hidden parts recombine as+ sets. At breed time the dominant parent's GLB is copied into the child's namespace+ and the inherited appearance is baked into a real composite child GLB.+- **Skills.** Allele recombination: each parent contributes its full allele set+ (expressed and recessive). Dominance decides what the child expresses, recessive+ alleles carry silently to the next generation, and matching alleles can trigger an+ emergent fusion skill per `FUSION_RULES`. The skills the child actually expresses+ are granted on-chain to the child's wallet with royalty provenance recorded (which+ parent each license descended from).+- **Pedigree.** A weighted score (generation depth weighted most, then emergent+ novelty and recessive variety) maps to a tier: common, uncommon, rare, legendary.+- **Recording and verification.** Each breed writes a `genome_breedings` row with the+ breeding key, both parent ids, the child id, the seed, the full child genome, its+ hash, generation, and pedigree tier. `verifyGenome` re-derives the child from the+ recorded seed plus the parent-genome snapshots captured at breed time and confirms+ the stored hash matches. Breeding is idempotent per `(parents, seed)` key: replaying+ the same pairing returns the same child instead of minting twins.++## Walkthrough++1. **Open [/genome](https://three.ws/genome).** Your agents load from `/api/agents`;+ public studs load from `/api/genome/stud`.+2. **Pick two parents.** Choose two agents you own, or pair one of yours with a+ public stud. An agent cannot breed with itself.+3. **Preview the offspring.** `POST /api/genome/preview` derives the child+ deterministically and echoes back the seed. You see the full trait blend, the+ real voice settings and `voice_id` the child would carry (playable via+ `/api/tts/eleven`), the bakeable body, the skill alleles (expressed, recessive,+ emergent), recorded mutations, and the pedigree tier. Nothing is minted.+4. **Reroll if you want a different draw.** A reroll changes the seed and re-previews.+ The seed you settle on is the one that gets committed.+5. **Breed.** `POST /api/genome/breed` with the same seed commits exactly the+ previewed child: a new agent with a fresh wallet, a baked composite GLB, blended+ voice, composed brain, and its expressed skills minted on-chain.+6. **Verify the lineage.** Every parent and child links to its family tree via+ `/api/genome/lineage`. The `verify=1` path re-derives and confirms the genome so+ anyone can check the child is real.++## Examples++Preview a pairing (read-only, nothing minted). See+[Authentication](./authentication.md) for the token or session cookie:++```bash+curl -s -X POST https://three.ws/api/genome/preview \+ -H 'content-type: application/json' \+ -H "authorization: Bearer $THREEWS_TOKEN" \+ -d '{"parent_a":"<agent-uuid-a>","parent_b":"<agent-uuid-b>"}'+# returns { seed, genome:{ generation, brain, voice, body, skills, mutations }, pedigree_tier, ... }+```++Commit exactly the previewed child by passing the echoed seed:++```bash+curl -s -X POST https://three.ws/api/genome/breed \+ -H 'content-type: application/json' \+ -H "authorization: Bearer $THREEWS_TOKEN" \+ -d '{"parent_a":"<agent-uuid-a>","parent_b":"<agent-uuid-b>","seed":"<seed-from-preview>"}'+# returns 201 { child:{ id, name, generation, avatar_id }, genome, genome_hash, seed }+```++Verify any child against its recorded parents and seed (public, no auth):++```bash+curl -s "https://three.ws/api/genome/lineage?agentId=<child-uuid>&verify=1"+# re-derives the genome from the stored seed + parent snapshots and confirms the hash+```++## States and limits++- **Ownership and consent.** You can always breed two agents you own for free.+ Pairing with someone else's public stud is allowed and may carry a `$THREE` stud+ fee paid to the stud owner; the preview surfaces the fee. Private agents you do not+ own are not breedable.+- **Breeding cooldown.** A parent can breed at most once per 6-hour window+ (`BREED_COOLDOWN_MS`). Breeding a parent still on cooldown returns HTTP 409+ `breeding_cooldown` with the remaining minutes. Cooldowns keep deep pedigrees+ scarce.+- **Stud fee settlement.** When a stud fee applies and no valid payment signature is+ attached, `/api/genome/breed` returns HTTP 402 with the required `$THREE` amount.+ Presence of a signature is not proof of payment; the fee must actually land in the+ stud's payout wallet, and a single payment cannot be reused across breedings.+- **Determinism.** Same parents plus same seed always yields the same child. Change+ the seed and you get a different (still valid) draw.+- **Graceful birth.** A copy or bake hiccup never blocks the birth; the child still+ references a real model, degrading to the copied base GLB if the composite bake+ fails.+- **Provenance is permanent.** The seed, genome, and hash are recorded so the lineage+ stays re-derivable and forgery-detectable indefinitely.++## Related++- [Instant Agent Genesis](./genesis.md): mint the parents in under a minute+- [Agent Skills](./agent-skills.md): the skill licenses that recombine+- [Agent Wallets](./agent-wallets.md): the fresh child wallet+- [Agent Reputation](./agent-reputation.md): how pedigree feeds standing+- [ERC-8004](./erc8004.md): on-chain identity for bred agents+- Pages: [/genome](https://three.ws/genome), [/agent-studio](https://three.ws/agent-studio)diff --git a/docs/guardian.md b/docs/guardian.mdnew file mode 100644index 000000000..2fe856e99--- /dev/null+++ b/docs/guardian.md@@ -0,0 +1,79 @@+# Guardian console: recover and inherit agent wallets, without ever touching a key++The Guardian console is the inbox for the other side of social recovery. When a friend names you a guardian or a beneficiary of their agent, that agent shows up here. This is where you help them back in: approve a recovery you trust, decline one you do not, confirm an inheritance when someone is truly gone, or push a ready process over the line. Every action runs through a threshold-approved, time-locked process that only ever changes who owns the agent. A private key is never decrypted, displayed, or moved.++Page: [/guardian](https://three.ws/guardian)+API: `GET /api/agents/recovery-inbox`, and the per-agent recovery actions under `/api/agents/:id/recovery/...`++## Why it exists++A funded agent should not die with a lost password, or with its owner. But the usual answer, exporting a seed phrase to a trusted contact, just moves the single point of failure. three.ws takes a different position: recovery and inheritance are ownership transfers, never key exports. The wallet secret stays encrypted at rest; the platform simply re-points the agent to a new owner account and signs for them afterward. There is nothing for an attacker to intercept.++The owner sets this up from their own wallet hub (naming guardians, an approval threshold, and optionally a beneficiary). But the owner is, by definition, the person who is locked out or gone, so they cannot be the one who acts. The guardian console is the surface for the people who can: the guardians and beneficiaries. They are not the owner, so they never see the owner-only Recovery tab inside the agent's hub. Being someone's safety net is a real, visible role in the graph, and this page gives it the weight it deserves.++## How it works++`GET /api/agents/recovery-inbox` lists every agent where you hold an active guardian or beneficiary role (`agent_recovery_guardians`). Each agent is decorated with its live recovery or inheritance process if one is open (`getActiveRequest`, `decorateRequest`), and a `needs_action` flag computed for you specifically:++- For a **recovery**, a guardian who is not the requester and has not already voted needs to act.+- For an **inheritance**, a beneficiary whose confirmation is awaited, or any guardian who has not voted, needs to act.++The response sorts agents that need your action first, then those with an open process, then the rest, and reports how many need you.++**The safety rails** (detailed in [custody](./custody.md)) are enforced by the recovery API, not the console:++- The requester cannot approve their own takeover; at least one other guardian must approve.+- The wallet auto-freezes for autonomous spend the moment a request opens (the real owner's own withdrawal stays open).+- Threshold approvals start a time-lock before the transfer can complete.+- The real owner can cancel instantly at any point; their presence defeats the request.+- Unmet requests expire.++**Inheritance** is a dead-man's switch: the owner enables it with an inactivity threshold and a grace window, "alive" is inferred from real activity or an explicit check-in, and when inactivity crosses the line an inheritance request opens to the beneficiary. It needs guardian confirmation (or the beneficiary's own, if no guardians are set) and the grace window before it completes.++**Actions** the console fires (all CSRF-protected, owner or guardian gated, never exposing a key):++- Approve or decline a recovery: `POST /api/agents/:id/recovery/requests/:rid/{approve,decline}`+- Confirm or decline an inheritance: `POST /api/agents/:id/recovery/requests/:rid/{confirm,decline}`+- Complete a ready transfer: `POST /api/agents/:id/recovery/requests/:rid/complete`+- Arm inheritance as a beneficiary when the owner has gone silent past their threshold: `POST /api/agents/:id/recovery/inheritance/arm`++## Walkthrough++1. Open [/guardian](https://three.ws/guardian). Signed out, it prompts you to sign in. Signed in with no roles, it explains what the console is for and invites you to ask a friend to name you.+2. Each agent you protect renders as a card: its name (linked to its profile), who owns it, when you were trusted, and your roles (guardian, beneficiary, or both). A badge at the top counts how many agents need your action.+3. If a process is open, the card tells its story in the agent's own voice ("I'm being recovered. If you trust this person is really my owner, approve."), plus the approval count, the safety-window countdown, and when it opened.+4. Act. For a recovery you trust, click **Approve recovery** (or **Decline**). For an inheritance you believe is real, click **Confirm inheritance**. Each action asks you to confirm, because these are consequential.+5. When the safety window has elapsed and the process is ready, click **Complete transfer** to pass control of the agent and its wallet to the new owner.+6. If you are a beneficiary and the owner has gone silent past their threshold with no active process, you can try to arm inheritance, which begins the grace window.++## Examples++Read your guardian inbox:++```bash+curl -s https://three.ws/api/agents/recovery-inbox \+ -H 'authorization: Bearer YOUR_TOKEN' \+ | jq '.data | {need_your_action: .actionable,+ agents: [.items[] | {agent: .agent_name, roles, needs_action,+ process: .active_request.kind, status: .active_request.status}]}'+```++The console reads this on load, resolves your viewer id (so it can tell whether you have already voted), and renders each item. Write actions are performed with a CSRF token; the console fetches one before every non-GET call.++## Guardrails, states, and limits++- **A key is never exposed.** Recovery and inheritance change ownership only. The wallet secret stays encrypted; completing a process re-points the agent, it does not reveal or move a secret.+- **You are not the owner here.** The console only ever shows agents where you are a guardian or beneficiary. It never exposes anyone's funds or keys, only the power to help them back in.+- **No self-takeover.** A recovery requester cannot approve their own request; an independent guardian approval is required.+- **Time-locked and cancelable.** Threshold approvals start a safety window; the real owner can cancel any time before completion, and their return defeats the request outright.+- **Auto-freeze during a dispute.** An open request freezes autonomous spend (owner withdrawal stays open), tracked separately so it lifts on resolution without overriding a freeze the owner set.+- **Confirmation on every consequential action.** Approve, confirm, decline, and complete each prompt for confirmation before firing.+- **Signed-out, empty, and error states** are all designed: sign-in prompt, "no one's named you yet", and an inline retry on failure.+- **Not the content-safety Guardian.** This console is unrelated to `@three-ws/guardian`, the AI content-moderation model that shares the name.++## Related++- [Custody you can verify](./custody.md) - the full recovery and inheritance model, the freeze switch, spend limits, and proof-of-custody+- [Financial controls](./financial-controls.md) - the plain-English spend rules on the same wallet rails+- [/integrity](https://three.ws/integrity) - the public Merkle attestation of every custodial wallet+- [/proof](https://three.ws/proof) - verify your own wallet's inclusion in the attestation, in your browserdiff --git a/docs/image-to-3d.md b/docs/image-to-3d.mdnew file mode 100644index 000000000..c8300aa15--- /dev/null+++ b/docs/image-to-3d.md@@ -0,0 +1,93 @@+# Image to 3D: turn a photo into a downloadable 3D model++Image to 3D is Forge's photo lane, opened directly. Drop in one to four photos of an object, taken from different angles, and get back a textured, downloadable GLB you can orbit, view in AR, and take into any engine. It is the fastest way to go from a real thing on your desk, or a single reference image, to a real 3D model, with no account and no key on the free lane.++Page: [/image-to-3d](https://three.ws/image-to-3d) · API: `/api/forge`++## Why it exists++Text-to-3D is great when you can describe a thing. But often you already have the thing, or a picture of it: a prop, a toy, a piece of furniture, a product shot. Reconstructing geometry from photos preserves the real proportions and surface that a text prompt can only approximate. Image to 3D gives that reconstruction its own entry point so a first-time visitor lands directly in photo mode instead of hunting for the tab, while everything else, the engine grid, the tiers, the live health status, the downloadable GLB, is the same Forge machinery underneath.++/ image-to-3d and [/forge](https://three.ws/forge) are the same application (`pages/forge.html`, driven by `src/forge.js`). The `/image-to-3d` route sets the page into photo mode and retitles it; the app is otherwise identical, so any engine, tier, or export you can reach from Forge you can reach here.++## How it works++When you add photos, the app switches to the `image` (image-intermediate) generation path. Each photo is uploaded straight to object storage through a presigned URL (`/api/forge-upload`), and the resulting public URLs are POSTed to `/api/forge` as `image_urls`. With more than one view the backend fuses them with multi-view conditioning, so the reconstructed mesh honors detail from every angle you supplied rather than guessing the unseen sides from a single frame.++Routing is free-first and health-aware, exactly as in Forge. Because the free NVIDIA NIM TRELLIS lane is text-only (it rejects user images), photo submissions filter it out and fall to the free reconstruction chain in `api/_lib/forge-tiers.js`, most preferred first:++1. **TRELLIS (self-host)**, our own Cloud Run GPU worker, a native single-hop image-to-3D lane (image to TRELLIS to GLB), zero vendor cost.+2. **Hunyuan3D (self-host)**, our own high-poly reconstruction worker, strong on people and organic subjects.+3. **Hunyuan3D / TRELLIS (free)** on Hugging Face Spaces, with automatic failover across Hunyuan3D 2.1, Hunyuan3D 2, TRELLIS, and TripoSR.++Paid and BYOK image engines stay explicitly selectable: **Meshy 6**, **Tripo v3.1**, **Rodin (Hyper3D)**, **Stable Fast 3D** (Stability), the **Replicate** TRELLIS lane, and your own Replicate account. A lane whose upstream is down is disabled in the engine picker with the real reason, and a selected engine that can't accept photos bounces to the standing photo default rather than failing after you commit.++The result is a job: the client polls `GET /api/forge?job=<id>` until the GLB lands, and an interrupted generation resumes from the same browser for 30 minutes. Every result reports the path, tier, and backend that produced it.++### Objects and props, not faces++Image to 3D reconstructs whole objects: a prop, a product, a toy, a sculpture, a piece of hardware. It is not a face-to-avatar pipeline. To turn a selfie into a rigged, animation-ready humanoid avatar, use the dedicated face reconstruction flow at [/create/selfie](https://three.ws/create/selfie), which runs a purpose-built face pipeline (head framing, identity preservation, rig) rather than general object reconstruction. Feeding a headshot into the general image lane treats the head as an object and will not produce a rigged avatar.++## Walkthrough++1. Open [/image-to-3d](https://three.ws/image-to-3d). The page opens in photo mode.+2. Add one to four photos of the same object. For best results shoot the same object from different angles (front, side, back, three-quarter) on a plain background.+3. Optionally pick a tier (Draft, Standard, High) and an engine. The default free reconstruction lane carries a **FREE** pill; down lanes are disabled with a reason.+4. Click Generate. A real elapsed-driven progress line runs against the ETA for the resolved engine and tier; a cold self-host worker adds an honest spin-up estimate.+5. When the model lands, orbit it, view it in AR, download the GLB, or run the post-generation tools (stylize, optimize, Game-Ready retopology).++## Examples++Send public image URLs to the same `/api/forge` endpoint. No key is required on the free lane.++```bash+# Multi-view reconstruction from three angles, standard tier, then poll.+JOB=$(curl -s -X POST 'https://three.ws/api/forge' \+ -H 'content-type: application/json' \+ -d '{"image_urls":["https://…/front.jpg","https://…/side.jpg","https://…/back.jpg"],"tier":"standard"}' \+ | python3 -c 'import sys,json;print(json.load(sys.stdin)["job_id"])')++curl "https://three.ws/api/forge?job=$JOB"+```++Single-image reconstruction is just one URL:++```bash+curl -X POST 'https://three.ws/api/forge' \+ -H 'content-type: application/json' \+ -d '{"image_urls":["https://…/sneaker.jpg"],"tier":"draft"}'+```++Poll until the GLB is ready in JavaScript:++```javascript+const start = await fetch('https://three.ws/api/forge', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ image_urls: ['https://…/chair.jpg'], tier: 'standard' }),+}).then((r) => r.json());++let job = start;+while (job.status !== 'done' && job.status !== 'error') {+ await new Promise((r) => setTimeout(r, 4000));+ job = await fetch(`https://three.ws/api/forge?job=${start.job_id}`).then((r) => r.json());+}+console.log(job.glb_url);+```++## States and limits++- **Up to four views** per generation; more views mean tighter multi-view fusion.+- **Free lane** requires no account. The **High tier** is $THREE hold-or-pay gated (quality gate, not vendor-cost recovery); a verified $THREE pass also lifts the free-lane quota.+- **Loading**: real elapsed counter; cold GPU workers surface an honest spin-up estimate.+- **Down or unconfigured engine**: disabled with the real reason, or a clean `backend_unconfigured` error. No mock output, ever.+- **Resume**: an interrupted job is pollable again for 30 minutes from the same browser.+- **Objects, not faces**: for a rigged humanoid from a selfie, use [/create/selfie](https://three.ws/create/selfie).+- Uploads cap at 8 MB per image; rate limits are per client IP.++## Related++- [Forge](./forge.md) is the full text-and-image-to-3D surface with every mode and engine.+- [Avatar reconstruction](./avatar-reconstruction.md) and [avatar creation](./avatar-creation.md) cover the face-to-avatar pipeline behind [/create/selfie](https://three.ws/create/selfie).+- The pipeline internals: [3D asset pipeline](./3d-asset-pipeline.md), [3D pipeline](./3d-pipeline.md), [3D API](./3d-api.md).+- Pages: [/create](https://three.ws/create), [/scene](https://three.ws/scene) (Scene Studio), [/gallery](https://three.ws/gallery).diff --git a/docs/index.html b/docs/index.htmlindex df236d788..f10d177fd 100644--- a/docs/index.html+++ b/docs/index.html@@ -768,6 +768,62 @@{ label: 'Everything on one page', path: 'agent-abilities/FULL-ARTICLE' },],},+ {+ title: 'Creation studios',+ links: [+ { label: 'Forge (text & image to 3D)', path: 'forge' },+ { label: 'Image to 3D', path: 'image-to-3d' },+ { label: 'Diorama (text to world)', path: 'diorama' },+ { label: 'Cosmos (living worlds)', path: 'cosmos' },+ { label: 'Splat viewer (Gaussian avatars)', path: 'splat' },+ { label: 'Scene Capture (video to point cloud)', path: 'capture' },+ { label: 'Restyle Studio', path: 'restyle' },+ { label: 'Scene Studio', path: 'scene-studio' },+ { label: 'Scene Composer', path: 'compose' },+ { label: 'Animation Studio', path: 'animation-studio' },+ { label: 'Avatar Studio', path: 'avatar-studio' },+ { label: 'Mocap Studio', path: 'mocap-studio' },+ { label: 'Selfie to Avatar', path: 'selfie-to-avatar' },+ { label: 'Daily Forge', path: 'daily-forge' },+ { label: 'AR Studio', path: 'ar-studio' },+ ],+ },+ {+ title: 'Voice & video',+ links: [+ { label: 'Voice Lab', path: 'voice-lab' },+ { label: 'Lipsync', path: 'lipsync' },+ { label: 'Talking Avatar Video', path: 'talking-avatar-video' },+ ],+ },+ {+ title: 'Build an agent',+ links: [+ { label: 'Instant Agent Genesis', path: 'genesis' },+ { label: 'Agent Genome (breeding)', path: 'genome' },+ { label: 'Agent Studio', path: 'agent-studio' },+ { label: 'Multi-LLM Brain', path: 'brain' },+ { label: 'Agent Galaxy', path: 'galaxy' },+ { label: 'Integrations', path: 'integrations' },+ ],+ },+ {+ title: 'Trading & markets',+ links: [+ { label: 'Coin Autopilot', path: 'autopilot' },+ { label: 'Signal Marketplace', path: 'signals' },+ { label: 'The AGI', path: 'agi' },+ { label: 'Alpha Co-pilot', path: 'alpha-copilot' },+ { label: 'Guardian console', path: 'guardian' },+ { label: 'Strategy Objects', path: 'strategy-objects' },+ { label: 'Mission Control (terminal)', path: 'terminal' },+ { label: 'Smart Money Radar', path: 'smart-money' },+ { label: 'Coin Radar', path: 'radar' },+ { label: 'Coin Clash', path: 'clash' },+ { label: 'x402 Studio', path: 'x402-studio' },+ { label: 'Fact Check', path: 'fact-check' },+ ],+ },{title: 'Getting started',links: [diff --git a/docs/integrations.md b/docs/integrations.mdnew file mode 100644index 000000000..ab74451fd--- /dev/null+++ b/docs/integrations.md@@ -0,0 +1,159 @@+# Integrations: drop-in 3D agents for any site++Integrations is the catalog of ways to put a three.ws agent on a website you do not+control the runtime of. One script tag gives any page a 3D avatar viewer, a talking+chat agent, a walk companion that roams the corner of the screen, a page narrator, a+live token market widget, or an MCP server that lets Claude and other AI tools drive+your agents. Every option is a paste-in snippet with no backend to run.++Page: [/integrations](https://three.ws/integrations)++## Why it exists++The platform's agents are only as useful as the places they can appear. Integrations+is the distribution layer: it turns an agent, a saved widget, or a live token feed+into something a marketer can paste into a CMS, a developer can wire into a framework,+or an AI assistant can call as a tool. It is the front page of embedding; the deep+per-method references live in [Embedding](./embedding.md) and [Widgets](./widgets.md),+and this doc is the map that points you to the right one.++## How it works++Every integration is a static, self-contained snippet loaded from three.ws. The+avatar, chat, and token widgets share one loader (`/embed.js`) that upgrades custom+elements or `data-widget` script tags into live iframes or web components. The walk+companion and page narrator ship their own small SDKs. Nothing needs an API server on+your side; the agent runtime, rendering, and (for chat) the model calls all run on+three.ws.++The catalog covers six integration types:++- **Avatar Viewer**: a `<threews-avatar>` web component that renders a rigged 3D+ avatar with optional JS control (`play('wave')`, poses, `hide-chrome`).+- **Talking Chat Agent**: a saved widget that renders a 3D agent which listens,+ answers, and speaks, driven by a `data-widget` id from [Widget Studio](https://three.ws/widgets).+- **Walk Companion**: a floating 3D character fixed to a corner of the page that+ walks, gestures, and speaks, loaded from `/walk-embed-sdk.js`.+- **Page Narrator**: an agent that reads and narrates the page it lives on, shipped as+ the `@three-ws/page-agent` package.+- **Token Market Widget**: a live pump.fun-style token feed rendered as a widget,+ driven by a `data-widget` id and the `pumpfun-feed` type.+- **MCP Integration**: the `@three-ws/avatar-agent-mcp` server, so Claude, Cursor, or+ any MCP-compatible assistant can render, speak, gesture, and emote your agents. See+ [MCP](./mcp.md).++## Walkthrough++1. **Open [/integrations](https://three.ws/integrations).** Filter the catalog by type+ (avatar, chat, companion, narrator, token, MCP).+2. **Try the live demo.** Each card has a working preview and a Try Live button that+ opens the real embed in a modal.+3. **Copy the snippet.** Every card exposes its exact paste-in code.+4. **Swap in your ids.** Replace the demo widget or avatar id with your own from+ [Widget Studio](https://three.ws/widgets), or your API key for the MCP server.+5. **Paste it into your site.** Drop the snippet anywhere in your HTML, CMS block, or+ framework component.++## Examples++Avatar Viewer (web component):++```html+<!-- Load once -->+<script src="https://three.ws/embed.js" defer></script>++<!-- Drop anywhere in your HTML -->+<threews-avatar avatar-id="avatar_demo_disk_cz" hide-chrome pose="idle"></threews-avatar>++<!-- Optional: JS control -->+<script>+ const el = document.querySelector('threews-avatar');+ await el.ready;+ el.play('wave');+</script>+```++Talking Chat Agent (saved widget):++```html+<script+ src="https://three.ws/embed.js"+ data-widget="wdgt_demo_talking"+ data-type="talking-agent"+ defer+></script>+<!-- Replace wdgt_demo_talking with your widget ID from three.ws/widgets -->+```++Walk Companion:++```html+<script+ src="https://three.ws/walk-embed-sdk.js"+ data-avatar="avatar_demo_disk_cz"+ data-position="bottom-right"+ data-env="studio"+ defer+></script>+```++Page Narrator:++```html+<script+ src="https://cdn.jsdelivr.net/npm/@three-ws/page-agent/dist/page-agent.global.js"+ data-page-agent+ data-avatar="nova"+ data-auto-narrate+ defer+></script>+```++Token Market Widget:++```html+<script+ src="https://three.ws/embed.js"+ data-widget="wdgt_demo_pumpfun"+ data-type="pumpfun-feed"+ data-width="420"+ data-height="600"+ defer+></script>+```++MCP Integration (`claude_desktop_config.json`):++```json+{+ "mcpServers": {+ "threews-avatar": {+ "command": "npx",+ "args": ["-y", "@three-ws/avatar-agent-mcp"],+ "env": { "THREEWS_API_KEY": "your-key-here" }+ }+ }+}+```++## States and limits++- **Get your own ids.** Demo ids in the snippets are live examples. Create your own+ avatars and widgets in [Widget Studio](https://three.ws/widgets) and swap them in.+- **Self-contained by design.** The embeds run entirely off three.ws; you host no+ backend. The chat and token widgets make their model and data calls server-side.+- **One loader, many widgets.** `/embed.js` can be loaded once and drive multiple+ avatar, chat, and token embeds on the same page.+- **MCP needs a key.** The MCP server authenticates with `THREEWS_API_KEY`; the other+ embeds are public and need no key.+- **Deeper control lives elsewhere.** This page is the catalog. For the full web+ component API, iframe and oEmbed options, CSS, and events, use the references below+ rather than duplicating them here.++## Related++- [Embedding Guide](./embedding.md): the full per-method reference (web component, iframe, oEmbed)+- [Widget Types](./widgets.md): every widget type and how to configure one+- [Embody](./embody.md): giving an agent a body in more contexts+- [MCP](./mcp.md): the avatar MCP server for AI assistants+- Pages: [/integrations](https://three.ws/integrations), [/widgets](https://three.ws/widgets)diff --git a/docs/lipsync.md b/docs/lipsync.mdnew file mode 100644index 000000000..613255fb1--- /dev/null+++ b/docs/lipsync.md@@ -0,0 +1,90 @@+# Lipsync: real-time mouth animation from speech++Two browser demos show the same idea from two angles: drive a 3D avatar's mouth from speech, live, with no server-side video rendering. `/lipsync` types a phrase, synthesizes it, and animates the mouth as the audio plays. `/lipsync/mic` opens your microphone and moves the mouth in real time as you talk. Both render the same avatar and both compute visemes frame-by-frame in the browser, feeding the avatar's `viseme_*` morph targets.++Page: [/lipsync](https://three.ws/lipsync) (TTS-driven) · [/lipsync/mic](https://three.ws/lipsync/mic) (microphone-driven)+API: `POST /api/tts/speak` (used only by the TTS demo)++## Why it exists++Lipsync is the difference between an avatar that speaks and a mannequin with audio playing near it. These demos are the reference implementations for the two lipsync paths the platform runs everywhere else: a viseme string from a phoneme-aware analyzer, and a frequency-band heuristic that works with nothing but an audio stream. Seeing both side by side makes the trade-off explicit, and each demo is a self-contained, copyable example of wiring an analyzer to morph targets on a glTF avatar.++Both demos load the same rig, [`public/avatars/default.glb`](../public/avatars/default.glb), which carries Oculus-style viseme morph targets (`viseme_aa`, `viseme_E`, `viseme_O`, and so on). There is no server-side audio analysis in either demo; everything happens on the client.++## How it works++### TTS demo (`/lipsync`)++Served from [`public/demos/lipsync-tts.html`](../public/demos/lipsync-tts.html). Flow: type a phrase, POST it to the TTS endpoint, receive an audio blob, play it through an `Audio` element, and let the third-party [`wawa-lipsync`](https://www.npmjs.com/package/wawa-lipsync) package (pinned `^0.0.2`) analyze the playing audio each frame.++1. The page imports `three`, `GLTFLoader`, `OrbitControls`, and `{ Lipsync } from 'wawa-lipsync'`, and constructs `const lipsync = new Lipsync()`.+2. On Speak it POSTs `{ text, voice, speed, format: 'mp3' }` to `/api/tts/speak`. The Voice dropdown offers nova (default), alloy, echo, fable, onyx, shimmer, ash, coral, sage; Speed offers 0.8x, 1.0x, 1.2x, 1.5x.+3. The returned bytes become an object URL on a `new Audio()` (`crossOrigin: 'anonymous'`), then `lipsync.connectAudio(audioEl)` (src set before connect, as wawa requires).+4. In the render loop, while playing, it calls `lipsync.processAudio()` and reads `lipsync.viseme` (one of `sil, aa, PP, FF, TH, DD, kk, CH, SS, nn, RR, ou`). A `VISEME_MAP` translates that code to the avatar's morph name (for example `aa -> viseme_aa`, `CH -> viseme_CH`, `ou -> viseme_O`, `sil -> null`).+5. Each frame every viseme weight is reset to 0, the active viseme's morph is targeted to 1.0, and the actual `morphTargetInfluences` are lerped toward the target (factor 0.5) so the mouth eases instead of snapping. A live viseme meter mirrors the current code.++`wawa-lipsync` computes visemes from per-band energies, band deltas, overall volume, and spectral centroid (`computeVisemeScores` plus temporal smoothing in `adjustScoresForConsistency`), exposing the winner as `.viseme`.++### Microphone demo (`/lipsync/mic`)++Served from [`public/demos/lipsync-mic.html`](../public/demos/lipsync-mic.html). This demo does **not** use wawa-lipsync. It imports the in-house analyzer [`src/lip-sync-analyser.js`](../src/lip-sync-analyser.js) (`LipSyncAnalyser`), the same viseme pipeline that drives streamed TTS in the live chat, sourced from your mic instead.++1. Start calls `getUserMedia({ audio: true })`, creates an `AudioContext`, wires `createMediaStreamSource(stream)` into an `AnalyserNode` (`fftSize: 256`, `smoothingTimeConstant: 0.7`). The analyzer node is deliberately not connected to `destination`, so your mic does not echo through the speakers.+2. `new LipSyncAnalyser()` is `connect()`-ed to that node, and each frame `analyser.sample()` returns a `{ viseme_name: weight }` map that is written straight to the avatar's `morphTargetInfluences` and a 9-bar meter.+3. The analyzer is a frequency-band heuristic: low band (0 to 500 Hz) drives open vowels (`viseme_aa`, `viseme_O`), the mid band (500 Hz to 2 kHz) drives mid vowels and nasals (`viseme_E`, `viseme_I`, `viseme_nn`), the high band (2 to 8 kHz) drives sibilants and fricatives (`viseme_SS`, `viseme_FF`, `viseme_CH`), and an amplitude dip drives a bilabial closure (`viseme_PP`). A silence gate below 0.15 overall amplitude eases everything to rest; otherwise weights EMA toward target (factor 0.25). `getAmplitude()` also exposes a smoothed 0..1 level so a rig with no viseme morphs can drive a single `jawOpen`/`mouthOpen` morph instead.+4. This demo registers the meshopt decoder before loading, because server-baked and Forge GLBs can ship `EXT_meshopt_compression`.++## Walkthrough++1. Open [/lipsync](https://three.ws/lipsync). Edit the text, pick a voice and speed, and press Speak. Watch the mouth move as the audio plays; the viseme meter shows the live code. Press Stop to interrupt.+2. Open [/lipsync/mic](https://three.ws/lipsync/mic) and press Start. Allow microphone access, then talk or sing. The mouth and the 9-bar meter follow your voice. Press Stop to release the mic and reset the mouth.++## Examples++Only the TTS demo hits an API. `/api/tts/speak` returns audio bytes you can decode and analyze exactly as the demo does.++```bash+# Synthesize speech to an MP3 file (the same call the /lipsync demo makes).+curl -X POST 'https://three.ws/api/tts/speak' \+ -H 'content-type: application/json' \+ -d '{ "text": "Welcome to three dot ws.", "voice": "nova", "speed": 1.0, "format": "mp3" }' \+ --output speech.mp3+```++```js+// Minimal browser lipsync loop with wawa-lipsync, mirroring the /lipsync demo.+import { Lipsync } from 'wawa-lipsync';+const lipsync = new Lipsync();+const res = await fetch('/api/tts/speak', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ text: 'Hello from three dot ws', voice: 'nova', format: 'mp3' }),+});+const audio = new Audio(URL.createObjectURL(await res.blob()));+audio.crossOrigin = 'anonymous';+lipsync.connectAudio(audio);+audio.play();+function tick() {+ if (!audio.paused) { lipsync.processAudio(); console.log(lipsync.viseme); }+ requestAnimationFrame(tick);+}+tick();+```++`POST /api/tts/speak` ([`api/tts/speak.js`](../api/tts/speak.js)) prefers the free NVIDIA NIM Magpie TTS lane when configured and falls back to OpenAI as a paid backstop. Body: `{ text, voice?, model?, format?, language?, speed? }`. `text` is required (max 4096 chars), `voice` defaults to `nova`, `format` defaults to `mp3`, `speed` clamps 0.5 to 2.0. It is rate-limited per user or per IP.++## States and limits++- **TTS demo errors.** A persistent, actionable banner with a Retry button covers network failure, `429` rate limit, `>=500` service errors, `400` bad text, audio playback failure, and blocked autoplay ("needs a click").+- **Mic demo permissions.** `getUserMedia` failures map by `DOMException.name`: `NotAllowedError`/`SecurityError` -> "Microphone blocked", `NotFoundError`/`OverconstrainedError` -> "No microphone found", `NotReadableError` -> "Microphone is busy", with a "Try again" button.+- **Morph naming.** The avatar uses Oculus-style `viseme_*` targets, not ARKit blendshape names. On load each demo logs how many of the expected viseme morphs it wired.+- **No TTS on the mic demo.** It analyzes live audio only; no network call.+- **Two different analyzers.** The TTS demo uses the third-party `wawa-lipsync` phoneme-style analyzer; the mic demo uses the in-house frequency-band `LipSyncAnalyser`. They map slightly different viseme sets.++## Related++- [Voice Lab](./voice-lab.md): clone a voice and synthesize it, the audio these demos animate.+- [Voice and lipsync tutorial](./tutorials/voice-and-lipsync.md): the full walkthrough, including wiring visemes to an agent body.+- [Talking Avatar Video](./talking-avatar-video.md): the server-rendered alternative for exporting a talking-head clip.+- [Animations](./animations.md): the runtime clip registry that plays alongside lipsync.+- Pages: [/lipsync](https://three.ws/lipsync), [/lipsync/mic](https://three.ws/lipsync/mic).diff --git a/docs/mocap-studio.md b/docs/mocap-studio.mdnew file mode 100644index 000000000..275238b9d--- /dev/null+++ b/docs/mocap-studio.md@@ -0,0 +1,81 @@+# Mocap Studio: drive a 3D avatar with your face, live in the browser++Mocap Studio turns your webcam into a face-mocap rig. Point the camera at yourself and a three.ws avatar mirrors your expressions and head movement in real time: eyes, brows, mouth, jaw, and head pose, all in the browser, with no rig setup, no plugin, and no download. Calibrate to your neutral face, record a clip, replay it, and save it. Saved clips can be private, unlisted, or public, and you can replay anyone's public clips on the avatar too.++Page: [/mocap-studio](https://three.ws/mocap-studio) · API: `/api/mocap/clips`++## Why it exists++Facial motion capture is normally a studio problem: markers, a helmet cam, dedicated software, and an export pipeline. Mocap Studio collapses all of that into a web page. The camera you already have, the avatar you already made, and a couple of clicks are enough to get expressive, recorded facial animation. It exists so a three.ws avatar can emote like a person, not just play canned clips, and so that expressiveness is capturable, saveable, and shareable as data (a small JSON clip) rather than a heavy video.++## How it works++The engine is `FaceMocap`, built on Google's MediaPipe Face Landmarker (a newer model than the FaceMesh that older browser-rigging libraries use). Per frame it outputs 52 ARKit blendshape scores, 478 3-D face landmarks (including iris), and a 4x4 facial transformation matrix for head pose in camera space. The pipeline is:++```+webcam → Face Landmarker → calibration delta → one-euro smoothing →+ ARKit morph targets + head bone rotation on the avatar+```++- **Calibration** subtracts your resting face as a baseline, so a neutral expression maps to a neutral avatar instead of an involuntary smirk.+- **One-euro smoothing** (Casiez et al., 2012) is an adaptive low-pass filter: it stays crisp on fast motion and heavily smooths slow motion, the standard trick in mocap pipelines to kill jitter without adding lag.+- **The blendshapes** drive the avatar's ARKit morph targets (resolved through the platform's canonical morph map, so different avatar rigs all respond), and the head-pose matrix rotates the avatar's head (or neck) bone within a clamped range.++The avatar loads into a `Viewer` scene with a procedural idle (breathing, blinking, subtle saccades). While mocap drives the head, the idle pauses its saccade and blink channels so it does not fight your captured motion.++### Loading an avatar++The studio resolves an avatar in order: a `?handle=<name>` deep link, then the signed-in user's own public avatar, then the platform default (`/avatars/default.glb`) so the camera and mocap pipeline are always usable. You can also type any three.ws handle to load that user's public avatar.++### Record, replay, save++Recording uses `FaceMocap`'s built-in clip buffer: every frame's blendshapes and head matrix are appended. Stop, and you have a clip with a duration and frame count. Replay drives the same avatar from the buffer. Download saves the clip as a JSON file locally. Save posts it to `/api/mocap/clips` with a name, description, tags, and a visibility of private, unlisted, or public. The clip list below the stage shows your own clips plus public ones; you can replay any of them and delete your own.++## Walkthrough++1. Open [/mocap-studio](https://three.ws/mocap-studio). An avatar loads (yours if you are signed in with a public avatar, otherwise the default). To use someone else's, type their handle and load it.+2. Click "Start camera" and allow webcam access. Your face appears in the small preview; the avatar starts mirroring you.+3. Sit with a relaxed, neutral face and click "Calibrate neutral" so the resting baseline is captured.+4. Click "Record", perform (talk, smile, raise your brows, turn your head), then click "Stop". The timer shows the clip length.+5. Click "Replay" to watch the avatar perform the captured clip.+6. Give it a name (and optional description, tags, visibility), then "Save clip", or "Download" to keep the JSON locally.+7. Browse the clip list and replay any public clip on the avatar.++## Examples++Mocap Studio is a browser tool; its examples are its deep link and the clip API.++- **Load a specific handle's avatar:** `https://three.ws/mocap-studio?handle=<username>`++The clip format saved is the object `FaceMocap` records: `{ format, duration, frames: [{ t, shapes, mat? }] }`. The API:++```bash+# List your clips plus public ones.+curl 'https://three.ws/api/mocap/clips?include_public=true&limit=30' \+ -H 'cookie: <session>'++# Save a recorded clip (visibility: private | unlisted | public).+curl -X POST 'https://three.ws/api/mocap/clips' \+ -H 'content-type: application/json' -H 'cookie: <session>' \+ -d '{"name":"eyebrow-raise","visibility":"public","tags":["face"],+ "clip":{"format":"arkit52","duration":3.2,"frames":[{"t":0,"shapes":[0,0,0]}]}}'++# Fetch one clip by id to replay it.+curl 'https://three.ws/api/mocap/clips/<clipId>' -H 'cookie: <session>'+```++## States & limits++- **Camera permission is required.** The whole pipeline depends on webcam access; nothing captures until you grant it. The video is processed locally in the browser to drive the avatar.+- **Calibrate for clean results.** Without calibration your resting expression is treated as neutral, so calibrate on a relaxed face for accurate deltas.+- **Head rotation is clamped.** The captured head pose drives the head/neck bone within a limited range, so extreme off-camera angles do not snap the neck.+- **Saving needs an account.** Recording, replaying, and downloading a clip are open to everyone; saving to the platform requires sign-in. An avatar association is only attached when you own the loaded avatar, otherwise the clip still saves, just without an avatar link.+- **Replay needs the camera started.** Playing a saved clip attaches to the same driver the camera set up, so start the camera before replaying a clip from the list.+- **Clips are data, not video.** A saved clip is compact JSON (blendshape scores plus head matrices per frame), so it is cheap to store and share and can replay on any compatible avatar, not a rendered movie.++## Related++- [Avatar Studio](./avatar-studio.md): build the avatar you drive here.+- [Animation Studio](./animation-studio.md): body posing and keyframed motion, the complement to facial capture.+- [Animations reference](./animations.md): how captured and authored motion fit the platform's clip registry.+- [/create](https://three.ws/create): make or import the avatar to perform with.diff --git a/docs/openai-pr/00-START-HERE.md b/docs/openai-pr/00-START-HERE.mdnew file mode 100644index 000000000..8b554db65--- /dev/null+++ b/docs/openai-pr/00-START-HERE.md@@ -0,0 +1,90 @@+# OpenAI Apps SDK submission — agent handoff pack++This directory contains standalone task briefs. Each `NN-*.md` file is a complete+prompt you can hand to one agent. They are ordered by impact and are mostly+independent, so several can run in parallel. Read this file first, then the brief+for your task.++## What we are shipping++three.ws is submitting its **3D Studio** app to OpenAI (ChatGPT Apps SDK / App+Directory). The submission target is the **free, keyless MCP connector** at+`https://three.ws/api/mcp-studio` plus its inline widget and the custom-GPT+Actions surface. A reviewer at OpenAI will exercise these surfaces and read the+manifests we expose. Everything they can reach must be correct, consistent, and+free of any paid or crypto surface.++The submission kit already exists at+[`prompts/store-submissions/_generated/`](../../prompts/store-submissions/_generated/)+(answer sheet `openai-submission.md`, `openai-actions.yaml`, `TRACKER.md`,+screenshots, evidence JSON). Your job is not to recreate it. Your job is to close+the specific gaps that would fail review or embarrass us in front of OpenAI.++## The map of the surface (so you know what you are touching)++| Surface | Where it lives | Notes |+| --- | --- | --- |+| Free MCP connector (submission target) | `api/mcp-studio.js`, `api/_mcp-studio/*` | Keyless. 9 tools. Real forge lane. |+| Inline ChatGPT widget (the real one) | `api/_mcp-studio/component.js` | `<model-viewer>` skybridge resource `ui://widget/three-studio-model.html` |+| Orphaned three.js widget | `apps-sdk/studio-viewer/*`, `scripts/build-apps-sdk-viewer.mjs`, `public/apps-sdk/*` | NOT wired to anything. See task 01. |+| Embodiment embed | `apps-sdk/embodiment/*`, `pages/embodiment/embed.html` | Persona widget iframes this. |+| AR-in-ChatGPT | `api/ar.js`, `api/_lib/ar-launch.js` | Every generation carries `arUrl`. |+| Custom GPT Actions (REST) | `api/3d/studio.js`, `prompts/store-submissions/_generated/openai-actions.yaml` | GPT Store listing is live. |+| Served manifests | `public/.well-known/*` | Publicly discoverable. See task 02. |+| Paid MCP server (NOT the submission) | `api/mcp-3d.js`, `api/_mcp3d/*` | x402/OAuth gated. Out of scope unless a task says so. |++## The tasks++| # | Brief | Priority | Blocks submit? |+| --- | --- | --- | --- |+| 01 | [Resolve the orphaned studio-viewer widget](01-orphan-widget-resolution.md) | P0 | Yes (dead code + false docs) |+| 02 | [Reconcile the served `.well-known` manifests with the zero-payment claim](02-wellknown-manifest-conflict.md) | P0 | Yes (reviewer-discoverable crypto surface) |+| 03 | [Make the `forge_free` tier story true everywhere](03-forge-free-tier-truth.md) | P1 | Yes (submission doc contradicts code) |+| 04 | [Close the test gaps on the ChatGPT-facing surface](04-openai-surface-test-coverage.md) | P1 | No, but required for "done" |+| 05 | [Serve the custom-GPT OpenAPI and align legal URLs](05-custom-gpt-openapi-serving.md) | P1 | Partial |+| 06 | [Fix doc accuracy and reconcile the tool-count story](06-docs-accuracy-reconciliation.md) | P1 | No |+| 07 | [Final live verification and submit checklist](07-final-verification-and-submit.md) | P2 (runs last) | Yes (the actual go/no-go) |++Run 01, 02, 03 first (they change code and docs the later tasks depend on). 04, 05,+06 can run in parallel after. 07 runs last, after everything else is merged.++## Rules every task must follow (from `CLAUDE.md`)++These are non-negotiable and OVERRIDE any default behavior:++1. **No mocks, no fake data, no placeholders, no TODOs, no stubs, no commented-out+ code.** If you write it, finish it and wire it. Real APIs only.+2. **Execute, do not interview.** Pick the most reasonable interpretation, do it,+ verify it, and report. Do not end your turn with "want me to proceed?".+3. **Every state is designed** (loading/empty/error/populated) for any UI you touch.+4. **Tests must pass:** run `npm test` (do NOT pipe through `tail` — it masks the+ exit code; a vitest failure gates the Playwright stage).+5. **Changelog:** any user-visible change gets an entry in+ [`data/changelog.json`](../../data/changelog.json) (date, plain-language title ++ summary, tags from feature/improvement/fix/sdk/infra/docs/security). Run+ `npm run build:pages` to regenerate and validate the feed. Internal-only chores+ do not get an entry.+6. **Docs ship with the feature.** If you touch a surface and its doc is now wrong,+ fix the doc in the same change. New page/route → `data/pages.json`.+7. **Commit gate — read this before staging anything.** `$THREE`+ (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`) is the only coin this platform+ promotes. Before any `git commit` whose diff references ANY crypto project other+ than `$THREE` — in code, docs, manifests, tests, or commit text — STOP and get+ explicit owner approval. Task 02 edits a manifest that currently mentions x402/+ USDC/Solana/Base; edits that keep or restructure those references need the owner's+ yes before commit. Do the work, stage nothing that trips the gate, and flag it.+8. **Do not push, deploy, or submit to OpenAI without owner approval.** Commit+ locally, prepare everything so the ship is one command, and say what remains.+9. **Never use the em-dash character.** Use a period, comma, colon, or parentheses.+10. **Concurrent agents share this worktree.** Stage explicit paths only (never+ `git add -A`). Re-check `git status` and `git diff --staged` right before you+ commit.++## Definition of done for the whole pack++- [ ] Every P0/P1 task's own definition of done is met.+- [ ] `npm test` is green.+- [ ] No surface a reviewer can reach advertises a paid or crypto capability.+- [ ] Every doc and manifest describing the ChatGPT surface matches the running code.+- [ ] `docs/openai-pr/07-final-verification-and-submit.md` checklist passes end to end.+- [ ] The only remaining steps are the human `[HUMAN: ...]` items in `TRACKER.md`.diff --git a/docs/openai-pr/01-orphan-widget-resolution.md b/docs/openai-pr/01-orphan-widget-resolution.mdnew file mode 100644index 000000000..9d2d9ca48--- /dev/null+++ b/docs/openai-pr/01-orphan-widget-resolution.md@@ -0,0 +1,118 @@+# Task 01 — Resolve the orphaned studio-viewer widget (P0)++Read [`00-START-HERE.md`](00-START-HERE.md) first for the shared rules and the map.++## The problem (verified, with evidence)++There are **two** inline-widget implementations in the tree, and they are not+connected:++1. **The widget ChatGPT actually renders** is the `<model-viewer>` component built+ inline in [`api/_mcp-studio/component.js`](../../api/_mcp-studio/component.js)+ (`COMPONENT_HTML`). It is served as the skybridge resource+ `ui://widget/three-studio-model.html` and is fully wired and tested.++2. **A second, unrelated three.js viewer** lives in+ [`apps-sdk/studio-viewer/src.js`](../../apps-sdk/studio-viewer/src.js) (619 lines,+ full GLTFLoader + OrbitControls + RoomEnvironment). It is built by+ [`scripts/build-apps-sdk-viewer.mjs`](../../scripts/build-apps-sdk-viewer.mjs)+ into `public/apps-sdk/studio-viewer.bundle.js` and `.../studio-viewer.html`.++The second one is **orphaned**:++- The consumer the build script names,+ `api/_mcp3d/studio-viewer-resource.js`, **does not exist** (confirmed:+ `ls` returns "No such file or directory").+- Nothing serves `ui://widget/studio-viewer.html`. The only references to that URI+ are the source comment in `apps-sdk/studio-viewer/src.js:7` and the build script+ comment in `scripts/build-apps-sdk-viewer.mjs:8`.+- The `/viewer` route in `vercel.json` maps to `/viewer.html`, a different page, not+ this bundle.+- The build is not in `prebuild`/`build`, so the committed bundle can silently go+ stale.++On top of that, [`apps-sdk/README.md`](../../apps-sdk/README.md) **describes the+orphaned viewer as if it were the live ChatGPT widget** (lines 17 and 59 claim the+bundle is "Bundled into the `ui://widget/studio-viewer.html` skybridge resource+served to ChatGPT" and "Read at runtime by+`api/_mcp3d/studio-viewer-resource.js`"). Both statements are false against the+current tree. For a handoff to OpenAI, a public README that misdescribes our own+integration is unacceptable.++## Your job++Pick ONE of these two resolutions, implement it fully, and make the README true.+Default to Option A unless you find a concrete reason the three.js viewer is+better for our submission (if so, state it in your report and do Option B).++### Option A (default) — Delete the dead path++The live `<model-viewer>` widget in `component.js` already renders GLBs inline in+ChatGPT, is tested, and is what the screenshots were taken against. The three.js+viewer duplicates it with no consumer.++1. Delete `apps-sdk/studio-viewer/` (the whole subdir), `scripts/build-apps-sdk-viewer.mjs`,+ the `build:apps-sdk-viewer` script in `package.json`, and the generated+ `public/apps-sdk/studio-viewer.bundle.js` + `public/apps-sdk/studio-viewer.html`+ (and any `dist/apps-sdk/*` copies). Grep first for every reference and remove+ each one so nothing dangles.+2. Rewrite [`apps-sdk/README.md`](../../apps-sdk/README.md) so the `studio-viewer`+ section is gone and the doc accurately describes the two things that DO ship from+ `apps-sdk/`: the embodiment engine, and a pointer to where the real ChatGPT widget+ lives (`api/_mcp-studio/component.js`). Do not leave a section describing a+ directory you just deleted.+3. Update [`STRUCTURE.md`](../../STRUCTURE.md) if it references `apps-sdk/studio-viewer`.++### Option B — Wire the three.js viewer as the real widget++Only if you determine the three.js viewer is materially better (PBR lighting, contact+shadow, animation mixer) than the CDN `<model-viewer>` and worth being the widget.++1. Create the missing resource module (the correct path, given the free connector+ owns the widget, is under `api/_mcp-studio/`, not `api/_mcp3d/`) that reads the+ built bundle and serves it as the `text/html+skybridge` resource. Register it in+ [`api/_mcp-studio/dispatch.js`](../../api/_mcp-studio/dispatch.js) alongside the+ existing `three-studio-model.html` resource and point the tool+ `openai/outputTemplate` at it.+2. Add `build:apps-sdk-viewer` to the build pipeline (`prebuild` or `build`) so the+ bundle can never go stale, and add it to the esbuild-bundle guard if applicable.+3. Add a test that the resource serves non-empty HTML containing the bundle and+ carries the required `openai/widgetCSP`/`widgetDescription` metadata.+4. Make `apps-sdk/README.md` accurate against the new wiring (correct file path,+ correct `ui://` URI, correct build step).++Whichever option: **the CSP must still allowlist exactly the origins the widget+fetches from** (three.ws, the R2 storage origin, and the CDN if used). Match what+`api/_mcp-studio/component.js` `componentCsp()` already does.++## Constraints++- Follow every rule in `00-START-HERE.md`.+- This is not a crypto surface, so the commit gate does not apply here, but still+ stage explicit paths only.+- No dead references left behind: after your change, `grep -rn "studio-viewer" .`+ (excluding node_modules) must return only intentional, accurate hits.++## Verification++- `grep -rn "apps-sdk/studio-viewer\|studio-viewer-resource\|widget/studio-viewer" . | grep -v node_modules`+ returns only what your chosen option intends (nothing for Option A; the real+ resource wiring for Option B).+- `npm test` is green (run the full suite, do not pipe through `tail`).+- For Option B: build the bundle, load the served resource, and confirm it renders a+ GLB. For Option A: confirm the live `<model-viewer>` widget still renders (exercise+ a `forge_free` call against `/api/mcp-studio` and open the resulting `viewerUrl`).+- `apps-sdk/README.md` reads correctly to someone with zero context and every file+ path and `ui://` URI in it resolves.++## Definition of done++- [ ] One option fully implemented, no half-state.+- [ ] `apps-sdk/README.md` is accurate; `STRUCTURE.md` updated if needed.+- [ ] No dangling references to the deleted/created paths.+- [ ] `npm test` green.+- [ ] `data/changelog.json` entry if this changed anything user-visible (Option B+ would; Option A is an internal cleanup and doc fix, which is `docs`-tagged only+ if the README is user-facing — use judgment, default to a short `docs`/`infra`+ entry).+- [ ] Report states which option you chose and why.diff --git a/docs/openai-pr/02-wellknown-manifest-conflict.md b/docs/openai-pr/02-wellknown-manifest-conflict.mdnew file mode 100644index 000000000..dc335c6a4--- /dev/null+++ b/docs/openai-pr/02-wellknown-manifest-conflict.md@@ -0,0 +1,114 @@+# Task 02 — Reconcile the served `.well-known` manifests with the zero-payment claim (P0)++Read [`00-START-HERE.md`](00-START-HERE.md) first. **This task touches a manifest+that references crypto/x402. The commit gate in `00-START-HERE.md` rule 7 applies:+do the work, but do NOT commit anything that references a non-$THREE crypto project+without explicit owner approval. Flag it in your report instead.**++## The problem (verified, with evidence)++Our OpenAI submission answer sheet+([`prompts/store-submissions/_generated/openai-submission.md`](../../prompts/store-submissions/_generated/openai-submission.md))+asserts the app has a **zero payment surface** and no crypto capability. But a public,+reviewer-discoverable manifest at a well-known path says the opposite.++[`public/.well-known/ai-plugin.json`](../../public/.well-known/ai-plugin.json)+currently reads (verbatim):++```+"description_for_human": "three.ws — 3D avatar/world generation and live crypto intelligence APIs, pay-per-call via x402.",+"description_for_model": "three.ws exposes a 3D model viewer plus a paid pay-per-call API catalog settled via the x402 protocol (HTTP 402, USDC on Solana and Base): ... The machine-readable catalog with prices and schemas is at https://three.ws/.well-known/x402.json ..."+```++And [`public/.well-known/openapi.yaml`](../../public/.well-known/openapi.yaml) (71KB)+describes the general REST platform (Auth/Avatars/Keys/OAuth/MCP) and does **not**+include the 3D Studio endpoints (`/api/3d/studio`, `/api/ar`, `forge_free`).++An OpenAI reviewer hitting `https://three.ws/.well-known/ai-plugin.json` sees a+crypto/payments pitch, directly contradicting the submission. This is the single+most likely thing to sink the review.++## Important scoping decision (this is why the task is delicate)++This manifest is **also a real, live product surface** for the general three.ws+platform and its x402 catalog. It is not junk to be deleted. The `$THREE` /+platform rules in `CLAUDE.md` say the x402 economy and launch directories are real+features, not leaks to be stripped. So the goal is **not** to erase the crypto+platform. The goal is to make sure the OpenAI-facing app is cleanly separable from+it and that the manifest a reviewer reads for the 3D Studio app does not conflate+the two.++Do NOT unilaterally gut the platform manifest. Instead, implement the option below+that keeps both stories true, and surface the decision in your report.++## Your job++Make the OpenAI-app surface and the paid-platform surface cleanly distinct at the+manifest layer. Recommended approach (implement this unless you find it wrong):++1. **Keep the existing platform manifest honest but move it off the bare+ `ai-plugin.json` default if that is what a ChatGPT reviewer keys on.** Confirm+ whether ChatGPT Apps SDK review actually reads `/.well-known/ai-plugin.json`+ (legacy ChatGPT-plugins manifest) at all, or whether the App Directory review is+ driven purely by the MCP connector metadata and the submitted OpenAPI. Document+ what you find with a source. This determines how much the manifest even matters.++2. **The 3D Studio app must have its own, self-describing, payment-free discovery+ artifact.** The custom-GPT OpenAPI already exists at+ `prompts/store-submissions/_generated/openai-actions.yaml` but is not served+ (Task 05 owns serving it). Coordinate with Task 05: the served, discoverable+ schema for the 3D Studio app must describe only `/api/3d/studio` and `/api/ar`,+ with `auth: none`, no x402, no prices, no chain references.++3. **Fix the misleading fields on the platform manifest that a 3D-app reviewer would+ see as conflicting**, without deleting the real x402 catalog:+ - `logo_url` is `favicon.ico` (`ai-plugin.json:14`). The submission cites a+ 512x512 owned-IP icon. At minimum the logo should be a real branded PNG, not the+ favicon.+ - Make it unambiguous, in both the human and model descriptions, which+ capabilities are free and which are paid, so nothing reads as "the 3D app costs+ crypto." The 3D generation lane IS free and keyless. Say so plainly.++4. **Add a test** asserting that whatever manifest describes the 3D Studio app (the+ served Task-05 schema) contains no payment/crypto tokens. Reuse the regex approach+ already in [`tests/mcp-studio.test.js`](../../tests/mcp-studio.test.js) (it asserts+ the MCP connector is crypto-surface-free) and apply it to the served 3D-app schema.++## What NOT to do++- Do not delete `public/.well-known/x402.json`, the x402 catalog, or the paid+ platform's own manifests. Those are real features.+- Do not strip existing other-coin references as if they were secrets (that+ enforcement is retired per `CLAUDE.md`). The commit gate is about not *committing*+ new non-$THREE references, not about scrubbing the working tree.+- Do not silently change what the paid platform advertises to its own users.++## Constraints++- Every rule in `00-START-HERE.md`, especially the commit gate (rule 7) and+ no-push/no-submit (rule 8).+- If your fix requires editing a file whose diff still references x402/USDC/Solana/+ Base/another chain, prepare the edit, run the tests, and STOP before commit with a+ one-line flag to the owner. Do not commit that diff yourself.++## Verification++- `curl -s https://three.ws/.well-known/ai-plugin.json` (or read the file) and+ confirm the 3D-app story is unambiguous and payment-free where it describes the app.+- The served 3D Studio schema (Task 05) passes the no-crypto-tokens test.+- `npm test` green.+- You can articulate, in one paragraph, exactly what an OpenAI reviewer sees at each+ well-known path and why none of it contradicts the submission.++## Definition of done++- [ ] The 3D Studio app has a served, payment-free, self-describing discovery artifact+ (jointly with Task 05).+- [ ] The platform `ai-plugin.json` no longer reads as "the 3D app is a paid crypto+ service"; free vs paid is explicit; logo is a real branded asset.+- [ ] A test asserts the 3D-app schema is crypto/payment-free.+- [ ] `npm test` green.+- [ ] Any commit that would trip the commit gate is prepared but NOT committed;+ flagged to the owner in your report with the exact diff.+- [ ] Report documents whether ChatGPT App Directory review actually reads+ `/.well-known/ai-plugin.json`, with a source.diff --git a/docs/openai-pr/03-forge-free-tier-truth.md b/docs/openai-pr/03-forge-free-tier-truth.mdnew file mode 100644index 000000000..0d178bad1--- /dev/null+++ b/docs/openai-pr/03-forge-free-tier-truth.md@@ -0,0 +1,95 @@+# Task 03 — Make the `forge_free` tier story true everywhere (P1, blocks submit)++Read [`00-START-HERE.md`](00-START-HERE.md) first.++## The problem (verified, with evidence)++The submission answer sheet and the code disagree about what quality tier+`forge_free` returns by default.++**The code** ([`api/_mcp-studio/tools.js`](../../api/_mcp-studio/tools.js),+`handleForgeFree`) defaults to `standard` and degrades `high` to `standard` on+402/timeout. Verbatim comment:++```+// Fast free lane by default. The deployed high-tier free engine (Hunyuan3D+// via HF Spaces) blocks the submit for 50-280s with no poll handle, which no+// ChatGPT tool call survives ... True high-by-default lands when the async+// self-host Hunyuan3D worker deploys (GCP_HUNYUAN3D_URL).+const tier = VALID_TIER.has(args.tier) ? args.tier : 'standard';+```++**The submission doc**+([`prompts/store-submissions/_generated/openai-submission.md`](../../prompts/store-submissions/_generated/openai-submission.md))+is internally inconsistent:+- Line ~31 correctly says the tools "default to the standard tier."+- Line ~146 (the tool table) says `forge_free` "Defaults to the highest quality tier+ (dense geometry + PBR textures)."++A reviewer who reads "highest quality tier" and then gets a standard-tier model has+caught us in a misstatement. Pick the honest resolution and make ALL surfaces agree.++## Your job++Choose based on whether the async high-tier worker can actually ship in this cycle.++### Path A (default, low-risk) — Tell the truth: standard by default++The behavior is fine and defensible (fast, reliable, free). Just make every doc and+metadata surface say "standard by default, higher tiers available on request."++1. Fix `openai-submission.md` line ~146 (and any other spot) so the `forge_free`+ description matches the code: standard default, `tier` param lets the caller ask+ for draft or high, high may take longer or degrade under load.+2. Grep every doc for the "highest quality"/"high tier by default" claim and fix each:+ [`docs/mcp-studio.md`](../../docs/mcp-studio.md),+ [`docs/mcp-3d-studio.md`](../../docs/mcp-3d-studio.md), the tool descriptions the+ MCP server itself returns in `tools/list` (check `tools.js` tool metadata strings),+ and `apps-sdk/README.md`.+3. Make sure the tool's own `description` string returned to ChatGPT is accurate, so+ the model never promises "highest quality" to the user.++### Path B — Make high-by-default real++Only if the async self-host Hunyuan3D worker (`GCP_HUNYUAN3D_URL`) can be deployed+and proven within this cycle. This is the "never downgrade quality" ideal, and GCP+GPU spend is pre-approved (`CLAUDE.md` standing resource approvals).++1. Deploy the async Hunyuan3D worker with a real poll handle (submit returns a job id+ immediately, poll returns progress, never blocks 50-280s). Its own+ `workers/<name>/cloudbuild.yaml`, service accounts pinned per `CLAUDE.md`.+2. Wire `handleForgeFree` to use it for the high tier with a real submit/poll flow+ that a ChatGPT tool call survives, and flip the default to `high`.+3. Prove it: a real `forge_free` call with no tier returns a high-tier GLB, end to+ end, no timeout, no degrade. Capture the evidence JSON.+4. THEN the "highest quality by default" doc language becomes true and can stay.++Deploying a worker is not a reason to stop (`CLAUDE.md` self-unblock). But if the+worker cannot be proven this cycle, do Path A. Do not leave a half-deployed worker+and a doc claiming it works.++## Constraints++- Every rule in `00-START-HERE.md`.+- No mock/fake generation. The evidence must be a real GLB from the real lane.+- This is not a crypto surface; commit gate does not apply.++## Verification++- `grep -rni "highest quality\|high.*by default\|high tier" prompts/store-submissions docs apps-sdk/README.md api/_mcp-studio`+ returns only statements that match the shipped behavior.+- A real `forge_free` call against `/api/mcp-studio` returns a tier consistent with+ every doc. Save the response JSON as evidence.+- `npm test` green (run `tests/mcp-forge-free.test.js` and `tests/mcp-studio.test.js`).++## Definition of done++- [ ] Every doc, the submission sheet, and the tool's own `description` agree with the+ code on the default tier.+- [ ] If Path B: worker deployed and proven with real evidence; default is genuinely+ high.+- [ ] If Path A: no surface claims "highest quality by default" anymore.+- [ ] `npm test` green.+- [ ] `data/changelog.json` entry only if user-visible behavior changed (Path B yes;+ Path A is a docs/accuracy fix, `docs` tag).+- [ ] Report states the path taken and includes the real `forge_free` evidence.diff --git a/docs/openai-pr/04-openai-surface-test-coverage.md b/docs/openai-pr/04-openai-surface-test-coverage.mdnew file mode 100644index 000000000..88e17c0e4--- /dev/null+++ b/docs/openai-pr/04-openai-surface-test-coverage.md@@ -0,0 +1,79 @@+# Task 04 — Close the test gaps on the ChatGPT-facing surface (P1)++Read [`00-START-HERE.md`](00-START-HERE.md) first.++## The problem++The core logic is well tested (`tests/mcp-studio.test.js`, `tests/ar-export.test.js`,+`tests/embodiment-*.test.js`), but three surfaces a reviewer will actually hit have+**no test on the surface itself**, only on the pure functions beneath them. For a+submission to OpenAI, the HTTP-visible behavior must be pinned so a refactor cannot+silently break what the reviewer sees.++### Gap 1 — `api/ar.js` HTTP handler is untested++`api/ar.js` is the "View in your space" / "Bring it to life" endpoint every generation+links to. Only the pure lib `api/_lib/ar-launch.js` is tested (`tests/ar-export.test.js`).+The handler's own behavior is unverified:+- User-agent branching (Android → Scene Viewer 302 intent; iOS/desktop → HTML launch+ page; `kind=avatar` → IRL handoff).+- The designed error page for a bad/missing `src`.+- `assertArAssetUrl` rejection (non-https, non-`.glb/.gltf`) surfacing as a proper+ error response, not a crash.+- `Vary: user-agent` and cache headers.++Write `tests/api/ar-endpoint.test.js` that invokes the handler with mocked requests+for each UA class and asserts status, `Location`/redirect, headers, and that the HTML+launch page contains the model URL and the AR launch elements. Follow the request/+response mocking pattern used by the other `tests/api/*.test.js` files in this repo.++### Gap 2 — `pages/embodiment/embed.html` wiring is untested++The persona widget iframes this page. Its param parsing (`persona/glb/name/state/+text/emotion/...`), the `GET /api/mcp3d/persona?id=` resolve, and the fallback when a+persona cannot be resolved are unverified. Add a test (jsdom or Playwright, match what+the repo already uses for page-level tests) that:+- Loads the page with `?glb=&name=` and asserts the stage mounts and the name renders.+- Loads with `?persona=<id>` against a mocked persona endpoint and asserts it resolves+ and renders.+- Loads with an unresolvable persona and asserts the designed error/empty state, not a+ blank void or console error.++### Gap 3 — No contract test binding `api/3d/studio.js` to `openai-actions.yaml`++The custom-GPT Actions response shape (`{status, glbUrl, viewerUrl, arUrl, format}` or+`{status:'pending', job, poll}`) must match the served OpenAPI schema (Task 05 serves+it). Add a contract test that loads the OpenAPI schema and validates a real+`api/3d/studio.js` response object against it (the response-shaper is pure and+exported per the file). Use an existing JSON-schema/OpenAPI validator already in+`package.json` if present; do not add a heavy new dependency for this.++## Constraints++- Every rule in `00-START-HERE.md`. No mocked *generation* results that pretend to be+ real GLBs where the test claims to exercise the real lane; where you must stub the+ forge call, stub at the network boundary and label it clearly, and keep at least one+ path that asserts the real shape.+- Match the existing test style, imports, and helpers. Read a neighboring+ `tests/api/*.test.js` before writing.+- Not a crypto surface; commit gate does not apply.++## Verification++- `npm test` green, with your three new test files running and passing.+- Deliberately break each surface locally (e.g. change a header in `api/ar.js`) and+ confirm the new test catches it, then revert. Report that you did this.++## Definition of done++- [ ] `tests/api/ar-endpoint.test.js` covers all UA classes, the error page, and+ headers.+- [ ] A page-level test covers `pages/embodiment/embed.html` param parsing, persona+ resolve, and the failure state.+- [ ] A contract test binds `api/3d/studio.js` output to the served OpenAPI (coordinate+ with Task 05 for the schema location).+- [ ] `npm test` green.+- [ ] Each new test demonstrably fails when its target is broken (verified, then+ reverted).+- [ ] No changelog entry needed (tests are internal) unless you also fixed a bug found+ while writing them, in which case that fix gets an entry.diff --git a/docs/openai-pr/05-custom-gpt-openapi-serving.md b/docs/openai-pr/05-custom-gpt-openapi-serving.mdnew file mode 100644index 000000000..8750dfc3a--- /dev/null+++ b/docs/openai-pr/05-custom-gpt-openapi-serving.md@@ -0,0 +1,82 @@+# Task 05 — Serve the custom-GPT OpenAPI and align legal URLs (P1)++Read [`00-START-HERE.md`](00-START-HERE.md) first. Coordinate with Task 02 (the+served schema must be payment-free) and Task 04 (a contract test binds to it).++## The problem (verified, with evidence)++The custom-GPT Actions schema+([`prompts/store-submissions/_generated/openai-actions.yaml`](../../prompts/store-submissions/_generated/openai-actions.yaml),+OpenAPI 3.1.0, `title: three.ws 3D Studio`) exists but is **not served anywhere+machine-discoverable**. It lives only under `prompts/store-submissions/_generated/`.++Meanwhile the served `public/.well-known/openapi.yaml` describes the general REST+platform and does NOT include `/api/3d/studio`, `/api/ar`, or `forge_free`. So the+machine-readable schema an OpenAI reviewer or the GPT Actions runtime can fetch does+not describe the 3D Studio GPT at all.++Additionally, the legal URLs inside `openai-actions.yaml` use `.html` suffixes+(`https://three.ws/legal/privacy.html`, `.../legal/tos.html`) while the submission doc+verifies the live URLs without `.html`. Both forms currently resolve (verified:+`vercel.json` rewrites `/legal/privacy/?` to `/legal/privacy.html`, and the `.html`+file is served directly), but the inconsistency is sloppy for a submission and should+be normalized to one canonical form.++## Your job++1. **Serve the 3D Studio OpenAPI at a stable, discoverable path.** Put the served+ copy where the GPT Action and a reviewer can fetch it over https, e.g.+ `public/.well-known/3d-studio-openapi.yaml` (or a `/api/3d/openapi.yaml` route).+ Pick the path that fits how this repo already serves the other `.well-known`+ schemas and wire it in `vercel.json` if a route is needed. Do NOT overwrite the+ platform's existing `public/.well-known/openapi.yaml`.++2. **Make the served 3D Studio schema self-contained and payment-free.** It must+ describe only `/api/3d/studio` (POST submit, GET poll) and `/api/ar`, with+ `auth: none`, no x402, no prices, no chain references. This is the artifact Task 02+ points at as the app's clean discovery surface.++3. **Single source of truth.** The served schema and+ `prompts/store-submissions/_generated/openai-actions.yaml` must not drift. Either+ generate the `_generated` copy from the served one (preferred, matches the+ `_generated/` build-script convention already in that dir) or make one a copy of+ the other with a script/check. Do not hand-maintain two copies.++4. **Normalize the legal URLs.** Pick the canonical form the rest of the submission+ uses (the no-`.html` form, e.g. `https://three.ws/legal/privacy`,+ `https://three.ws/legal/tos`) and use it consistently in the served schema, the+ `_generated` copy, and `openai-submission.md`. Confirm every legal URL you cite+ returns 200 (both `privacy` and `tos` at minimum).++5. **Lint it.** `npx @redocly/cli lint <served-schema>` must pass clean (the TRACKER+ claims the `_generated` copy already lints clean; keep it that way for the served+ one).++## Constraints++- Every rule in `00-START-HERE.md`. The served schema must pass Task 02's+ no-crypto-tokens test, so keep it strictly the two free endpoints.+- Not a crypto surface if you keep it clean; just do not paste x402 content into it.+- If you add a `vercel.json` route, remember `vercel.json` is a LIVE config consumed+ by the server (`CLAUDE.md`); edit it carefully and keep the route table valid.++## Verification++- The served schema is fetchable (`curl` the local dev server or read the built+ `dist/` copy) and validates with `@redocly/cli lint`.+- Every legal URL in the schema returns 200 (test both privacy and tos).+- Task 04's contract test validates a real `api/3d/studio.js` response against it.+- `npm run build:pages` / the normal build still succeeds; `npm test` green.++## Definition of done++- [ ] The 3D Studio OpenAPI is served at a stable https path, describing only the two+ free endpoints, `auth: none`, no payment/crypto content.+- [ ] The served copy and the `_generated` copy are kept in sync by a script or check,+ not by hand.+- [ ] All legal URLs normalized to one canonical form and verified 200.+- [ ] Schema lints clean.+- [ ] `npm test` green; build succeeds.+- [ ] `data/changelog.json` entry (`docs` or `infra` tag) since a new public schema+ path is developer-visible; add the route to `data/pages.json` only if it is a+ human page (a raw schema usually is not).diff --git a/docs/openai-pr/06-docs-accuracy-reconciliation.md b/docs/openai-pr/06-docs-accuracy-reconciliation.mdnew file mode 100644index 000000000..fc34dcc92--- /dev/null+++ b/docs/openai-pr/06-docs-accuracy-reconciliation.md@@ -0,0 +1,74 @@+# Task 06 — Fix doc accuracy and reconcile the tool-count story (P1)++Read [`00-START-HERE.md`](00-START-HERE.md) first. This task cleans up the+documentation drift the audit found, EXCEPT the two docs owned by other tasks+(`apps-sdk/README.md` studio-viewer section is Task 01; the `forge_free` tier claim is+Task 03). Do not fight those tasks for those specific edits; coordinate.++## The problems (verified)++1. **Tool-count inconsistency.** The free MCP connector exposes **9** tools: 6+ generation (`forge_free`, `text_to_avatar`, `mesh_forge`, `rig_mesh`,+ `forge_avatar`, `refine_model`) + 3 persona (`create_agent_persona`,+ `get_agent_persona`, `persona_say`). But docs tell different stories:+ - `openai-submission.md` says "Nine tools."+ - `docs/mcp-studio.md` headline tool table lists six, with the persona tools in a+ later "Embodiment" section.+ - Code comments drift: `tools.js:1-8` says "Six generation tools (five generators ++ refine_model)"; `tests/mcp-studio.test.js` comment says "five allowed generation+ tools" while the asserted array has six.+ Reconcile these so every count is consistent and correct. The authoritative number+ is whatever the running server returns from `tools/list` — verify it, then make all+ docs and comments match.++2. **model-viewer version is not single-sourced.** Three surfaces load different+ `model-viewer` versions: `api/ar.js` launch page (3.5.0 via jsdelivr), the MCP+ widget in `component.js` (3.5.0), and `/viewer.html` (4.0.0). Pick one version,+ pin it in one place they all reference (a constant/shared import), or at minimum+ document the intended version per surface and why they differ. A reviewer opening+ two of our surfaces should not get two different renderer versions with no reason.++3. **`docs/mcp-studio.md` cross-reference check.** It points the custom-GPT contract to+ `./api-reference.md`. Verify that file exists and actually documents `/api/3d/studio`.+ If not, fix the pointer to the authoritative schema (the served OpenAPI from Task 05)+ or add the missing section. No dead doc links.++4. **General accuracy sweep of the ChatGPT-surface docs.** Read+ `docs/mcp-studio.md`, `docs/chatgpt-ar.md`, `docs/mcp-3d-studio.md`, and+ `docs/ar.md` end to end against the code. Every `ui://` URI, file path, endpoint,+ env var, and example must resolve and be correct. Fix any that are stale. The audit+ already confirmed `docs/chatgpt-ar.md` correctly points at `component.js` (good) and+ that `apps-sdk/README.md` is the worst offender (Task 01 owns that one).++## Constraints++- Every rule in `00-START-HERE.md`. Docs are real implementations: every code sample+ must run, every link must resolve to a live path (`CLAUDE.md` documentation rules).+- Not a crypto surface; commit gate does not apply. Do not introduce any non-$THREE+ coin reference into the docs.+- Coordinate: leave the `apps-sdk/README.md` studio-viewer section to Task 01 and the+ `forge_free` tier language to Task 03. If those tasks have not landed yet, note the+ dependency rather than duplicating their edits.++## Verification++- Start from the live `tools/list` output (call `/api/mcp-studio` with an+ `initialize` + `tools/list` JSON-RPC batch) and confirm the count and names, then+ grep every doc/comment for tool counts and confirm they match.+- `grep -rn "model-viewer@" api public docs` shows a single intended version story.+- Every internal doc link resolves (spot-check with a link checker or by opening each+ referenced path).+- `npm test` green (docs changes should not break tests, but run it).++## Definition of done++- [ ] Tool count is consistent and correct (9) across `openai-submission.md`,+ `docs/mcp-studio.md`, code comments, and test comments.+- [ ] model-viewer version is single-sourced or its per-surface difference is+ documented and justified.+- [ ] `docs/mcp-studio.md` cross-references resolve; no dead links in any+ ChatGPT-surface doc.+- [ ] All ChatGPT-surface docs are accurate against the code (paths, URIs, endpoints,+ env vars, examples).+- [ ] `data/changelog.json` entry with the `docs` tag.+- [ ] `npm test` green.diff --git a/docs/openai-pr/07-final-verification-and-submit.md b/docs/openai-pr/07-final-verification-and-submit.mdnew file mode 100644index 000000000..6ab364213--- /dev/null+++ b/docs/openai-pr/07-final-verification-and-submit.md@@ -0,0 +1,83 @@+# Task 07 — Final live verification and submit checklist (P2, runs last)++Read [`00-START-HERE.md`](00-START-HERE.md) first. **Run this only after tasks+01-06 are merged.** This is the go/no-go gate before the app is submitted to OpenAI.++## Purpose++The submission answer sheet+([`prompts/store-submissions/_generated/openai-submission.md`](../../prompts/store-submissions/_generated/openai-submission.md))+asserts many "verified live" facts, dated 2026-07-14. Deployments move. Before we put+this in front of OpenAI, re-verify every claim against the *currently deployed*+production, close the loose `[HUMAN: ...]` items where you can, and produce a clean+go/no-go report. Do not submit; prepare so the human's final submit is one action.++## The checklist (run every item, record the result)++### A. The MCP connector is live, keyless, and crypto-free+- [ ] `POST https://three.ws/api/mcp-studio` with an `initialize` request returns the+ server info (`three-ws-3d-studio-free`, protocol `2025-06-18`) with no auth.+- [ ] `tools/list` returns exactly the expected 9 tools (matches Task 06's reconciled+ count) with correct `openai/*` annotations and `outputTemplate` linkage.+- [ ] `resources/list` returns the widget skybridge resources with their+ `openai/widgetCSP`, `widgetDescription`, `widgetDomain` metadata.+- [ ] A real `forge_free` call returns a real GLB with `glbUrl`, `viewerUrl`, `arUrl`,+ and NO internal ids (`job_id`, `creation_id`, `backend`) and NO crypto/payment+ fields. Save the response as fresh evidence (overwrite the stale+ `_generated/*forge_free.json` evidence if the shape changed).+- [ ] The connector response body contains no x402/payment/crypto tokens (the+ `tests/mcp-studio.test.js` regex should still pass against live output).++### B. Every reviewer-discoverable manifest is consistent (depends on Task 02, 05)+- [ ] `https://three.ws/.well-known/ai-plugin.json` does not present the 3D app as a+ paid crypto service; free vs paid is explicit; logo is a real branded asset.+- [ ] The served 3D Studio OpenAPI (Task 05) is fetchable, lints clean, describes only+ the free endpoints, and every legal URL in it returns 200.+- [ ] `https://three.ws/legal/privacy` and `https://three.ws/legal/tos` return 200 in+ the exact form the submission and schema cite.++### C. The widget and AR surfaces render (depends on Task 01, 04)+- [ ] The inline widget renders a real GLB in a `window.openai`-less browser via its+ standalone/`viewerUrl` path (loading, ready, empty, error states all reachable).+- [ ] `GET /api/ar?src=<glb>&title=<t>` returns the correct surface per device class+ (Scene Viewer intent on Android UA, launch page on iOS/desktop UA); the error+ page renders for a bad `src`.+- [ ] `kind=avatar` returns the IRL "Bring it to life" handoff.++### D. The custom GPT Actions surface works (depends on Task 05)+- [ ] `POST https://three.ws/api/3d/studio` submits and returns the documented shape;+ `GET ?job=&title=` polls to completion with a real GLB.+- [ ] The response validates against the served OpenAPI (Task 04's contract test).++### E. Submission kit is current+- [ ] `openai-submission.md` facts all re-verified against the checks above; fix any+ that drifted. Update the date.+- [ ] Screenshots in `prompts/store-submissions/_generated/openai-screenshots/` show+ the CURRENT shipped widget and resolve the `[HUMAN verify]` dimension flag+ (confirm they meet OpenAI's required screenshot dimensions; re-shoot against the+ live widget if stale). If Task 01 chose to delete the orphaned three.js viewer,+ make sure no screenshot or evidence file still points at+ `https://three.ws/apps-sdk/studio-viewer.html` as "the widget."+- [ ] `TRACKER.md` `[HUMAN: ...]` items: resolve every one you technically can (e.g.+ the duplicate-draft-GPT deletion if you have access); leave only items that+ genuinely require the human's partner-portal login, and list them explicitly.+- [ ] `npm test` green on the merged tree.++## Constraints++- Every rule in `00-START-HERE.md`. Especially rule 8: **do NOT submit to OpenAI, push,+ or deploy.** Prepare everything; the human does the final submit in the partner+ portal.+- If any check fails, do not paper over it. Root-cause it, fix it (or route it back to+ the owning task 01-06), and re-run. A red check is a blocker, not a footnote.+- Do not commit anything that trips the commit gate (rule 7); flag it.++## Definition of done++- [ ] Every checklist item has a recorded PASS with evidence, or a FAIL with the fix+ applied and re-verified to PASS.+- [ ] `openai-submission.md` and `TRACKER.md` reflect the current, verified reality.+- [ ] The only open items are `[HUMAN: ...]` steps that truly require the owner+ (partner-portal submit, portal-side actions), listed explicitly in your report.+- [ ] Final report is a clean go/no-go: either "ready to submit, remaining human steps+ are X, Y" or "not ready, blockers are A, B and here is the state of each."diff --git a/docs/radar.md b/docs/radar.mdnew file mode 100644index 000000000..5da4cffa4--- /dev/null+++ b/docs/radar.md@@ -0,0 +1,86 @@+# Coin Radar: every pump.fun launch, scored in its first 90 seconds++Coin Radar is a live screener for pump.fun. Every new coin appears here with the Coin Intelligence Engine's read of its first roughly 90 seconds of trading: bundle versus organic demand, wallet concentration, dev behaviour, fresh-wallet swarms, and risk flags, plus a 0 to 100 quality score. It answers one question fast, before the candle prints: is this launch real, or is it a coordinated exit dressed up as a crowd?++Page: [/radar](https://three.ws/radar)++API: `/api/pump/coin-intel` (feed, market pulse, per-coin detail). The detail drawer also reads `/api/oracle/coin` for conviction context.++> Naming trap for API users: `/radar` is served by `api/pump/coin-intel.js`, and `/coin-intel` is served by `api/pump/intel.js`. The names look swapped. They are two distinct read models over the same engine.++## Why it exists++The most dangerous moment on pump.fun is the first minute, when the tape is thin and a bundle of bot wallets can manufacture the look of organic demand. A human cannot audit funder graphs and timing entropy in real time. The Coin Intelligence Engine does, on the live firehose, and Radar is its screener: a scannable board that turns raw first-90-seconds behaviour into a quality score and a short list of named risks, so you can filter out the coordinated launches and focus on the ones with a real crowd. It is the top of the [trading surfaces](./trading-surfaces.md) funnel: Radar surfaces a launch worth a look, you watch it, and if it earns conviction you open it in [Mission Control](./terminal.md) to act.++## How it works++The page mounts `mountRadar` from `src/radar.js` and polls `/api/pump/coin-intel` every 12 seconds (paused when the tab is hidden), rendering a market-pulse strip, a filterable grid or list of coins, and a detail drawer. It uses no streaming; it is a REST poller.++The scores are not computed by the API, which is a pure read model over the Postgres table `pump_coin_intel` (plus `pump_coin_wallets` and `pump_coin_outcomes`). They are produced upstream by the engine in `workers/agent-sniper/intel/`. A watcher holds its own PumpPortal websocket, subscribes to each new mint's trades, and observes a **90-second window** (`windowMs = 90_000`) with the creator's launch buy seeded as trade zero. When the window closes, a deterministic, pure signal function scores it and enrichment (classification, funder-graph clustering, smart-money cross-reference) is folded in before the record is persisted. A serverless cron twin shares the exact same finalize path, so records are byte-identical however they were produced.++The core signal math, measured from the first observed trade (burst window 3s, snipe window 5s):++- **Bundle score (0 to 1).** Needs at least 4 buys and 4 in the 3-second burst; blends burst density and clustering (the share of near-identical buy sizes, since bots fund identical amounts), scaled by a wallet multiplier.+- **Organic score (0 to 1).** A weighted blend of buyer diversity, timing entropy, the inverse of bundle, the inverse of snipe ratio, and the inverse of top-1 concentration, then discounted if the dev sold or fresh wallets dominate, and adjusted by funder connectivity.+- **Snipe ratio.** Share of buy volume landing within the first 5 seconds.+- **Concentration.** Per-wallet net buy share; reported as top-1, top-5, and top-10.+- **Dev behaviour.** `dev_sold` is set when the creator had any sell; `dev_buy_sol` comes from the launch transaction.+- **Fresh wallets and clusters.** Fresh-wallet ratio is the share of buyers with at most one prior transaction (null below 3 known); connectivity is the largest common-funder cluster over known funders.++Those roll into a **quality score (0 to 100)**: start from organic times 100, subtract for bundle, top-1 concentration, a dev sell, and fresh-wallet ratio, add a small bonus for unique buyers, then add smart-money bonuses (up to +8 for proven wallets in), and clamp.++**Risk flags** are named, not numeric: `bundle_launch` (bundle 0.6+), `dev_dumped`, `single_whale` (top-1 0.5+), `low_diversity` (fewer than 5 buyers), `fresh_wallet_swarm` (fresh ratio 0.7+), `sell_pressure`, `sniped` (snipe 0.85+ with fewer than 8 buyers), and `coordinated_cluster` (connectivity 0.4+).++The UI colors quality as Healthy at 70 and up, Mixed from 40 to 69, and High risk below 40; a null score renders "Unscored," never a fake zero.++## Walkthrough++1. Open [/radar](https://three.ws/radar). The pulse strip aggregates the whole tape (24h and 1h observed counts, the healthy/mixed/risky split, smart-money-touched and flagged shares).+2. Use the toolbar to filter by narrative category, drag the minimum-quality slider, toggle smart-money-only or news, and hide flagged coins (a client-side drop of danger-flagged launches). Sort by newest, quality, smart money, buyers, or volume. All filters serialize to the URL for shareable views.+3. Press `/` to focus search and type a name, ticker, or mint. Press `g` or `l` to switch grid and list, `r` to refresh.+4. Click any coin for the drawer: the full signal grid, the top-50 wallet ledger, the smart-money notable roster, the outcome (if labeled), and an asynchronously injected Oracle conviction section.+5. On a coin worth tracking, use Watch to add it to your [Watchlist](https://three.ws/watchlist), then open it in [Mission Control](./terminal.md) to trade.++## Examples++The feed is public and IP rate-limited.++```bash+# The radar feed: newest launches with the engine's first-90s read+curl 'https://three.ws/api/pump/coin-intel?limit=60&network=mainnet&sort=new'++# The market-pulse aggregate (independent of your filters)+curl 'https://three.ws/api/pump/coin-intel?stats=1&network=mainnet'++# One coin's full intel plus its top-50 wallet ledger+curl 'https://three.ws/api/pump/coin-intel?mint=<MINT>&wallets=1&network=mainnet'+```++```javascript+// Pull the feed and keep only clean, smart-money-touched launches+const { coins } = await fetch(+ 'https://three.ws/api/pump/coin-intel?limit=60&network=mainnet&smart_money=1'+).then((r) => r.json());++const clean = coins.filter(+ (c) => (c.quality_score ?? 0) >= 70 && !(c.risk_flags || []).includes('bundle_launch')+);+console.log(clean.map((c) => `${c.symbol} q${c.quality_score}`));+```++## States and limits++- **Auth.** None. The feed, pulse, and detail reads are fully public over CORS and IP rate-limited (`mcpIp`).+- **No streaming.** Radar polls every 12 seconds and shows a "Live, updated Ns ago" indicator; polling pauses when the tab is hidden and refetches on return.+- **Warm-up.** A coin has no score until its 90-second observation window closes and finalize runs. Coins older than the engine's deploy, or mid-observation, return 404 on the detail read and render a "Not observed" state.+- **Honest nulls.** A signal that was not measured is null and renders "not measured," never a fabricated 0. The market-pulse path degrades to zeros and empties gracefully if the engine tables are cold.+- **Empty and error states.** The board has designed loading (skeleton grid), empty ("Radar is clear, waiting for the next launch"), no-match (with a reset), and error (with a retry) states. On a silent poll failure it keeps the prior coins and only blanks to an error when nothing is cached.++## Related++- [The trading surfaces: Radar, Mission Control, Live Trade Feed, Watchlist, Coin Intelligence](./trading-surfaces.md)+- [Oracle: the conviction engine](./oracle.md) fuses this intel into a single conviction score+- [Smart Money Radar](./smart-money.md) is the pedigree layer Radar surfaces inline+- [Mission Control](./terminal.md) is where a Radar find gets traded+- [Coin pages](./coin-pages.md) cross-link the per-mint intel and conviction views+- Pages: [/radar](https://three.ws/radar) · [/coin-intel](https://three.ws/coin-intel) · [/watchlist](https://three.ws/watchlist)diff --git a/docs/restyle.md b/docs/restyle.mdnew file mode 100644index 000000000..b3bc6558c--- /dev/null+++ b/docs/restyle.md@@ -0,0 +1,93 @@+# Restyle Studio: re-skin any GLB without regenerating its mesh++Restyle Studio changes what a 3D model is made of, not what it is. Load any GLB, and you can flip it to chrome, gold, glass, or wood with one click, describe a look in plain language and let an AI propose the physically based material for it, fan a preset out into a strip of reproducible colorway variants, or fine-tune metalness, roughness, color, and emissive live. The mesh, its geometry, and its UVs are never touched. Only the material factors change, so a restyle is fast, cheap, and never distorts the model. Every AI restyle and every saved checkpoint mints a real, validated, durably stored GLB in a parent-to-child version lineage, so nothing you make here is a throwaway browser preview.++Page: [/restyle](https://three.ws/restyle) · API: `/api/material-studio`++## Why it exists++Generating a 3D model is the expensive step. Once you have a good mesh, wanting it in a different finish should not mean paying to regenerate the whole thing and risking a worse shape. Restyle Studio separates the two. Skin is cheap and reversible; geometry is precious and left alone. That makes iterating on look-and-feel a tight loop: try chrome, try worn copper, try glass, save the two you like as durable versions, export the winner. It also gives the rest of the platform one shared material vocabulary. Restyle Studio consumes the same PBR preset library (`@three-ws/viewer-presets`) and the same GLB optimize-and-validate path that [Avatar Studio](./avatar-studio.md) uses, instead of inventing a parallel one.++## How it works++The page is a Three.js scene with `RoomEnvironment` image-based lighting, so metals and glass reflect something real rather than reading as flat grey. Four capabilities sit on top of the loaded model:++- **Preset library (14 looks).** One click applies a physically based material across every standard material in the model. The presets are `chrome`, `gold`, `copper`, `brushedSteel`, `gunmetal`, `matte` (plastic), `glossy` (plastic), `rubber`, `ceramic`, `glass`, `wood`, `stone`, `neon`, and `holographic`. Each carries tuned color, metalness, roughness, environment-map intensity, and (for neon and holographic) emissive values.+- **AI restyle from an instruction.** Type something like "make it chrome", "worn copper", or "cyberpunk neon" and the server asks IBM Granite (watsonx.ai) to propose a glTF 2.0 PBR material (base color, metallic, roughness, emissive factors). The factors come back, get applied to the in-browser preview instantly, and are also applied server-side to the source GLB and re-exported as a durable, validated model. If you leave the "also generate a texture" option on, the studio additionally asks the platform text-to-image lane (`/api/v1/ai/image`, the same NVIDIA NIM FLUX / Vertex stack Forge uses) for a seamless tileable material swatch and applies it as the base-color map. The flat PBR restyle always lands even if texture generation is skipped or hits its free daily quota.+- **Seeded colorway variants.** Pick a base preset, a seed, and a count (1 to 12), and the studio fans it into a strip of variants using a `mulberry32` seeded PRNG. The same base plus the same seed always produces the byte-identical set, so a colorway you liked is reproducible forever. Clicking a swatch applies it live. "Save all as versions" turns those variants into real, separately addressable GLBs, each branching off the same parent version.+- **Live manual controls.** Sliders for metalness, roughness, and emissive intensity, plus base-color and emissive-color pickers, set the same property across every standard material at once. A Reset button restores every material to its captured original values.++### Version lineage++Two kinds of history live side by side. The in-browser breadcrumb records every preset and slider tweak and never leaves the tab. The durable version lineage is the real one: every AI restyle and every "Save version" checkpoint uploads a `gltf-validator`-checked GLB and records it with the same immutable parent-to-child shape the `refine_model` MCP tool uses. Clicking any version in the Versions strip reloads that exact GLB. A restyle or a variant set can extend one thread or branch off an earlier version, so the lineage is a tree, not just a line.++### One core, two transports++The endpoint is free and hosted (no wallet, no account, no x402), bounded by server-side rate limits rather than payment, the same doctrine `forge_free` and the free 3D Studio use. The `restyle_material` MCP tool is a thin paid stdio client (0.05 USDC) over this same endpoint, so the free web page and the paid agent tool can never drift. One implementation, two transports.++## Walkthrough++1. Open [/restyle](https://three.ws/restyle). The platform's default humanoid loads so the stage is never empty. To bring your own model, drag a `.glb`/`.gltf` onto the stage, use the file picker, or paste a public model URL into "Load URL". You can also deep-link a model with `?url=https://.../model.glb`.+2. Click a preset (start with **Chrome** or **Gold**) and watch the whole model re-skin against real reflections. Orbit to inspect it.+3. Type an instruction in the AI restyle box, for example `brushed titanium with a faint blue sheen`, and press the button. Granite proposes the material, it applies instantly, and a new durable version is minted.+4. Nudge the metalness and roughness sliders, or change the base color, to fine-tune.+5. Set a seed and a count, generate variants, and click through the swatch strip. Hit "Save all as versions" to keep the whole set as durable GLBs.+6. Click "Save version" to checkpoint the current look, or "Export" to download `restyled.glb`. The export runs through the shared optimize-and-validate path, so the note tells you the final size and whether it is valid glTF.+7. Revisit any earlier state by clicking its entry in the Versions strip.++## Examples++The API is public and rate-limited. `glb_url` must be a publicly resolvable https URL (the studio checkpoints local file drops to a URL first, behind the scenes).++```bash+# Discovery document: actions, preset names, and the lineage contract.+curl 'https://three.ws/api/material-studio'++# AI restyle: instruction in, applied + re-exported GLB out.+curl -X POST 'https://three.ws/api/material-studio?action=restyle' \+ -H 'content-type: application/json' \+ -d '{"glb_url":"https://three.ws/avatars/realistic-female.glb","instruction":"polished chrome"}'++# Seeded colorway variants of a preset (reproducible for a given seed).+curl -X POST 'https://three.ws/api/material-studio?action=variants' \+ -H 'content-type: application/json' \+ -d '{"glb_url":"https://three.ws/avatars/realistic-female.glb","preset":"gold","seed":7,"count":6}'+```++A restyle response carries the applied factors plus the version lineage:++```json+{+ "ok": true,+ "glbUrl": "https://.../material-studio/.../restyled.glb",+ "sourceGlbUrl": "https://three.ws/avatars/realistic-female.glb",+ "instruction": "polished chrome",+ "factors": {+ "baseColorFactor": [0.79, 0.81, 0.83, 1],+ "metallicFactor": 1,+ "roughnessFactor": 0.05,+ "emissiveFactor": [0, 0, 0]+ },+ "materialsEdited": 4,+ "lineage": [ { "index": 0, "glbUrl": "…" }, { "index": 1, "glbUrl": "…" } ],+ "activeIndex": 1+}+```++Pass the returned `lineage` array back as `parent_lineage` on the next call to extend the same thread, and add `parent_index` to branch off an earlier version instead of the latest.++## States & limits++- **Only standard PBR materials are edited.** A material must expose metalness, roughness, and a color to be restyled. Non-PBR or custom-shader materials are left as they are.+- **AI restyle and Save need a public model URL.** A locally dropped file is checkpointed to a URL in the background first; until that resolves, AI restyle and Save show an honest note rather than failing silently. Loading a public `.glb` via "Load URL" skips the wait.+- **Texture generation is best-effort.** Past the free daily quota the image lane returns a payment-required signal; the studio surfaces that as a note and keeps the flat PBR restyle it already applied. It never fakes a texture.+- **Bounded, not gated.** The web endpoint is free but rate-limited per IP (separate limits for uploads and restyle/variants). Instructions are capped at 300 characters and uploads at 64 MB.+- **Reset vs. revert.** Reset restores the original material values in the current tab. Reverting to an earlier durable GLB is a separate action: click its entry in the Versions strip.+- **No mesh changes.** Geometry, UVs, and rigging are never modified, so a restyle can never break animation or distort a shape.++## Related++- [Avatar Studio](./avatar-studio.md): shares the same GLB optimize-and-validate path and material vocabulary.+- [Scene Composer](./compose.md) and [Scene Studio](./scene-studio.md): arrange and edit restyled models in a full scene.+- [MCP tools reference](./mcp-tools.md): the paid `restyle_material` agent twin of this endpoint.+- [/forge](https://three.ws/forge): generate the models you bring here.diff --git a/docs/scene-studio.md b/docs/scene-studio.mdnew file mode 100644index 000000000..a8ad7d6ce--- /dev/null+++ b/docs/scene-studio.md@@ -0,0 +1,61 @@+# Scene Studio: the full three.js editor, in your browser++Scene Studio is the complete [mrdoob/three.js](https://github.com/mrdoob/three.js) editor (release r184, MIT-licensed), vendored into three.ws and wrapped in the site chrome. It is the heavyweight scene tool: import GLBs and other assets, move and rotate and scale them with transform gizmos, edit materials and lights and cameras through a full property sidebar, script objects with live JavaScript, play the scene, and export it. Where [Scene Composer](./compose.md) is a focused avatar-plus-props arranger and [Animation Studio](./animation-studio.md) is a posing and keyframing tool, Scene Studio is the general-purpose 3D authoring surface underneath them.++Page: [/scene](https://three.ws/scene)++## Why it exists++Most of the three.ws studios are purpose-built: one does avatars, one does poses, one does materials. That focus is a feature, but it leaves a gap for the times you want to just open a real 3D editor and build a scene with no rails. Rather than reinvent that, three.ws vendors the canonical three.js editor, the same tool the three.js project itself ships, and mounts it inside the platform so it inherits the nav, the theme, and the handoff plumbing. You get a mature, battle-tested editor with an object hierarchy, a scripting console, undo/redo, and glTF export, and it speaks the same GLB format every other three.ws surface produces and consumes.++## How it works++The editor is ported from the upstream `editor/index.html` with a small set of local changes: it mounts into a container under the site nav instead of taking over `document.body`, it drops the service worker, and it applies three.ws chrome overrides. It is dark-locked, because the vendored editor CSS only ships a dark theme. The core is the upstream `Editor` object driving the standard panels: `Viewport`, `Toolbar`, `Sidebar`, `Menubar`, `Player`, and the `Animation` timeline, all wired through the editor's signal bus.++- **Import.** Drag assets into the viewport or use the menubar's import. GLB/glTF load through the shared loader (`loader.js`), which decodes meshopt- and Draco-compressed buffers, so three.ws models load without extra steps. The editor also handles the other formats the upstream editor supports.+- **Transform.** Select an object in the hierarchy or viewport and use the translate/rotate/scale gizmos. The sidebar exposes exact numeric transforms.+- **Materials, lights, cameras.** The Object, Geometry, and Material tabs in the sidebar edit every property the three.js material and light models expose: color, metalness, roughness, maps, intensity, shadows, fog, background, and environment.+- **Scripting.** The editor bundles CodeMirror (with JavaScript and GLSL modes) and a Tern.js autocomplete engine seeded with three.js type definitions, so you can attach live scripts to objects and write shaders with completion.+- **Play and export.** The Player runs the scene (scripts included). The menubar exports the scene or selected objects to glTF/GLB, and the Draco encoder is bundled for compressed export.++### Handoff from Animation Studio++Scene Studio is the render target for animations built in [Animation Studio](./animation-studio.md). When you click "Open in Scene Studio" there, the studio bakes your keyframed animation into a GLB, stashes it in IndexedDB, and navigates to `/scene?handoff=1`. Scene Studio picks the model up on boot (`takeSceneHandoff`), drops it into the scene with its animation track ready, and you record it to video from the editor's render menu. The GLB is passed through browser storage, not the network, so nothing large is uploaded to move a model between the two tools.++## Walkthrough++1. Open [/scene](https://three.ws/scene). The empty editor loads with an object hierarchy on one side and the property sidebar on the other.+2. Drag a `.glb` into the viewport (or use Menubar ▸ import). It appears in the hierarchy.+3. Click it to select. Use the toolbar gizmos, or the keyboard, to move, rotate, and scale it. Fine-tune exact values in the sidebar.+4. Open the Material tab to change its color, metalness, roughness, or maps. Add a light from the Add menu and set its intensity and shadows.+5. Add more objects to compose the scene. Adjust the scene background, fog, and environment in the sidebar's Scene tab.+6. Attach a script to an object if you want runtime behavior, and press Play to run it.+7. Export the finished scene to GLB from the menubar.++## Examples++Scene Studio is an interactive editor, not an HTTP API, so the concrete examples are its entry points:++- **Open it empty:** [https://three.ws/scene](https://three.ws/scene)+- **Receive a handoff:** `https://three.ws/scene?handoff=1`: used by Animation Studio's "Open in Scene Studio" button; the model to load is read from IndexedDB, not the URL.++A typical round trip from another studio:++1. Build a walk cycle in [Animation Studio](./animation-studio.md) on a rigged avatar.+2. Click "Open in Scene Studio". The baked animated GLB is stashed and `/scene?handoff=1` opens.+3. In Scene Studio, add a ground plane, a key light, and a camera, position the avatar, and use Render ▸ Video to capture the loop.++## States & limits++- **Dark theme only.** The vendored editor chrome ships a single dark skin; the studio locks the page to dark so the panels render correctly, regardless of your site theme preference.+- **Desktop-class tool.** This is the full three.js editor with dense panels and gizmo interactions. It expects a pointer and a reasonably sized viewport; it is not tuned for small touch screens the way the other studios are.+- **Vendored, MIT-licensed.** The editor is a vendored copy of three.js r184 under MIT. Attribution and the upstream license live in [src/scene-studio/vendor/](../src/scene-studio/vendor) (see the vendor `README`/`LICENSE`). Local changes are limited to the container mount, theme lock, and chrome overrides.+- **Handoff is browser-local.** The Animation Studio handoff moves the GLB through IndexedDB in the same browser. Opening `/scene?handoff=1` directly, with nothing stashed, just gives you an empty editor.+- **Export format.** Scenes export to glTF/GLB (Draco available). That is the same format Restyle Studio, Scene Composer, and the viewer all read, so a scene authored here flows back into the rest of the platform.++## Related++- [Scene Composer](./compose.md): the lighter avatar-plus-props arranger with Forge integration.+- [Animation Studio](./animation-studio.md): builds the animated GLBs Scene Studio records to video.+- [Restyle Studio](./restyle.md): re-skin the models before or after composing them.+- [3D asset pipeline](./3d-asset-pipeline.md): how GLB, glTF, and clip formats relate across the platform.diff --git a/docs/selfie-to-avatar.md b/docs/selfie-to-avatar.mdnew file mode 100644index 000000000..6721197d6--- /dev/null+++ b/docs/selfie-to-avatar.md@@ -0,0 +1,84 @@+# Selfie to Avatar: scan your face into a rigged 3D character++Point your camera at your face, hold still for a countdown, and about a minute later you have a rigged, animation-ready 3D avatar in the browser. The scanner captures a single clean frontal photo (side angles optional), gates it for quality on-device, and hands it to a server-side face-reconstruction pipeline that fits your likeness onto a pre-rigged humanoid template. No modeling, no rig setup, no download of desktop tools.++Page: [/create/selfie](https://three.ws/create/selfie) (the working surface) · [/scan](https://three.ws/scan) (redirects here) · [/features/scan](https://three.ws/features/scan) (overview)+API: `POST /api/avatars/reconstruct` · `GET /api/avatars/regenerate-status` · `GET /api/avatars/:id`++## Why it exists++Every other surface on three.ws (agents, the marketplace, Play worlds, talking-avatar video, AR) needs a body to drive. A text prompt gives you a character; a selfie gives you *yourself*. The scanner is the shortest path from a real face to a shareable, riggable GLB, and it runs entirely from a phone or laptop browser with a camera. The output is not a static bust: it is a humanoid with a skeleton and a full ARKit blendshape set, so it can walk, emote, lip-sync, and be exported the moment it finishes.++`/scan` is a thin alias kept for links and marketing. On load it runs `window.location.replace('/create/selfie' + location.search)`, because `/create/selfie` carries the complete flow including the bring-your-own-key path. Document and link to `/create/selfie`.++## How it works++The client half lives in three modules the page imports on demand: [`src/selfie-capture.js`](../src/selfie-capture.js) (camera and upload UI), [`src/selfie-refine.js`](../src/selfie-refine.js) (`assessPhoto` / `refineSelfie`), and [`src/selfie-pipeline.js`](../src/selfie-pipeline.js) (the bridge to the backend). A fourth module, [`src/face-quality.js`](../src/face-quality.js), runs a live 468-point face mesh for framing feedback.++1. **Capture, in the browser.** `getUserMedia({ video: { facingMode: 'user', width: { ideal: 1280 }, height: { ideal: 1706 } } })` opens the front camera. A real-time wireframe overlay tracks head pose, yaw, centering, blur, and luminance, and only unlocks the shutter when the face passes. A 3-2-1 countdown fires, then `shoot()` draws the current video frame to a canvas and calls `canvas.toBlob(blob, 'image/jpeg', 0.92)`. This is a **single still**, not a video scan. Camera support is feature-detected; if none exists, the shutter is disabled and an "Upload instead" path takes any image file.+2. **Optional side angles.** Under an "Add side angles" disclosure you can capture two extra stills (`left`, `right`, turned ~45 degrees). They raise fidelity and the ETA, but only the frontal is required.+3. **Refine, in the browser.** `assessPhoto` gates the frontal (no face is the only hard block; blur, illustration, or a distant subject are non-fatal warnings). `refineSelfie` isolates the subject from its background and reframes to a clean head-and-shoulders square, then downscales (max 1024px, JPEG quality 0.88). The refined frontal is previewed so you see exactly what the engine sees.+4. **Submit.** The pipeline POSTs the photos as data URIs to `/api/avatars/reconstruct` and gets back a `jobId`.+5. **Reconstruct, server-side.** The reconstruct handler (`api/avatars/_actions.js`) selects a provider through [`api/_lib/regen-provider.js`](../api/_lib/regen-provider.js). The production lane is **GCP**: it POSTs `{ images, body_type }` to the Cloud Run service `avatar-pipeline-controller` (env `GCP_RECONSTRUCTION_URL`), which runs the [`workers/avatar-reconstruction/`](../workers/avatar-reconstruction/) FastAPI app. That pipeline (`face_texture_transfer_v2`) uses **MediaPipe FaceLandmarker** (468 landmarks, Apache-2.0) to transfer your face texture and geometry onto a fixed-topology, pre-rigged Wolf3D/Ready-Player-Me-style humanoid template carrying a Mixamo-compatible skeleton, 52 ARKit blendshapes, and 15 visemes. Full engine detail is in [avatar-reconstruction.md](./avatar-reconstruction.md).+6. **Auto-rig fallback.** The template is born rigged. If a generic mesh comes back unrigged and a rig model is configured, `reconstruct-finalize.js` chains a `rerig` job (GCP UniRig, `workers/unirig`) and moves the job through a `rigging` status before surfacing the avatar. If rigging is impossible it delivers the static mesh tagged `unrigged` rather than nothing.+7. **Poll and finish.** The client polls `GET /api/avatars/regenerate-status?jobId=...` every ~3 seconds (backing off on errors). On `status: 'done'` it fetches the finished avatar from `GET /api/avatars/:id` and shows it in a `<model-viewer>`.++### The text-to-avatar variant++The same `/api/avatars/reconstruct` endpoint accepts a `prompt` instead of `photos`. It runs a Flux text-to-image step (with a suffix that forces a head-and-shoulders portrait), then feeds that image into the identical reconstruct and auto-rig pipeline. One endpoint, two front doors.++## Walkthrough++1. Open [/create/selfie](https://three.ws/create/selfie). Sign in if prompted (the job resumes after login).+2. Allow camera access. Center your face in the wireframe until the shutter unlocks; good light and a plain background help.+3. Let the countdown run and hold still for the capture. Review the frame, or retake.+4. Optionally open "Add side angles" and capture a left and right turn for higher fidelity.+5. Press the submit button (labeled with the ETA, ~90s frontal-only or ~120s with sides). Watch the build steps: mesh, geometry and textures, auto-rig.+6. When it lands, use "Open my avatar" to view it, "Customize in editor" to edit, "Turn this into an agent", or the export buttons (.GLB, .FBX) and share panel.++## Examples++The reconstruct endpoint is authenticated. With a session cookie or a bearer token scoped `avatars:write`:++```bash+# Submit a reconstruction from a single frontal data-URI (or a hosted image URL).+curl -X POST 'https://three.ws/api/avatars/reconstruct' \+ -H 'content-type: application/json' \+ -H 'authorization: Bearer <TOKEN>' \+ -d '{+ "name": "My selfie avatar",+ "photos": ["data:image/jpeg;base64,/9j/4AAQ..."],+ "visibility": "private",+ "params": { "bodyType": "average", "style": "realistic" }+ }'+# -> 202 { "ok": true, "jobId": "…", "status": "queued", "eta": 90, "provider": "gcp" }++# Poll until done, then fetch the rigged GLB.+curl -H 'authorization: Bearer <TOKEN>' \+ 'https://three.ws/api/avatars/regenerate-status?jobId=<JOBID>'+# -> { "ok": true, "jobId": "…", "status": "done", "resultAvatarId": "<ID>" }++curl -H 'authorization: Bearer <TOKEN>' 'https://three.ws/api/avatars/<ID>'+# -> { "avatar": { "url": "<signed GLB url>", "model_url": null, ... } }+```++Request body: `name` (1-120, required), `photos` (1-6 image URLs or data URIs) **or** `prompt` (3-600 chars), optional `description`, `visibility` (`private` | `unlisted` | `public`), `params`, and the BYOK pair `provider_key` + `provider_name`. Status values progress `queued` -> `running` -> (`rigging`) -> `done` | `failed`.++## States and limits++- **Auth is required.** No session or scoped token returns `401`, and the page redirects to `/login?next=/create/selfie`, resuming the pending job afterward via `sessionStorage`. The `/features/scan` marketing line "no account for first scan" does not match the shipped API; treat sign-in as required.+- **Cost.** On the platform-hosted GCP lane there is no per-use charge in the reconstruct handler; usage is rate-limited (`limits.upload`), and over-quota returns `402 plan_limit`.+- **Bring your own key.** If no platform reconstruction backend is configured, the server returns `402 { code: 'regen_needs_byok', providers: ['meshy','tripo'] }` and the page shows a key-entry form. Meshy and Tripo run image-to-3D with your own API key; credit exhaustion surfaces as `402 insufficient_credits`.+- **Single frame.** Despite "captures several angles automatically" in some copy, the scanner takes one manual still per slot; side angles are an optional manual add.+- **Timing.** The build screen says "1-2 minutes"; the poll timeout is 8 minutes with a "taking unusually long" warning after 10.+- **Quality gating.** Only a frontal with no detectable face hard-blocks. Blur, illustrations, or multiple faces are surfaced as warnings you can proceed past.+- **Error handling.** Camera denial distinguishes `NotAllowedError` ("Camera access was denied... use Upload instead") from other failures. Job failures map to friendly messages (no face, content-safety flag, blur, service unavailable, timeout, out-of-memory). Poll tolerates up to 5 consecutive network errors with backoff before "Lost connection to the avatar engine." Rate limits (`429`) start a 60-second cooldown with a live countdown. Pending jobs resume across reloads.+- **Output.** glTF 2.0 GLB with a Mixamo-standard humanoid rig, 52 ARKit blendshapes, and 15 visemes. Private avatars return a short-lived signed `url`; `model_url` is the public CDN URL once you make it public.++## Related++- [Avatar reconstruction pipeline](./avatar-reconstruction.md): the full engine: MediaPipe face-texture transfer, geometry morph, the Wolf3D/RPM template, and the Cloud Run worker.+- [Avatar pipeline](./avatar-pipeline.md): the distinct Forge text-to-3D generation lane.+- [Character Studio](./character-studio.md): customize and dress the avatar after you scan it.+- [Talking Avatar Video](./talking-avatar-video.md) and [Lipsync](./lipsync.md): drive the finished avatar's mouth.+- Pages: [/create/selfie](https://three.ws/create/selfie), [/create](https://three.ws/create), [/features/scan](https://three.ws/features/scan).diff --git a/docs/signals.md b/docs/signals.mdnew file mode 100644index 000000000..da11f851a--- /dev/null+++ b/docs/signals.md@@ -0,0 +1,96 @@+# Signal Marketplace: pay-per-signal copy trading, ranked by proven edge++The Signal Marketplace is a directory of live trading feeds published by real, verified traders on three.ws. Each feed emits entry and exit signals bound to the publisher's actual on-chain fills. Your agent subscribes, pays per signal or per epoch in USDC over x402, and auto-mirrors each call through the same firewall and spend policy your wallet always runs under. Feeds are ranked not by follower count but by proven realized edge, so a thin feed riding one lucky call can never top a deep, consistent one.++Page: [/signals](https://three.ws/signals) (feed detail at `/signals/<slug>`)+API: `GET /api/signals/marketplace`, `GET /api/signals/feed`, `GET/POST/DELETE /api/signals/subscribe`, `GET /api/signals/stream`++## Why it exists++Copy trading has two chronic problems: you cannot tell who is actually good, and mirroring someone means trusting them with your funds. The marketplace fixes both.++Every signal is minted from the publisher's real position ledger, the same ledger their public verification badge is computed from, so a seller cannot hand-author a winning call they never took. And a feed's rank is its proven realized edge, confidence-regressed toward neutral until enough signals have closed. That means the board rewards traders who are consistently right over many trades, not loud ones with a single screenshot. Losers are counted; nothing is hidden.++On the buyer side, your agent's own custodial wallet pays and signs. You never hand a key to a stranger. The mirror runs through the identical guarded trade path your agent uses everywhere else, so a bad signal cannot spend past your caps or trade into a rug the firewall would block.++## How it works++A **feed** (`signal_feeds`) belongs to a publisher agent and carries its pricing (`price_per_signal_usdc`, `price_per_epoch_usdc`, `epoch_seconds`), what it emits (entries, exits, whether sizing is revealed), and a minimum-conviction floor.++**Emissions are minted from real fills.** `syncFeedEmissions` walks the publisher's `agent_sniper_positions`: a position opening becomes an `entry` emission (sized by conviction, which is derived from how large the entry is versus the publisher's own median entry); a position closing backfills that entry's realized outcome (`win`/`loss`/flat) and, if the feed publishes exits, mints a distinct `exit`. It is idempotent, so a re-run never double-emits, and an exit is never emitted for a coin that was never entered.++**Ranking is proven edge, regressed.** `feedEdgeScore` fuses the feed's hit rate and average realized ROI, regressed toward the publisher's own verified track-record score until enough signals have closed. The marketplace sorts on that by default; you can re-sort by ROI, hit rate, subscribers, or newest. A feed with fewer than 10 closed signals is flagged "Building track record" and its edge stays pulled toward neutral.++**Delivery pays then mirrors.** For each active subscription, `deliverSubscription` claims an idempotent delivery row per emission, settles the x402 payment (live mode only), then auto-mirrors:++- **Billing.** `per_signal` charges only on entries (exits ride free once the entry is paid); `per_epoch` charges once per paid window and stamps `epoch_paid_until` so same-epoch deliveries do not re-charge.+- **Payment.** Uses `transferUsdcGuarded` from the subscriber agent's wallet to the feed's payout address. If the payment is blocked (spend cap or frozen wallet) or fails, the delivery is recorded `unpaid` and the mirror is skipped. The platform never trades unpaid alpha.+- **Mirror.** An entry buys a size derived from your base size, the signal's size multiple, your scaling, and your per-trade cap; an exit sells your full holding of that mint. Both run through `runFollowerTrade`, the shared guarded path, with your slippage and firewall level (`block` or `warn`).++The marketplace read is public and cacheable (no auth); subscribing is owner-authenticated and CSRF-protected because it commits your agent's wallet to paying and trading.++## Walkthrough++1. Open [/signals](https://three.ws/signals). The board loads the top feeds for the current network, each card showing the publisher, a "Proven edge" score and bar, hit rate, average ROI, closed-versus-total signal counts, price, and subscriber count.+2. Sort with the segmented control: proven edge (default), ROI, hit rate, subscribers, or newest. Switch network (mainnet/devnet) with the adjacent control. Both reflect into the URL so any view is shareable.+3. Click a feed to open its detail page (`/signals/<slug>`): full accountability stats plus recent emissions, each with its realized outcome and a Solscan link to the real buy or sell fill that produced it.+4. Subscribe from your own agent. Choose `simulate` to mirror without paying or trading (trust-building) or `live` to pay and mirror within your spend policy. Set your base size, sizing scaling, slippage, per-trade cap, and whether to copy exits.+5. Your agent pays per signal or per epoch as new emissions land, and mirrors each one. Watch deliveries and fills accrue.+6. Kill any time. Setting `killed` halts all further payment and trading the instant it is set, honored before any payment or trade fires.++## Examples++Read the top feeds by proven edge:++```bash+curl -s 'https://three.ws/api/signals/marketplace?network=mainnet&sort=edge&limit=10' \+ | jq '.feeds[] | {rank, title, edge_score, hit_rate: .stats.hit_rate, per_signal: .pricing.per_signal_usdc}'+```++Subscribe an agent in simulate mode first (mirrors, spends nothing):++```bash+curl -s https://three.ws/api/signals/subscribe \+ -H 'authorization: Bearer YOUR_TOKEN' \+ -H 'content-type: application/json' \+ -d '{+ "feed_slug": "FEED_SLUG",+ "subscriber_agent_id": "YOUR_AGENT_UUID",+ "network": "mainnet",+ "mode": "simulate",+ "base_sol": 0.1,+ "copy_exits": true+ }'+```++Go live within your caps, then instantly kill if needed:++```bash+# flip an existing subscription to live+curl -s https://three.ws/api/signals/subscribe -H 'authorization: Bearer YOUR_TOKEN' \+ -H 'content-type: application/json' -d '{ "id": 123, "mode": "live" }'++# hard stop: no further pay or trade+curl -s https://three.ws/api/signals/subscribe -H 'authorization: Bearer YOUR_TOKEN' \+ -H 'content-type: application/json' -d '{ "id": 123, "killed": true }'+```++## Guardrails, states, and limits++- **Simulate versus live.** Simulate mirrors and sizes orders but pays nothing and trades nothing. Live pays the x402 USDC and executes the mirror, always within the agent's server-side spend policy.+- **Pay-then-trade, never trade-then-pay.** If the x402 payment is blocked by a spend cap or a frozen wallet, or fails, the mirror is skipped and the delivery is marked unpaid. Alpha is never traded on credit.+- **Every mirror is firewalled.** Entries route through `runFollowerTrade` with your firewall level; the rug/honeypot defense that guards all agent trades applies here too. WSOL and dust-sized orders are skipped with a recorded reason.+- **Instant kill.** `killed` on a subscription halts payment and trading before the next delivery. A paused or stopped subscription simply stops delivering; kill is the emergency stop.+- **Proven-edge ranking, not popularity.** Rank is confidence-regressed realized edge. Sub-10-closed-signal feeds are flagged and regressed toward neutral, so they cannot leapfrog proven ones.+- **Idempotent delivery.** One delivery per (subscription, emission); a retry no-ops. Per-epoch billing charges once per window.+- **Empty and reconnecting states.** With no live feeds on the selected network, the grid shows a designed empty state pointing to the leaderboard. On a transient fetch failure after first load, the last known board stays up and the live dot reads "reconnecting".+- **Publisher honesty is enforced at the source.** Emissions bind to real `buy_sig`/`sell_sig` fills; a publisher cannot fabricate a signal or hide a loss.++## Related++- [Custody you can verify](./custody.md) - the spend caps, freeze, and audit trail the subscriber wallet pays and trades under+- [Financial controls](./financial-controls.md) - the plain-English rules and firewall the mirror respects+- [Oracle](./oracle.md) - the conviction engine and its own follow/copy tier+- [x402](./x402.md) - the USDC payment protocol every signal settles over+- [Trader card](./trader-card.md) - the verified track record that regresses a feed's edge+- [/leaderboard](https://three.ws/leaderboard) - build a verified record, then publish a feed of your owndiff --git a/docs/smart-money.md b/docs/smart-money.mdnew file mode 100644index 000000000..94bb51ca2--- /dev/null+++ b/docs/smart-money.md@@ -0,0 +1,99 @@+# Smart Money Radar: follow the wallets that actually win++Smart Money Radar is a live, first-party reputation graph of every pump.fun wallet. It crosses each coin's buyers with which coins actually graduated, folds the result into a per-wallet track record, and surfaces two things you cannot get from a price chart: which wallets keep picking winners, and what that proven money is buying right now. Every number is earned from on-chain outcomes, not a hand-curated allowlist.++Page: [/smart-money](https://three.ws/smart-money)++API: `/api/pump/smart-money` (feed, leaderboard, per-coin, per-wallet). The coin drawer also reads `/api/oracle/coin` for conviction context.++## Why it exists++The single most predictive early signal on pump.fun is not the chart, it is who is buying. A wallet that has repeatedly entered coins that went on to graduate is worth watching; a wallet that dumps every launch it touches is worth avoiding. That information exists on chain, but nobody keeps a running scorecard in time. Smart Money Radar is that scorecard. It re-earns every wallet's reputation continuously from real outcomes, so a coin's "pedigree" is the buy-weighted track record of the wallets actually in it, and a wallet's rank is its own history of picking coins that graduated. This is the same proven-wallet ledger the WHO pillar of [Oracle](./oracle.md) draws on, exposed as its own browsable surface.++## How it works++The page is a self-contained module inside `pages/smart-money.html` that polls `/api/pump/smart-money` every 20 seconds (paused when the tab is hidden). It has three tabs: **Smart money is buying** (the coin feed), **Top wallets** (the leaderboard), and **Watchlist** (a local list of up to 200 mints in `localStorage`).++The numbers are produced by a cron rollup (`api/cron/smart-money-rollup.js`) in three phases that write to `wallet_reputation`, `coin_smart_money`, and a `smart_money_scored` dedupe ledger:++**Phase A: judge and fold.** Six hours after launch, a coin's outcome is binary: present in `pumpfun_graduations` is a win, otherwise a dud. For the top 60 buyers of each judged coin, per-wallet deltas are folded into `wallet_reputation`. An entry counts as **early** when the wallet's first buy is within 180 seconds of the coin's first trade, and a **dump** when the wallet sold at least half of what it bought.++**Phase B: recompute reputation.** For each touched wallet the score is:++```+win_rate = wins / (wins + duds)+early_win_rate = early_wins / early_entries+dump_rate = dumps / (wins + duds)+confidence = clamp(judged / 12, 0, 1) # full confidence at 12 judged coins+earlyBonus = clamp((early_win_rate - win_rate) * 0.4, 0, 20)+dumpPenalty = dump_rate * 0.4+smart_money_score = round((win_rate + earlyBonus - dumpPenalty) * confidence, 1)+```++The label follows from the profile: a creator with 3 or more launches and zero graduations is a `rugger`; fewer than 4 judged coins is `fresh`; a dump rate of 60 percent or more is a `dumper`; a score of 70 or more is `smart_money`; 5 or more early entries with a win rate under 25 percent is a `sniper`; everything else is `neutral`.++**Phase C: score live coins.** For every coin launched in the last 3 hours, `coin_smart_money` is computed from its non-creator buyers (creators do not lend pedigree to their own coin):++```+weightedAvg = sum(reputation * buy) / sum(buy) # unknown wallets score 0, dragging it down+networkBonus = min(smart_wallet_count, 5) * 4 # capped at +20+smart_money_score = round(clamp(weightedAvg + networkBonus, 0, 100), 1)+```++A wallet is "proven smart money" at reputation 70 or more. The card's smart-money **share** is proven buy volume over total buy volume. The top 8 wallets by score become the coin's `notable` roster, each re-resolved to its live label so the display never goes stale.++## Walkthrough++1. Open [/smart-money](https://three.ws/smart-money). The hero shows live totals: proven wallets, proven win rate, tracked capital, coins on radar, and last-updated.+2. Stay on **Smart money is buying**. Filter by `On radar (fresh)`, `Graduated`, or `All`, and sort by pedigree, smart-money share, smart buy volume, proven wallets in, or freshest. Each card shows the pedigree badge, the share bar, and up to four notable wallet labels.+3. Click a coin to open its drawer: the full notable roster, and an Oracle conviction slot fetched separately from `/api/oracle/coin`.+4. Switch to **Top wallets**. Filter by label (`smart_money`, `sniper`, `dumper`, or all), or paste a wallet address to jump straight to it. The sortable table shows win rate, early-win rate, dump rate, record, volume, and score.+5. Click any wallet to see its recent coins and cross-navigate back to a coin it bought. Star coins to your Watchlist to track them locally.++## Examples++Every read is public and IP rate-limited (600 requests per minute per IP).++```bash+# The live feed: coins ranked by smart-money score, graduated ones included+curl 'https://three.ws/api/pump/smart-money?limit=100&graduated=1'++# The wallet leaderboard: proven wallets with at least 4 judged coins+curl 'https://three.ws/api/pump/smart-money?leaderboard=1&limit=100&min_coins=4'++# One coin's pedigree and notable roster+curl 'https://three.ws/api/pump/smart-money?mint=<MINT>'++# One wallet's track record and recent coins+curl 'https://three.ws/api/pump/smart-money?wallet=<WALLET>'+```++```javascript+// Find the freshest coins where proven money already has real skin in+const { coins } = await fetch(+ 'https://three.ws/api/pump/smart-money?limit=100&graduated=0'+).then((r) => r.json());++const conviction = coins+ .filter((c) => c.smart_wallet_count >= 2)+ .sort((a, b) => b.smart_money_score - a.smart_money_score);++for (const c of conviction.slice(0, 5)) {+ console.log(c.symbol, 'pedigree', c.smart_money_score, 'proven wallets', c.smart_wallet_count);+}+```++## States and limits++- **Auth.** The read APIs are public and require no account. The rollup cron is Bearer-authenticated with `CRON_SECRET`.+- **Rate limit.** 600 requests per minute per IP; over that returns 429.+- **Warm-up window.** A coin is not judged until roughly 6 hours after launch, so a very fresh coin shows "not scored yet." The per-coin read deliberately returns `200 { found: false }` rather than a 404 for an unscored mint.+- **Empty and error states.** The feed, leaderboard, and watchlist each have designed empty copy ("No proven money on a fresh coin yet," "No wallets ranked yet"). A wallet with no history returns 404 and renders "No track record yet." A failed full refresh shows a stale-data reconnecting bar with a Retry button and escalates its message after repeated failures.+- **Two engines, one name.** This page reads `/api/pump/smart-money` (the graduation-outcome rollup). A sibling endpoint, `/api/intel/smart-money`, is a distinct funder-cluster and sybil-detection graph used by other surfaces. They answer related questions from different tables; do not conflate them.++## Related++- [Oracle: the conviction engine](./oracle.md) uses this proven-wallet ledger as its WHO pillar+- [The trading surfaces](./trading-surfaces.md) map, including the Coin Intelligence cross-coin trader board+- [Coin Radar](./radar.md) and [Mission Control](./terminal.md) surface the same pedigree read inline+- Pages: [/smart-money](https://three.ws/smart-money) · [/radar](https://three.ws/radar) · [/oracle](https://three.ws/oracle)diff --git a/docs/splat.md b/docs/splat.mdnew file mode 100644index 000000000..72bf9a10a--- /dev/null+++ b/docs/splat.md@@ -0,0 +1,64 @@+# Splat Viewer: photoreal Gaussian-splat avatars in the browser++The Splat Viewer renders Gaussian-splat and radiance-field scenes right in your browser, the photoreal output of capture engines like GaussianAvatars and HumanGaussian. Load a `.ply`, `.splat`, or `.ksplat` by URL, drop a file in, or try a built-in sample, and orbit a photoreal avatar or scene with no plugin, no upload to a server, and no account. All decoding happens client-side.++Page: [/splat](https://three.ws/splat)++## Why it exists++Mesh avatars (GLB) are lightweight, riggable, and universal, and that is what most of three.ws generates. But the photoreal frontier of avatar capture is radiance fields: Gaussian splatting reconstructs a person or a scene as millions of tiny anisotropic blobs that render with real skin, hair, and lighting no polygon budget can match. Those captures ship as `.ply`, `.splat`, or `.ksplat` files, and most tools to view them are desktop apps. The Splat Viewer is the browser front door: a place to open any splat scene, evaluate a capture engine's output, and share a photoreal avatar with a link. It complements [/avatar-engines](https://three.ws/avatar-engines), which surveys the capture methods; the viewer is where their output actually renders.++## How it works++The viewer (`src/splat-viewer.js`) is entirely client-side. It uses `@mkkellogg/gaussian-splats-3d`, already a platform dependency (the same library the Forge Studio Lab uses), lazy-loaded on first render so the page shell paints instantly. Format is detected from the filename extension: `.ply` maps to the PLY scene format, `.ksplat` to the compressed KSplat format, and everything else to the antimatter15 `.splat` layout (32 bytes per splat). The decoded buffer is handed to a `GS.Viewer` with built-in orbit controls, and every state is designed: idle, fetching, decoding, error, and a live HUD showing the scene label.++There are three ways to load a scene:++- **By URL.** Paste a link and the viewer fetches the bytes and decodes them. To survive cross-origin blocks, it rewrites the human-facing URLs of common asset hosts to their CORS-enabled raw form: GitHub `raw`/`blob` links become `raw.githubusercontent.com`, Hugging Face `/blob/` becomes `/resolve/`, and Dropbox links are forced to a direct download. When a host still blocks the browser fetch, the error state tells you to download the file and upload it instead.+- **By file.** Pick a file or drag and drop a `.ply`/`.splat`/`.ksplat` onto the stage. The file is read locally and never leaves your machine; a download button is offered for the loaded buffer.+- **Samples.** Two procedurally generated scenes ship in the page: a radiance shell (6,000 splats) and a synthetic head-and-shoulders bust (14,000 splats) that evokes what a real GaussianAvatars capture looks like in the viewer. These are synthetic, generated in-browser, and downloadable.++A deep link, `?src=<url>&name=<label>`, loads a scene straight from the URL on page load, so a photoreal avatar is shareable with a single link. A recenter control rebuilds the viewer from the cached buffer (the most reliable camera reset across splat-lib versions), and the viewer tears down cleanly on navigation.++## Walkthrough++1. Open [/splat](https://three.ws/splat).+2. Try a sample first: click the radiance shell or the head bust to see the viewer in action.+3. Load your own scene: paste a `.ply`/`.splat`/`.ksplat` URL and click Render, or drop a file onto the stage, or pick one from disk.+4. Orbit, zoom, and pan with the built-in controls. The HUD shows the scene label and splat count.+5. Recenter if the camera drifts. Download the loaded buffer if you loaded a file or a sample.+6. Share a scene by appending `?src=<url>` to the page URL.++## Examples++The viewer is driven by the URL, so sharing and embedding is just a link.++```+# Open a scene directly by deep link.+https://three.ws/splat?src=https://huggingface.co/<user>/<repo>/resolve/main/avatar.ply&name=My%20Avatar++# A GitHub-hosted splat: the viewer rewrites blob/raw links to the CORS raw host automatically.+https://three.ws/splat?src=https://github.com/<user>/<repo>/blob/main/scene.splat+```++Supported inputs at a glance:++- `.ply`: Gaussian-splat point cloud in PLY format.+- `.splat`: the antimatter15 layout (32 bytes per splat).+- `.ksplat`: the compressed KSplat format for faster loads.++## States and limits++- **Idle**: prompts you to load a splat, drop a file, or try a sample.+- **Fetching / decoding**: shows the host and the buffer size in MB; large radiance fields take a moment to decode.+- **Error**: an invalid file reports "that file isn't a valid splat"; a blocked fetch explains the CORS limit and suggests downloading then uploading; the retry loads a sample so the stage is never dead.+- **CORS**: only hosts that send permissive cross-origin headers load by URL; the viewer auto-rewrites GitHub, Hugging Face, and Dropbox links, but other hosts may require a local upload.+- **Client-side only**: files you upload are decoded in the browser and never sent to a server. There is no generation here; this is a viewer for captures produced elsewhere.+- Rendering runs on WebGL; very large scenes are bounded by your device's GPU and memory.++## Related++- [/avatar-engines](https://three.ws/avatar-engines) surveys the photoreal capture engines (GaussianAvatars, HumanGaussian and peers) whose output this viewer renders.+- [Avatar creation](./avatar-creation.md) and [avatar pipeline](./avatar-pipeline.md) cover the mesh (GLB) avatar path.+- [Scene Capture](./capture.md) reconstructs point clouds from video, a related radiance-adjacent capture flow.+- Pages: [/create](https://three.ws/create), [/scene](https://three.ws/scene).diff --git a/docs/strategy-objects.md b/docs/strategy-objects.mdnew file mode 100644index 000000000..1df86af9b--- /dev/null+++ b/docs/strategy-objects.md@@ -0,0 +1,103 @@+# Strategy Objects and the Strategy Lab++A Strategy Object is a trade strategy as a first-class thing you can own: a structured, validated rule set (entry conditions, sizing, take-profit, stop-loss, risk caps) that your agent can equip and run on-chain, ranked on a leaderboard by real live performance and forkable by anyone. The Strategy Lab is the workbench: write a strategy as data, validate it, backtest it against real captured pump.fun history with the exact evaluator the live worker uses, and run it live or in simulation, end to end. Both run strategies as additional constraints on top of your agent's server-side spend policy, never a way around it.++Pages: [/strategies](https://three.ws/strategies) (the library and leaderboard), [/strategy-lab](https://three.ws/strategy-lab) (the workbench)+API: `GET/POST /api/strategies`, `GET /api/strategies/leaderboard`, `GET/PATCH/DELETE /api/strategies/:id`, `POST /api/strategies/:id/{fork,publish}`, `GET/POST/DELETE /api/dca-strategies`, and the Lab's `POST /api/pump/strategy-{validate,backtest,run,close-all}`++## Why it exists++Most "strategies" in crypto are a screenshot and a promise. three.ws makes a strategy an object with a real schema, a real owner, and a real, on-chain track record. That does three things at once.++First, it makes strategies honest. A Strategy Object's performance is aggregated from real closed positions (`agent_strategy_positions`) across every agent that equipped it. A strategy with no closed trades is labeled "Unproven", never dressed up with a fabricated backtest curve. The leaderboard ranks by verified live ROI, not by claims.++Second, it makes them composable. Because a strategy is data with a validated shape, it can be forked (the rules copy into your library with lineage credited to the author, and you run them under your own spend policy, no wallet access is ever transferred), edited, versioned, published, and equipped on any agent you own.++Third, it makes them safe to run. The strategy's own caps (per-trade size, slippage, concurrency) are layered on top of the agent's server-side spend leash. The runtime sizes a buy from the strategy config, but the trade still passes through the full guard and custody path, so a strategy can never spend past your limits.++## How it works++### The Strategy Object schema++Every strategy is normalized and validated by `api/_lib/strategy-schema.js` before it persists. Free text is impossible; a malformed rule set cannot be saved. The config has four sections:++- **entry**: trigger (`new_launch`), `max_age_minutes`, optional min/max market cap, min liquidity, `require_socials`, creator-history gates (`max_creator_launches`, `min_creator_graduated`), and `require_sol_quote`.+- **sizing**: `amount_sol` per trade and `max_slippage_bps`.+- **exits**: `take_profit_pct`, a mandatory `stop_loss_pct`, optional `trailing_stop_pct`, and `max_hold_minutes`. Validation requires a stop-loss and at least one upside exit.+- **risk**: `max_concurrent_positions` and `cooldown_minutes`.++The schema enforces hard bounds on every field, so a stored config can never carry a nonsense number into the runtime. Two pure, synchronous functions, `matchesEntry` (does this real launch pass the entry gate) and `shouldExit` (should this open position close now), are the same logic the runtime and the backtest both use, so a backtest reflects live behavior rather than a flattering fiction.++### The library, leaderboard, and forking++`/strategies` has three surfaces on one page: the marketplace of published strategies (proven first), the leaderboard ranked by real live ROI, and your own library (create, edit, publish, equip, delete). The full-page builder lives in the URL (`?editor=new` or `?editor=<id>`) so it survives reload and the back button. Forking copies the rules only, credits lineage to the author, and gives you fresh ownership; equipping attaches the strategy to an agent you own, which then runs it under its own spend policy.++### The Strategy Lab++`/strategy-lab` is where you build and prove a declarative pump.fun strategy against real data:++- **Validate** (`POST /api/pump/strategy-validate`) checks the spec with the same validator the runner uses, so a broken spec is caught before anything runs.+- **Backtest** (`POST /api/pump/strategy-backtest`) replays the compiled strategy over the real captured universe: `pump_coin_intel` (per-launch bundle, organic, concentration, quality, category signals) joined to `pump_coin_outcomes` (graduated, pumped, flat, rugged, ATH multiple, last market cap). It uses the exact entry gate and exit priority the live worker uses. It does not synthesize launches or invent price paths; exits are evaluated at the two real price points it actually observed (the ATH multiple and the last observed multiple), entry slippage and impact are modeled from recorded early-window liquidity, and every limitation (survivorship, labeling lag, sample size) is reported in a `caveats` field.+- **Run** (`POST /api/pump/strategy-run`) executes the strategy for a bounded duration and streams events over Server-Sent Events. In **simulate** mode it needs no wallet and spends nothing; in **live** mode it requires auth, an agent you own with a provisioned Solana wallet, and every buy passes a `policyGuard` that calls the same `checkBuyAllowed` spend-policy check the rest of the platform uses.+- **Close all** (`POST /api/pump/strategy-close-all`) exits open strategy positions.++### DCA and subscription builders++`/api/dca-strategies` runs recurring, scheduled buys (executed by the `run-dca` cron). Each strategy is validated (agent, delegation, token in and out, amount per execution, a daily or weekly period, and slippage capped server-side), and non-GET methods over a cookie session require a CSRF token because these move real funds on a schedule.++## Walkthrough++1. Open [/strategies](https://three.ws/strategies) and browse the published marketplace, or switch to the leaderboard to see strategies ranked by real live ROI.+2. Click **New strategy**. The full-page builder opens. Set your entry conditions, per-trade size and slippage, a required stop-loss and at least one upside exit, and your risk caps. Save.+3. To prove it, open [/strategy-lab](https://three.ws/strategy-lab), paste or write the spec, and **Validate**. Fix any field-tagged errors it returns.+4. **Backtest** it against the real captured history. Read the results and the `caveats` before you trust them.+5. **Run** it in Simulate mode first: watch the live SSE stream of entries, exits, and logs with no funds at risk.+6. Equip the strategy on an agent you own (or flip the Lab run to Live with that agent), and it trades within that agent's spend policy. Fork, edit, publish, or delete from your library at any time.++## Examples++List published strategies and the live leaderboard:++```bash+curl -s 'https://three.ws/api/strategies?scope=published&limit=10' \+ | jq '.data.strategies[] | {name, proven: .performance.proven, roi: .performance.roi_pct}'++curl -s 'https://three.ws/api/strategies/leaderboard?limit=10' \+ | jq '.data.leaders[] | {rank, name, roi_pct: .performance.roi_pct}'+```++Backtest a spec against real captured pump.fun history:++```bash+curl -s https://three.ws/api/pump/strategy-backtest \+ -H 'content-type: application/json' \+ -d '{+ "strategy": {+ "network": "mainnet",+ "entry": { "trigger": "new_launch", "max_age_minutes": 30, "min_liquidity_sol": 5 },+ "sizing": { "amount_sol": 0.1, "max_slippage_bps": 500 },+ "exits": { "take_profit_pct": 100, "stop_loss_pct": 40 },+ "risk": { "max_concurrent_positions": 3 }+ }+ }' | jq '{summary, caveats}'+```++## Guardrails, states, and limits++- **Strategy caps never override the spend leash.** Per-trade size, slippage, and concurrency are additional constraints on top of the agent's server-side policy. A live run's buys pass `checkBuyAllowed`; a strategy cannot spend past your limits.+- **Simulate versus live.** The Lab defaults to Simulate (no wallet, no funds). Live requires auth, an owned agent with a provisioned Solana wallet, and enforces the spend policy on every buy.+- **A stop-loss is mandatory.** Validation rejects any strategy without a stop-loss and requires at least one upside exit (take-profit, trailing stop, or max hold). Every field is clamped to hard bounds.+- **Proven, not promised.** Performance is aggregated from real closed on-chain positions. No closed trades means "Unproven", not a synthetic curve. The leaderboard ranks by verified live ROI.+- **Backtest honesty.** The backtester replays real captured history with the live evaluator; it never invents launches, outcomes, or price paths, and reports its own limitations in `caveats`.+- **Forking transfers rules, not wallets.** A fork copies the config with lineage credited; the forker runs it under their own spend policy. No wallet access is ever transferred.+- **Deleting is safe.** Deleting a strategy stops equipped agents from running it; open positions stay yours to manage.+- **DCA moves real funds on a schedule.** Create and cancel are CSRF-gated over a session, slippage is capped server-side, and allowed output tokens plus the default chain are operator config, never hardcoded.++## Related++- [Custody you can verify](./custody.md) - the spend limits and audit trail every live run is bounded by+- [Financial controls](./financial-controls.md) - the plain-English rules and firewall layered on the same enforcement point+- [Oracle](./oracle.md) - the conviction engine an entry gate can require before it fires+- [Trading surfaces](./trading-surfaces.md) - where equipped strategies execute through the guarded path+- [Trading arenas](./trading-arenas.md) - competitive surfaces where strategies are put to the test+- [/strategies](https://three.ws/strategies) and [/strategy-lab](https://three.ws/strategy-lab) - the library and the workbenchdiff --git a/docs/talking-avatar-video.md b/docs/talking-avatar-video.mdnew file mode 100644index 000000000..0520c9ea5--- /dev/null+++ b/docs/talking-avatar-video.md@@ -0,0 +1,81 @@+# Talking Avatar Video: render a lip-synced clip from an avatar++Pick one of your three.ws avatars, upload an audio track, add an optional scene description, and a GPU worker renders a lip-synced talking-head video you can download as MP4. The lipsync and rendering happen server-side on a dedicated Cloud Run worker; the browser is just a picker, an uploader, and a player.++Page: [/create/video](https://three.ws/create/video)+API: `POST /api/avatar/presign-audio` · `POST /api/avatar/video-generate` · `GET /api/avatar/video-status`++## Why it exists++Real-time browser lipsync (see [Lipsync](./lipsync.md)) is perfect for live avatars, but it cannot produce a finished, shareable file with rendered frames, matched motion, and a scene. Talking Avatar Video is the export path: it takes an avatar you already own and an audio track you supply and returns a polished clip. It closes the loop from "I made an avatar" to "here is a video of my avatar saying this," without any local tooling.++Note on scope: the shipped flow uploads an audio file. It does not synthesize speech from a typed script and it does not offer a voice picker inside this page (the page's marketing meta text mentions "type a script, pick a voice," but the UI does neither). To generate the audio first, use [Voice Lab](./voice-lab.md) and bring the resulting clip here.++## How it works++The page ([`pages/create/video.html`](../pages/create/video.html)) loads [`src/create-video.js`](../src/create-video.js), which uses `apiFetch` from [`src/account.js`](../src/account.js) and a `<model-viewer>` preview.++1. **Auth gate.** On load it checks `GET /api/auth/me`; if you are not signed in it redirects to `/login?next=%2Fcreate%2Fvideo`.+2. **Pick an avatar.** It calls `GET /api/avatars` and renders your avatar library into a thumbnail bar, auto-selecting the first. The selected GLB is shown in a `<model-viewer>`. Private avatars resolve their GLB lazily through `GET /api/avatars/:id` (a short-lived signed URL). With no avatars it falls back to `/avatars/default.glb`.+3. **Upload audio.** Drag in or pick a WAV, MP3, M4A, OGG, or FLAC file. The client POSTs `{ filename, content_type }` to `/api/avatar/presign-audio`, gets a presigned PUT URL plus a `public_url`, and PUTs the raw bytes to R2/S3. If presign fails it falls back to a base64 data URI.+4. **Describe the scene (optional).** A textarea takes a scene description such as "A person speaking on a stage with dramatic lighting." This is a scene prompt, not a script.+5. **Generate.** With an avatar and audio ready, Generate POSTs `{ image_url, audio_url, avatar_id?, prompt? }` to `/api/avatar/video-generate`. The server SSRF-guards both URLs (https on the app or S3 domain), resolves the avatar image if only an `avatar_id` was sent (with an ownership/visibility check), and forwards to the worker.+6. **Render, server-side.** The generate endpoint calls the **LongCat-Video-Avatar-1.5** worker on Google Cloud Run (`POST {LONGCAT_WORKER_URL}/generate`, bearer-authenticated), which produces the lip-synced frames. The endpoint returns `202 { job_id, status }`.+7. **Poll.** The client polls `GET /api/avatar/video-status?job_id=...` every 5 seconds (20-minute safety timeout). Status runs `queued` -> `running` -> `done` | `failed`, with an optional `progress` (0 to 1).+8. **Download.** On `done`, the `video_url` is set as the `<video>` source and the download anchor (`download="avatar-video.mp4"`). Progress copy: "Takes 2 to 4 minutes on GPU. Hang tight."++## Walkthrough++1. Open [/create/video](https://three.ws/create/video) and sign in.+2. Pick an avatar from the thumbnail bar; it loads into the preview.+3. Drop in or browse for an audio file (WAV, MP3, or M4A).+4. Optionally type a scene description.+5. Press Generate video. Watch the status: uploading audio, queuing, rendering frames with a percentage.+6. When it finishes, play the result inline and press Download to save the MP4, or New video to start over.++## Examples++All three endpoints require a signed-in session.++```bash+# 1. Presign an audio upload slot.+curl -X POST 'https://three.ws/api/avatar/presign-audio' \+ -H 'authorization: Bearer <TOKEN>' -H 'content-type: application/json' \+ -d '{ "filename": "line.mp3", "content_type": "audio/mpeg" }'+# -> { "upload_url": "<PUT url>", "public_url": "https://…/line.mp3", "storage_key": "u/<uid>/audio/<uuid>.mp3" }++# 2. PUT the raw bytes to the presigned URL.+curl -X PUT '<PUT url>' -H 'content-type: audio/mpeg' --data-binary @line.mp3++# 3. Kick off generation with an avatar image + the uploaded audio.+curl -X POST 'https://three.ws/api/avatar/video-generate' \+ -H 'authorization: Bearer <TOKEN>' -H 'content-type: application/json' \+ -d '{ "image_url": "https://…/avatar.png", "audio_url": "https://…/line.mp3",+ "avatar_id": "<AVATAR_ID>", "prompt": "A person talking on a bright stage." }'+# -> 202 { "job_id": "…", "status": "queued" }++# 4. Poll until done, then fetch video_url.+curl -H 'authorization: Bearer <TOKEN>' \+ 'https://three.ws/api/avatar/video-status?job_id=<JOB_ID>'+# -> { "job_id": "…", "status": "done", "progress": 1, "video_url": "https://…/out.mp4", "error": null, "updated_at": "…" }+```++`audio_url` is required; `image_url` may be omitted when `avatar_id` is present (the server resolves the avatar's stored image). `prompt` defaults to "A person talking naturally."++## States and limits++- **Auth required.** The page gates on `/api/auth/me`; every endpoint re-checks the session and returns `401` otherwise.+- **Free tier: one lifetime generation.** Free-plan users get exactly one video. The quota is reserved race-safely (a `usage_events` row is inserted before the worker call and released if submission fails, so an outage never burns the trial). On exhaustion the server returns `402 free_trial_used` and the page relabels the retry button "Upgrade plan" linking to `/dashboard`. Paid plans are unlimited.+- **Rate limits.** Per-user and global rate limits on `video-generate` return `429`.+- **Input formats.** Audio: WAV, MP3, M4A, OGG, FLAC (validated against an allow-list; `415` otherwise). Uploads go to R2/S3 under `u/{userId}/audio/{uuid}.{ext}`.+- **SSRF guard.** `image_url` and `audio_url` must be https on the app origin or the S3 public domain, else `400 invalid_request`.+- **Ownership.** `video-status` verifies the job belongs to you (`404` if unknown, `403` if another user's). Avatar image resolution enforces owner-or-public visibility.+- **Timing and errors.** Renders take ~2 to 4 minutes; the client times out after 20 minutes. UI states cover idle, uploading audio, queuing, rendering with a percent, done, and error (upload failed, could not start, failed on the server, timed out). Server errors include `502 worker_unreachable`/`worker_error` and `503 worker_unconfigured`.+- **Output.** MP4, downloaded straight from the worker's `video_url`.++## Related++- [Voice Lab](./voice-lab.md): clone or synthesize the audio track you upload here.+- [Lipsync](./lipsync.md): the real-time, in-browser lipsync path (no export).+- [Selfie to Avatar](./selfie-to-avatar.md) and [Avatar reconstruction](./avatar-reconstruction.md): create the avatar you render.+- Pages: [/create/video](https://three.ws/create/video), [/create](https://three.ws/create), [/dashboard](https://three.ws/dashboard).diff --git a/docs/terminal.md b/docs/terminal.mdnew file mode 100644index 000000000..a672d2119--- /dev/null+++ b/docs/terminal.md@@ -0,0 +1,98 @@+# Mission Control: the keyboard-first pump.fun trading terminal++Mission Control is the cockpit of the three.ws trading stack. It fuses the live pump.fun launch firehose with intel scores, Trade Safety Firewall verdicts, and smart-money flow into one keyboard-driven, three-pane terminal, streams your agent's open positions with live PnL, and lets you buy or sell in a single keystroke from your agent's custodial Solana wallet behind the platform's server-side firewall and MEV-protected execution path. Every other trading surface is read-only. This is the one where you pull the trigger.++Page: [/terminal](https://three.ws/terminal)++APIs (all real, all called by the page): `/api/pump/trades-stream` (SSE firehose), `/api/pump/intel`, `/api/pump/safety`, `/api/intel/smart-money`, `/api/pump/coin`, `/api/pump/price-history`, `/api/pump/dex-trades`, `/api/sniper/stream` (SSE positions), `/api/sniper/leaderboard`, `/api/sniper/history`, `/api/sniper/radar`, `/api/agents/:id/solana`, `/api/agents/:id/solana/holdings`, `/api/agents/:id/solana/trade`.++## Why it exists++Early pump.fun trading punishes context-switching. The launch is on one tab, the intel score on another, the wallet in a third, and by the time you have alt-tabbed to all of them the candle is gone. Mission Control collapses the whole loop into a single screen you drive from the home row: read the launch, read whether it is real, size it, and send the order without ever touching the mouse. It sits at the top of the [trading surfaces](./trading-surfaces.md) map. Radar and Coin Intelligence answer "what launched and is it real," the Live Trade Feed answers "what won," and Mission Control is where you act on all of it. It is the only surface that executes.++## How it works++The page mounts `mountMissionControl` from `src/mission-control/index.js` and lays out three panes:++- **Feed (left).** Three switchable sources. `live` is the new-mint and graduation firehose over Server-Sent Events (`/api/pump/trades-stream`). `signals` is the Coin Intelligence Engine's scored feed (`/api/pump/intel?view=feed`), each coin carrying a 0 to 100 `quality_score`, a verdict, and risk flags. `radar` is the pre-launch precursor stream (`/api/sniper/radar`).+- **Focus (center).** The selected coin's identity and market state (`/api/pump/coin`), its candlestick chart (`/api/pump/price-history`, Birdeye with a GeckoTerminal fallback and a last-good-candles degrade), the live trade tape (`/api/pump/dex-trades` polled every 8s for graduated pairs the stream misses), the firewall verdict, and the smart-money read.+- **Positions (right).** Your agent's open positions with streaming unrealized PnL over SSE (`/api/sniper/stream`, DB-polled every 1.5s), spot holdings (`/api/agents/:id/solana/holdings`, refreshed every 30s), and a one-tap quick exit.++Each row in the feed is enriched on demand by `enrich.js`, which fans out three cached reads per mint: intel (`/api/pump/intel?mint=`), the Trade Safety Firewall (`/api/pump/safety?mint=&amount=`, which runs an SPL authority audit plus an on-chain simulated buy then sell round-trip and returns `allow` / `warn` / `block`), and smart money (`/api/intel/smart-money?mint=`). Failures cache `null` and mark the field unavailable rather than retry-storming or faking a value.++Every SSE endpoint self-closes about every 90 seconds by design; `realtime.js` treats an `event: close` as normal and fast-reconnects, with exponential backoff only on real errors.++## The keyboard++The keyboard is the point. Shortcuts are suppressed while focus is in an input, textarea, or select, and ignored when a modifier key is held.++| Key | Action |+| --- | --- |+| `j` / down arrow | Next launch in the feed |+| `k` / up arrow | Previous launch |+| `b` | Buy at the active size preset |+| `s` | Sell the entire position |+| `1`-`6` | Pick a buy-size preset |+| `/` | Focus the feed filter box |+| `g` | Jump to the top of the feed |+| `x` | Toggle Express mode (instant vs confirm-first) |+| `?` | Open or close the shortcuts overlay |+| `Esc` | Close overlay, blur input, or clear |++## Filters and saved views++The filter bar (state in `store.js`) narrows the feed by source, free-text query (name, symbol, or mint substring), a minimum-intel floor that cycles through 0 / 40 / 60 / 80, a firewall verdict (`allow` or `warn`; a `block` coin is always hidden when a verdict filter is set), a smart-money-only toggle, a has-socials toggle, and a market-cap band (nano under 10k, micro 10k to 50k, small 50k to 250k, mid 250k and up, in USD). Any filter set can be saved as a named **view**, persisted per user in `localStorage` (`mc:views:v1:<userId>`, up to 24, newest first). Buy-size presets default to 0.1, 0.25, 0.5, and 1 SOL and persist at `mc:presets:v1`.++## Firewall, MEV, and trading from your agent wallet++Trading is the guarded path, and the client checks are only a fast gate: the server is the real authority. `POST /api/agents/:id/solana/trade` is owner-only (session or bearer auth, then agent-ownership verification) and, for a real execute, requires a single-use `x-csrf-token` and an `idempotency_key`. A `{ preview: true }` call returns a live quote and moves no funds. On execute the server runs a fixed enforcement order: fresh quote, kill switch, per-trade cap, daily budget, spend-limit enforcement, price-impact breaker, then the Trade Safety Firewall (`assessTradeSafety`; a `block` returns HTTP 422 `firewall_blocked`), then SOL headroom, then it claims the idempotency slot and submits through the MEV engine (`submitProtected`: dynamic compute budget from a real simulation, a Helius priority-fee estimate, and a Jito single-tx bundle with a real tip on mainnet, falling back transparently to a protected raw send). The agent's key is decrypted only at signing time via `recoverSolanaAgentKeypair`, and every attempt is audit-logged. A retried idempotency key never double-spends; a previously failed key returns 409. The firewall thresholds live in `api/_lib/trade-firewall.js`: block at score 45 and below, warn at 70 and below, with a fatal check (a dead sell leg or no venue) forcing `block` regardless of score.++Express mode (`trade.js`): the first trade always shows a confirm modal; accepting sets a per-agent express flag so later orders execute instantly. `x` toggles it back off.++## Walkthrough++1. Open [/terminal](https://three.ws/terminal). Signed out, the cockpit is fully readable and the trade ticket reads "Sign in to trade."+2. Sign in and select a trading agent. The topbar shows the agent's Solana address and SOL balance (`/api/agents/:id/solana`, polled every 30s).+3. Leave the feed on `live` and watch new mints arrive. Press `j` and `k` to move the selection; each row enriches with its intel score, firewall verdict, and smart-money read.+4. On a coin you like, press `1`-`6` to choose a size preset, glance at the Focus pane's firewall verdict and security cells, then press `b`. The first buy asks you to confirm; accept to arm Express for that agent.+5. Watch the fill and the new position stream into the right pane with live PnL. Press `s` to exit the whole position when you are done.++## Examples++The read surfaces powering the panes are public and IP rate-limited, so you can pull the same data any agent sees:++```bash+# The Signals feed: scored launches from the Coin Intelligence Engine+curl 'https://three.ws/api/pump/intel?view=feed&network=mainnet&limit=20'++# The Trade Safety Firewall verdict for a mint at a 0.05 SOL probe size+curl 'https://three.ws/api/pump/safety?mint=<MINT>&network=mainnet&amount=0.05'++# Who reputable is net-buying a coin+curl 'https://three.ws/api/intel/smart-money?mint=<MINT>&network=mainnet'+```++Stream the same new-mint firehose the Feed pane consumes:++```javascript+const es = new EventSource('https://three.ws/api/pump/trades-stream');+es.addEventListener('mint', (e) => console.log('new launch', JSON.parse(e.data)));+es.addEventListener('graduation', (e) => console.log('graduated', JSON.parse(e.data)));+// The stream self-closes about every 90s; reconnect on 'close'.+```++## States and limits++- **Auth.** The page runs read-only signed out. Trading, `/api/sniper/history`, and the holdings and trade endpoints require a session or bearer token plus ownership of the agent. Signed out, the ticket links to `/login?next=%2Fterminal`.+- **Rate limits.** The public reads are IP rate-limited (`mcpIp` on the stream and smart-money, `publicIp` on safety, `authedReadIp` on sniper history). The trade endpoint is auth and CSRF gated.+- **Streaming.** All SSE endpoints self-close roughly every 90 seconds and the client fast-reconnects; connection pills surface `live`, `reconnecting`, or `down`.+- **Honest empty and error states.** Enrichment caches `null` on failure and marks the field unavailable. The chart never fabricates candles (it degrades to last-good with a `stale` marker or shows empty). Positions distinguish "stream unreachable" from "no open positions," and the trade tape shows "Waiting for trades..." rather than inventing fills.+- **Refresh cadences.** Balance and holdings 30s, signals and radar 12s, dex-trades 8s, position poll 1.5s.++## Related++- [The trading surfaces: Radar, Mission Control, Live Trade Feed, Watchlist, Coin Intelligence](./trading-surfaces.md)+- [Coin Radar](./radar.md) and [Smart Money Radar](./smart-money.md) feed the same intel into their own surfaces+- [Oracle: the conviction engine](./oracle.md) supplies the fused conviction score+- [Financial controls and custody guardrails](./financial-controls.md) and [custody](./custody.md) document the server-side rails every order runs through+- Pages: [/terminal](https://three.ws/terminal) · [/radar](https://three.ws/radar) · [/trades](https://three.ws/trades) · [/watchlist](https://three.ws/watchlist)diff --git a/docs/three-microbuy.md b/docs/three-microbuy.mdindex beab94101..223dc084a 100644--- a/docs/three-microbuy.md+++ b/docs/three-microbuy.md@@ -48,20 +48,42 @@ happen).reserves the day's budget in Redis *before* broadcasting a buy, so a flood ofconcurrent calls can never collectively overshoot the cap. A DB sum over`three_microbuy_runs` is the fallback when Redis is down.+- **Fail-closed.** If *neither* Redis nor the ledger DB can confirm today's spend,+ the buy is **refused** (`cap_unverifiable`), not allowed. Unbounded real-money+ spend is the one outcome the cap exists to prevent, so the engine never assumes+ "zero spent" on an infrastructure outage.- **Fail-closed toll.** Because the endpoint refuses the toll whenever a buy can'thappen (disabled, unfunded, cap reached), a direct payer can force buys only upto the same daily ceiling the loop obeys — there is no amplification past the cap.+- **Self-healing ledger.** The loop and endpoint create `three_microbuy_runs` on+ first use, so the DB cap fallback and the records always work even on a fresh or+ behind database — the migration owns it in a real deploy, this is the backstop.- **Kill switches.** `X402_AUTONOMOUS_ENABLED=false` (global) or`THREE_MICROBUY_ENABLED` unset stops everything; `THREE_MICROBUY_LOOP_ENABLED=false`pauses only the driver while leaving the endpoint payable.+- **No wasted hammering.** A tick stops early on a fully-failed wave (cap exhausted,+ disabled, unfunded, or an RPC/DB outage) instead of firing every remaining call+ for nothing — reported as `stop_reason` in the tick response.- **Not in the generic ring.** `three-buy` is `autobuy:false` in[ring-catalog.js](../api/_lib/x402/ring-catalog.js), so the generic ring rotation- never fires real buys — only its dedicated driver does.+ never fires real buys — only its dedicated driver does (pinned by a test).Every call writes an immutable row to `three_microbuy_runs`([migration](../api/_lib/migrations/20260717233000_three_microbuy.sql)) — confirmed,pending, skipped, or failed — so there is never a silent no-op.+## Observability++- **Tick response.** `/api/cron/three-buy-loop` returns `fired`, `paid`, `buys`,+ `pending`, `errors`, `toll_spent_usd`, `daily_spent_usd`, `daily_cap_usd`, and+ `stop_reason` for the tick.+- **Public stats.** `microbuyStats()` (lifetime + today's buys, $THREE bought, USDC+ deployed, cap-used %) is surfaced on the `$THREE` token stats API+ ([api/three-token/[action].js](../api/three-token/%5Baction%5D.js) → `/api/three-token/stats`)+ under `token.microbuy`, alongside the daily buyback summary.+- **Ring volume.** The x402 tolls show up in the ring dashboards tagged+ `pipeline='three-buy'` (per-endpoint volume ledger + `x402_autonomous_log`).+## Turning it on```bash@@ -85,7 +107,7 @@ curl -s -H "Authorization: Bearer $CRON_SECRET" https://three.ws/api/cron/three-```The response reports `fired`, `paid`, `buys`, `pending`, `errors`, `toll_spent_usd`,-`daily_spent_usd`, and `daily_cap_usd` for the tick.+`daily_spent_usd`, `daily_cap_usd`, and `stop_reason` for the tick.## Configurationdiff --git a/docs/voice-lab.md b/docs/voice-lab.mdnew file mode 100644index 000000000..d07058d4d--- /dev/null+++ b/docs/voice-lab.md@@ -0,0 +1,86 @@+# Voice Lab: clone your voice in the browser++Record 20 to 30 seconds of clear speech and Voice Lab creates a digital replica of your voice that you can type into and play back instantly, save to a personal library, and later assign to any three.ws agent. The recording, the live waveform, and the voice library all run in the browser; cloning and synthesis run server-side through ElevenLabs Instant Voice Cloning behind a platform proxy so your key never leaves the server.++Page: [/voice](https://three.ws/voice)+API: `POST /api/tts/eleven-clone` (clone) · `POST /api/tts/eleven` (synthesize) · `PUT`/`POST`/`DELETE /api/agents/:id/voice` (assign to an agent)++## Why it exists++An agent that speaks in a generic stock voice is a demo. An agent that speaks in *your* voice is a character. Voice Lab is the on-ramp: it turns a short browser recording into a reusable voice identity, then hands that identity to the rest of the platform (the chat agent, talking-avatar surfaces, the marketplace) without you ever touching an API. It is deliberately a two-step product: clone here, then wire the saved voice into an agent from the agent editor, so the same clone can back several agents.++## How it works++The page ([`pages/voice.html`](../pages/voice.html)) loads a single module, [`src/voice-lab.js`](../src/voice-lab.js), which owns three panels: the recorder, the "My Voices" library, and a text-to-speech playground.++1. **Record.** `getUserMedia({ audio: { channelCount: 1, echoCancellation: true, noiseSuppression: true, autoGainControl: true, sampleRate: 48000 } })` opens the mic. A `MediaRecorder` (negotiating `audio/webm;codecs=opus` first, then webm, ogg, or mp4) captures in 250ms slices while a Web Audio `AnalyserNode` (`fftSize: 2048`) drives a live 64-bar waveform and an 8-bar level meter. Four reading scripts are offered so you have something natural to say. The recommended length is 25 seconds; the UI encourages stopping any time after 25s, auto-stops at 60s, and rejects anything under 3s.+2. **Review.** You play the take back, name the voice (1 to 64 chars), and either re-record or clone.+3. **Clone.** The recording is POSTed as `multipart/form-data` to `/api/tts/eleven-clone`. The shared library [`api/_lib/elevenlabs.js`](../api/_lib/elevenlabs.js) dynamically imports `@elevenlabs/elevenlabs-js`, constructs an `ElevenLabsClient`, and calls `client.voices.ivc.create({ name, description, files })` (ElevenLabs Instant Voice Cloning). The endpoint returns a `voice_id`.+4. **Save.** The `voice_id` is written to a browser voice library (`localStorage` key `voicelab_voices_v1`, up to 20 voices). Each card offers "Play sample" and "Remove".+5. **Play.** The playground picks any of *your* cloned voices, takes up to 500 characters of text, and POSTs `{ voiceId, text }` to `/api/tts/eleven`. That endpoint synthesizes with the server default model `eleven_flash_v2_5`, streams back `audio/mpeg`, and caches each clip in R2 for 30 days keyed on a hash of the inputs (the response header `x-tts-cache: hit|miss` tells you which).++### Comparing voice models++The live `/voice` playground synthesizes with a single default model (`eleven_flash_v2_5`). The side-by-side **model** comparison and per-agent voice tuning (stability, similarity, style sliders) live in the **agent editor** ([`src/agent-edit.js`](../src/agent-edit.js)), which reads the live model catalog from `GET /api/tts/eleven/voices` and lets you audition across the three ElevenLabs models:++- `eleven_flash_v2_5`: Flash v2.5, lowest latency, real-time (the default).+- `eleven_turbo_v2_5`: Turbo v2.5, balanced latency and quality.+- `eleven_multilingual_v2`: Multilingual v2, highest quality, 29 languages.++## Walkthrough++1. Open [/voice](https://three.ws/voice) and sign in (both endpoints require auth).+2. Allow microphone access. Press record (or hit Space), read one of the scripts aloud for 20 to 30 seconds, and stop.+3. Play the take back. If it is clean, name the voice and press Clone. If not, re-record.+4. Wait a few seconds for "cloned successfully". The new voice appears in My Voices with its `voice_id`.+5. Open the playground, pick the voice, type or drop in a sample, and press Speak (or Cmd/Ctrl+Enter). Playback is instant on a cache hit.+6. To give the voice to an agent, open that agent in the agent editor and assign the saved voice there.++## Examples++Both endpoints are authenticated (session cookie or bearer token). Cloning also requires a paid ElevenLabs tier server-side.++```bash+# Clone a voice from a recorded sample (multipart).+curl -X POST 'https://three.ws/api/tts/eleven-clone' \+ -H 'authorization: Bearer <TOKEN>' \+ -F 'name=My studio voice' \+ -F '[email protected];type=audio/webm'+# -> 200 { "voice_id": "…", "name": "My studio voice", "status": "ready", "requires_verification": false }++# Synthesize speech with a cloned voice (streams audio/mpeg).+curl -X POST 'https://three.ws/api/tts/eleven' \+ -H 'authorization: Bearer <TOKEN>' \+ -H 'content-type: application/json' \+ -d '{ "voiceId": "<VOICE_ID>", "text": "Welcome to three dot ws." }' \+ --output hello.mp3++# Assign the cloned voice to an agent, with model + settings.+curl -X PUT 'https://three.ws/api/agents/<AGENT_ID>/voice' \+ -H 'authorization: Bearer <TOKEN>' \+ -H 'content-type: application/json' \+ -d '{ "voice_id": "<VOICE_ID>", "voice_model": "eleven_turbo_v2_5",+ "voice_settings": { "stability": 0.5, "similarity_boost": 0.75, "style": 0.5, "use_speaker_boost": true } }'+# -> { "voice_provider": "elevenlabs", "voice_id": "…", "voice_model": "eleven_turbo_v2_5", ... }+```++The agent-voice handler ([`api/agents/_id/voice.js`](../api/agents/_id/voice.js), reached at `/api/agents/:id/voice`) also exposes `GET` (status), `POST /api/agents/:id/voice/clone` (clone directly from raw audio, with a 30-second minimum and a 3-clones-per-day limit), and `DELETE` (revert to the browser voice). Assigning or clearing a clone deletes the previous ElevenLabs clone to free quota.++## States and limits++- **Recorder states.** `idle` -> `recording` (live waveform, timer, level meter) -> `review` (playback, name, Clone / Re-record) -> `cloning` (spinner) -> `done` (green check, `voice_id` shown, actions: Try in playground / Add to an agent / Record another).+- **Auth required.** Both TTS endpoints return `401 unauthorized` without a session or bearer token. Requests send `credentials: 'include'`.+- **Server config.** ElevenLabs must be configured (`ELEVENLABS_API_KEY`) or the endpoints return `503 not_configured`.+- **Paid cloning tier.** Instant Voice Cloning is an ElevenLabs paid-tier (Starter and up) feature. On a free upstream tier the API surfaces the upstream `can_not_use_instant_voice_cloning` body verbatim as a `502`.+- **Length rules.** Voice Lab recommends 20 to 30 seconds, auto-stops at 60, and rejects under 3. The separate agent-clone endpoint (`POST /api/agents/:id/voice/clone`) enforces a 30-second floor and 3 clones per user per day.+- **Synthesis limits.** 500 characters per playground request; 1000 characters per hour per user (reserved-then-refunded so a failed synth does not burn quota). Clips are cached in R2 for 30 days.+- **Audio size.** Clone uploads are capped at ~10 MB.+- **"Add to an agent" on `/voice`** links to the dashboard; the actual assignment happens in the agent editor. The cloned `voice_id` lives in browser `localStorage` until you assign it.+- **Error copy.** Mic denial, recorder failure, too-short recording, missing name, network failure, and clone failure each map to a specific message; the playground shows "Synthesizing...", then a size and cached/generated tag, or an error.++## Related++- [Voice and lipsync tutorial](./tutorials/voice-and-lipsync.md): the authoritative step-by-step, including wiring a cloned voice into an agent.+- [Lipsync](./lipsync.md): how synthesized speech drives an avatar's mouth in real time.+- [Talking Avatar Video](./talking-avatar-video.md): render a talking-head clip from an avatar and an audio track.+- Pages: [/voice](https://three.ws/voice), [/dashboard](https://three.ws/dashboard).diff --git a/docs/x402-studio.md b/docs/x402-studio.mdnew file mode 100644index 000000000..17bc435bb--- /dev/null+++ b/docs/x402-studio.md@@ -0,0 +1,102 @@+# x402 Studio: the Stripe of x402++x402 Studio is the merchant console for running a paid x402 business on three.ws. In one page you define products and pricing, point them at a payout wallet, add named agent wallets with spend caps, send and receive real USDC (addressed by `.sol` name or `@username`, not just raw base58), drag-and-drop a hosted storefront, generate an embeddable pay button for any site, add charity or round-up giving, and lock down CORS and security. Everything settles on-chain in USDC, Solana first.++Page: [/x402/studio](https://three.ws/x402/studio)++APIs: `/api/x402-merchant` (settings), `/api/x402-skus` (products), `/api/sns` (name resolution), `/api/x402/pay-by-name` (USDC send). See [x402: paid agent skills](./x402.md) for the underlying payment protocol.++## Why it exists++x402 turns any HTTP endpoint into a paid one: the server answers `402 Payment Required` with a manifest, the caller pays in USDC, and the call retries and settles. That primitive is powerful but low-level. Studio is the console on top of it, the difference between "you can hand-write a 402 challenge" and "you can run a storefront." A merchant configures once and gets hosted checkout links, a shareable storefront, a copy-paste pay button, revenue stats, and payouts to a wallet they control, without writing payment code. It is the seller-facing companion to the [x402 buyer client](./x402-buyer.md) and the [paid endpoint catalog](./x402-endpoints.md).++## How it works++The page (`public/x402/studio.js`) is a dependency-free vanilla-JS single-page app with seven hash-routed tabs: Overview, Products, Wallets, Storefront, Embed builder, Giving, and Security and API. Every request goes through a helper that sends the session cookie (`credentials: 'include'`). All USDC amounts use 6 decimals.++**Merchant settings** (`/api/x402-merchant`) is one row per user in `x402_merchant_settings`. A `GET` lazily creates it and returns your payout and agent wallets, default settlement network (`solana` by default, with `base` also allowed), branding, CORS allow-list, security caps, giving config, and storefront layout. It never returns the API key hash. A `PUT` validates against a Zod schema and upserts. `POST ?action=rotate-key` mints an `x402_live_...` key, stores only its SHA-256 hash and an 18-character prefix, and shows the secret once. A public `GET ?store=<handle>` returns a published storefront and its active products for `/store/<handle>`.++**Products** (`/api/x402-skus`) are hosted checkout links in `x402_skus`. A product carries a permanent slug, a paid target endpoint (which must itself return 402), a method, an optional request body, branding, and an optional display price. Creating one yields a shareable link at `/pay/c/<slug>` that opens the drop-in payment modal pre-wired to the target. Owner reads compute `paid_calls` and `gross_atomics` from settled calls; `GET ?id=<id>&stats=1` returns full revenue stats and the last 25 payments; `GET ?slug=<slug>` is the public checkout read.++**Payout and agent wallets.** The payout wallet (Solana, with an EVM/Base option) is where settled USDC lands. Agent wallets are named on-chain identities with a role of `payer` (auto-pays for services) or `payout` (receives), a chain, and independent per-call and daily caps stored as atomics. Up to 50 agent wallets are allowed.++**SNS name resolution** (`/api/sns`) resolves a `.sol` name (including subdomains like `nich.threews.sol`) to an address, and reverse-resolves an address to its primary `.sol`, via Bonfida's `@bonfida/spl-name-service` `resolve()` on Solana mainnet. It always answers 200 (`resolved: false` on a miss, not a 404) and caches results in-process (5 minutes positive, 60 seconds negative).++**Real USDC send** (`/api/x402/pay-by-name`) routes a payment by name across three namespaces in order: a raw base58 address, a `<name>.sol` resolved on-chain, or an `@username` mapped to that user's default agent's Solana address. Studio uses `mode: 'prep'`, which builds an unsigned SPL USDC transfer (mint `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`) with your Phantom wallet as fee payer and source, returns the base64 transaction for signing, and caps the amount at 10,000 USDC per call. This send path is Solana-only (Phantom plus SPL USDC); Base is supported as a payout, agent, or charity destination, not in the send tool.++**Storefront builder.** A palette of eight blocks (hero, product grid, single product, text, image, button, divider, footer) drops onto a canvas with HTML5 drag-and-drop and reorder. Save keeps it a draft; Publish sets `store_published` and serves it at `/store/<handle>`. Layout is capped at 60 blocks.++**Embed builder.** Pick a product, a label, a size, a shape, and a theme, and it generates a working pay button. The generated snippet loads the x402 runtime and a `data-x402-*` attributed button:++```html+<!-- x402 pay button, powered by three.ws -->+<script type="module" src="https://three.ws/x402.js"></script>+<button+ data-x402-endpoint="https://your-api.example.com/paid"+ data-x402-method="GET"+ data-x402-merchant="<merchant-id>"+ data-x402-action="Summarize article"+ style="...">Pay · Summarize article</button>+```++The `type="module"` on the script is load-bearing: `/x402.js` uses `import.meta.url`, which throws in a classic script.++**Giving.** A charity split donates a fixed share of every settled payment to a cause wallet, stored as `charity_bps` (percent times 100, 0 to 10000). Round-up rounds the buyer's total up to the nearest unit (1, 0.5, 0.25, 0.1, or 5 USDC) and sends the difference to the same cause wallet. Round-up requires a charity address first, and the server enforces that the charity address matches its declared chain.++**Security and CORS.** Max per-call and per-day USDC caps, an optional Sign-In-With-X requirement, settlement-network selection, and a CORS allow-list (one origin per line, `https://host[:port]`, up to 50; empty means three.ws-hosted pages only). The developer section holds an optional facilitator URL, a settlement webhook, and the rotatable API key.++## Walkthrough++1. Open [/x402/studio](https://three.ws/x402/studio). Signed out, it shows a sign-in card linking `/login?next=/x402/studio`.+2. On **Wallets**, set your Solana payout address (use the Resolve `.sol` button to paste a name instead of an address). This is where settled USDC lands.+3. On **Products**, create a product: name it, give it a slug, point it at your paid endpoint that returns 402, and save. Copy its `/pay/c/<slug>` link.+4. On **Embed builder**, pick that product, style the button, and copy the snippet into any site.+5. Optionally publish a **Storefront** at `/store/<handle>`, add **Giving**, and tighten **Security and API** (caps, CORS, an API key).+6. To pay someone, use the send tool: enter a `.sol` name or address and an amount, and approve the transfer in Phantom.++## Examples++```bash+# Resolve a .sol name (or @username) to a Solana address (public, no auth)+curl 'https://three.ws/api/sns?name=nich.threews.sol'++# Read a public storefront and its active products+curl 'https://three.ws/api/x402-merchant?store=<handle>'++# Read a public checkout SKU (what /pay/c/<slug> loads)+curl 'https://three.ws/api/x402-skus?slug=<slug>'+```++```javascript+// Build an unsigned USDC transfer addressed by name (mode: 'prep')+const res = await fetch('https://three.ws/api/x402/pay-by-name', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({+ name: 'nich.threews.sol',+ amount_usdc: 5,+ mode: 'prep',+ payer_wallet: '<YOUR_SOLANA_ADDRESS>',+ }),+});+const { tx_base64, blockhash } = await res.json();+// Deserialize tx_base64, sign with Phantom, and send. Amount is capped at 10,000 USDC per call.+```++## States and limits++- **Auth.** The console requires a session; every mutating endpoint is owner-scoped (401 unauthenticated, 403 for another user's resource) and rate-limited. Public reads (storefront, checkout SKU, SNS resolve) need no auth.+- **Spend confirmation.** A USDC send always requires explicit Phantom approval, is capped at 10,000 USDC per call server-side, and rejects a self-pay. Agent-signed sends additionally enforce the agent's per-transaction and daily caps and re-check the recipient against fresh resolution (409 `recipient_changed`) to defend against name-poisoning. Archiving a product, removing an agent wallet, and rotating the API key each require an explicit confirm.+- **Validation.** Solana addresses base58 32-44, EVM `0x` plus 40 hex, slugs lowercase and hyphenated 3-64, publishing requires a globally unique handle (409 `handle_taken`), and CORS origins must be `https?://` origins.+- **Empty states.** Dedicated empties for no products, no agent wallets, nothing to embed, and an empty storefront canvas, plus a retry card on a fatal boot error.+- **Networks.** SNS and the send tool are Solana mainnet only. Settlement supports Solana and Base; the default is Solana.++## Related++- [x402: paid agent skills](./x402.md): the payment protocol Studio sits on top of+- [x402 revenue and receipts](./x402-revenue.md): where settled payments are recorded+- [x402 paid endpoints](./x402-endpoints.md): the platform's own catalog of paid endpoints+- [x402 buyer client](./x402-buyer.md): the caller side of a 402 challenge+- [x402 developer tools](./x402-dev-tools.md) and [x402 distribution](./x402-distribution.md)+- Pages: [/x402/studio](https://three.ws/x402/studio) · [/x402](https://three.ws/x402)diff --git a/public/changelog.json b/public/changelog.jsonindex 8d96faaf5..1d2cdffc0 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,11 +1,381 @@{- "generated_at": "2026-07-18T00:31:02.467Z",+ "generated_at": "2026-07-18T00:40:02.697Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws","url": "https://three.ws"},"entries": [+ {+ "date": "2026-07-18",+ "type": "launch",+ "title": "Docs · Agent Galaxy",+ "summary": "Every published agent embedded by IBM Granite on watsonx.ai, projected into a navigable 3D constellation with natural-language semantic search.",+ "link": "/docs/galaxy",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-18",+ "type": "launch",+ "title": "Docs · Agent Genome",+ "summary": "Breed two agents into a provably-inherited child: recombined brain, voice, body, and on-chain skill licenses, each breeding event seed-recorded with a verifiable family tree.",+ "link": "/docs/genome",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-18",+ "type": "launch",+ "title": "Docs · Agent Studio",+ "summary": "Author an agent's brain, memory, body, money, and skills in one place, beside a persistent live 3D avatar that updates everywhere as you edit.",+ "link": "/docs/agent-studio",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-18",+ "type": "launch",+ "title": "Docs · Alpha Co-pilot",+ "summary": "Your 3D agent reads a real pump.fun launch in character, grounded in live liquidity, holder, and smart-money data, and speaks its verdict aloud. Fabricated figures are rejected; the owner acts only within server-enforced spend limits.",+ "link": "/docs/alpha-copilot",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-18",+ "type": "launch",+ "title": "Docs · Animation Studio",+ "summary": "Pose any avatar or the built-in mannequin with FK/IK, keyframe a timeline, preview live, and export an animated GLB or clip JSON. Save clips to your account and list them for sale in USDC.",+ "link": "/docs/animation-studio",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-18",+ "type": "launch",+ "title": "Docs · AR Studio",+ "summary": "Place any number of 3D models and avatars into one live camera scene: model sources, the WebXR/passthrough/desktop rendering ladder, gestures, shared live rooms, and shareable arrangements.",+ "link": "/docs/ar-studio",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-18",+ "type": "launch",+ "title": "Docs · Avatar Studio",+ "summary": "Build a rigged 3D avatar from scratch with no selfie: choose a base body, sculpt face and body morphs, add outfits and accessories, and export a GLB.",+ "link": "/docs/avatar-studio",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-18",+ "type": "launch",+ "title": "Docs · Coin Autopilot",+ "summary": "A hands-off token cockpit: set buyback-and-burn and holder-distribution rules with USDC floors and guardrails, and let your agent run the coin autonomously.",+ "link": "/docs/autopilot",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-18",+ "type": "launch",+ "title": "Docs · Coin Clash",+ "summary": "Token-gated community warfare: every coin community is an army. Hold the coin, enlist, and rally for your faction in timed on-chain battles.",+ "link": "/docs/clash",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-18",+ "type": "launch",+ "title": "Docs · Coin Radar",+ "summary": "Live pump.fun launch intelligence: every new coin scored in its first 90 seconds for bundle vs organic, wallet concentration, dev behaviour, and risk flags.",+ "link": "/docs/radar",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-18",+ "type": "launch",+ "title": "Docs · Cosmos (living worlds)",+ "summary": "How NVIDIA Cosmos renders a photoreal video world behind a transparent 3D avatar: the async generation job, preview and download, and the designed fallback.",+ "link": "/docs/cosmos",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-18",+ "type": "launch",+ "title": "Docs · Daily Forge",+ "summary": "A new 3D creative challenge every day: a deterministic theme, the free no-signup forge lane, a localStorage streak with milestones, a community strip, and an AR handoff.",+ "link": "/docs/daily-forge",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-18",+ "type": "launch",+ "title": "Docs · Diorama (text to world)",+ "summary": "How one sentence becomes an explorable 3D diorama: an LLM composes a placed scene, each object is forged to a real GLB and assembled live, then saved to a public gallery permalink, exported to Scene Studio, or taken into AR.",+ "link": "/docs/diorama",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-18",+ "type": "launch",+ "title": "Docs · Fact Check",+ "summary": "Sourced fact-checking with cryptographic content attestations, a published accuracy benchmark, and a free daily quota then pay-per-check via x402.",+ "link": "/docs/fact-check",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-18",+ "type": "launch",+ "title": "Docs · Forge (text & image to 3D)",+ "summary": "How the Forge turns a text prompt, photos, or a sketch into a downloadable textured 3D model (GLB): the free-first engine grid with live health status, input modes, output formats, job resume, and background generation.",+ "link": "/docs/forge",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-18",+ "type": "launch",+ "title": "Docs · Guardian console",+ "summary": "Recover and inherit agent wallets through a threshold-approved, time-locked process that never exposes a private key.",+ "link": "/docs/guardian",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-18",+ "type": "launch",+ "title": "Docs · Image to 3D",+ "summary": "Turn 1 to 4 photos of an object into a textured GLB on the free self-hosted reconstruction lane. When to use it versus Selfie to Avatar for faces, the multi-view flow, and the API.",+ "link": "/docs/image-to-3d",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-18",+ "type": "launch",+ "title": "Docs · Instant Agent Genesis",+ "summary": "A prompt or a selfie becomes a rigged 3D AI agent with its own custodial Solana and EVM wallets and an optional on-chain identity, in under a minute.",+ "link": "/docs/genesis",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-18",+ "type": "launch",+ "title": "Docs · Integrations",+ "summary": "The catalog of one-script-tag embeds for any site: 3D avatar viewers, chat agents, walk companions, page narrators, live token widgets, and the MCP server.",+ "link": "/docs/integrations",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-18",+ "type": "launch",+ "title": "Docs · Lipsync",+ "summary": "Two in-browser lipsync demos: TTS-driven mouth animation and live-mic viseme detection, both driving an avatar's viseme morph targets in real time.",+ "link": "/docs/lipsync",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-18",+ "type": "launch",+ "title": "Docs · Mission Control",+ "summary": "The keyboard-first pump.fun trading terminal: the launch firehose fused with intel scores, firewall verdicts, and smart-money flow, streaming positions with live PnL, and one-keystroke guarded trading.",+ "link": "/docs/terminal",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-18",+ "type": "launch",+ "title": "Docs · Mocap Studio",+ "summary": "Drive a 3D avatar's face live from your webcam in the browser: MediaPipe face landmarks mapped to ARKit blendshapes, smoothing, record and replay, and save.",+ "link": "/docs/mocap-studio",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-18",+ "type": "launch",+ "title": "Docs · Multi-LLM Brain",+ "summary": "Send one prompt to Claude, GPT, Qwen, ModelScope, Groq and more at once, with side-by-side streaming and per-model latency and token stats.",+ "link": "/docs/brain",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-18",+ "type": "launch",+ "title": "Docs · Restyle Studio",+ "summary": "Re-skin any GLB without regenerating its mesh: 14 PBR material presets, plain-language AI restyle, seeded colorway variants, live metalness and roughness, and a durable revertable version lineage.",+ "link": "/docs/restyle",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-18",+ "type": "launch",+ "title": "Docs · Scene Capture (video to point cloud)",+ "summary": "Turn a phone video of any space into an explorable coloured 3D point cloud with feed-forward reconstruction, tunable sampling parameters, and live WebGL rendering.",+ "link": "/docs/capture",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-18",+ "type": "launch",+ "title": "Docs · Scene Composer",+ "summary": "Forge props from text, attach them to your avatar's skeleton bones, arrange and scale freely, then export a GLB or save the result as a reusable outfit.",+ "link": "/docs/compose",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-18",+ "type": "launch",+ "title": "Docs · Scene Studio",+ "summary": "The in-browser three.js editor: import GLBs, arrange with transform gizmos, edit materials and lights, script, and export complete glTF scenes.",+ "link": "/docs/scene-studio",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-18",+ "type": "launch",+ "title": "Docs · Selfie to Avatar",+ "summary": "Point your camera at your face and get a rigged 3D avatar in about a minute, free and in the browser. The capture flow, the reconstruction pipeline, and where the avatar goes next.",+ "link": "/docs/selfie-to-avatar",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-18",+ "type": "launch",+ "title": "Docs · Signal Marketplace",+ "summary": "Verified traders publish live entry and exit signals as x402-metered feeds ranked by proven on-chain accuracy; a subscriber agent pays per signal or epoch and auto-mirrors through the guarded path.",+ "link": "/docs/signals",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-18",+ "type": "launch",+ "title": "Docs · Smart Money Radar",+ "summary": "A live first-party reputation graph of every pump.fun wallet: cross each coin's buyers with the coins that actually graduated to surface the wallets that keep picking winners.",+ "link": "/docs/smart-money",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-18",+ "type": "launch",+ "title": "Docs · Splat viewer (Gaussian avatars)",+ "summary": "Render photoreal Gaussian-splat and radiance-field avatars in the browser: supported formats (.ply, .splat, .ksplat), client-side decoding, and the engines whose output it displays.",+ "link": "/docs/splat",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-18",+ "type": "launch",+ "title": "Docs · Strategy Objects",+ "summary": "Ownable, forkable, leaderboard-ranked trade strategies your agent can equip and run on-chain within your spend policy, plus the Strategy Lab for validation and backtesting.",+ "link": "/docs/strategy-objects",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-18",+ "type": "launch",+ "title": "Docs · Talking Avatar Video",+ "summary": "Pick an avatar, provide an audio track, and render a downloadable lip-synced talking-head MP4 on a server-side worker.",+ "link": "/docs/talking-avatar-video",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-18",+ "type": "launch",+ "title": "Docs · The AGI",+ "summary": "One autonomous agent that is superhuman at exactly one thing, trading memecoins on pump.fun, and nothing else. Its embodied 3D body, its logged decisions with stated confidence, and its chain-proven record.",+ "link": "/docs/agi",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-18",+ "type": "launch",+ "title": "Docs · Voice Lab",+ "summary": "Clone your voice from a short browser recording, play it in the TTS playground, and assign it to an agent.",+ "link": "/docs/voice-lab",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-18",+ "type": "launch",+ "title": "Docs · x402 Studio",+ "summary": "The merchant console for running a paid x402 business: products and pricing, payout and agent wallets, real USDC send and receive with .sol resolution, a storefront and pay-button builder, giving, and security.",+ "link": "/docs/x402-studio",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-07-18",+ "type": "update",+ "title": "36 new in-depth feature guides in the docs",+ "summary": "The docs now carry a dedicated, in-depth guide for every major studio and surface that was missing one: the 3D creation studios (Forge, Image to 3D, Diorama, Cosmos, Splat viewer, Scene Capture, Restyle, Scene Studio, Scene Composer, Animation Studio, Avatar Studio, Mocap Studio, Selfie to Avatar, Daily Forge, AR Studio), voice and video (Voice Lab, Lipsync, Talking Avatar Video), agent building (Instant Agent Genesis, Agent Genome, Agent Studio, Multi-LLM Brain, Agent Galaxy, Integrations), and the trading and markets surfaces (Coin Autopilot, Signal Marketplace, the AGI, Alpha Co-pilot, Guardian, Strategy Objects, Mission Control, Smart Money Radar, Coin Radar, Coin Clash, x402 Studio, Fact Check). Each guide explains why the feature exists, how it actually works, a first-time walkthrough, runnable examples, its states and limits, and links to related surfaces. Browse them from the docs sidebar.",+ "link": "/docs/forge",+ "tags": [+ "docs"+ ]+ },{"date": "2026-07-18","type": "update",@@ -17,6 +387,17 @@"improvement"]},+ {+ "date": "2026-07-18",+ "type": "update",+ "title": "On-chain reads stay smooth when a data provider hits its daily cap",+ "summary": "The platform reads Solana through a prioritized chain of RPC providers and automatically fails over the instant one is throttled. It now recognizes the specific 'daily request limit reached' signal that metered providers return when a plan's daily quota is spent, and parks that provider for the rest of the day instead of re-checking it every few minutes. On-chain data (balances, prices, live trades) keeps flowing through a healthy provider without a stumble, and the failover leaves the retry chatter behind. A dedicated reserve endpoint was also wired in as deep insurance for the rare case the whole free provider pool is down at once.",+ "link": null,+ "tags": [+ "infra",+ "improvement"+ ]+ },{"date": "2026-07-18","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 4c40e4766..1ffdf50a5 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -6,6 +6,302 @@<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/><description>What's new on three.ws — features, improvements, and releases, newest first.</description><language>en</language>+ <item>+ <title>Docs · Agent Galaxy</title>+ <link>https://three.ws/docs/galaxy</link>+ <guid isPermaLink="false">2026-07-18:Docs · Agent Galaxy</guid>+ <pubDate>Sat, 18 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Every published agent embedded by IBM Granite on watsonx.ai, projected into a navigable 3D constellation with natural-language semantic search.</description>+ </item>+ <item>+ <title>Docs · Agent Genome</title>+ <link>https://three.ws/docs/genome</link>+ <guid isPermaLink="false">2026-07-18:Docs · Agent Genome</guid>+ <pubDate>Sat, 18 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Breed two agents into a provably-inherited child: recombined brain, voice, body, and on-chain skill licenses, each breeding event seed-recorded with a verifiable family tree.</description>+ </item>+ <item>+ <title>Docs · Agent Studio</title>+ <link>https://three.ws/docs/agent-studio</link>+ <guid isPermaLink="false">2026-07-18:Docs · Agent Studio</guid>+ <pubDate>Sat, 18 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Author an agent's brain, memory, body, money, and skills in one place, beside a persistent live 3D avatar that updates everywhere as you edit.</description>+ </item>+ <item>+ <title>Docs · Alpha Co-pilot</title>+ <link>https://three.ws/docs/alpha-copilot</link>+ <guid isPermaLink="false">2026-07-18:Docs · Alpha Co-pilot</guid>+ <pubDate>Sat, 18 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Your 3D agent reads a real pump.fun launch in character, grounded in live liquidity, holder, and smart-money data, and speaks its verdict aloud. Fabricated figures are rejected; the owner acts only within server-enforced spend limits.</description>+ </item>+ <item>+ <title>Docs · Animation Studio</title>+ <link>https://three.ws/docs/animation-studio</link>+ <guid isPermaLink="false">2026-07-18:Docs · Animation Studio</guid>+ <pubDate>Sat, 18 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Pose any avatar or the built-in mannequin with FK/IK, keyframe a timeline, preview live, and export an animated GLB or clip JSON. Save clips to your account and list them for sale in USDC.</description>+ </item>+ <item>+ <title>Docs · AR Studio</title>+ <link>https://three.ws/docs/ar-studio</link>+ <guid isPermaLink="false">2026-07-18:Docs · AR Studio</guid>+ <pubDate>Sat, 18 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Place any number of 3D models and avatars into one live camera scene: model sources, the WebXR/passthrough/desktop rendering ladder, gestures, shared live rooms, and shareable arrangements.</description>+ </item>+ <item>+ <title>Docs · Avatar Studio</title>+ <link>https://three.ws/docs/avatar-studio</link>+ <guid isPermaLink="false">2026-07-18:Docs · Avatar Studio</guid>+ <pubDate>Sat, 18 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Build a rigged 3D avatar from scratch with no selfie: choose a base body, sculpt face and body morphs, add outfits and accessories, and export a GLB.</description>+ </item>+ <item>+ <title>Docs · Coin Autopilot</title>+ <link>https://three.ws/docs/autopilot</link>+ <guid isPermaLink="false">2026-07-18:Docs · Coin Autopilot</guid>+ <pubDate>Sat, 18 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>A hands-off token cockpit: set buyback-and-burn and holder-distribution rules with USDC floors and guardrails, and let your agent run the coin autonomously.</description>+ </item>+ <item>+ <title>Docs · Coin Clash</title>+ <link>https://three.ws/docs/clash</link>+ <guid isPermaLink="false">2026-07-18:Docs · Coin Clash</guid>+ <pubDate>Sat, 18 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Token-gated community warfare: every coin community is an army. Hold the coin, enlist, and rally for your faction in timed on-chain battles.</description>+ </item>+ <item>+ <title>Docs · Coin Radar</title>+ <link>https://three.ws/docs/radar</link>+ <guid isPermaLink="false">2026-07-18:Docs · Coin Radar</guid>+ <pubDate>Sat, 18 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Live pump.fun launch intelligence: every new coin scored in its first 90 seconds for bundle vs organic, wallet concentration, dev behaviour, and risk flags.</description>+ </item>+ <item>+ <title>Docs · Cosmos (living worlds)</title>+ <link>https://three.ws/docs/cosmos</link>+ <guid isPermaLink="false">2026-07-18:Docs · Cosmos (living worlds)</guid>+ <pubDate>Sat, 18 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>How NVIDIA Cosmos renders a photoreal video world behind a transparent 3D avatar: the async generation job, preview and download, and the designed fallback.</description>+ </item>+ <item>+ <title>Docs · Daily Forge</title>+ <link>https://three.ws/docs/daily-forge</link>+ <guid isPermaLink="false">2026-07-18:Docs · Daily Forge</guid>+ <pubDate>Sat, 18 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>A new 3D creative challenge every day: a deterministic theme, the free no-signup forge lane, a localStorage streak with milestones, a community strip, and an AR handoff.</description>+ </item>+ <item>+ <title>Docs · Diorama (text to world)</title>+ <link>https://three.ws/docs/diorama</link>+ <guid isPermaLink="false">2026-07-18:Docs · Diorama (text to world)</guid>+ <pubDate>Sat, 18 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>How one sentence becomes an explorable 3D diorama: an LLM composes a placed scene, each object is forged to a real GLB and assembled live, then saved to a public gallery permalink, exported to Scene Studio, or taken into AR.</description>+ </item>+ <item>+ <title>Docs · Fact Check</title>+ <link>https://three.ws/docs/fact-check</link>+ <guid isPermaLink="false">2026-07-18:Docs · Fact Check</guid>+ <pubDate>Sat, 18 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Sourced fact-checking with cryptographic content attestations, a published accuracy benchmark, and a free daily quota then pay-per-check via x402.</description>+ </item>+ <item>+ <title>Docs · Forge (text & image to 3D)</title>+ <link>https://three.ws/docs/forge</link>+ <guid isPermaLink="false">2026-07-18:Docs · Forge (text & image to 3D)</guid>+ <pubDate>Sat, 18 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>How the Forge turns a text prompt, photos, or a sketch into a downloadable textured 3D model (GLB): the free-first engine grid with live health status, input modes, output formats, job resume, and background generation.</description>+ </item>+ <item>+ <title>Docs · Guardian console</title>+ <link>https://three.ws/docs/guardian</link>+ <guid isPermaLink="false">2026-07-18:Docs · Guardian console</guid>+ <pubDate>Sat, 18 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Recover and inherit agent wallets through a threshold-approved, time-locked process that never exposes a private key.</description>+ </item>+ <item>+ <title>Docs · Image to 3D</title>+ <link>https://three.ws/docs/image-to-3d</link>+ <guid isPermaLink="false">2026-07-18:Docs · Image to 3D</guid>+ <pubDate>Sat, 18 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Turn 1 to 4 photos of an object into a textured GLB on the free self-hosted reconstruction lane. When to use it versus Selfie to Avatar for faces, the multi-view flow, and the API.</description>+ </item>+ <item>+ <title>Docs · Instant Agent Genesis</title>+ <link>https://three.ws/docs/genesis</link>+ <guid isPermaLink="false">2026-07-18:Docs · Instant Agent Genesis</guid>+ <pubDate>Sat, 18 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>A prompt or a selfie becomes a rigged 3D AI agent with its own custodial Solana and EVM wallets and an optional on-chain identity, in under a minute.</description>+ </item>+ <item>+ <title>Docs · Integrations</title>+ <link>https://three.ws/docs/integrations</link>+ <guid isPermaLink="false">2026-07-18:Docs · Integrations</guid>+ <pubDate>Sat, 18 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>The catalog of one-script-tag embeds for any site: 3D avatar viewers, chat agents, walk companions, page narrators, live token widgets, and the MCP server.</description>+ </item>+ <item>+ <title>Docs · Lipsync</title>+ <link>https://three.ws/docs/lipsync</link>+ <guid isPermaLink="false">2026-07-18:Docs · Lipsync</guid>+ <pubDate>Sat, 18 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Two in-browser lipsync demos: TTS-driven mouth animation and live-mic viseme detection, both driving an avatar's viseme morph targets in real time.</description>+ </item>+ <item>+ <title>Docs · Mission Control</title>+ <link>https://three.ws/docs/terminal</link>+ <guid isPermaLink="false">2026-07-18:Docs · Mission Control</guid>+ <pubDate>Sat, 18 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>The keyboard-first pump.fun trading terminal: the launch firehose fused with intel scores, firewall verdicts, and smart-money flow, streaming positions with live PnL, and one-keystroke guarded trading.</description>+ </item>+ <item>+ <title>Docs · Mocap Studio</title>+ <link>https://three.ws/docs/mocap-studio</link>+ <guid isPermaLink="false">2026-07-18:Docs · Mocap Studio</guid>+ <pubDate>Sat, 18 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Drive a 3D avatar's face live from your webcam in the browser: MediaPipe face landmarks mapped to ARKit blendshapes, smoothing, record and replay, and save.</description>+ </item>+ <item>+ <title>Docs · Multi-LLM Brain</title>+ <link>https://three.ws/docs/brain</link>+ <guid isPermaLink="false">2026-07-18:Docs · Multi-LLM Brain</guid>+ <pubDate>Sat, 18 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Send one prompt to Claude, GPT, Qwen, ModelScope, Groq and more at once, with side-by-side streaming and per-model latency and token stats.</description>+ </item>+ <item>+ <title>Docs · Restyle Studio</title>+ <link>https://three.ws/docs/restyle</link>+ <guid isPermaLink="false">2026-07-18:Docs · Restyle Studio</guid>+ <pubDate>Sat, 18 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Re-skin any GLB without regenerating its mesh: 14 PBR material presets, plain-language AI restyle, seeded colorway variants, live metalness and roughness, and a durable revertable version lineage.</description>+ </item>+ <item>+ <title>Docs · Scene Capture (video to point cloud)</title>+ <link>https://three.ws/docs/capture</link>+ <guid isPermaLink="false">2026-07-18:Docs · Scene Capture (video to point cloud)</guid>+ <pubDate>Sat, 18 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Turn a phone video of any space into an explorable coloured 3D point cloud with feed-forward reconstruction, tunable sampling parameters, and live WebGL rendering.</description>+ </item>+ <item>+ <title>Docs · Scene Composer</title>+ <link>https://three.ws/docs/compose</link>+ <guid isPermaLink="false">2026-07-18:Docs · Scene Composer</guid>+ <pubDate>Sat, 18 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Forge props from text, attach them to your avatar's skeleton bones, arrange and scale freely, then export a GLB or save the result as a reusable outfit.</description>+ </item>+ <item>+ <title>Docs · Scene Studio</title>+ <link>https://three.ws/docs/scene-studio</link>+ <guid isPermaLink="false">2026-07-18:Docs · Scene Studio</guid>+ <pubDate>Sat, 18 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>The in-browser three.js editor: import GLBs, arrange with transform gizmos, edit materials and lights, script, and export complete glTF scenes.</description>+ </item>+ <item>+ <title>Docs · Selfie to Avatar</title>+ <link>https://three.ws/docs/selfie-to-avatar</link>+ <guid isPermaLink="false">2026-07-18:Docs · Selfie to Avatar</guid>+ <pubDate>Sat, 18 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Point your camera at your face and get a rigged 3D avatar in about a minute, free and in the browser. The capture flow, the reconstruction pipeline, and where the avatar goes next.</description>+ </item>+ <item>+ <title>Docs · Signal Marketplace</title>+ <link>https://three.ws/docs/signals</link>+ <guid isPermaLink="false">2026-07-18:Docs · Signal Marketplace</guid>+ <pubDate>Sat, 18 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Verified traders publish live entry and exit signals as x402-metered feeds ranked by proven on-chain accuracy; a subscriber agent pays per signal or epoch and auto-mirrors through the guarded path.</description>+ </item>+ <item>+ <title>Docs · Smart Money Radar</title>+ <link>https://three.ws/docs/smart-money</link>+ <guid isPermaLink="false">2026-07-18:Docs · Smart Money Radar</guid>+ <pubDate>Sat, 18 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>A live first-party reputation graph of every pump.fun wallet: cross each coin's buyers with the coins that actually graduated to surface the wallets that keep picking winners.</description>+ </item>+ <item>+ <title>Docs · Splat viewer (Gaussian avatars)</title>+ <link>https://three.ws/docs/splat</link>+ <guid isPermaLink="false">2026-07-18:Docs · Splat viewer (Gaussian avatars)</guid>+ <pubDate>Sat, 18 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Render photoreal Gaussian-splat and radiance-field avatars in the browser: supported formats (.ply, .splat, .ksplat), client-side decoding, and the engines whose output it displays.</description>+ </item>+ <item>+ <title>Docs · Strategy Objects</title>+ <link>https://three.ws/docs/strategy-objects</link>+ <guid isPermaLink="false">2026-07-18:Docs · Strategy Objects</guid>+ <pubDate>Sat, 18 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Ownable, forkable, leaderboard-ranked trade strategies your agent can equip and run on-chain within your spend policy, plus the Strategy Lab for validation and backtesting.</description>+ </item>+ <item>+ <title>Docs · Talking Avatar Video</title>+ <link>https://three.ws/docs/talking-avatar-video</link>+ <guid isPermaLink="false">2026-07-18:Docs · Talking Avatar Video</guid>+ <pubDate>Sat, 18 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Pick an avatar, provide an audio track, and render a downloadable lip-synced talking-head MP4 on a server-side worker.</description>+ </item>+ <item>+ <title>Docs · The AGI</title>+ <link>https://three.ws/docs/agi</link>+ <guid isPermaLink="false">2026-07-18:Docs · The AGI</guid>+ <pubDate>Sat, 18 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>One autonomous agent that is superhuman at exactly one thing, trading memecoins on pump.fun, and nothing else. Its embodied 3D body, its logged decisions with stated confidence, and its chain-proven record.</description>+ </item>+ <item>+ <title>Docs · Voice Lab</title>+ <link>https://three.ws/docs/voice-lab</link>+ <guid isPermaLink="false">2026-07-18:Docs · Voice Lab</guid>+ <pubDate>Sat, 18 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Clone your voice from a short browser recording, play it in the TTS playground, and assign it to an agent.</description>+ </item>+ <item>+ <title>Docs · x402 Studio</title>+ <link>https://three.ws/docs/x402-studio</link>+ <guid isPermaLink="false">2026-07-18:Docs · x402 Studio</guid>+ <pubDate>Sat, 18 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>The merchant console for running a paid x402 business: products and pricing, payout and agent wallets, real USDC send and receive with .sol resolution, a storefront and pay-button builder, giving, and security.</description>+ </item>+ <item>+ <title>36 new in-depth feature guides in the docs</title>+ <link>https://three.ws/docs/forge</link>+ <guid isPermaLink="false">2026-07-18:36 new in-depth feature guides in the docs</guid>+ <pubDate>Sat, 18 Jul 2026 12:00:00 GMT</pubDate>+ <category>docs</category>+ <description>The docs now carry a dedicated, in-depth guide for every major studio and surface that was missing one: the 3D creation studios (Forge, Image to 3D, Diorama, Cosmos, Splat viewer, Scene Capture, Restyle, Scene Studio, Scene Composer, Animation Studio, Avatar Studio, Mocap Studio, Selfie to Avatar, Daily Forge, AR Studio), voice and video (Voice Lab, Lipsync, Talking Avatar Video), agent building (Instant Agent Genesis, Agent Genome, Agent Studio, Multi-LLM Brain, Agent Galaxy, Integrations), and the trading and markets surfaces (Coin Autopilot, Signal Marketplace, the AGI, Alpha Co-pilot, Guardian, Strategy Objects, Mission Control, Smart Money Radar, Coin Radar, Coin Clash, x402 Studio, Fact Check). Each guide explains why the feature exists, how it actually works, a first-time walkthrough, runnable examples, its states and limits, and links to related surfaces. Browse them from the docs sidebar.</description>+ </item><item><title>Image understanding is more reliable across every image host</title><link>https://three.ws/pulse</link>@@ -14,6 +310,14 @@<category>fix</category><description>The vision endpoint (used to describe and check 3D renders and avatars) now fetches your image itself and hands it straight to the free model, instead of asking the model's server to go fetch the link. Some image hosts block that server-side fetch, which used to push the request onto a paid fallback and, when that fallback was unavailable, fail outright. Now the free lane serves the request regardless of how the image is hosted, so describe/critique calls stop returning errors on perfectly good images.</description></item>+ <item>+ <title>On-chain reads stay smooth when a data provider hits its daily cap</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-07-18:On-chain reads stay smooth when a data provider hits its daily cap</guid>+ <pubDate>Sat, 18 Jul 2026 12:00:00 GMT</pubDate>+ <category>infra</category>+ <description>The platform reads Solana through a prioritized chain of RPC providers and automatically fails over the instant one is throttled. It now recognizes the specific 'daily request limit reached' signal that metered providers return when a plan's daily quota is spent, and parks that provider for the rest of the day instead of re-checking it every few minutes. On-chain data (balances, prices, live trades) keeps flowing through a healthy provider without a stumble, and the failover leaves the retry chatter behind. A dedicated reserve endpoint was also wired in as deep insurance for the rare case the whole free provider pool is down at once.</description>+ </item><item><title>Solana price and trade reads now ride a dedicated premium connection</title><link>https://three.ws/pulse</link>diff --git a/public/features.json b/public/features.jsonindex c722e4ebe..d2b41f5ec 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-18T00:31:02.453Z",+ "generated_at": "2026-07-18T00:40:02.682Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",@@ -2457,6 +2457,366 @@"tags": [],"showcase": true},+ {+ "path": "/docs/forge",+ "title": "Docs · Forge (text & image to 3D)",+ "description": "How the Forge turns a text prompt, photos, or a sketch into a downloadable textured 3D model (GLB): the free-first engine grid with live health status, input modes, output formats, job resume, and background generation.",+ "added": "2026-07-18",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },+ {+ "path": "/docs/image-to-3d",+ "title": "Docs · Image to 3D",+ "description": "Turn 1 to 4 photos of an object into a textured GLB on the free self-hosted reconstruction lane. When to use it versus Selfie to Avatar for faces, the multi-view flow, and the API.",+ "added": "2026-07-18",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },+ {+ "path": "/docs/diorama",+ "title": "Docs · Diorama (text to world)",+ "description": "How one sentence becomes an explorable 3D diorama: an LLM composes a placed scene, each object is forged to a real GLB and assembled live, then saved to a public gallery permalink, exported to Scene Studio, or taken into AR.",+ "added": "2026-07-18",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },+ {+ "path": "/docs/cosmos",+ "title": "Docs · Cosmos (living worlds)",+ "description": "How NVIDIA Cosmos renders a photoreal video world behind a transparent 3D avatar: the async generation job, preview and download, and the designed fallback.",+ "added": "2026-07-18",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },+ {+ "path": "/docs/splat",+ "title": "Docs · Splat viewer (Gaussian avatars)",+ "description": "Render photoreal Gaussian-splat and radiance-field avatars in the browser: supported formats (.ply, .splat, .ksplat), client-side decoding, and the engines whose output it displays.",+ "added": "2026-07-18",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },+ {+ "path": "/docs/capture",+ "title": "Docs · Scene Capture (video to point cloud)",+ "description": "Turn a phone video of any space into an explorable coloured 3D point cloud with feed-forward reconstruction, tunable sampling parameters, and live WebGL rendering.",+ "added": "2026-07-18",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },+ {+ "path": "/docs/restyle",+ "title": "Docs · Restyle Studio",+ "description": "Re-skin any GLB without regenerating its mesh: 14 PBR material presets, plain-language AI restyle, seeded colorway variants, live metalness and roughness, and a durable revertable version lineage.",+ "added": "2026-07-18",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },+ {+ "path": "/docs/scene-studio",+ "title": "Docs · Scene Studio",+ "description": "The in-browser three.js editor: import GLBs, arrange with transform gizmos, edit materials and lights, script, and export complete glTF scenes.",+ "added": "2026-07-18",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },+ {+ "path": "/docs/compose",+ "title": "Docs · Scene Composer",+ "description": "Forge props from text, attach them to your avatar's skeleton bones, arrange and scale freely, then export a GLB or save the result as a reusable outfit.",+ "added": "2026-07-18",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },+ {+ "path": "/docs/animation-studio",+ "title": "Docs · Animation Studio",+ "description": "Pose any avatar or the built-in mannequin with FK/IK, keyframe a timeline, preview live, and export an animated GLB or clip JSON. Save clips to your account and list them for sale in USDC.",+ "added": "2026-07-18",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },+ {+ "path": "/docs/avatar-studio",+ "title": "Docs · Avatar Studio",+ "description": "Build a rigged 3D avatar from scratch with no selfie: choose a base body, sculpt face and body morphs, add outfits and accessories, and export a GLB.",+ "added": "2026-07-18",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },+ {+ "path": "/docs/mocap-studio",+ "title": "Docs · Mocap Studio",+ "description": "Drive a 3D avatar's face live from your webcam in the browser: MediaPipe face landmarks mapped to ARKit blendshapes, smoothing, record and replay, and save.",+ "added": "2026-07-18",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },+ {+ "path": "/docs/selfie-to-avatar",+ "title": "Docs · Selfie to Avatar",+ "description": "Point your camera at your face and get a rigged 3D avatar in about a minute, free and in the browser. The capture flow, the reconstruction pipeline, and where the avatar goes next.",+ "added": "2026-07-18",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },+ {+ "path": "/docs/voice-lab",+ "title": "Docs · Voice Lab",+ "description": "Clone your voice from a short browser recording, play it in the TTS playground, and assign it to an agent.",+ "added": "2026-07-18",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },+ {+ "path": "/docs/lipsync",+ "title": "Docs · Lipsync",+ "description": "Two in-browser lipsync demos: TTS-driven mouth animation and live-mic viseme detection, both driving an avatar's viseme morph targets in real time.",+ "added": "2026-07-18",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },+ {+ "path": "/docs/talking-avatar-video",+ "title": "Docs · Talking Avatar Video",+ "description": "Pick an avatar, provide an audio track, and render a downloadable lip-synced talking-head MP4 on a server-side worker.",+ "added": "2026-07-18",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },+ {+ "path": "/docs/galaxy",+ "title": "Docs · Agent Galaxy",+ "description": "Every published agent embedded by IBM Granite on watsonx.ai, projected into a navigable 3D constellation with natural-language semantic search.",+ "added": "2026-07-18",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },+ {+ "path": "/docs/ar-studio",+ "title": "Docs · AR Studio",+ "description": "Place any number of 3D models and avatars into one live camera scene: model sources, the WebXR/passthrough/desktop rendering ladder, gestures, shared live rooms, and shareable arrangements.",+ "added": "2026-07-18",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },+ {+ "path": "/docs/genesis",+ "title": "Docs · Instant Agent Genesis",+ "description": "A prompt or a selfie becomes a rigged 3D AI agent with its own custodial Solana and EVM wallets and an optional on-chain identity, in under a minute.",+ "added": "2026-07-18",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },+ {+ "path": "/docs/genome",+ "title": "Docs · Agent Genome",+ "description": "Breed two agents into a provably-inherited child: recombined brain, voice, body, and on-chain skill licenses, each breeding event seed-recorded with a verifiable family tree.",+ "added": "2026-07-18",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },+ {+ "path": "/docs/agent-studio",+ "title": "Docs · Agent Studio",+ "description": "Author an agent's brain, memory, body, money, and skills in one place, beside a persistent live 3D avatar that updates everywhere as you edit.",+ "added": "2026-07-18",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },+ {+ "path": "/docs/brain",+ "title": "Docs · Multi-LLM Brain",+ "description": "Send one prompt to Claude, GPT, Qwen, ModelScope, Groq and more at once, with side-by-side streaming and per-model latency and token stats.",+ "added": "2026-07-18",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },+ {+ "path": "/docs/integrations",+ "title": "Docs · Integrations",+ "description": "The catalog of one-script-tag embeds for any site: 3D avatar viewers, chat agents, walk companions, page narrators, live token widgets, and the MCP server.",+ "added": "2026-07-18",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },+ {+ "path": "/docs/autopilot",+ "title": "Docs · Coin Autopilot",+ "description": "A hands-off token cockpit: set buyback-and-burn and holder-distribution rules with USDC floors and guardrails, and let your agent run the coin autonomously.",+ "added": "2026-07-18",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },+ {+ "path": "/docs/signals",+ "title": "Docs · Signal Marketplace",+ "description": "Verified traders publish live entry and exit signals as x402-metered feeds ranked by proven on-chain accuracy; a subscriber agent pays per signal or epoch and auto-mirrors through the guarded path.",+ "added": "2026-07-18",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },+ {+ "path": "/docs/agi",+ "title": "Docs · The AGI",+ "description": "One autonomous agent that is superhuman at exactly one thing, trading memecoins on pump.fun, and nothing else. Its embodied 3D body, its logged decisions with stated confidence, and its chain-proven record.",+ "added": "2026-07-18",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },+ {+ "path": "/docs/alpha-copilot",+ "title": "Docs · Alpha Co-pilot",+ "description": "Your 3D agent reads a real pump.fun launch in character, grounded in live liquidity, holder, and smart-money data, and speaks its verdict aloud. Fabricated figures are rejected; the owner acts only within server-enforced spend limits.",+ "added": "2026-07-18",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },+ {+ "path": "/docs/guardian",+ "title": "Docs · Guardian console",+ "description": "Recover and inherit agent wallets through a threshold-approved, time-locked process that never exposes a private key.",+ "added": "2026-07-18",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },+ {+ "path": "/docs/strategy-objects",+ "title": "Docs · Strategy Objects",+ "description": "Ownable, forkable, leaderboard-ranked trade strategies your agent can equip and run on-chain within your spend policy, plus the Strategy Lab for validation and backtesting.",+ "added": "2026-07-18",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },+ {+ "path": "/docs/terminal",+ "title": "Docs · Mission Control",+ "description": "The keyboard-first pump.fun trading terminal: the launch firehose fused with intel scores, firewall verdicts, and smart-money flow, streaming positions with live PnL, and one-keystroke guarded trading.",+ "added": "2026-07-18",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },+ {+ "path": "/docs/smart-money",+ "title": "Docs · Smart Money Radar",+ "description": "A live first-party reputation graph of every pump.fun wallet: cross each coin's buyers with the coins that actually graduated to surface the wallets that keep picking winners.",+ "added": "2026-07-18",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },+ {+ "path": "/docs/radar",+ "title": "Docs · Coin Radar",+ "description": "Live pump.fun launch intelligence: every new coin scored in its first 90 seconds for bundle vs organic, wallet concentration, dev behaviour, and risk flags.",+ "added": "2026-07-18",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },+ {+ "path": "/docs/clash",+ "title": "Docs · Coin Clash",+ "description": "Token-gated community warfare: every coin community is an army. Hold the coin, enlist, and rally for your faction in timed on-chain battles.",+ "added": "2026-07-18",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },+ {+ "path": "/docs/x402-studio",+ "title": "Docs · x402 Studio",+ "description": "The merchant console for running a paid x402 business: products and pricing, payout and agent wallets, real USDC send and receive with .sol resolution, a storefront and pay-button builder, giving, and security.",+ "added": "2026-07-18",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },+ {+ "path": "/docs/fact-check",+ "title": "Docs · Fact Check",+ "description": "Sourced fact-checking with cryptographic content attestations, a published accuracy benchmark, and a free daily quota then pay-per-check via x402.",+ "added": "2026-07-18",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },+ {+ "path": "/docs/daily-forge",+ "title": "Docs · Daily Forge",+ "description": "A new 3D creative challenge every day: a deterministic theme, the free no-signup forge lane, a localStorage streak with milestones, a community strip, and an AR handoff.",+ "added": "2026-07-18",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },{"path": "/docs/crypto-api","title": "Docs · Crypto Data API",diff --git a/public/llms-full.txt b/public/llms-full.txtindex d02cb9093..bb56b4953 100644--- a/public/llms-full.txt+++ b/public/llms-full.txt@@ -1504,6 +1504,222 @@ URL: https://three.ws/crypto-apiOne free, keyless API for on-chain and market data: DEX pairs, prices, swap quotes, TVL, Solana RPC reads, and ENS/SNS name resolution — CoinGecko, DefiLlama, Jupiter, DexScreener and Solana RPC bundled behind one bill. Live provider table rendered from the real registry, generated OpenAPI 3.1 spec, free tier then BYOK, plan, or x402 pay-per-call.+### Docs · Forge (text & image to 3D)++URL: https://three.ws/docs/forge++How the Forge turns a text prompt, photos, or a sketch into a downloadable textured 3D model (GLB): the free-first engine grid with live health status, input modes, output formats, job resume, and background generation.++### Docs · Image to 3D++URL: https://three.ws/docs/image-to-3d++Turn 1 to 4 photos of an object into a textured GLB on the free self-hosted reconstruction lane. When to use it versus Selfie to Avatar for faces, the multi-view flow, and the API.++### Docs · Diorama (text to world)++URL: https://three.ws/docs/diorama++How one sentence becomes an explorable 3D diorama: an LLM composes a placed scene, each object is forged to a real GLB and assembled live, then saved to a public gallery permalink, exported to Scene Studio, or taken into AR.++### Docs · Cosmos (living worlds)++URL: https://three.ws/docs/cosmos++How NVIDIA Cosmos renders a photoreal video world behind a transparent 3D avatar: the async generation job, preview and download, and the designed fallback.++### Docs · Splat viewer (Gaussian avatars)++URL: https://three.ws/docs/splat++Render photoreal Gaussian-splat and radiance-field avatars in the browser: supported formats (.ply, .splat, .ksplat), client-side decoding, and the engines whose output it displays.++### Docs · Scene Capture (video to point cloud)++URL: https://three.ws/docs/capture++Turn a phone video of any space into an explorable coloured 3D point cloud with feed-forward reconstruction, tunable sampling parameters, and live WebGL rendering.++### Docs · Restyle Studio++URL: https://three.ws/docs/restyle++Re-skin any GLB without regenerating its mesh: 14 PBR material presets, plain-language AI restyle, seeded colorway variants, live metalness and roughness, and a durable revertable version lineage.++### Docs · Scene Studio++URL: https://three.ws/docs/scene-studio++The in-browser three.js editor: import GLBs, arrange with transform gizmos, edit materials and lights, script, and export complete glTF scenes.++### Docs · Scene Composer++URL: https://three.ws/docs/compose++Forge props from text, attach them to your avatar's skeleton bones, arrange and scale freely, then export a GLB or save the result as a reusable outfit.++### Docs · Animation Studio++URL: https://three.ws/docs/animation-studio++Pose any avatar or the built-in mannequin with FK/IK, keyframe a timeline, preview live, and export an animated GLB or clip JSON. Save clips to your account and list them for sale in USDC.++### Docs · Avatar Studio++URL: https://three.ws/docs/avatar-studio++Build a rigged 3D avatar from scratch with no selfie: choose a base body, sculpt face and body morphs, add outfits and accessories, and export a GLB.++### Docs · Mocap Studio++URL: https://three.ws/docs/mocap-studio++Drive a 3D avatar's face live from your webcam in the browser: MediaPipe face landmarks mapped to ARKit blendshapes, smoothing, record and replay, and save.++### Docs · Selfie to Avatar++URL: https://three.ws/docs/selfie-to-avatar++Point your camera at your face and get a rigged 3D avatar in about a minute, free and in the browser. The capture flow, the reconstruction pipeline, and where the avatar goes next.++### Docs · Voice Lab++URL: https://three.ws/docs/voice-lab++Clone your voice from a short browser recording, play it in the TTS playground, and assign it to an agent.++### Docs · Lipsync++URL: https://three.ws/docs/lipsync++Two in-browser lipsync demos: TTS-driven mouth animation and live-mic viseme detection, both driving an avatar's viseme morph targets in real time.++### Docs · Talking Avatar Video++URL: https://three.ws/docs/talking-avatar-video++Pick an avatar, provide an audio track, and render a downloadable lip-synced talking-head MP4 on a server-side worker.++### Docs · Agent Galaxy++URL: https://three.ws/docs/galaxy++Every published agent embedded by IBM Granite on watsonx.ai, projected into a navigable 3D constellation with natural-language semantic search.++### Docs · AR Studio++URL: https://three.ws/docs/ar-studio++Place any number of 3D models and avatars into one live camera scene: model sources, the WebXR/passthrough/desktop rendering ladder, gestures, shared live rooms, and shareable arrangements.++### Docs · Instant Agent Genesis++URL: https://three.ws/docs/genesis++A prompt or a selfie becomes a rigged 3D AI agent with its own custodial Solana and EVM wallets and an optional on-chain identity, in under a minute.++### Docs · Agent Genome++URL: https://three.ws/docs/genome++Breed two agents into a provably-inherited child: recombined brain, voice, body, and on-chain skill licenses, each breeding event seed-recorded with a verifiable family tree.++### Docs · Agent Studio++URL: https://three.ws/docs/agent-studio++Author an agent's brain, memory, body, money, and skills in one place, beside a persistent live 3D avatar that updates everywhere as you edit.++### Docs · Multi-LLM Brain++URL: https://three.ws/docs/brain++Send one prompt to Claude, GPT, Qwen, ModelScope, Groq and more at once, with side-by-side streaming and per-model latency and token stats.++### Docs · Integrations++URL: https://three.ws/docs/integrations++The catalog of one-script-tag embeds for any site: 3D avatar viewers, chat agents, walk companions, page narrators, live token widgets, and the MCP server.++### Docs · Coin Autopilot++URL: https://three.ws/docs/autopilot++A hands-off token cockpit: set buyback-and-burn and holder-distribution rules with USDC floors and guardrails, and let your agent run the coin autonomously.++### Docs · Signal Marketplace++URL: https://three.ws/docs/signals++Verified traders publish live entry and exit signals as x402-metered feeds ranked by proven on-chain accuracy; a subscriber agent pays per signal or epoch and auto-mirrors through the guarded path.++### Docs · The AGI++URL: https://three.ws/docs/agi++One autonomous agent that is superhuman at exactly one thing, trading memecoins on pump.fun, and nothing else. Its embodied 3D body, its logged decisions with stated confidence, and its chain-proven record.++### Docs · Alpha Co-pilot++URL: https://three.ws/docs/alpha-copilot++Your 3D agent reads a real pump.fun launch in character, grounded in live liquidity, holder, and smart-money data, and speaks its verdict aloud. Fabricated figures are rejected; the owner acts only within server-enforced spend limits.++### Docs · Guardian console++URL: https://three.ws/docs/guardian++Recover and inherit agent wallets through a threshold-approved, time-locked process that never exposes a private key.++### Docs · Strategy Objects++URL: https://three.ws/docs/strategy-objects++Ownable, forkable, leaderboard-ranked trade strategies your agent can equip and run on-chain within your spend policy, plus the Strategy Lab for validation and backtesting.++### Docs · Mission Control++URL: https://three.ws/docs/terminal++The keyboard-first pump.fun trading terminal: the launch firehose fused with intel scores, firewall verdicts, and smart-money flow, streaming positions with live PnL, and one-keystroke guarded trading.++### Docs · Smart Money Radar++URL: https://three.ws/docs/smart-money++A live first-party reputation graph of every pump.fun wallet: cross each coin's buyers with the coins that actually graduated to surface the wallets that keep picking winners.++### Docs · Coin Radar++URL: https://three.ws/docs/radar++Live pump.fun launch intelligence: every new coin scored in its first 90 seconds for bundle vs organic, wallet concentration, dev behaviour, and risk flags.++### Docs · Coin Clash++URL: https://three.ws/docs/clash++Token-gated community warfare: every coin community is an army. Hold the coin, enlist, and rally for your faction in timed on-chain battles.++### Docs · x402 Studio++URL: https://three.ws/docs/x402-studio++The merchant console for running a paid x402 business: products and pricing, payout and agent wallets, real USDC send and receive with .sol resolution, a storefront and pay-button builder, giving, and security.++### Docs · Fact Check++URL: https://three.ws/docs/fact-check++Sourced fact-checking with cryptographic content attestations, a published accuracy benchmark, and a free daily quota then pay-per-check via x402.++### Docs · Daily Forge++URL: https://three.ws/docs/daily-forge++A new 3D creative challenge every day: a deterministic theme, the free no-signup forge lane, a localStorage streak with milestones, a community strip, and an AR handoff.+### Docs · Crypto Data APIURL: https://three.ws/docs/crypto-apidiff --git a/public/llms.txt b/public/llms.txtindex 1b049a6de..8d305d74c 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -267,6 +267,42 @@ Docs, tutorials, and reference.- [Crypto Data API](https://three.ws/crypto): Free, keyless crypto data for AI agents in one API: token snapshots, security/rug signals, holder concentration, live pump.fun launches, bonding-curve status, whale activity, trending tokens, wallet portfolios and ticker-availability checks. No key, no account, no paywall.- [3D API](https://three.ws/3d): Free, keyless 3D API for AI agents: turn a text prompt into a real GLB model and validate/optimize any glTF/GLB, all from one URL with a live OpenAPI 3.1 spec. Free draft generation and inspection graduate to paid Forge Pro quality tiers and animation-ready Rigged Avatars. No key, no account.- [Crypto API](https://three.ws/crypto-api): One free, keyless API for on-chain and market data: DEX pairs, prices, swap quotes, TVL, Solana RPC reads, and ENS/SNS name resolution — CoinGecko, DefiLlama, Jupiter, DexScreener and Solana RPC bundled behind one bill. Live provider table rendered from the real registry, generated OpenAPI 3.1 spec, free tier then BYOK, plan, or x402 pay-per-call.+- [Docs · Forge (text & image to 3D)](https://three.ws/docs/forge): How the Forge turns a text prompt, photos, or a sketch into a downloadable textured 3D model (GLB): the free-first engine grid with live health status, input modes, output formats, job resume, and background generation.+- [Docs · Image to 3D](https://three.ws/docs/image-to-3d): Turn 1 to 4 photos of an object into a textured GLB on the free self-hosted reconstruction lane. When to use it versus Selfie to Avatar for faces, the multi-view flow, and the API.+- [Docs · Diorama (text to world)](https://three.ws/docs/diorama): How one sentence becomes an explorable 3D diorama: an LLM composes a placed scene, each object is forged to a real GLB and assembled live, then saved to a public gallery permalink, exported to Scene Studio, or taken into AR.+- [Docs · Cosmos (living worlds)](https://three.ws/docs/cosmos): How NVIDIA Cosmos renders a photoreal video world behind a transparent 3D avatar: the async generation job, preview and download, and the designed fallback.+- [Docs · Splat viewer (Gaussian avatars)](https://three.ws/docs/splat): Render photoreal Gaussian-splat and radiance-field avatars in the browser: supported formats (.ply, .splat, .ksplat), client-side decoding, and the engines whose output it displays.+- [Docs · Scene Capture (video to point cloud)](https://three.ws/docs/capture): Turn a phone video of any space into an explorable coloured 3D point cloud with feed-forward reconstruction, tunable sampling parameters, and live WebGL rendering.+- [Docs · Restyle Studio](https://three.ws/docs/restyle): Re-skin any GLB without regenerating its mesh: 14 PBR material presets, plain-language AI restyle, seeded colorway variants, live metalness and roughness, and a durable revertable version lineage.+- [Docs · Scene Studio](https://three.ws/docs/scene-studio): The in-browser three.js editor: import GLBs, arrange with transform gizmos, edit materials and lights, script, and export complete glTF scenes.+- [Docs · Scene Composer](https://three.ws/docs/compose): Forge props from text, attach them to your avatar's skeleton bones, arrange and scale freely, then export a GLB or save the result as a reusable outfit.+- [Docs · Animation Studio](https://three.ws/docs/animation-studio): Pose any avatar or the built-in mannequin with FK/IK, keyframe a timeline, preview live, and export an animated GLB or clip JSON. Save clips to your account and list them for sale in USDC.+- [Docs · Avatar Studio](https://three.ws/docs/avatar-studio): Build a rigged 3D avatar from scratch with no selfie: choose a base body, sculpt face and body morphs, add outfits and accessories, and export a GLB.+- [Docs · Mocap Studio](https://three.ws/docs/mocap-studio): Drive a 3D avatar's face live from your webcam in the browser: MediaPipe face landmarks mapped to ARKit blendshapes, smoothing, record and replay, and save.+- [Docs · Selfie to Avatar](https://three.ws/docs/selfie-to-avatar): Point your camera at your face and get a rigged 3D avatar in about a minute, free and in the browser. The capture flow, the reconstruction pipeline, and where the avatar goes next.+- [Docs · Voice Lab](https://three.ws/docs/voice-lab): Clone your voice from a short browser recording, play it in the TTS playground, and assign it to an agent.+- [Docs · Lipsync](https://three.ws/docs/lipsync): Two in-browser lipsync demos: TTS-driven mouth animation and live-mic viseme detection, both driving an avatar's viseme morph targets in real time.+- [Docs · Talking Avatar Video](https://three.ws/docs/talking-avatar-video): Pick an avatar, provide an audio track, and render a downloadable lip-synced talking-head MP4 on a server-side worker.+- [Docs · Agent Galaxy](https://three.ws/docs/galaxy): Every published agent embedded by IBM Granite on watsonx.ai, projected into a navigable 3D constellation with natural-language semantic search.+- [Docs · AR Studio](https://three.ws/docs/ar-studio): Place any number of 3D models and avatars into one live camera scene: model sources, the WebXR/passthrough/desktop rendering ladder, gestures, shared live rooms, and shareable arrangements.+- [Docs · Instant Agent Genesis](https://three.ws/docs/genesis): A prompt or a selfie becomes a rigged 3D AI agent with its own custodial Solana and EVM wallets and an optional on-chain identity, in under a minute.+- [Docs · Agent Genome](https://three.ws/docs/genome): Breed two agents into a provably-inherited child: recombined brain, voice, body, and on-chain skill licenses, each breeding event seed-recorded with a verifiable family tree.+- [Docs · Agent Studio](https://three.ws/docs/agent-studio): Author an agent's brain, memory, body, money, and skills in one place, beside a persistent live 3D avatar that updates everywhere as you edit.+- [Docs · Multi-LLM Brain](https://three.ws/docs/brain): Send one prompt to Claude, GPT, Qwen, ModelScope, Groq and more at once, with side-by-side streaming and per-model latency and token stats.+- [Docs · Integrations](https://three.ws/docs/integrations): The catalog of one-script-tag embeds for any site: 3D avatar viewers, chat agents, walk companions, page narrators, live token widgets, and the MCP server.+- [Docs · Coin Autopilot](https://three.ws/docs/autopilot): A hands-off token cockpit: set buyback-and-burn and holder-distribution rules with USDC floors and guardrails, and let your agent run the coin autonomously.+- [Docs · Signal Marketplace](https://three.ws/docs/signals): Verified traders publish live entry and exit signals as x402-metered feeds ranked by proven on-chain accuracy; a subscriber agent pays per signal or epoch and auto-mirrors through the guarded path.+- [Docs · The AGI](https://three.ws/docs/agi): One autonomous agent that is superhuman at exactly one thing, trading memecoins on pump.fun, and nothing else. Its embodied 3D body, its logged decisions with stated confidence, and its chain-proven record.+- [Docs · Alpha Co-pilot](https://three.ws/docs/alpha-copilot): Your 3D agent reads a real pump.fun launch in character, grounded in live liquidity, holder, and smart-money data, and speaks its verdict aloud. Fabricated figures are rejected; the owner acts only within server-enforced spend limits.+- [Docs · Guardian console](https://three.ws/docs/guardian): Recover and inherit agent wallets through a threshold-approved, time-locked process that never exposes a private key.+- [Docs · Strategy Objects](https://three.ws/docs/strategy-objects): Ownable, forkable, leaderboard-ranked trade strategies your agent can equip and run on-chain within your spend policy, plus the Strategy Lab for validation and backtesting.+- [Docs · Mission Control](https://three.ws/docs/terminal): The keyboard-first pump.fun trading terminal: the launch firehose fused with intel scores, firewall verdicts, and smart-money flow, streaming positions with live PnL, and one-keystroke guarded trading.+- [Docs · Smart Money Radar](https://three.ws/docs/smart-money): A live first-party reputation graph of every pump.fun wallet: cross each coin's buyers with the coins that actually graduated to surface the wallets that keep picking winners.+- [Docs · Coin Radar](https://three.ws/docs/radar): Live pump.fun launch intelligence: every new coin scored in its first 90 seconds for bundle vs organic, wallet concentration, dev behaviour, and risk flags.+- [Docs · Coin Clash](https://three.ws/docs/clash): Token-gated community warfare: every coin community is an army. Hold the coin, enlist, and rally for your faction in timed on-chain battles.+- [Docs · x402 Studio](https://three.ws/docs/x402-studio): The merchant console for running a paid x402 business: products and pricing, payout and agent wallets, real USDC send and receive with .sol resolution, a storefront and pay-button builder, giving, and security.+- [Docs · Fact Check](https://three.ws/docs/fact-check): Sourced fact-checking with cryptographic content attestations, a published accuracy benchmark, and a free daily quota then pay-per-check via x402.+- [Docs · Daily Forge](https://three.ws/docs/daily-forge): A new 3D creative challenge every day: a deterministic theme, the free no-signup forge lane, a localStorage streak with milestones, a community strip, and an AR handoff.- [Docs · Crypto Data API](https://three.ws/docs/crypto-api): Developer reference for the free, keyless Crypto Data API bundle: the one-call discovery endpoint (GET /api/crypto), the generated OpenAPI 3.1 spec, and every endpoint's inputs, outputs, states, and curl examples — token snapshots, bonding status, whales, trending, wallet portfolios, and symbol availability.- [Docs · The autonomous economy](https://three.ws/docs/autonomous-economy): How the three.ws on-chain treasury funds itself and where every dollar flows: the funding-root and engine wallets, the topup/sweepback loop, the allowlist- and destination-locks that keep money inside platform-owned wallets, and the two leak scanners that audit every signer wallet on-chain every minute — plus how to verify there's no leak yourself.- [Docs · Walk Avatar](https://three.ws/docs/walk): Developer and user documentation for the three.ws walking-avatar system: the /walk page, iframe embeds, the JavaScript SDK, the postMessage event contract, companion mode, analytics, and the Chrome extension.diff --git a/public/sitemap/index.html b/public/sitemap/index.htmlindex c9f3a97f0..e67cbff6d 100644--- a/public/sitemap/index.html+++ b/public/sitemap/index.html@@ -58,7 +58,7 @@<main class="sm-wrap"><div class="sm-hero"><h1>Sitemap</h1>- <p>All 466 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>+ <p>All 502 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p><div class="sm-formats"><a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a><a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>@@ -70,7 +70,7 @@</div><div class="sm-filter"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>- <input id="sm-filter-input" type="search" placeholder="Filter 466 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />+ <input id="sm-filter-input" type="search" placeholder="Filter 502 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" /><kbd aria-hidden="true">/</kbd></div><p class="sm-filter-count" id="sm-filter-count" role="status" aria-live="polite"></p>@@ -1795,7 +1795,7 @@<section class="sm-section" id="learn"><header>- <h2>Learn<span class="sm-count" data-count>77</span></h2>+ <h2>Learn<span class="sm-count" data-count>113</span></h2><p class="sm-section-desc">Docs, tutorials, and reference.</p></header><ul class="sm-list">@@ -1827,6 +1827,258 @@<span class="sm-desc">One free, keyless API for on-chain and market data: DEX pairs, prices, swap quotes, TVL, Solana RPC reads, and ENS/SNS name resolution — CoinGecko, DefiLlama, Jupiter, DexScreener and Solana RPC bundled behind one bill. Live provider table rendered from the real registry, generated OpenAPI 3.1 spec, free tier then BYOK, plan, or x402 pay-per-call.</span></a></li>+ <li>+ <a href="/docs/forge">+ <span class="sm-title">Docs · Forge (text & image to 3D)</span>+ <span class="sm-path">/docs/forge</span>+ <span class="sm-desc">How the Forge turns a text prompt, photos, or a sketch into a downloadable textured 3D model (GLB): the free-first engine grid with live health status, input modes, output formats, job resume, and background generation.</span>+ </a>+ </li>+ <li>+ <a href="/docs/image-to-3d">+ <span class="sm-title">Docs · Image to 3D</span>+ <span class="sm-path">/docs/image-to-3d</span>+ <span class="sm-desc">Turn 1 to 4 photos of an object into a textured GLB on the free self-hosted reconstruction lane. When to use it versus Selfie to Avatar for faces, the multi-view flow, and the API.</span>+ </a>+ </li>+ <li>+ <a href="/docs/diorama">+ <span class="sm-title">Docs · Diorama (text to world)</span>+ <span class="sm-path">/docs/diorama</span>+ <span class="sm-desc">How one sentence becomes an explorable 3D diorama: an LLM composes a placed scene, each object is forged to a real GLB and assembled live, then saved to a public gallery permalink, exported to Scene Studio, or taken into AR.</span>+ </a>+ </li>+ <li>+ <a href="/docs/cosmos">+ <span class="sm-title">Docs · Cosmos (living worlds)</span>+ <span class="sm-path">/docs/cosmos</span>+ <span class="sm-desc">How NVIDIA Cosmos renders a photoreal video world behind a transparent 3D avatar: the async generation job, preview and download, and the designed fallback.</span>+ </a>+ </li>+ <li>+ <a href="/docs/splat">+ <span class="sm-title">Docs · Splat viewer (Gaussian avatars)</span>+ <span class="sm-path">/docs/splat</span>+ <span class="sm-desc">Render photoreal Gaussian-splat and radiance-field avatars in the browser: supported formats (.ply, .splat, .ksplat), client-side decoding, and the engines whose output it displays.</span>+ </a>+ </li>+ <li>+ <a href="/docs/capture">+ <span class="sm-title">Docs · Scene Capture (video to point cloud)</span>+ <span class="sm-path">/docs/capture</span>+ <span class="sm-desc">Turn a phone video of any space into an explorable coloured 3D point cloud with feed-forward reconstruction, tunable sampling parameters, and live WebGL rendering.</span>+ </a>+ </li>+ <li>+ <a href="/docs/restyle">+ <span class="sm-title">Docs · Restyle Studio</span>+ <span class="sm-path">/docs/restyle</span>+ <span class="sm-desc">Re-skin any GLB without regenerating its mesh: 14 PBR material presets, plain-language AI restyle, seeded colorway variants, live metalness and roughness, and a durable revertable version lineage.</span>+ </a>+ </li>+ <li>+ <a href="/docs/scene-studio">+ <span class="sm-title">Docs · Scene Studio</span>+ <span class="sm-path">/docs/scene-studio</span>+ <span class="sm-desc">The in-browser three.js editor: import GLBs, arrange with transform gizmos, edit materials and lights, script, and export complete glTF scenes.</span>+ </a>+ </li>+ <li>+ <a href="/docs/compose">+ <span class="sm-title">Docs · Scene Composer</span>+ <span class="sm-path">/docs/compose</span>+ <span class="sm-desc">Forge props from text, attach them to your avatar's skeleton bones, arrange and scale freely, then export a GLB or save the result as a reusable outfit.</span>+ </a>+ </li>+ <li>+ <a href="/docs/animation-studio">+ <span class="sm-title">Docs · Animation Studio</span>+ <span class="sm-path">/docs/animation-studio</span>+ <span class="sm-desc">Pose any avatar or the built-in mannequin with FK/IK, keyframe a timeline, preview live, and export an animated GLB or clip JSON. Save clips to your account and list them for sale in USDC.</span>+ </a>+ </li>+ <li>+ <a href="/docs/avatar-studio">+ <span class="sm-title">Docs · Avatar Studio</span>+ <span class="sm-path">/docs/avatar-studio</span>+ <span class="sm-desc">Build a rigged 3D avatar from scratch with no selfie: choose a base body, sculpt face and body morphs, add outfits and accessories, and export a GLB.</span>+ </a>+ </li>+ <li>+ <a href="/docs/mocap-studio">+ <span class="sm-title">Docs · Mocap Studio</span>+ <span class="sm-path">/docs/mocap-studio</span>+ <span class="sm-desc">Drive a 3D avatar's face live from your webcam in the browser: MediaPipe face landmarks mapped to ARKit blendshapes, smoothing, record and replay, and save.</span>+ </a>+ </li>+ <li>+ <a href="/docs/selfie-to-avatar">+ <span class="sm-title">Docs · Selfie to Avatar</span>+ <span class="sm-path">/docs/selfie-to-avatar</span>+ <span class="sm-desc">Point your camera at your face and get a rigged 3D avatar in about a minute, free and in the browser. The capture flow, the reconstruction pipeline, and where the avatar goes next.</span>+ </a>+ </li>+ <li>+ <a href="/docs/voice-lab">+ <span class="sm-title">Docs · Voice Lab</span>+ <span class="sm-path">/docs/voice-lab</span>+ <span class="sm-desc">Clone your voice from a short browser recording, play it in the TTS playground, and assign it to an agent.</span>+ </a>+ </li>+ <li>+ <a href="/docs/lipsync">+ <span class="sm-title">Docs · Lipsync</span>+ <span class="sm-path">/docs/lipsync</span>+ <span class="sm-desc">Two in-browser lipsync demos: TTS-driven mouth animation and live-mic viseme detection, both driving an avatar's viseme morph targets in real time.</span>+ </a>+ </li>+ <li>+ <a href="/docs/talking-avatar-video">+ <span class="sm-title">Docs · Talking Avatar Video</span>+ <span class="sm-path">/docs/talking-avatar-video</span>+ <span class="sm-desc">Pick an avatar, provide an audio track, and render a downloadable lip-synced talking-head MP4 on a server-side worker.</span>+ </a>+ </li>+ <li>+ <a href="/docs/galaxy">+ <span class="sm-title">Docs · Agent Galaxy</span>+ <span class="sm-path">/docs/galaxy</span>+ <span class="sm-desc">Every published agent embedded by IBM Granite on watsonx.ai, projected into a navigable 3D constellation with natural-language semantic search.</span>+ </a>+ </li>+ <li>+ <a href="/docs/ar-studio">+ <span class="sm-title">Docs · AR Studio</span>+ <span class="sm-path">/docs/ar-studio</span>+ <span class="sm-desc">Place any number of 3D models and avatars into one live camera scene: model sources, the WebXR/passthrough/desktop rendering ladder, gestures, shared live rooms, and shareable arrangements.</span>+ </a>+ </li>+ <li>+ <a href="/docs/genesis">+ <span class="sm-title">Docs · Instant Agent Genesis</span>+ <span class="sm-path">/docs/genesis</span>+ <span class="sm-desc">A prompt or a selfie becomes a rigged 3D AI agent with its own custodial Solana and EVM wallets and an optional on-chain identity, in under a minute.</span>+ </a>+ </li>+ <li>+ <a href="/docs/genome">+ <span class="sm-title">Docs · Agent Genome</span>+ <span class="sm-path">/docs/genome</span>+ <span class="sm-desc">Breed two agents into a provably-inherited child: recombined brain, voice, body, and on-chain skill licenses, each breeding event seed-recorded with a verifiable family tree.</span>+ </a>+ </li>+ <li>+ <a href="/docs/agent-studio">+ <span class="sm-title">Docs · Agent Studio</span>+ <span class="sm-path">/docs/agent-studio</span>+ <span class="sm-desc">Author an agent's brain, memory, body, money, and skills in one place, beside a persistent live 3D avatar that updates everywhere as you edit.</span>+ </a>+ </li>+ <li>+ <a href="/docs/brain">+ <span class="sm-title">Docs · Multi-LLM Brain</span>+ <span class="sm-path">/docs/brain</span>+ <span class="sm-desc">Send one prompt to Claude, GPT, Qwen, ModelScope, Groq and more at once, with side-by-side streaming and per-model latency and token stats.</span>+ </a>+ </li>+ <li>+ <a href="/docs/integrations">+ <span class="sm-title">Docs · Integrations</span>+ <span class="sm-path">/docs/integrations</span>+ <span class="sm-desc">The catalog of one-script-tag embeds for any site: 3D avatar viewers, chat agents, walk companions, page narrators, live token widgets, and the MCP server.</span>+ </a>+ </li>+ <li>+ <a href="/docs/autopilot">+ <span class="sm-title">Docs · Coin Autopilot</span>+ <span class="sm-path">/docs/autopilot</span>+ <span class="sm-desc">A hands-off token cockpit: set buyback-and-burn and holder-distribution rules with USDC floors and guardrails, and let your agent run the coin autonomously.</span>+ </a>+ </li>+ <li>+ <a href="/docs/signals">+ <span class="sm-title">Docs · Signal Marketplace</span>+ <span class="sm-path">/docs/signals</span>+ <span class="sm-desc">Verified traders publish live entry and exit signals as x402-metered feeds ranked by proven on-chain accuracy; a subscriber agent pays per signal or epoch and auto-mirrors through the guarded path.</span>+ </a>+ </li>+ <li>+ <a href="/docs/agi">+ <span class="sm-title">Docs · The AGI</span>+ <span class="sm-path">/docs/agi</span>+ <span class="sm-desc">One autonomous agent that is superhuman at exactly one thing, trading memecoins on pump.fun, and nothing else. Its embodied 3D body, its logged decisions with stated confidence, and its chain-proven record.</span>+ </a>+ </li>+ <li>+ <a href="/docs/alpha-copilot">+ <span class="sm-title">Docs · Alpha Co-pilot</span>+ <span class="sm-path">/docs/alpha-copilot</span>+ <span class="sm-desc">Your 3D agent reads a real pump.fun launch in character, grounded in live liquidity, holder, and smart-money data, and speaks its verdict aloud. Fabricated figures are rejected; the owner acts only within server-enforced spend limits.</span>+ </a>+ </li>+ <li>+ <a href="/docs/guardian">+ <span class="sm-title">Docs · Guardian console</span>+ <span class="sm-path">/docs/guardian</span>+ <span class="sm-desc">Recover and inherit agent wallets through a threshold-approved, time-locked process that never exposes a private key.</span>+ </a>+ </li>+ <li>+ <a href="/docs/strategy-objects">+ <span class="sm-title">Docs · Strategy Objects</span>+ <span class="sm-path">/docs/strategy-objects</span>+ <span class="sm-desc">Ownable, forkable, leaderboard-ranked trade strategies your agent can equip and run on-chain within your spend policy, plus the Strategy Lab for validation and backtesting.</span>+ </a>+ </li>+ <li>+ <a href="/docs/terminal">+ <span class="sm-title">Docs · Mission Control</span>+ <span class="sm-path">/docs/terminal</span>+ <span class="sm-desc">The keyboard-first pump.fun trading terminal: the launch firehose fused with intel scores, firewall verdicts, and smart-money flow, streaming positions with live PnL, and one-keystroke guarded trading.</span>+ </a>+ </li>+ <li>+ <a href="/docs/smart-money">+ <span class="sm-title">Docs · Smart Money Radar</span>+ <span class="sm-path">/docs/smart-money</span>+ <span class="sm-desc">A live first-party reputation graph of every pump.fun wallet: cross each coin's buyers with the coins that actually graduated to surface the wallets that keep picking winners.</span>+ </a>+ </li>+ <li>+ <a href="/docs/radar">+ <span class="sm-title">Docs · Coin Radar</span>+ <span class="sm-path">/docs/radar</span>+ <span class="sm-desc">Live pump.fun launch intelligence: every new coin scored in its first 90 seconds for bundle vs organic, wallet concentration, dev behaviour, and risk flags.</span>+ </a>+ </li>+ <li>+ <a href="/docs/clash">+ <span class="sm-title">Docs · Coin Clash</span>+ <span class="sm-path">/docs/clash</span>+ <span class="sm-desc">Token-gated community warfare: every coin community is an army. Hold the coin, enlist, and rally for your faction in timed on-chain battles.</span>+ </a>+ </li>+ <li>+ <a href="/docs/x402-studio">+ <span class="sm-title">Docs · x402 Studio</span>+ <span class="sm-path">/docs/x402-studio</span>+ <span class="sm-desc">The merchant console for running a paid x402 business: products and pricing, payout and agent wallets, real USDC send and receive with .sol resolution, a storefront and pay-button builder, giving, and security.</span>+ </a>+ </li>+ <li>+ <a href="/docs/fact-check">+ <span class="sm-title">Docs · Fact Check</span>+ <span class="sm-path">/docs/fact-check</span>+ <span class="sm-desc">Sourced fact-checking with cryptographic content attestations, a published accuracy benchmark, and a free daily quota then pay-per-check via x402.</span>+ </a>+ </li>+ <li>+ <a href="/docs/daily-forge">+ <span class="sm-title">Docs · Daily Forge</span>+ <span class="sm-path">/docs/daily-forge</span>+ <span class="sm-desc">A new 3D creative challenge every day: a deterministic theme, the free no-signup forge lane, a localStorage streak with milestones, a community strip, and an AR handoff.</span>+ </a>+ </li><li><a href="/docs/crypto-api"><span class="sm-title">Docs · Crypto Data API</span>diff --git a/tests/api/three-microbuy-cap.test.js b/tests/api/three-microbuy-cap.test.jsnew file mode 100644index 000000000..68869e585--- /dev/null+++ b/tests/api/three-microbuy-cap.test.js@@ -0,0 +1,45 @@+// The safety-critical sizing rule for the $THREE micro-buy daily cap. Pure BigInt+// math — the one place "never spend past the ceiling" is decided, used by both the+// Redis fast path and the DB fallback in api/_lib/token/microbuy.js. If this rule is+// wrong, the micro-buy loop can overspend real USDC, so it is pinned here.++import { describe, it, expect } from 'vitest';+import { wouldExceedCap, usdToUsdcAtomics } from '../../api/_lib/token/buyback-math.js';++describe('wouldExceedCap — micro-buy daily cap rule', () => {+ const cap = usdToUsdcAtomics(50); // $50 daily ceiling → 50_000_000 atomics+ const buy = usdToUsdcAtomics(0.01); // $0.01 per buy → 10_000 atomics++ it('allows a buy strictly under the cap', () => {+ expect(wouldExceedCap(0n, buy, cap)).toBe(false);+ expect(wouldExceedCap(cap - buy, buy, cap)).toBe(false); // exactly fills the cap+ });++ it('refuses the buy that would cross the cap', () => {+ expect(wouldExceedCap(cap, buy, cap)).toBe(true); // already at the cap+ expect(wouldExceedCap(cap - buy + 1n, buy, cap)).toBe(true); // one atomic over+ });++ it('is exact at the boundary — the last affordable buy fills the cap precisely', () => {+ // $50 / $0.01 = 5000 buys. The 5000th fills it; the 5001st is refused.+ let spent = 0n;+ let allowed = 0;+ for (let i = 0; i < 6000; i++) {+ if (wouldExceedCap(spent, buy, cap)) break;+ spent += buy;+ allowed += 1;+ }+ expect(allowed).toBe(5000);+ expect(spent).toBe(cap);+ });++ it('accepts string / number / bigint atomics interchangeably', () => {+ expect(wouldExceedCap('49990000', 10000, cap)).toBe(false); // $49.99 + $0.01 = $50.00+ expect(wouldExceedCap('49990001', 10000, cap)).toBe(true); // one atomic over+ });++ it('a zero cap refuses any positive buy but allows a zero buy', () => {+ expect(wouldExceedCap(0n, buy, 0n)).toBe(true);+ expect(wouldExceedCap(0n, 0n, 0n)).toBe(false);+ });+});diff --git a/tests/solana-rpc-rotating-fetch.test.js b/tests/solana-rpc-rotating-fetch.test.jsindex b0fc04be8..11039be84 100644--- a/tests/solana-rpc-rotating-fetch.test.js+++ b/tests/solana-rpc-rotating-fetch.test.js@@ -1,5 +1,9 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';-import { makeRotatingFetch } from '../api/_lib/solana/connection.js';+import {+ makeRotatingFetch,+ classifyRpcBody,+ markEndpointCooldown,+} from '../api/_lib/solana/connection.js';// A Response carrying either a raw string body or a JSON-encoded object, the way a// Solana RPC node answers a JSON-RPC POST.@@ -99,3 +103,54 @@ describe('makeRotatingFetch — never leaks an unvalidated upstream body', () =>expect(fetchSpy).toHaveBeenCalledTimes(1);});});++// QuickNode signals an exhausted DAILY cap with `-32003 "daily request limit reached+// - upgrade your account"`. Over HTTP it arrives as a 429; on providers that answer+// 200 + JSON-RPC error it must still be treated as a fail-over signal (a capacity+// problem the next lane does not share), and it must park the endpoint for the long+// quota window, not a 10-minute rate-limit blip that re-probes a dead-for-the-day lane.+describe('provider daily-limit (-32003 / "request limit reached")', () => {+ const HOUR = 3_600_000;++ it('classifies a 200 + -32003 body as a fail-over (429), not a usable response', () => {+ const bad = classifyRpcBody(+ JSON.stringify({ jsonrpc: '2.0', id: 1, error: { code: -32003, message: 'daily request limit reached - upgrade your account' } }),+ );+ expect(bad).not.toBeNull();+ expect(bad.status).toBe(429);+ });++ it('classifies the phrase alone (unknown code) as capacity too', () => {+ const bad = classifyRpcBody(+ JSON.stringify({ jsonrpc: '2.0', id: 1, error: { code: -32099, message: 'request limit reached' } }),+ );+ expect(bad).not.toBeNull();+ expect(bad.status).toBe(429);+ });++ it('parks a daily-limit 429 for the long quota window, not the short rate-limit one', () => {+ const quota = markEndpointCooldown('https://q.daily-limit.test/', 429, 'daily request limit reached');+ const plain = markEndpointCooldown('https://q.plain-429.test/', 429, 'slow down');+ expect(quota).toBeGreaterThan(HOUR); // 6h quota park+ expect(plain).toBeLessThanOrEqual(15 * 60_000); // ~10m transient+ });++ it('fails over a 200 + -32003 endpoint to a healthy next lane', async () => {+ const origFetch = global.fetch;+ try {+ const capped = { jsonrpc: '2.0', id: 1, error: { code: -32003, message: 'daily request limit reached' } };+ const fetchSpy = vi.fn(async (url) =>+ String(url).includes('capped') ? resp(capped) : resp(VALID),+ );+ global.fetch = fetchSpy;+ const out = await makeRotatingFetch(['https://capped.test/', 'https://healthy.test/'])(null, {+ method: 'POST',+ body: '{}',+ });+ expect((await out.json()).result).toEqual({ ok: true });+ expect(fetchSpy).toHaveBeenCalledTimes(2);+ } finally {+ global.fetch = origFetch;+ }+ });+});diff --git a/tests/solana-rpc-url-guard.test.js b/tests/solana-rpc-url-guard.test.jsindex 9bdcfba4f..233387622 100644--- a/tests/solana-rpc-url-guard.test.js+++ b/tests/solana-rpc-url-guard.test.js@@ -2,6 +2,8 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest';import {isHttpUrl,normalizeRpcUrl,+ normalizeWsUrl,+ resolveWsEndpoint,solanaRpcEndpoints,} from '../api/_lib/solana/connection.js';import { RpcFallback, rpcFallbackFromEnv } from '../api/_lib/solana/rpc-fallback.js';@@ -150,3 +152,63 @@ describe('RpcFallback — never hands new Connection a non-http(s) URL', () => {expect(() => rpc.getConnection()).not.toThrow();});});++describe('normalizeWsUrl: coerces an env WS endpoint into a ws(s):// URL', () => {+ it('passes through a clean wss URL unchanged', () => {+ expect(normalizeWsUrl('wss://example.quiknode.pro/token')).toBe('wss://example.quiknode.pro/token');+ expect(normalizeWsUrl('ws://localhost:8900')).toBe('ws://localhost:8900');+ });+ it('maps http(s) to its ws(s) form', () => {+ expect(normalizeWsUrl('https://example.quiknode.pro/token')).toBe('wss://example.quiknode.pro/token');+ expect(normalizeWsUrl('http://localhost:8899')).toBe('ws://localhost:8899');+ });+ it('prepends wss:// to a scheme-less host', () => {+ expect(normalizeWsUrl('example.quiknode.pro/token')).toBe('wss://example.quiknode.pro/token');+ });+ it('strips a single pair of surrounding quotes', () => {+ expect(normalizeWsUrl('"wss://example.quiknode.pro/token"')).toBe('wss://example.quiknode.pro/token');+ });+ it('returns "" for empty or unsalvageable values', () => {+ expect(normalizeWsUrl('')).toBe('');+ expect(normalizeWsUrl(' ')).toBe('');+ expect(normalizeWsUrl(null)).toBe('');+ expect(normalizeWsUrl('bareword')).toBe('');+ expect(normalizeWsUrl('ftp://example.com')).toBe('');+ });+});++describe('resolveWsEndpoint: SOLANA_RPC_WS_URL override, derive-from-primary default', () => {+ let saved;+ beforeEach(() => {+ saved = process.env.SOLANA_RPC_WS_URL;+ delete process.env.SOLANA_RPC_WS_URL;+ });+ afterEach(() => {+ if (saved === undefined) delete process.env.SOLANA_RPC_WS_URL;+ else process.env.SOLANA_RPC_WS_URL = saved;+ });++ it('derives the socket from the primary HTTP endpoint when unset', () => {+ expect(resolveWsEndpoint('https://mainnet.helius-rpc.com/?api-key=k', 'mainnet')).toBe(+ 'wss://mainnet.helius-rpc.com/?api-key=k',+ );+ });+ it('uses a mainnet SOLANA_RPC_WS_URL override, normalized to wss', () => {+ process.env.SOLANA_RPC_WS_URL = 'https://ded.quiknode.pro/token';+ expect(resolveWsEndpoint('https://mainnet.helius-rpc.com/?api-key=k', 'mainnet')).toBe(+ 'wss://ded.quiknode.pro/token',+ );+ });+ it('ignores the override on devnet so a mainnet socket never crosses clusters', () => {+ process.env.SOLANA_RPC_WS_URL = 'wss://ded.quiknode.pro/token';+ expect(resolveWsEndpoint('https://devnet.helius-rpc.com/?api-key=k', 'devnet')).toBe(+ 'wss://devnet.helius-rpc.com/?api-key=k',+ );+ });+ it('falls back to deriving when the override is unsalvageable', () => {+ process.env.SOLANA_RPC_WS_URL = 'not a url';+ expect(resolveWsEndpoint('https://mainnet.helius-rpc.com/?api-key=k', 'mainnet')).toBe(+ 'wss://mainnet.helius-rpc.com/?api-key=k',+ );+ });+});