Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
docs(all): regenerate the ALL.md aggregate so it stops serving stale doc copies
nirholas96f00265f5f1
diff --git a/docs/ALL.md b/docs/ALL.mdindex 05e05e689..75ccd884c 100644--- a/docs/ALL.md+++ b/docs/ALL.md@@ -1,7 +1,7 @@<!-- GENERATED by scripts/combine-docs.mjs — do not edit by hand. Edit the source files under docs/ and re-run. --># three.ws — Combined Documentation-> Single-file snapshot of every document under [`docs/`](.). Generated 2026-08-14 from **524 files** (~7351 KB).+> Single-file snapshot of every document under [`docs/`](.). Generated 2026-08-15 from **524 files** (~7416 KB).> The individual source files remain the canonical, editable copies — this file is a read-only aggregate.## Table of contents@@ -602,7 +602,11 @@ Base URL: `https://three.ws`> This page documents the **free** 3D endpoints. Higher-quality generation and> rigging are paid: **Forge Pro** (quality tiers) at [`/api/x402/forge`](https://three.ws/api/x402/forge)-> and **Rigged Avatars** (animation-ready skeletons) via [`/api/forge?action=rig`](https://three.ws/api/forge).+> and **Rigged Avatars** (animation-ready skeletons) via `POST /api/forge?action=rig`.+> The rig action is POST-only, so there is nothing to open at `/api/forge` itself;+> for a browsable view of what the forge can do, open+> [`/api/forge?catalog`](https://three.ws/api/forge?catalog) (the path / tier /+> backend matrix).Prefer a browsable landing page? See [three.ws/3d](https://three.ws/3d) — hero,live endpoint table, a runnable inspection console, an embedded 3D viewer, and the@@ -718,9 +722,9 @@ model comes straight back:```json{"status": "done",- "glbUrl": "https://three.ws/cdn/forge/anon/a1b2c3d4.glb",- "viewerUrl": "https://three.ws/viewer?src=https%3A%2F%2Fthree.ws%2Fcdn%2Fforge%2Fanon%2Fa1b2c3d4.glb",- "arUrl": "https://three.ws/api/ar?src=https%3A%2F%2Fthree.ws%2Fcdn%2Fforge%2Fanon%2Fa1b2c3d4.glb&title=a%20small%20ceramic%20robot%20figurine",+ "glbUrl": "https://pub-2534e921bf9c4314addcd4d8a6e98b7b.r2.dev/forge/40659d6097b0/0a527906-a087-45b7-afd4-8d401495787b.glb",+ "viewerUrl": "https://three.ws/viewer?src=https%3A%2F%2Fpub-2534e921bf9c4314addcd4d8a6e98b7b.r2.dev%2Fforge%2F40659d6097b0%2F0a527906-a087-45b7-afd4-8d401495787b.glb",+ "arUrl": "https://three.ws/api/ar?src=https%3A%2F%2Fpub-2534e921bf9c4314addcd4d8a6e98b7b.r2.dev%2Fforge%2F40659d6097b0%2F0a527906-a087-45b7-afd4-8d401495787b.glb&title=a%20small%20ceramic%20robot%20figurine","format": "glb","tier": "draft","free": true,@@ -728,6 +732,22 @@ model comes straight back:}```+**Treat `glbUrl` as opaque.** It is a fully-qualified URL on the object store, not+a path you can build yourself: the host comes from deployment config and the key+is assigned per generation. Follow the URL you were handed and pass it verbatim+into `viewerUrl` / `arUrl` style links rather than reconstructing one.++Server-side and CLI downloads (`curl -O`, a worker fetching bytes) can use+`glbUrl` directly. **Browser code on another origin should not**: the object+store answers without CORS headers and is rate-limited for bursts. Swap the host+for the first-party CDN instead, which serves the identical object with+`Access-Control-Allow-Origin: *` and a long edge cache:++```js+// https://<object-store>/forge/<hash>/<id>.glb → https://three.ws/cdn/forge/<hash>/<id>.glb+const browserUrl = 'https://three.ws/cdn/' + new URL(glbUrl).pathname.replace(/^\//, '');+```+`arUrl` is the place-in-your-room link (`/api/ar`): opened on a phone itlaunches AR directly — Scene Viewer on Android, Quick Look on iOS (GLB→USDZconverted in-page) — and on desktop it falls back to the interactive viewer.@@ -771,7 +791,7 @@ GET /api/3d/generate?job=f1.eyJwIjoibnZpZGlh...&title=a%20small%20ceramic%20robo{ "status": "pending", "job": "f1...", "poll": "/api/3d/generate?job=f1...&title=...", "retryAfter": 3 }// ready-{ "status": "done", "job": "f1...", "glbUrl": "https://three.ws/cdn/forge/anon/done.glb",+{ "status": "done", "job": "f1...", "glbUrl": "https://<object-store>/forge/<hash>/<id>.glb","viewerUrl": "https://three.ws/viewer?src=...", "arUrl": "https://three.ws/api/ar?src=...&title=...","format": "glb", "tier": "draft", "free": true }@@ -804,11 +824,11 @@ curl -s -X POST https://three.ws/api/3d/generate \# → { "status": "pending", "job": "f1...", "poll": "/api/3d/generate?job=f1..." }# (or { "status": "done", "glbUrl": "..." } if it finished inline)-# 2. Poll until done, then download the GLB+# 2. Poll until done, then download the GLB at the glbUrl you were handedcurl -s 'https://three.ws/api/3d/generate?job=f1...'-# → { "status": "done", "glbUrl": "https://three.ws/cdn/forge/anon/....glb", ... }+# → { "status": "done", "glbUrl": "https://<object-store>/forge/<hash>/<id>.glb", ... }-curl -sL -o model.glb 'https://three.ws/cdn/forge/anon/....glb'+curl -sL -o model.glb '<the glbUrl from step 2>'```The `glbUrl` is a real, durable GLB — open `viewerUrl` in a browser to inspect it,@@ -893,11 +913,14 @@ to create, no monthly plan, no key to provision — just one USDC payment per mo### Quality tiers-| Tier | Price (USDC) | Geometry | Textures | Best for |-|------------|--------------|---------------------|-----------------|-----------------------------------|-| `draft` | **$0.05** | ~12k tris, low-poly | none | Blockout, iteration, previews |-| `standard` | **$0.15** | ~30k tris, balanced | none | The default for most assets |-| `high` | **$0.50** | ~200k tris, max | **PBR + HD** | Hero assets, product/NFT renders |+| Tier | Price (USDC) | Geometry | Textures | Best for |+|------------|--------------|---------------------|---------------------|-----------------------------------|+| `draft` | **$0.05** | ~12k tris, low-poly | baked, 1K | Blockout, iteration, previews |+| `standard` | **$0.15** | ~30k tris, balanced | baked, 2K | The default for most assets |+| `high` | **$0.50** | ~200k tris, max | **PBR + HD**, 4K | Hero assets, product/NFT renders |++Every tier ships a textured mesh; the ladder is bake resolution plus, at `high`,+full PBR material channels rather than a single baked colour map.Prices are the flat per-call retail price and are the single source of truth in[`api/_lib/forge-tiers.js`](https://github.com/nirholas/three.ws/blob/main/api/_lib/forge-tiers.js);@@ -944,7 +967,7 @@ tier at deploy time without touching settlement.```bashcurl -s 'https://three.ws/api/forge?job=f1.eyJ…'- # → { "status": "done", "glb_url": "https://three.ws/cdn/forge/…/model.glb", … }+ # → { "status": "done", "glb_url": "https://<object-store>/forge/<hash>/<id>.glb", … }```A draft prompt often finishes inside the submit window and comes back inline with@@ -1006,9 +1029,8 @@ re-validated per hop.{"url": "https://three.ws/avatars/cesium-man.glb","valid": true,- "sizeBytes": 495956,"stats": {- "vertices": 3272,+ "vertices": 3273,"triangles": 4672,"materials": 1,"textures": 1,@@ -1019,9 +1041,13 @@ re-validated per hop."scenes": 1,"skins": 1,"joints": 19,+ "indexedPrimitives": 1,+ "nonIndexedPrimitives": 0,+ "extensionsRequired": [],"container": "glb",- "generator": "COLLADA2GLTF"+ "generator": "glTF-Transform v4.4.0"},+ "sizeBytes": 438044,"recommendations": [{"severity": "info",@@ -1029,14 +1055,35 @@ re-validated per hop."fix": "No action needed — the model is already well-suited for web delivery."}],- "validation": { "valid": true, "numErrors": 0, "numWarnings": 0, "numInfos": 0, "numHints": 0 },- "ts": "2026-07-07T00:00:00.000Z"+ "validation": {+ "valid": true,+ "validatorVersion": "2.0.0-dev.3.10",+ "numErrors": 0,+ "numWarnings": 1,+ "numInfos": 0,+ "numHints": 0,+ "issues": [+ {+ "code": "NODE_SKINNED_MESH_NON_ROOT",+ "message": "Node with a skinned mesh is not root. Parent transforms will not affect a skinned mesh.",+ "severity": "warning",+ "pointer": "/nodes/2"+ }+ ],+ "truncated": false+ },+ "ts": "2026-08-15T06:37:05.768Z"}```+That is the verbatim response for the URL in the curl block below, so you can+diff your own call against it.+`recommendations` is ordered **most severe first** (`critical` → `warn` →-`info`); each item is a `{ severity, issue, fix }` triple — the problem and the-concrete action. `valid` reflects the glTF-Validator's error count.+`info`); each item is a `{ severity, issue, fix }` triple: the problem and the+concrete action. `valid` reflects the glTF-Validator's error count, so a model+can be `valid: true` and still carry warnings, as this one does. `validation.issues`+carries those individual findings (`truncated` says whether the list was cut).### curl@@ -1235,7 +1282,8 @@ Source: [scripts/optimize-glb.mjs](../scripts/optimize-glb.mjs). Lossless geomet"tracks": [{ "name": "Hips.position", "type": "vector", "times": [...], "values": [...] },{ "name": "Hips.quaternion", "type": "quaternion", "times": [...], "values": [...] }- // …one position + one quaternion track per canonical bone (≈53 tracks)+ // …one quaternion track per canonical bone, plus the single Hips position+ // track: 52 + 1 = 53 tracks for a full clip]}```@@ -1248,7 +1296,7 @@ Track names are **canonical bone names** (`Hips`, `Spine`, `LeftArm`, …) so th{ "name": "idle", "url": "/animations/clips/idle.json", "label": "Idle", "icon": "🧍", "loop": true }```-**The canonical skeleton** is a 53-bone humanoid set defined in [src/glb-canonicalize.js](../src/glb-canonicalize.js): the torso chain (`Hips → Spine → Spine1 → Spine2 → Neck → Head`), both arms (`Shoulder → Arm → ForeArm → Hand`) with full finger chains, and both legs (`UpLeg → Leg → Foot → ToeBase`). `public/avatars/cz.glb` is the reference rig every clip is retargeted against.+**The canonical skeleton** is the 52-bone humanoid set exported as `CANONICAL_BONES` from [src/glb-canonicalize.js](../src/glb-canonicalize.js): the torso chain (`Hips → Spine → Spine1 → Spine2 → Neck → Head`), both arms (`Shoulder → Arm → ForeArm → Hand`) with full finger chains, and both legs (`UpLeg → Leg → Foot → ToeBase`). `public/avatars/cz.glb` is the reference rig every clip is retargeted against.---@@ -1453,7 +1501,10 @@ Every `pipeline-*` route is a synchronous, pay-per-call endpoint:1. You `POST` a JSON body with the source URL + options.2. If you send no `X-PAYMENT` header, you get a `402` challenge quoting the price- in USDC (Solana mainnet; Base when configured).+ in USDC. The challenge carries one `accepts` entry per network the platform+ can settle on: the Solana USDC entry leads whenever the Solana rail is+ settleable, with Base as the alternative. Read the network off the challenge+ rather than assuming one.3. You settle and retry with `X-PAYMENT`. The server validates your input URL(SSRF-guarded, magic-byte sniffed), submits the worker job, polls it tocompletion, validates the output bytes, mirrors the result into first-party@@ -1464,6 +1515,40 @@ Every `pipeline-*` route is a synchronous, pay-per-call endpoint:Prices are env-overridable per the [pricing model](x402-endpoints.md#pricing-model)(`X402_PRICE_<UPPER_SNAKE_SLUG>`).+## Paying for a stage++There is no x402 command-line tool to shell out to: signing the challenge is the+part that needs your wallet, so paying happens in code. Every stage sample below+is the unpaid `curl`, which returns the 402 challenge and costs nothing. To+actually run a stage, wrap `fetch` once with our published buyer package and call+the same URL:++```bash+npm install @three-ws/x402-fetch+```++```js+import { withX402 } from '@three-ws/x402-fetch';+import { privateKeyToWallet } from '@three-ws/x402-fetch/wallet';++// maxPaymentUsd is a hard ceiling: the wrapper refuses a challenge above it.+const pay = withX402(privateKeyToWallet(process.env.WALLET_PRIVATE_KEY), { maxPaymentUsd: 0.1 });++const res = await pay('https://three.ws/api/x402/pipeline-rig', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ glb_url: 'https://three.ws/avatars/mannequin.glb', rig_type: 'biped' }),+});++const { output_url } = await res.json();+console.log(output_url);+```++The wrapper answers the 402, signs the payment, and retries the same request, all+before your `await` resolves. Paying from a three.ws agent wallet instead of a+raw key, or settling on Solana, is covered in+[x402 buyer client](#sec-511).+## Stages### Rig — `POST /api/x402/pipeline-rig` — $0.05@@ -1472,15 +1557,16 @@ Infers a humanoid skeleton and binds it to a static mesh with skin weights, so tmodel can walk, wave, and emote. **In:** a static GLB. **Out:** a rigged GLB.```bash-# 1. Discover the price (unpaid request returns the 402 challenge)+# Unpaid: returns the 402 challenge with the price and the networks it settles on.curl -s -X POST https://three.ws/api/x402/pipeline-rig \-H 'content-type: application/json' \-d '{"glb_url":"https://three.ws/avatars/mannequin.glb","rig_type":"biped"}'+```++Paid (send the same body through the wrapper above), the response is:-# 2. Pay with an x402 client (settles the 402 and retries automatically)-npx @x402/fetch POST https://three.ws/api/x402/pipeline-rig \- --json '{"glb_url":"https://three.ws/avatars/mannequin.glb","rig_type":"biped"}'-# → { "stage":"rig", "output_url":"https://three.ws/cdn/x402-pipeline/rig/….glb", ... }+```json+{ "stage": "rig", "output_url": "https://three.ws/cdn/x402-pipeline/rig/….glb" }```### Remesh — `POST /api/x402/pipeline-remesh` — $0.03@@ -1490,11 +1576,14 @@ target face count, with the texture re-baked onto the new topology. **In:** a GLoptions. **Out:** a cleaned GLB with predictable topology.```bash-npx @x402/fetch POST https://three.ws/api/x402/pipeline-remesh \- --json '{"glb_url":"https://three.ws/avatars/brainstem.glb","remesh_mode":"quad","target_faces":20000}'-# → { "stage":"remesh", "output_url":"…", "face_count":20000, "quad_ratio":0.98, "textured":true }+curl -s -X POST https://three.ws/api/x402/pipeline-remesh \+ -H 'content-type: application/json' \+ -d '{"glb_url":"https://three.ws/avatars/brainstem.glb","remesh_mode":"quad","target_faces":20000}'```+Paid response: `{ "stage":"remesh", "output_url":"…", "face_count":20000,+"quad_ratio":0.98, "textured":true }`+Options: `remesh_mode` (`triangle` | `quad` | `lowpoly`), `operation` (`full` |`simplify` | `repair` | `convert`, triangle mode only), `target_faces`(1,000–500,000), `texture_size` (512 | 1024 | 2048).@@ -1507,11 +1596,14 @@ topology, so the asset drops into a real-time engine within budget. **In:** a GL`poly_budget`. **Out:** an engine-ready GLB.```bash-npx @x402/fetch POST https://three.ws/api/x402/pipeline-gameready \- --json '{"glb_url":"https://three.ws/avatars/fox.glb","topology":"quad","poly_budget":12000}'-# → { "stage":"gameready", "output_url":"…", "poly_budget":12000, "quad_ratio":0.97 }+curl -s -X POST https://three.ws/api/x402/pipeline-gameready \+ -H 'content-type: application/json' \+ -d '{"glb_url":"https://three.ws/avatars/fox.glb","topology":"quad","poly_budget":12000}'```+Paid response: `{ "stage":"gameready", "output_url":"…", "poly_budget":12000,+"quad_ratio":0.97 }`+Options: `topology` (`quad` | `tri`), `poly_budget` (1,000–500,000), `texture_size`(1024 | 2048).@@ -1522,11 +1614,14 @@ rebuild the mesh itself (not a shader), so the look survives export to any engin**In:** a GLB + `style`. **Out:** a restyled GLB.```bash-npx @x402/fetch POST https://three.ws/api/x402/pipeline-stylize \- --json '{"glb_url":"https://three.ws/avatars/mannequin.glb","style":"voxel","resolution":48}'-# → { "stage":"stylize", "output_url":"…", "style":"voxel", "resolution":48 }+curl -s -X POST https://three.ws/api/x402/pipeline-stylize \+ -H 'content-type: application/json' \+ -d '{"glb_url":"https://three.ws/avatars/mannequin.glb","style":"voxel","resolution":48}'```+Paid response: `{ "stage":"stylize", "output_url":"…", "style":"voxel",+"resolution":48 }`+Options: `style` (`voxel` | `brick` | `voronoi` | `lowpoly`), `resolution`(clamped per filter).@@ -1537,11 +1632,14 @@ reference view image→3D reconstruction needs so it never bakes a room into themesh. **In:** an image (PNG/JPEG/WEBP/GIF). **Out:** a transparent PNG.```bash-npx @x402/fetch POST https://three.ws/api/x402/pipeline-rembg \- --json '{"image_url":"https://three.ws/avatars/thumbs/default.png","model":"rmbg2"}'-# → { "stage":"rembg", "output_url":"https://three.ws/cdn/x402-pipeline/rembg/….png" }+curl -s -X POST https://three.ws/api/x402/pipeline-rembg \+ -H 'content-type: application/json' \+ -d '{"image_url":"https://three.ws/avatars/thumbs/default.png","model":"rmbg2"}'```+Paid response: `{ "stage":"rembg", "output_url":+"https://three.ws/cdn/x402-pipeline/rembg/….png" }`+Options: `model` (`rmbg2` | `u2net` | `isnet` | `u2net_human_seg` | `silueta`).## A full flow@@ -1549,19 +1647,43 @@ Options: `model` (`rmbg2` | `u2net` | `isnet` | `u2net_human_seg` | `silueta`).Generate a mesh, then rig and optimize it — three paid calls, each output URLfeeding the next input:-```bash-# 1. Generate ($0.05 draft tier) → poll /api/forge?job=<id> for the GLB-FORGE=$(npx @x402/fetch POST https://three.ws/api/x402/forge \- --json '{"prompt":"a brass steampunk owl, full body","tier":"draft"}')-GLB=$(echo "$FORGE" | jq -r '.glb_url')+```js+import { withX402 } from '@three-ws/x402-fetch';+import { privateKeyToWallet } from '@three-ws/x402-fetch/wallet';++const pay = withX402(privateKeyToWallet(process.env.WALLET_PRIVATE_KEY), { maxPaymentUsd: 0.1 });-# 2. Rig it ($0.05)-RIGGED=$(npx @x402/fetch POST https://three.ws/api/x402/pipeline-rig \- --json "{\"glb_url\":\"$GLB\"}" | jq -r '.output_url')+const post = async (url, body) => {+ const res = await pay(url, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(body),+ });+ if (!res.ok) throw new Error(`${url} → ${res.status} ${await res.text()}`);+ return res.json();+};-# 3. Make it game-ready ($0.03)-npx @x402/fetch POST https://three.ws/api/x402/pipeline-gameready \- --json "{\"glb_url\":\"$RIGGED\",\"poly_budget\":15000}"+// 1. Generate ($0.05 draft tier). A fast lane answers with status:"done" and the+// GLB inline; anything slower hands back a job token you poll for FREE.+const forge = await post('https://three.ws/api/x402/forge', {+ prompt: 'a brass steampunk owl, full body',+ tier: 'draft',+});+let glbUrl = forge.glb_url ?? null;+while (!glbUrl) {+ await new Promise((r) => setTimeout(r, 5000));+ const poll = await fetch(`https://three.ws${forge.poll_url}`).then((r) => r.json());+ if (poll.status === 'failed') throw new Error(poll.error);+ glbUrl = poll.glb_url ?? null;+}++// 2. Rig it ($0.05), then 3. make it game-ready ($0.03).+const rigged = await post('https://three.ws/api/x402/pipeline-rig', { glb_url: glbUrl });+const ready = await post('https://three.ws/api/x402/pipeline-gameready', {+ glb_url: rigged.output_url,+ poly_budget: 15000,+});+console.log(ready.output_url);```## Operator configuration@@ -1999,12 +2121,21 @@ difficulty, impostor signing key, or mismatched opened secret each FAIL.```json{"protocol": "three-vanity/v1",- "serviceKey": { "curve": "ed25519", "publicKeyBase58": "…", "publicKeyHex": "…", "use": "receipt-signing" },+ "serviceKey": { "curve": "ed25519", "keyId": "…", "publicKeyBase58": "…", "publicKeyHex": "…", "use": "receipt-signing" },"schemes": { … },- "endpoints": { "grind": "/api/x402/vanity-verifiable", "verifyPage": "/vanity/verify" }+ "endpoints": {+ "grind": "https://three.ws/api/x402/vanity",+ "verifiableGrind": "https://three.ws/api/x402/vanity-verifiable",+ "certRegistry": "https://three.ws/api/vanity/cert",+ "verifyPage": "https://three.ws/vanity/verify"+ }}```+Endpoint URLs are absolute, so a verifier that fetched the document has everything+it needs without knowing the origin. `grind` is the plain vanity endpoint;+`verifiableGrind` is the one that issues the receipts this protocol specifies.+The SDK pins `THREE_VANITY_SERVICE_KEY`; for production verification, cross-checkit against the live well-known document (`fetchServiceKey()` / `--fetch-key` /the web page does this automatically). On key rotation, update the well-known@@ -2253,7 +2384,7 @@ touched in production. It needs `docker` and ports 5817, 5818 and 3817.# AgenC-[AgenC](#sec-075) is the on-chain coordination protocol three.ws reads from for+AgenC is the on-chain coordination protocol three.ws reads from fortask discovery and agent identity. three.ws exposes a small set of **read**endpoints over it and bridges three.ws agent handles to AgenC agent IDs. This pagedocuments what is wired today — including, plainly, what is not.@@ -2276,6 +2407,7 @@ work is posted, and how a task moves from posted → claimed → completed.| Endpoint | Method | Returns ||---|---|---|| `/api/agenc/list-tasks?creator=<base58>&cluster=devnet` | GET | Task PDAs for a creator. |+| `/api/agenc/recent-tasks?cluster=devnet[&limit=6]` | GET | The newest task PDAs three.ws itself wrote on-chain, from the platform's own journal. || `/api/agenc/get-task?taskPda=<base58>&cluster=devnet[&lifecycle=1]` | GET | Task state, optionally with lifecycle events. || `/api/agenc/get-task?creator=<base58>&taskId=<hex\|label>&cluster=devnet` | GET | Same, addressed by creator + task id. || `/api/agenc/get-agent?agentPda=<base58>&cluster=devnet` | GET | Agent registry record. |@@ -2287,6 +2419,51 @@ when unused. Both `devnet` and `mainnet` clusters are addressable via `cluster`.`cluster` defaults to `mainnet`; note the AgenC program's populated deployment ison **devnet** today, so a mainnet read of a real task normally returns `not_found`.+### Finding a task to read++`list-tasks` can only answer once you already know a creator wallet, which is no+help to a client holding nothing. `recent-tasks` closes that gap: it returns the+task PDAs three.ws has posted, claimed, or settled through the [Agora](#sec-075)+rail, newest first, read from the platform's own journal rather than the chain+(one DB query, no `getProgramAccounts` scan, so it answers in milliseconds).++```bash+curl -s 'https://three.ws/api/agenc/recent-tasks?cluster=devnet&limit=3'+```++```json+{+ "ok": true,+ "cluster": "devnet",+ "count": 3,+ "degraded": false,+ "tasks": [+ { "taskPda": "4TyX1R7t7m…6gpR", "lastActivityAt": "2026-08-06T05:53:35.045Z",+ "rewardLabel": "0.002 SOL", "kinds": ["claimed_task", "completed_task", "earned"] }+ ]+}+```++It is a pointer list, not a source of truth: the journal records what three.ws+wrote, so verify anything you act on with `get-task`, which reads the chain.+`degraded: true` with an empty `tasks` array means the journal was unreachable+and the chain reads are unaffected. [`/agenc/embodied`](https://three.ws/agenc/embodied)+uses this endpoint to offer live tasks to a visitor who has no address in hand.++### Task states++`state` is AgenC's on-chain `TaskState` enum, verbatim. There are six, and the+labels are exactly these strings (two of them contain a space):++`Open` · `In Progress` · `Pending Validation` · `Completed` · `Cancelled` ·+`Disputed`++There is no `Claimed` and no `Expired`: a claim moves a task to `In Progress`, and+a lapsed deadline leaves it `Open` until its creator cancels. Client code that+keys on state (a color map, an animation switch, a CSS class) must use these+strings. Note that `class="state-In Progress"` is not one class name but two, so+match on a data attribute (`[data-state='In Progress']`) instead.+`x402-services` is the odd one out: it reads the x402 Bazaar rather than the chain,and returns each discovered endpoint with a deterministic `taskIdSeed` so the sameservice always maps to the same AgenC task PDA when someone posts it. `maxPrice` is@@ -2297,7 +2474,7 @@ an atomic amount (`10000` = 0.01 USDC), not a decimal.| Status | Body `error` | Meaning ||---|---|---|| 400 | `validation_error` | A missing or malformed parameter; the message names it. |-| 404 | `not_found` | Unknown action, or the PDA holds no such task/agent on that cluster. |+| 404 | `not_found` | Unknown action, or the PDA holds no such task/agent on that cluster. An address that holds some *other* account decodes as a discriminator mismatch and is reported here too, not as a 500. || 405 | `method_not_allowed` | Wrong verb (the reads are GET, `link` is POST). || 429 | `rate_limited` | Per-IP limit; retry after the window in the response. || 502 | `facilitator_error` | `x402-services` only: every Bazaar facilitator failed. |@@ -13381,9 +13558,11 @@ page shows it as a star figure next to the hire count.`hirer_agent_id` and ordered by `spent_usd` descending.Both leaderboards respect agent privacy: `url` is `null` when the agent's-identity is not public, which makes the page render an unlinked row, and+identity is not public *or* no longer exists (a deleted agent leaves no identity+row to link to), which makes the page render an unlinked row, and`avatar_thumbnail_url` is populated only when the linked avatar's visibility is-`public` or `unlisted`. A row with no avatar renders initials instead.+`public` or `unlisted`. A row with no avatar renders initials instead, and so+does a row whose stored thumbnail has since been pruned.**`recent[]`**: the latest completed hires ordered by `completed_at` descending,with the skill, the amount, the network, and the settlement signature.@@ -13859,21 +14038,29 @@ The `<agent-3d>` element accepts several source forms. Priority when multiple at<agent-3d body="./product.glb"></agent-3d>```-Programmatically (SDK):+Programmatically, the same loader the element uses is a named export of the published bundle:```js-import { assertValid } from '@three-ws/avatar-schema';--// Fetch the manifest from wherever it lives — your resolver, an IPFS-// gateway, or a plain HTTPS URL — then validate it against the schema.-const res = await fetch('https://cdn.acme.com/aria/manifest.json');-const manifest = await res.json();+import { loadManifest, normalize } from 'https://three.ws/agent-3d/1.5.2/agent-3d.js';++// One call for every source form the element accepts: agent:// (resolved+// through the ERC-8004 registry on the named chain), ipfs://, ar://, and+// plain HTTPS.+// Any live agent on the platform serves one, so this runs as written:+const manifest = await loadManifest(+ 'https://three.ws/api/agents/27a0f649-3b59-4552-bb0b-faf616ac448b/manifest',+);-// Throws if the document does not match the canonical avatar manifest schema.-assertValid(manifest);+console.log(manifest.name, manifest.body.uri);```-`assertValid` throws if the document does not match the canonical avatar manifest schema, and returns normally when it does. Prefer `validate(manifest)` when you want a `{ valid, errors }` result instead of an exception. Resolve any relative paths in the manifest against the URL you fetched it from.+`loadManifest` returns the manifest already normalized. It records the directory the manifest was fetched from in `_baseURI`, which is what makes the bundle's relative paths (`instructions.md`, `skills/wave/`, `memory/MEMORY.md`) resolvable, and it adapts an ERC-8004 registration JSON into this manifest shape when that is what the URI serves. Call `fetchRelative(manifest, 'instructions.md')` to pull a bundle file against that base. If you already hold the parsed JSON, `normalize(json, { baseURI })` does the shape work alone.++> `@three-ws/avatar-schema` is **not** the validator for this document. It+> validates the *avatar* manifest (`avatar.v1.json`: `schemaVersion`, `mesh`,+> `skeleton`, `owner`), which describes a 3D body, not an agent. Running+> `assertValid` from that package on an agent manifest always throws. See+> [Agents vs. avatars](#sec-073) for why the two are separate.---@@ -24971,7 +25158,7 @@ curl -X POST https://three.ws/api/pay/execute \}```-If the endpoint answers without a `402`, it was free. You get `paid: false` and the session is never touched.+If the endpoint answers a success without a `402`, it was free. You get `paid: false` and the session is never touched. If it answers an error status without a `402`, nothing was payable and nothing succeeded: you get `502 endpoint_error` with the real `upstream_status` and `upstream_body`, and the session is still never touched.### Governance errors@@ -26921,13 +27108,15 @@ path is the canonical one.| Parameter | Default | Meaning ||---|---|---|| `category` | all | Exact category slug, as returned by `/api/plugins/categories` |-| `q` | none | Case-insensitive substring match on name or description (first 80 chars used) |+| `q` | none | Case-insensitive substring match on name or description (first 80 chars used). Taken literally: `%` and `_` are escaped, not treated as wildcards. || `sort` | `popular` | `popular` (install count), `new` (newest first), or `az` (name). An unknown value falls back to `popular`. || `limit` | `20` | 1 to 40 || `cursor` | `0` | Opaque offset. Pass back the `next_cursor` from the previous page verbatim. |`cursor` must be a non-negative integer; anything else is a `400`-(`validation_error`), never a 500. `next_cursor` is `null` on the last page.+(`validation_error`), never a 500. `next_cursor` is `null` on the last page. The+sort is fully ordered (ties break on the plugin id), so paging through the whole+catalogue returns every plugin exactly once.```bashcurl -s 'https://three.ws/api/plugins/list?sort=az&limit=2' | jq '.data.items[].identifier'@@ -27019,8 +27208,10 @@ metadata ranges are refused (`400`, `validation_error`). The transfer is cappedat 64 KB and aborted mid-stream if the host exceeds it (`422`, `fetch_failed`).**Errors:** `400` (missing / unparseable / non-http `manifest_url`, blocked-host), `422` (`fetch_failed` for a non-2xx, unparseable, or oversized response;-`invalid_manifest` when the JSON is not a manifest), `429`.+host), `422` (`fetch_failed` for a non-2xx or oversized response;+`invalid_manifest` when the response is not JSON at all, which is what linking a+repository page instead of the raw file produces, or when the JSON is not a+manifest), `429`.### Publish a plugin@@ -27051,11 +27242,128 @@ reads to you. Responds with the same plugin shape the list returns.**Manifest rules:** `identifier` is required, alphanumeric plus `.`, `-`, `_`,and at most 128 characters; `meta.title` is required; `api` must be a non-empty-array of at most 100 tools, each with a `name` and a `description`. A violation-is a `422` (`invalid_manifest`) naming the specific rule.+array of at most 100 tool objects. Each tool needs a `name` of 1 to 64 letters,+digits, underscores, or hyphens (the charset every model provider accepts for a+tool definition, since installers pass these straight through) and a non-empty+`description` of at most 1024 characters. The whole manifest must serialize to+64 KB or less, the same ceiling the import fetch enforces, because it is stored+verbatim and re-served on every read. A violation is a `422`+(`invalid_manifest`) naming the specific rule.**Errors:** `401` (no auth), `403` (`csrf_missing` / `csrf_invalid`), `400`-(malformed body), `422` (`invalid_manifest`), `429`.+(malformed body), `413` (body over the manifest ceiling), `422`+(`invalid_manifest`), `429`.++---++## IPFS Pinning API++Puts bytes on IPFS and reports whether they are still held there. Both actions+live in `api/pinning/[action].js`.++The pinning credential is server-held and never reaches the browser, which is+the whole reason this endpoint exists: the Avatar Studio mint flow+(`character-studio/src/library/mint-utils.js`) posts an avatar here instead of+talking to a pinning provider directly. Providers are tried in order, Pinata+first and web3.storage second, matching `api/_lib/ipfs-pin.js`.++### Pin a file++```+POST /api/pinning/pin+```++Authenticated: a session cookie or a bearer token. Rate limited to 30 pins per+hour per user.++| Field | Required | Meaning |+|---|---|---|+| `sourceUrl` | yes | Either a `data:` URL carrying the bytes inline, or an `https://` URL on the platform's own storage domain. Any other host is a `400`. |+| `kind` | yes | `glb` or `manifest`. Anything else is a `400`. |+| `filename` | no | The name filed at the provider. Reduced to `A-Za-z0-9._-` and capped at 128 characters; a value that survives none of that, or is not a string, falls back to `avatar.glb` or `manifest.json` by `kind`. Omitted on a storage-URL pin, the object's own key is used. |++Three size ceilings apply, and they are different numbers because they bound+different things:++| Ceiling | Value | Applies to |+|---|---|---|+| Request body | 8 MB | The whole JSON document, enforced by the server for every endpoint |+| Inline payload | 5 MB | The decoded bytes of a `data:` URL. Base64 inflates raw bytes by 4/3, so 5 MB of payload is about 6.7 MB of body |+| Storage source | 50 MB | The object fetched from an `https://` source URL |++Anything larger than the inline ceiling should be uploaded to storage first and+pinned by URL, which is what the 50 MB lane is for.++```bash+curl -X POST https://three.ws/api/pinning/pin \+ -H "Authorization: Bearer $THREE_WS_TOKEN" \+ -H "Content-Type: application/json" \+ -d '{"sourceUrl":"data:application/json;base64,eyJuYW1lIjoiS25pZ2h0In0=","kind":"manifest","filename":"knight.json"}'+```++```json+{+ "ok": true,+ "cid": "QmYazpLPRXtuBsCQk64LpXohMxSGJa3RoQTx9fckJgPY9o",+ "gatewayUrl": "https://ipfs.io/ipfs/QmYazpLPRXtuBsCQk64LpXohMxSGJa3RoQTx9fckJgPY9o",+ "gatewayUrls": [+ "https://ipfs.io/ipfs/QmYazpLPRXtuBsCQk64LpXohMxSGJa3RoQTx9fckJgPY9o",+ "https://dweb.link/ipfs/QmYazpLPRXtuBsCQk64LpXohMxSGJa3RoQTx9fckJgPY9o",+ "https://w3s.link/ipfs/QmYazpLPRXtuBsCQk64LpXohMxSGJa3RoQTx9fckJgPY9o",+ "https://gateway.pinata.cloud/ipfs/QmYazpLPRXtuBsCQk64LpXohMxSGJa3RoQTx9fckJgPY9o"+ ],+ "provider": "pinata"+}+```++`gatewayUrl` is the single canonical read URL; `gatewayUrls` is every gateway+worth trying. A freshly pinned CID takes minutes to propagate across the public+network, so the provider's own gateway (last in the list) is the one guaranteed+to serve it immediately.++**Errors:** `400` (`validation_error`: missing `sourceUrl`, bad `kind`,+malformed `data:` URL, or a source host the platform does not own), `401`+(`unauthorized`), `413` (`payload_too_large`, naming the ceiling that was+crossed), `415` (body was not JSON), `429` (`rate_limited`), `502`+(`fetch_failed`: the source URL was unreachable or redirected), `503`+(`pinning_unconfigured`).++A request that is malformed always answers `4xx`, including on a deployment+with no provider configured: the `503` is reached only once the request itself+is known to be valid.++### Check whether a CID is still pinned++```+GET /api/pinning/status?cid=<cid>+```++Public, unauthenticated, rate limited by IP. `cid` must be 16 to 128+alphanumeric characters.++```bash+curl "https://three.ws/api/pinning/status?cid=QmYazpLPRXtuBsCQk64LpXohMxSGJa3RoQTx9fckJgPY9o"+```++```json+{+ "cid": "QmYazpLPRXtuBsCQk64LpXohMxSGJa3RoQTx9fckJgPY9o",+ "pinned": true,+ "provider": "pinata",+ "unreachableProviders": [],+ "gatewayUrls": ["https://ipfs.io/ipfs/QmYazpLPRXtuBsCQk64LpXohMxSGJa3RoQTx9fckJgPY9o"]+}+```++`pinned: false` means every provider that answered said it is not holding the+CID. It never means "we could not tell": a provider that failed to answer is+named in `unreachableProviders` instead, and if none of them answered the+response is a `503` (`pinning_check_failed`) rather than a `200`. Treat+`unreachableProviders` as non-empty before acting on `pinned: false`, because a+partial answer is still a partial answer.++**Errors:** `400` (`validation_error`: missing or out-of-bounds `cid`), `429`+(`rate_limited`), `503` (`pinning_unconfigured` or `pinning_check_failed`).---@@ -29880,7 +30188,7 @@ three-ws-avatar --version``````-0.2.1+0.2.0```Or run it without installing. The package has exactly one binary, so `npx` resolves it directly:@@ -29892,7 +30200,7 @@ npx @three-ws/avatar-cli --versionPin the version in anything automated so a future release cannot change your build's behavior:```bash-npx @three-ws/[email protected] validate manifest.json+npx @three-ws/[email protected] validate manifest.json```Node 18 or newer. The CLI has one runtime dependency, `@three-ws/avatar-schema`, which carries the JSON Schema it validates against.@@ -29949,7 +30257,7 @@ three-ws-avatar init --owner <id> --name <name> --mesh <path> [options]| Flag | Required | Description ||---|---|---|-| `--owner <caip10\|0x…>` | yes | Owner identity. Full CAIP-10 (`eip155:1:0xabc…`) or a bare `0x…` address, which is assumed to be `eip155:1`. |+| `--owner <caip10\|sol\|0x…>` | yes | Owner identity. Full CAIP-10 (`eip155:1:0xabc…`), a bare Solana address, which is assumed to be `solana:mainnet-beta`, or a bare `0x…` address, which is assumed to be `eip155:1`. || `--name <string>` | yes | Display name. If it looks like a name service handle (`nick.eth`, `nick.ws`, `nick.sol`) it also becomes the manifest `id`. || `--mesh <path>` | yes | Path to a `.glb`, `.gltf`, or `.vrm` file. Must exist; the extension decides `mesh.format`. || `--skeleton <name>` | no | One of `avaturn`, `mixamo`, `rpm`, `vrm-humanoid`, `custom`. Default `avaturn`. |@@ -31886,8 +32194,19 @@ node --env-file=.env.local scripts/backfill-avatar-thumbnails.mjs --limit=2000 -node --env-file=.env.local scripts/backfill-avatar-thumbnails.mjs --restyle=200 --limit=200```-Requires `DATABASE_URL` and the `S3_*` credentials, both of which live in-`.env.local`.+Requires `DATABASE_URL` plus the `S3_*` credentials (`S3_BUCKET`,+`S3_ACCESS_KEY_ID`, `S3_SECRET_ACCESS_KEY`, `S3_ENDPOINT`, `S3_PUBLIC_DOMAIN`).+Only `DATABASE_URL` is in `.env.local`; the authoritative copy of the `S3_*` set+lives on the Cloud Run service, so `--env-file=.env.local` alone exits with+`S3_BUCKET is unset`. Export them into the shell first:++```bash+eval "$(gcloud run services describe three-ws-api --region us-central1 \+ --project aerial-vehicle-466722-p5 --format=json \+ | node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{for(const e of JSON.parse(s).spec.template.spec.containers[0].env||[])if(e.name.startsWith("S3_")&&e.value)console.log(`export ${e.name}=${JSON.stringify(e.value)}`)})')"+```++Then any of the commands above runs as written.## Rendering a thumbnail yourself@@ -32157,6 +32476,7 @@ create table if not exists payment_sessions (max_per_tx_usdc bigint check (max_per_tx_usdc > 0),allowed_hosts text[] not null default '{}',network text not null default 'solana' check (network in ('solana', 'base')),+ connector_ref text,status text not null default 'active'check (status in ('active', 'exhausted', 'expired', 'cancelled')),@@ -32174,11 +32494,16 @@ Three details in there are load-bearing.**Money is `bigint`, never `float`.** USDC has six decimals, so every amount is stored in atomic units and converted at the edges. A rounding error in a budget check is a security bug, not a display bug.```js+// USDC has 6 decimals everywhere we settle (Solana mainnet and Base mainnet).+export const USDC_DECIMALS = 6;+const USDC_SCALE = 10 ** USDC_DECIMALS;+export function usdToAtomics(usd) {- return BigInt(Math.round(Number(usd) * 1_000_000));+ return BigInt(Math.round(Number(usd) * USDC_SCALE));}+export function atomicsToUsd(atomics) {- return Number(atomics) / 1_000_000;+ return Number(atomics) / USDC_SCALE;}```@@ -32255,13 +32580,22 @@ Now the policy runs, in order, cheapest and most decisive first: status, then exThe allowlist check is the one worth showing, because the subdomain rule is where these go wrong:```js-const canonicalAllowlist = allowedHosts.map(normalizeHost).filter(Boolean);-const allowed = canonicalAllowlist.some(- (h) => targetHost === h || targetHost.endsWith(`.${h}`),-);+export function canonicalizeAllowlist(allowedHosts) {+ if (!Array.isArray(allowedHosts)) return [];+ return allowedHosts.map(normalizeHost).filter(Boolean);+}++export function hostMatches(targetHost, entry) {+ if (!targetHost || !entry) return false;+ return targetHost === entry || targetHost.endsWith(`.${entry}`);+}```-`targetHost.endsWith('.' + h)` and not `targetHost.endsWith(h)`. Without the dot, an allowlist entry of `example.com` also authorizes `evil-example.com`, and an attacker who can steer your agent to a URL just needs to register the right domain. Hosts are normalized through the URL parser first, so `HTTPS://Example.COM:443/x` and `example.com` compare equal.+The verdict is then `canonical.some((entry) => hostMatches(targetHost, entry))`.++`targetHost.endsWith('.' + entry)` and not `targetHost.endsWith(entry)`. Without the dot, an allowlist entry of `example.com` also authorizes `evil-example.com`, and an attacker who can steer your agent to a URL just needs to register the right domain. That is exactly why this is a named function with a test behind it rather than an inline `endsWith`. Hosts are normalized through the URL parser first, so `HTTPS://Example.COM:443/x` and `example.com` compare equal.++These predicates live in [`api/_lib/pay/policy.js`](https://github.com/nirholas/three.ws/blob/main/api/_lib/pay/policy.js) and are shared with the dry-run simulator, so a simulated verdict and an enforced one can never disagree.### Phase 3: the atomic reservation@@ -32298,18 +32632,25 @@ Row-level locking means the second `UPDATE` re-evaluates its `WHERE` clause agai```jsif (!updated) {+ // Could be exhausted mid-race; check to give a precise errorconst [fresh] = await sql`SELECT budget_usdc, spent_usdc FROM payment_sessions WHERE id = ${session.id}`;const remaining = fresh ? BigInt(fresh.budget_usdc) - BigInt(fresh.spent_usdc) : 0n;- throw new SpendGovernorError(- 'insufficient_budget',- `Insufficient session budget. Need $${atomicsToUsd(amount)}, remaining $${atomicsToUsd(remaining)}`,- { need_usd: atomicsToUsd(amount), remaining_usd: atomicsToUsd(remaining) },+ // The SQL predicate already decided; budgetVerdict only phrases the failure,+ // using the same wording the simulator shows for a predicted shortfall.+ throwVerdict(+ budgetVerdict(amount, remaining) ?? {+ code: 'insufficient_budget',+ message: 'Session was not active when the payment was reserved',+ detail: { need_usd: atomicsToUsd(amount), remaining_usd: atomicsToUsd(remaining) },+ },);}```+`throwVerdict` raises a `SpendGovernorError` carrying the machine-readable `code` the API layer maps to a status (`insufficient_budget` becomes a `402`).+No advisory locks, no transaction retry loop, no distributed lock service. One statement whose `WHERE` clause is the invariant. If you take one thing from this article, take this: **write the budget check as a predicate in the `UPDATE`, not as a `SELECT` before it.**Note that this is a *reservation*, taken before the payment is attempted. Optimistic ordering, because the alternative is holding budget open across a network call to a third party.@@ -32473,15 +32814,25 @@ It gets back the result it wanted plus the receipt it did not ask for: amount, nA budget is debited from the developer's credit balance the moment the session is created, which means an expiry that just marks a row `expired` quietly keeps their money. A sweep runs every five minutes and refunds the difference:```js-const allExpired = await sql`- UPDATE payment_sessions+const expiredRows = await sql`+ WITH due AS (+ SELECT id FROM payment_sessions+ WHERE status = 'active'+ AND expires_at < now()+ ORDER BY expires_at ASC+ LIMIT ${BATCH_LIMIT}+ FOR UPDATE SKIP LOCKED+ )+ UPDATE payment_sessions sSET status = 'expired', updated_at = now()- WHERE status = 'active'- AND expires_at < now()- RETURNING id, user_id, budget_usdc, spent_usdc+ FROM due+ WHERE s.id = due.id+ RETURNING s.id, s.user_id, s.budget_usdc, s.spent_usdc`;```+The batch limit lives inside the `UPDATE` rather than in a JS slice of the result, and that is not a detail. An unbounded `UPDATE` flips every due session to `expired` while only the sliced head is ever refunded, and the remainder is then invisible to the next tick, which only looks at `status = 'active'`. Whatever this tick does not claim stays active and is swept next time. `FOR UPDATE SKIP LOCKED` keeps concurrent ticks on disjoint rows.+Then, per row, with an idempotency key derived from the session id so overlapping ticks cannot double-refund:```js@@ -32513,15 +32864,15 @@ An autonomous agent with a private key is a liability you cannot bound. An auton## Resources-- **Source:** [`api/pay/execute.js`](https://github.com/nirholas/three.ws/blob/main/api/pay/execute.js) is the request path, [`api/_lib/pay/spend-governor.js`](https://github.com/nirholas/three.ws/blob/main/api/_lib/pay/spend-governor.js) is the governor, [`api/_lib/pay/payment-session.js`](https://github.com/nirholas/three.ws/blob/main/api/_lib/pay/payment-session.js) is the lifecycle+- **Source:** [`api/pay/execute.js`](https://github.com/nirholas/three.ws/blob/main/api/pay/execute.js) is the request path, [`api/_lib/pay/spend-governor.js`](https://github.com/nirholas/three.ws/blob/main/api/_lib/pay/spend-governor.js) is the governor, [`api/_lib/pay/policy.js`](https://github.com/nirholas/three.ws/blob/main/api/_lib/pay/policy.js) holds the shared policy predicates, [`api/_lib/pay/payment-session.js`](https://github.com/nirholas/three.ws/blob/main/api/_lib/pay/payment-session.js) is the lifecycle, and [`api/cron/payment-session-sweep.js`](https://github.com/nirholas/three.ws/blob/main/api/cron/payment-session-sweep.js) is the expiry-and-refund sweep- **MCP server:** [`@three-ws/agentcore-payments-mcp`](https://github.com/nirholas/three.ws/tree/main/packages/agentcore-payments-mcp)- **x402:** [x402.org](https://www.x402.org), the HTTP-native pay-per-call standard the payments settle over- **Model Context Protocol:** [modelcontextprotocol.io](https://modelcontextprotocol.io)-- **Our previous Builder Center article:** [How we metered a SaaS product through AWS Marketplace with the AWS SDK for JavaScript v3](https://builder.aws.com/content/3ESpll50BdSp9eiCEIxcfG9pGUN/how-we-metered-a-saas-product-through-aws-marketplace-with-the-aws-sdk-for-javascript-v3), which covers the other half of this: how the credits that fund a session get billed to an AWS invoice+- **Our previous Builder Center article:** [How we metered a SaaS product through AWS Marketplace with the AWS SDK for JavaScript v3](https://builder.aws.com/content/3ESpll50BdSp9eiCEIxcfG9pGUN/how-we-metered-a-saas-product-through-aws-marketplace-with-the-aws-sdk-for-javascript-v3), which covers the other half of this: how an AWS Marketplace subscription resolves into the same access check that grants a session----*three.ws is a verified AWS Partner and an open-source platform for 3D AI agents and on-chain communities, available on AWS Marketplace with AWS billing wired into its metered API. Live at [three.ws](https://three.ws).*+*three.ws is a verified AWS Partner and an open-source platform for 3D AI agents and on-chain communities, with an AWS Marketplace listing built and awaiting publication. Live at [three.ws](https://three.ws).*---@@ -32544,6 +32895,8 @@ tags: [aws, marketplace, saas, serverless, api]# One paywall, two economies: putting AWS Marketplace metering in front of an x402 API+> **Editor's note (2026-08-15).** This is the repo copy of an article published on the AWS Builder Center on 30 May 2026, kept as it was published. One thing has moved since: the AWS Marketplace listing is still awaiting publication, and the pricing decision landed on a **free** listing with no AWS pricing dimensions, so the AWS-metered path described below is built and deployed but not yet billing anyone. Every code sample is still the code that ships. For the current status see [aws-marketplace.md](#sec-122).+We run [three.ws](https://three.ws), an open-source platform for 3D AI agents and on-chain communities. Our paid API already had a billing system: **x402**, the HTTP-native pay-per-call protocol where a request to a metered endpoint either carries a subscription key or gets a `402 Payment Required`. That works great for developers who pay in stablecoins.But a lot of teams don't want to touch crypto to pay an invoice. They want it on their AWS bill — drawn down from credits, counted toward their EDP commitment, one line item under *AWS Marketplace Software*. So we listed three.ws as a **SaaS usage-based product on AWS Marketplace** and wired AWS billing straight into the same access check that already powered x402.@@ -32839,14 +33192,16 @@ The OAuth flow is the textbook one: dynamic client registration (RFC 7591), PKCE## Surface two: paid tools that pay for themselves-This is the part I am most proud of. The npm package `@three-ws/mcp-server` exposes a suite of paid tools that take **no subscription and no API key**. Each call settles per-use in USDC over the x402 protocol (the HTTP 402 Payment Required status code, finally put to work). You configure a wallet address, not a key.+This is the part I am most proud of. The npm package `@three-ws/mcp-server` exposes a suite of paid tools that take **no subscription and no API key**. Each call settles per-use in USDC over the x402 protocol (the HTTP 402 Payment Required status code, finally put to work). You configure a wallet address, not a key. Settlement is USDC on Solana mainnet, `exact` scheme.++Four of the paid tools, to give the shape of the suite (the [package README](https://github.com/nirholas/three.ws/blob/main/mcp-server/README.md) carries the full list and the current prices, which come straight from each tool's source):| Tool | Price | What it returns ||---|---|---|| `get_pose_seed` | $0.001 | A deterministic seed and full Euler-rotation pose map for the pose-studio mannequin, plus a preview URL. || `pump_snapshot` | $0.005 | A live token snapshot: USD price (Jupiter), 24h volume and pair (Dexscreener), mint metadata and image, and on-chain top-holder distribution (Solana RPC). || `agent_reputation` | $0.01 | ERC-8004 on-chain reputation for an agent: score, total stake, and the latest reputation events from the canonical registry (default Base). |-| `vanity_grinder` | up to $0.50 | A Solana keypair whose address starts with a prefix you choose. Settled USDC scales with the work actually done, capped at $0.50. |+| `vanity_grinder` | $0.05 | A Solana keypair whose address starts with a prefix you choose. A flat `exact` settlement regardless of how many attempts the grind took: `@x402/svm` ships no metered `upto` scheme, so Solana bills one price per successful grind. |Setup is a wallet, not an account:@@ -32857,7 +33212,6 @@ Setup is a wallet, not an account:"command": "npx","args": ["-y", "@three-ws/mcp-server"],"env": {- "MCP_EVM_PAYMENT_ADDRESS": "0xYourBaseWallet","MCP_SVM_PAYMENT_ADDRESS": "YourSolanaWallet"}}@@ -32886,7 +33240,7 @@ The npm package is a stdio-to-HTTP bridge. It speaks MCP over stdio to the clien## Where AWS comes in-The platform stores its assets on S3-compatible object storage and is available to subscribe through AWS Marketplace, so usage lands on your AWS bill and counts toward existing commitments (the Marketplace metering integration calls AWS in `us-east-1`). three.ws is an AWS Partner (APN Software Path, Technology Partner).+The platform stores its assets on S3-compatible object storage, and its AWS Marketplace listing is built and awaiting publication, so procurement can go through AWS instead of a new vendor relationship (the Marketplace integration calls AWS in `us-east-1`). The subscription itself is free and issues the API key; the paid tools still settle per call in USDC. three.ws is an AWS Partner (APN Software Path, Technology Partner).The MCP server itself is intentionally cloud-agnostic: it is an npm bridge to an HTTP API, so it drops into a Bedrock agent, a Strands agent, a Claude Code session, or anything else that speaks MCP, without caring where the agent runs. If you are building agentic systems on AWS and want them to use paid external tools without a human managing keys, this is a working pattern you can copy.@@ -32900,7 +33254,7 @@ If you wire it into something, or you want to list a paid tool of your own, the----*three.ws is an open-source platform for 3D AI agents and on-chain communities, an AWS Partner and available on AWS Marketplace. Live at [three.ws](https://three.ws).*+*three.ws is an open-source platform for 3D AI agents and on-chain communities, an AWS Partner with an AWS Marketplace listing built and awaiting publication. Live at [three.ws](https://three.ws).*---@@ -33360,10 +33714,14 @@ creation time (`saas-create-product` says the EventBridge configuration appears# three.ws on AWS Marketplace-three.ws is a verified AWS Partner and listed on AWS Marketplace as an API-based (SaaS) product. The AWS subscription is a **free front door**: subscribing links your AWS account to a three.ws account and issues an x402 access key. Actual usage is then paid per-call in USDC over the x402 / HTTP 402 protocol — the same as every other x402 endpoint. AWS Marketplace itself does not meter or bill usage.+three.ws is a verified AWS Partner. The AWS Marketplace product is an API-based (SaaS) listing, and the AWS subscription is a **free front door**: subscribing links your AWS account to a three.ws account and issues an x402 access key. Actual usage is then paid per-call in USDC over the x402 / HTTP 402 protocol, the same as every other x402 endpoint. AWS Marketplace itself does not meter or bill usage.++> **Listing status (checked 2026-08-15): not yet public.** Every endpoint described below is built and deployed, but the product has not been created in the AWS Marketplace Management Portal, so there is nothing to subscribe to on the AWS side yet. The Marketplace credentials (`AWS_MP_*`) are correspondingly unset in production, so `POST /api/aws-marketplace/subscription` answers `503 not_configured` today. The remaining steps are AWS-console work and Seller Operations approval, tracked in [aws-marketplace-listing-kit.md](#sec-121). Until then, use x402 directly: no AWS subscription is required to call `/api/x402/*`.## Subscribing via AWS Marketplace+This is the flow once the listing is public.+1. Find the three.ws listing on [AWS Marketplace](https://aws.amazon.com/marketplace).2. Choose **Subscribe** — the AWS Marketplace subscription is free.3. After confirming in AWS, you are redirected to `https://three.ws/aws-marketplace/welcome` to complete account setup.@@ -33372,7 +33730,7 @@ three.ws is a verified AWS Partner and listed on AWS Marketplace as an API-based## Billing-The AWS Marketplace subscription is free — there are no AWS pricing dimensions, no contract, and no AWS-side metering. Usage is paid per-call in USDC via x402 (HTTP 402): every call returns a structured 402 challenge, your wallet or facilitator pays in USDC, and the request retries automatically. This is identical to how a non-AWS caller pays, so there is nothing to reconcile on your AWS invoice.+The AWS Marketplace subscription is free: there are no AWS pricing dimensions, no contract, and no AWS-side metering. Usage is paid per-call in USDC via x402 (HTTP 402): every call returns a structured 402 challenge, your wallet or facilitator pays in USDC, and the request retries automatically. This is identical to how a non-AWS caller pays, so there is nothing to reconcile on your AWS invoice.## AWS account@@ -33435,7 +33793,7 @@ For platform support, open an issue at [github.com/nirholas/three.ws/issues](htttitle: "three.ws on AWS: giving AI agents a body, a wallet, and an AWS bill"venue: AWS Builder Center / APN Partner Spotlightaccount: three.ws (official)-description: "A look at three.ws, an AWS Technology Partner building browser-native 3D AI agents that you can buy through AWS Marketplace, govern before they act, embed like a video, and let pay for their own work, all on infrastructure that meters to your AWS bill."+description: "A look at three.ws, an AWS Technology Partner building browser-native 3D AI agents that you will buy through AWS Marketplace, govern before they act, embed like a video, and let pay for their own work."tags: [aws, marketplace, agentic-ai, generative-ai, 3d, open-source]canonical: https://three.ws/docs/aws-partner-spotlight.md---@@ -33446,7 +33804,7 @@ Most enterprise AI agents live inside a chat box. For a lot of work that is exac[three.ws](https://three.ws) is built on a simple thesis: the next interface for AI is spatial, embeddable, and able to act. The platform gives an AI agent a body. You describe an agent in a sentence, and in a few minutes it becomes a textured, rigged, talking 3D character. You give it a brain, optionally a wallet and an on-chain identity, and you drop it onto any web page with a single line of HTML, as easily as embedding a video. The agent renders right in the browser, holds a conversation, remembers across visits, reacts to the page around it, and when you let it, pays for the data and tools it needs to be useful.-three.ws is an **AWS Technology Partner in the AWS Partner Network** and is **live on AWS Marketplace**, so an enterprise can adopt all of this through procurement it already trusts. This is a look at what the team has built, what they are building next, and why running it with AWS makes embodied agents something a business can actually buy, govern, and put into production.+three.ws is an **AWS Technology Partner in the AWS Partner Network**, and the AWS Marketplace listing is built and awaiting publication, so an enterprise will be able to adopt all of this through procurement it already trusts. This is a look at what the team has built, what they are building next, and why running it with AWS makes embodied agents something a business can actually buy, govern, and put into production.---@@ -33484,9 +33842,9 @@ The throughline across all of it is a single, ambitious idea: an agent you can sthree.ws runs across several clouds, each carrying the work it is best at, and AWS carries the parts where its strengths matter most: storage and delivery of the 3D assets, a slice of the rendering, the operational visibility a serious platform needs, and, most importantly for an enterprise, procurement.-The platform is listed on **AWS Marketplace** as a usage-based product. That single fact changes how a business can adopt it. Instead of a separate vendor relationship and a new way to pay, an enterprise subscribes through the marketplace it already uses, and consumption shows up as one line item on the AWS bill, drawn from existing credits and counted toward existing commitments. No crypto and no card are required to get started. The finance and security teams see something familiar, and the builders get an agent platform without a procurement detour.+The platform is being listed on **AWS Marketplace** as an API-based (SaaS) product. That single fact changes how a business can adopt it. Instead of a separate vendor relationship and a new way to pay, an enterprise subscribes through the marketplace it already uses, and the subscription itself is free: it links the AWS account, issues an API key, and hands the builders an agent platform without a procurement detour. The finance and security teams see something familiar. (The listing is complete on our side and waiting on AWS publication; until it goes public, the same API is reachable directly.)-What makes this genuinely novel is what sits underneath. three.ws agents can already pay for tools on their own, by the call, over an open payment rail. The team connected that same rail to AWS Marketplace, so one product now bills two ways through the very same door. A large enterprise pays through AWS and sees a clean line item. An independent developer pays per call with stablecoins and needs no account at all. Both are reaching the identical capability. The choice of how to pay is theirs, and the platform meters whichever world the caller comes from. That is a clean, pay-for-what-you-use model that fits how enterprises actually want to adopt agentic AI: autonomous where it helps, bounded by policy, and auditable end to end.+What makes this genuinely novel is what sits underneath. three.ws agents can already pay for tools on their own, by the call, over an open payment rail. The team wired AWS Marketplace into the very same access check, so one product serves two economies through one door. An enterprise buyer arrives through AWS procurement. An independent developer pays per call with stablecoins and needs no account at all. Both reach the identical capability, and the platform recognizes whichever world the caller comes from without forking its authorization path. That is a clean, pay-for-what-you-use model that fits how enterprises actually want to adopt agentic AI: autonomous where it helps, bounded by policy, and auditable end to end.Running on AWS also brings the operational posture an enterprise expects. The team manages its AWS footprint as code, so the environment is reproducible and reviewable rather than hand-assembled. Activity is centralized where an AWS-native operations team already looks, so the people responsible for uptime and security can watch the platform with the tools they already trust. And the whole thing is grouped as a single application in the AWS console, with cost and operational views in one place.@@ -33512,14 +33870,14 @@ Voice and presence are getting deeper, with real-time spoken conversation, voice## In short-three.ws gives an AI agent a body, a memory, a personality, an identity, and the ability to act and pay, then makes it embeddable in a single line of HTML. AWS is what makes it adoptable at enterprise scale: a platform you can buy through AWS Marketplace, govern before it acts, watch with the tools you already run, and bill, by the call, to your AWS account, against the very same capability an independent developer reaches with no account at all.+three.ws gives an AI agent a body, a memory, a personality, an identity, and the ability to act and pay, then makes it embeddable in a single line of HTML. AWS is what makes it adoptable at enterprise scale: a platform you will buy through AWS Marketplace, govern before it acts, and watch with the tools you already run, reaching the very same capability an independent developer reaches with no account at all.-One product. Two ways to pay. One AWS bill.+One product. Two ways in. One authorization path.**Learn more**- Platform: [three.ws](https://three.ws)-- AWS Marketplace and procurement: `three.ws/docs/aws-marketplace.md`-- How agents reach and pay for tools: `three.ws/docs/x402.md`, `three.ws/docs/mcp.md`+- AWS Marketplace and procurement: [three.ws/docs/aws-marketplace](#sec-122)+- How agents reach and pay for tools: [three.ws/docs/x402](#sec-519), [three.ws/docs/mcp](#sec-276)---@@ -35324,21 +35682,25 @@ The CDN bundle is served from three.ws (Google Cloud Run + CDN). The URL includeThe CDN also maintains rolling channel aliases:-| URL pattern | Tracks |+Every channel is a directory holding the same file name, so only the path segment changes:++| URL | Tracks ||---|---|-| `[email protected]` | Exact version (immutable) |-| `[email protected]` | Latest `1.5.x` patch |-| `[email protected]` | Latest `1.x` minor |-| `agent-3d.js` | Latest stable (any version) |+| `https://three.ws/agent-3d/1.5.2/agent-3d.js` | Exact version (immutable) |+| `https://three.ws/agent-3d/1.5/agent-3d.js` | Latest `1.5.x` patch |+| `https://three.ws/agent-3d/1/agent-3d.js` | Latest `1.x` minor |+| `https://three.ws/agent-3d/latest/agent-3d.js` | Latest stable (any version) |**Recommendation:** Pin to a full `MAJOR.MINOR.PATCH` version in production. Upgrade intentionally after reviewing the migration notes for the target version.-Each versioned bundle ships with a `integrity.json` sidecar for [Subresource Integrity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity) verification:+The immutable exact-version directory ships an `integrity.json` sidecar for [Subresource Integrity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity) verification. The rolling channels deliberately have none, because their contents change:```-https://three.ws/agent-3d/1.5.1/integrity.json+https://three.ws/agent-3d/1.5.2/integrity.json```+The same SHA-384 hashes are published for every version at once in the CDN version index, `https://three.ws/agent-3d/versions.json`.+---## Smart Contract Versioning@@ -35448,7 +35810,7 @@ For contributors and maintainers. A release follows these steps:5. A GitHub Release is created from the tag with the changelog entry as the body.6. `npm run build:all` produces the platform bundle and the CDN library build.7. `npm run publish:lib` copies the CDN bundle into `dist/agent-3d/{version}/`, generates an `integrity.json` sidecar with SHA-384 hashes, updates the rolling channel aliases (`1.5`, `1`, `latest`), and writes a `versions.json` manifest.-8. The image is deployed to Google Cloud Run (`npm run build` then `npm run deploy:gcp`), which serves the updated `dist/` directory — including the CDN library build — from the `three-ws-api` service.+8. The image is deployed to Google Cloud Run with `npm run deploy:gcp:full`, which serves the updated `dist/` directory (including the CDN library build) from the `three-ws-api` service. That one command runs the full `build:gcp` chain and then `deploy:gcp`; a bare `npm run build` is not enough on its own, because the deploy gate checks `dist/` for the UMD library that `build:lib:full` and `publish:lib` put there.The SDK (`@three-ws/sdk`) is published to npm separately:@@ -38680,7 +39042,7 @@ The three.ws avatar builder is an open-source 3D avatar editor (full body customAVATURN_API_KEY=xxxxx```-Sign up at [avaturn.me/developer](https://avaturn.me/developer).+Sign up through the [Avaturn developer docs](https://docs.avaturn.me/).#### `AVATURN_API_URL`**Optional.** Override for self-hosted or staging photo pipeline deployments. Defaults to `https://api.avaturn.me`.@@ -38860,7 +39222,7 @@ A **live configuration file** consumed at runtime by the Cloud Run server ([`ser}```-**Cron jobs** are declared here as the source of truth for the schedule (currently 103 entries); in production they are driven by **Google Cloud Scheduler**, each job hitting its `/api/cron/*` handler on the Cloud Run service:+**Cron jobs** are declared here as the source of truth for the schedule. Read the `crons` array itself for the current set rather than trusting a count quoted in prose. In production they are driven by **Google Cloud Scheduler**, each job hitting its `/api/cron/*` handler on the Cloud Run service:```json"crons": [@@ -39469,7 +39831,7 @@ npm run verify## Publishing MCP servers & standalone mirrors-Every MCP server package (any directory with both a `package.json` and a `server.json` — the 32 under `packages/*-mcp`, plus `packages/agent-sniper`, `mcp-server`, and `mcp-bridge`) ships to three destinations. All steps are idempotent and default to a safe dry run.+Every MCP server package ships to three destinations. The authoritative list is the `SERVERS` array at the top of `scripts/publish-mcp-servers.mjs`: the `packages/*-mcp` directories that carry both a `package.json` and a `server.json`, plus `packages/agent-sniper`, `mcp-server`, and `mcp-bridge`. Read that array rather than a count quoted here. All steps are idempotent and default to a safe dry run.**1. npm + the official MCP registry** (`registry.modelcontextprotocol.io`):@@ -39580,7 +39942,7 @@ Skills are the best way to extend three.ws without touching core code. A skill i4. **Write a `SKILL.md`** documenting what your skill does, what permissions it requires, and how to install it.-5. **Share it.** Post it in [GitHub Discussions](https://github.com/nirholas/three.ws/discussions), or list it on the platform's skill marketplace so agents can install it.+5. **Share it.** Open a [GitHub issue](https://github.com/nirholas/three.ws/issues/new) announcing it, or list it on the platform's skill marketplace so agents can install it.---@@ -39616,8 +39978,7 @@ Check [existing issues](https://github.com/nirholas/three.ws/issues) before open## Getting Help-- **[GitHub Discussions](https://github.com/nirholas/three.ws/discussions)** — design questions, architecture ideas, general "how does X work"-- **[GitHub Issues](https://github.com/nirholas/three.ws/issues)** — bug reports and concrete feature requests+- **[GitHub Issues](https://github.com/nirholas/three.ws/issues)**: bug reports, concrete feature requests, design questions, and general "how does X work". Discussions are not enabled on the repository, so issues are the one channel.Core team response times: typically 2-3 business days on GitHub. If a PR has been open for a week with no review, a polite bump on the PR is welcome.@@ -42833,7 +43194,7 @@ Point a reverse proxy / load balancer at the container, add your domain and TLS,## Required environment variables-Copy [`.env.example`](../.env.example) to `.env.local` for local work, and set the same variables on your host. On Cloud Run they live on the service (`gcloud run services update three-ws-api --region us-central1 --set-env-vars …`); on any other host, set them however that platform injects environment. Secret-type variables should be stored as secrets, not plaintext — and never trust a `vercel env pull` as a complete export, since it returns empty for secret-type vars.+Copy [`.env.example`](../.env.example) to `.env.local` for local work, and set the same variables on your host. On Cloud Run they live on the service (`gcloud run services update three-ws-api --region us-central1 --update-env-vars NAME=value`); on any other host, set them however that platform injects environment. Use `--update-env-vars`, which merges: `--set-env-vars` REPLACES the service's entire environment, so passing one key with it wipes every other variable the service had. Secret-type variables should be stored as secrets, not plaintext. Never trust a `vercel env pull` as a complete export, since it returns empty for secret-type vars.```bashcp .env.example .env.local@@ -42900,14 +43261,15 @@ Without Redis, rate limits run in-memory per serverless instance. This is fine f```env# Avatar builder — origin where the in-browser avatar builder iframe is hosted.-# Defaults to http://localhost:5173 in dev. Production deployments should host the-# character-studio/ workspace (it is a separate Vite/React app) and point this env-# var at its origin. Same export contract, same humanoid rig, open-source-# and self-hostable.-VITE_CHARACTER_STUDIO_URL=https://studio.three.ws+# LEAVE THIS UNSET for a normal deployment. When unset it resolves SAME-ORIGIN to+# <your origin>/avatar-studio, where the build already ships the character-studio/+# bundle (the Vite dev middleware serves character-studio/build there in dev).+# Set it only to point at a standalone studio dev server while developing+# character-studio/ itself, e.g. http://localhost:5173.+# VITE_CHARACTER_STUDIO_URL=http://localhost:5173# Photo-to-avatar pipeline-# Get key at https://avaturn.me/developer+# Get key through the Avaturn developer docs: https://docs.avaturn.me/AVATURN_API_KEY=AVATURN_API_URL=https://api.avaturn.meVITE_AVATURN_EDITOR_URL=https://editor.avaturn.me/@@ -43144,7 +43506,7 @@ The embed routes explicitly set `frame-ancestors *` so the embed iframe can be h### Background cron jobs-The `crons` array in `vercel.json` declares every scheduled job (100 at time of writing: economy tick, on-chain crawl, delegation indexing, DCA, subscriptions, coin-launch lifecycle, treasury top-ups, and more). That array is the authoritative count; read it rather than trusting a number quoted in prose. In production these run as **Google Cloud Scheduler jobs** (one per entry) each firing `GET /api/cron/<name>` with an `Authorization: Bearer $CRON_SECRET` header. A representative slice:+The `crons` array in `vercel.json` declares every scheduled job (economy tick, on-chain crawl, delegation indexing, DCA, subscriptions, coin-launch lifecycle, treasury top-ups, and more). That array is the authoritative list and count; read it rather than trusting a number quoted in prose. In production these run as **Google Cloud Scheduler jobs** (one per entry) each firing `GET /api/cron/<name>` with an `Authorization: Bearer $CRON_SECRET` header. A representative slice:| Cron | Schedule | Purpose ||---|---|---|@@ -43198,7 +43560,7 @@ cp .env.example .env# Build and testforge build-forge test -vv # 25 tests across three contracts+forge test -vv # the full Solidity suite under contracts/test/# Dry run firstforge script script/Deploy.s.sol --rpc-url https://sepolia.base.org@@ -46832,7 +47194,7 @@ Body:| Field | Required | Notes || ----- | -------- | ----- || `name` | yes | Display name, ≤64 chars. |-| `prompt` | one of | Text description of the body to generate. |+| `prompt` | one of | Text description of the body to generate, ≤600 chars. || `image_url` | one of | A reference image URL to reconstruct into 3D. Provide **exactly one** of `prompt` / `image_url`. || `personality` | no | Flavor text stored on the persona, ≤600 chars. || `voice` | no | A TTS voice id (see `GET /api/tts/voices`). Defaults to `nova`. |@@ -48030,6 +48392,19 @@ Run these against production first to find real user-facing breakage, then again- `npm run audit:console`: console errors per page. `npm run audit:overlays`, `npm run audit:inline-handlers`, `npm run audit:routes`, `npm run audit:route-shadowing`: overlay/handler/route health.- `npm run audit:docs`: dead doc links and commands naming scripts that no longer exist.+`audit:console` drives a real browser per route, so a machine already busy with+other browser fleets or test workers distorts it: navigations blow the 30s+budget and the dev server itself can miss its boot window, and both land in the+report as page failures they are not. It reuses a dev server already answering+on :3000 when there is one, which is the cheapest way to keep a long sweep+honest. Four env knobs cover the rest: `CONCURRENCY` (default 5) routes checked+at once, `SETTLE_MS` (default 3000) the per-route wait for async work to land,+`SERVER_BOOT_MS` (default 240000) how long Vite gets to come up, and+`REUSE_PROBE_MS` (default 20000) how long the :3000 reuse probe waits for an+answer. Lower the first, raise the rest, on a loaded box. Treat a run whose+failures are all navigation timeouts or `net::ERR_*` as unmeasured rather than+red, and re-run it when the machine is quiet.+## What to do1. Run the full battery above. Triage every failure into: broken for users (fix now), cosmetic (fix now if under 15 minutes), false positive (note why).@@ -50329,7 +50704,7 @@ genuinely invested in the user's progress.## Every runnable example in the repo-The repo ships 40 examples: 11 web component demos, 10 end-to-end projects, and 19 package example sets. This table is generated from what is on disk, so it cannot list one that was deleted or miss one that was added. The machine-readable version is [data/examples.json](../data/examples.json).+The repo ships 43 examples: 11 web component demos, 10 end-to-end projects, and 22 package example sets. This table is generated from what is on disk, so it cannot list one that was deleted or miss one that was added. The machine-readable version is [data/examples.json](../data/examples.json).### Example projects@@ -50361,8 +50736,11 @@ The repo ships 40 examples: 11 web component demos, 10 end-to-end projects, and| [`packages/pumpfun-mcp/examples`](../packages/pumpfun-mcp/examples) | Two runnable examples. Both spawn this package's own MCP server over stdio (the same node src/index.js entry point the README documents), speak real MCP JSON-RPC to it, and read live Solana mainnet data through the canonical three.ws backend. | `node packages/pumpfun-mcp/examples/list-tools.mjs` || [`sdk/example`](../sdk/example) | Ship a cross-chain 3D AI agent with EVM + Solana identity, a chat panel, and discoverable .well-known endpoints. | `npm run dev, then open /sdk/example/index.html` || [`packages/sign-language/example`](../packages/sign-language/example) | American Sign Language for 3D avatars. | `node packages/sign-language/example/compile-utterance.mjs` |+| [`packages/skill-license/example`](../packages/skill-license/example) | On-chain skill licenses for agents - each purchased skill is a 1/1 SPL NFT plus a deterministic SkillLicense PDA. Mint, verify, and read trustless skill access in one import, no database required. | `node packages/skill-license/example/verify-license.mjs` || [`tour-sdk/examples`](../tour-sdk/examples) | The guide walks from feature to feature across your real pages. | `npm run dev, then open /tour-sdk/examples/shopify-storefront.html` || [`packages/vanity-mcp/examples`](../packages/vanity-mcp/examples) | Two runnable examples. Both spawn this package's own MCP server over stdio (the same node src/index.js entry point the README documents), speak real MCP JSON-RPC to it, and read the live grind-bounty market. | `node packages/vanity-mcp/examples/list-tools.mjs` |+| [`packages/vision-mcp/examples`](../packages/vision-mcp/examples) | Two runnable examples. Both spawn this package's own MCP server over stdio (the same node src/index.js entry point the README documents), speak real MCP JSON-RPC to it, and hit the live three.ws vision pipeline. | `node packages/vision-mcp/examples/list-tools.mjs` |+| [`packages/voice/examples`](../packages/voice/examples) | Run it from the package directory: | `node packages/voice/examples/voice-loop.mjs` || [`packages/x402-fetch/examples`](../packages/x402-fetch/examples) | Two runnable scripts against the live three.ws x402 Market Data API. Node 20+ is the only requirement; the package has zero production dependencies. | `node packages/x402-fetch/examples/discover.mjs` || [`packages/x402-mcp/examples`](../packages/x402-mcp/examples) | Two runnable examples. Both spawn this package's own MCP server over stdio (the same node src/index.js entry point the README documents), speak real MCP JSON-RPC to it, and hit live data. Neither one pays for anything. | `node packages/x402-mcp/examples/inspect-price.mjs` || [`x402-modal-sdk/examples`](../x402-modal-sdk/examples) | A drop-in payment modal for any x402 paid endpoint. | `node x402-modal-sdk/examples/server.mjs` |@@ -53297,7 +53675,12 @@ unaffected: no other feature depends on these variables.## APIAll three calls are owner-only: the session (or bearer) user must own the-agent. Browser mutations carry the standard CSRF token.+agent. The two mutations (POST and DELETE) additionally require the standard+CSRF token in `x-csrf-token` when the caller authenticates with a session+cookie: without it they answer `403 csrf_missing` and change nothing. Bearer+callers are exempt, because a bearer token is not attached automatically by a+browser the way a cookie is. Mint one from `GET /api/csrf-token`; the shared+front-end client attaches it for you.### `GET /api/agents/:id/memory/seed/github`@@ -53370,13 +53753,21 @@ with the connection row itself, and then asks GitHub to revoke the OAuth grant| Code | HTTP | Meaning ||---|---|---|| `unauthorized` | 401 | Sign-in required |+| `csrf_missing` / `csrf_invalid` | 403 | A cookie-authenticated POST or DELETE arrived without a valid `x-csrf-token` || `not_found` | 404 | No such agent, or it is not yours (a malformed id also answers 404, never a 500) || `not_connected` | 412 | Connect GitHub first; the response carries `connect_url` || `invalid_selection` | 400 | A selected key is not in the catalog you were shown; `rejected` names each one || `empty_selection` | 400 | Pick your profile or at least one repository || `distill_error` | 502 | The selected material yielded no usable facts; add a README or another repository |+| `distill_unavailable` | 503 | Every model provider was busy, so nothing was read into memory and the existing memories are untouched. Carries `retry_at` (when this agent's next seed is allowed) and `providers_tried` || rate limited | 429 | One seed per agent per 6 hours |+Only `distill_error` and `distill_unavailable` are reachable after the seed+budget has been charged: the budget is taken once the selection is known good,+immediately before the README reads and the distilling pass. Every other+refusal above happens before that point and leaves your window intact, so a+mistyped or stale pick costs you nothing but the retry.+## Source| Piece | File |@@ -55916,8 +56307,9 @@ forecast horizon as timestamped points.```jsonc{- "timestamps": ["2025-01-01T00:00:00Z", "2025-01-02T00:00:00Z", "..."],- "values": [12500, 13200, 0],+ // Both arrays are elided here. A real call sends at least 64 aligned points.+ "timestamps": ["2025-01-01T00:00:00Z", "2025-01-02T00:00:00Z" /* ...62 more */],+ "values": [12500, 13200 /* ...62 more */],"freq": "1D", // pandas-style: 1min, 5min, 1h, 1D, 1W, 1ME, ..."prediction_length": 14, // optional, 1–96; defaults to model horizon"label": "daily_revenue_usd" // optional, echoed back for traceability@@ -59798,7 +60190,7 @@ The same live market data behind every three.ws `/markets` page — coin prices,- **Free index (start here):** [`GET /api/x402/market`](https://three.ws/api/x402/market): lists every paid `market-*` endpoint with its live price, params, and a runnable example, including the `market-heatmap` and `market-mood` siblings below- **Discovery:** every endpoint is listed in [`/.well-known/x402.json`](https://three.ws/.well-known/x402.json), so x402scan, agentic.market, and CDP Bazaar crawlers index it automatically-- **Pricing:** $0.001 USDC per call for every category; the `market-pulse` bundle is $0.005+- **Pricing:** $0.001 USDC per call for every category endpoint in the table below; the `market-pulse` bundle is $0.005, and the `market-heatmap` / `market-mood` composites are $0.002- **Rails:** x402 v2, `exact` scheme — USDC on Solana mainnet or Base mainnet## Why pay when the pages are free?@@ -59831,7 +60223,7 @@ Full per-endpoint parameter docs are in the free index (`/api/x402/market`) and## The datapoint fabric — 1,000,000+ standalone endpoints-Beyond the 17 category endpoints, **every individual datapoint is its own paid endpoint**: one URL, one value, one micro-payment. The fabric at `/api/x402/d/<family>/<id>/<metric>` makes every (family, id, metric) triple individually addressable — ~17,500 coins × 20 metrics, ~15,500 yield pools × 7, ~6,000 protocols × 6, **per-contract token market + security for any Solana mint or EVM address** (10 + 6 metrics, unbounded), plus chains, stablecoins, exchanges, categories, DEXs, fees/revenue, derivative venues, and the no-id global/gas/fear-greed families. **$0.0005 USDC per datapoint** (override per family with `X402_PRICE_DATAPOINT_<FAMILY>`).+Beyond the 17 category endpoints, **every individual datapoint is its own paid endpoint**: one URL, one value, one micro-payment. The fabric at `/api/x402/d/<family>/<id>/<metric>` makes every (family, id, metric) triple individually addressable: ~17,000 coins × 20 metrics, ~15,000 yield pools × 7, ~6,000 protocols × 6, **per-contract token market + security for any Solana mint or EVM address** (10 + 6 metrics, unbounded), plus chains, stablecoins, exchanges, categories, DEXs, fees/revenue, derivative venues, and the no-id global/gas/fear-greed families. The free catalog reports the live total as `endpoint_count_approx` (1,126,963 across 15 families at the time of writing); that field is the source of truth, not this paragraph. **$0.0005 USDC per datapoint** (override per family with `X402_PRICE_DATAPOINT_<FAMILY>`).```bash# Free catalog: families, metrics, prices, live endpoint count@@ -60618,11 +61010,20 @@ Refetch it rather than pinning a copy. Tools get added; a policy fetched at builtime goes stale, and a stale allowlist is how a new mutating tool ends up trustedby an old config.-> Six tool names are published by two different servers (`sns_resolve`,+> Nine tool names are published by two different servers (`sns_resolve`,> `find_services`, `pay_and_call`, `list_animations`, `render_avatar`,-> `kol_leaderboard`). The namespaced `mcp__<server>__<tool>` id is the key, not+> `kol_leaderboard`, `create_agent_persona`, `get_agent_persona`, `persona_say`).+> The namespaced `mcp__<server>__<tool>` id is the key, not> the bare name. The `<server>` segment is the name **you** gave that server in> your own client config; the policy uses the id three.ws publishes for it.+>+> That list grows as servers are added, so re-derive it rather than trusting the+> names above:+>+> ```bash+> curl -s https://three.ws/mcp-catalog.json \+> | jq -r '.tools | group_by(.name)[] | select(length > 1) | .[0].name'+> ```---@@ -68220,6 +68621,8 @@ A score you cannot audit is an opinion. Oracle grades itself in public, and theDuring a database outage the endpoint answers `503` rather than an empty record, so "no wins yet" can never be a dressed-up outage.+That rule is the whole Oracle read surface, not one endpoint. `/api/oracle/feed`, `/categories`, `/agent-stats`, `/follow`, `/movers`, `/signal`, `/stats`, `/history`, and the `/social` ingest all separate a connectivity failure from an ordinary SQL fault: the first propagates as `503` with a `Retry-After` and is never cached, the second still degrades to the documented empty answer. The distinction matters because these responses get CDN-cached for 60 to 120 seconds, so a blip lasting seconds used to pin "nothing is moving", "nobody is armed", or "no plays right now" on the product for minutes after the database recovered. `/api/oracle/og` follows the same rule in its own shape: a card built from a failed read still renders (a social scraper needs an image back), but it is served `no-store` so the next scrape re-reads a recovered database instead of caching "Not yet scored" on a Prime coin for 15 minutes. The contract is pinned in `tests/oracle/api-db-outage.test.js`.+**The realized-hit-rate calibration.** The fitted model answers "what fraction of launches like this one spike or graduate". A user reading a card wants "of the coins Oracle already scored at 99, how many actually won". Nothing reconciled those two, so a card reading conviction 99 quoted a training-label probability above 95 percent for a band that realized 26 percent. `scripts/oracle-calibrate.mjs` closes the gap: it measures the realized rug-aware win rate per score band over resolved production coins, smooths it into a monotone ladder with pool-adjacent-violators (isotonic regression), and writes `api/_lib/oracle/conviction-calibration.json`. `hitRateFor()` then serves that realized rate next to every score, and the public tier boundaries sit on the plateaus this fit exposes. Run it bare to fit and report, `--write` to update the shipped JSON. It reads the production database when `DATABASE_URL` is set and otherwise the live `/api/oracle/backtest`, which runs the same aggregation server-side, so neither path invents a number.**A third question: what the fleet actually banked.** `/api/cron/oracle-calibrate` (Cloud Scheduler) joins conviction to the fleet's *realized PnL* on mints it really traded, buckets by conviction band, and writes `oracle_calibration`. A win here is a positive realized PnL on a real fill, which is neither the trained event nor the site's rug-aware win: exit timing belongs to the fleet, so a gap between this table and `/api/oracle/backtest` is expected rather than a bug. Each band carries a bounded `correction_factor` (observed over claimed, clamped to 0.7-1.3, and pinned at 1.0 until the band has enough real trades). That factor is deliberately **not** written back onto the canonical `oracle_conviction` score: the calibration is measured against that score, so mutating it would feed into its own measurement and oscillate. It is exposed at `GET /api/oracle/calibration` and applied where it belongs, in the sniper optimizer's Rule O, which tunes each arm's entry threshold toward the band that realized wins.@@ -68271,22 +68674,29 @@ GET https://three.ws/api/oracle/signal?network=mainnet&min_score=72&limit=5GET https://three.ws/api/oracle/signal?mint=<mint>```-Returns the current highest-conviction plays, or one coin's verdict, each with the pillar breakdown, badges, and an explicit recommendation: action (buy, watch, skip), confidence, and a size factor (1.0 for prime, 0.75 for strong, 0 for everything else). Your agent multiplies the size factor by its own per-trade budget and it has a position size. The shape:+Returns the current highest-conviction plays, or one coin's verdict, each with the pillar breakdown, badges, and an explicit recommendation: action (buy, watch, skip), confidence, and a size factor (1.0 for prime, 0.75 for strong, 0 for everything else). Your agent multiplies the size factor by its own per-trade budget and it has a position size.++The list form answers `{ network, count, top, plays, generated_at }`: `plays` is the ranked array, `top` is `plays[0]` (or `null` when nothing clears `min_score`), and `count` is the array's length. The single-mint form answers `{ network, mint, signal, generated_at }` instead, carrying one verdict under `signal`. Both wrap the same play object:```json{"mint": "…", "symbol": "…","conviction": 88, "tier": "strong", "category": "ai",+ "smart_wallet_count": 4,"pillars": { "pedigree": 82, "structure": 88, "narrative": 80, "momentum": 90 },+ "badges": ["smart-money"],"recommendation": {"action": "buy", // buy | watch | skip"confidence": "medium", // high | medium | low"size_factor": 0.75, // 0 to 1 suggested sizing multiplier"note": "strong conviction, favorable across pedigree and structure"- }+ },+ "scored_at": "2026-08-14T06:42:47.867Z"}```+`count: 0` means the oracle sees no play clearing your `min_score` right now, and an agent should stand down. It never means the engine is down: a database outage answers 503 with a `Retry-After` rather than an empty board, so an empty `plays` array is always a real verdict.+Recommendations map from tier: prime to `buy/high/1.0`, strong to `buy/medium/0.75`, lean to `watch`, watch/avoid to `skip`. Reads are cached 3 seconds with stale-while-revalidate, so polling is cheap.### A minimal agent loop in JavaScript@@ -68295,8 +68705,8 @@ Recommendations map from tier: prime to `buy/high/1.0`, strong to `buy/medium/0.const API = 'https://three.ws/api/oracle/signal?network=mainnet&min_score=72&limit=5';async function tick(budgetSol) {- const { signals } = await fetch(API).then(r => r.json());- for (const s of signals || []) {+ const { plays } = await fetch(API).then(r => r.json());+ for (const s of plays || []) {const { action, size_factor } = s.recommendation;if (action !== 'buy') continue;const size = budgetSol * size_factor;@@ -68327,7 +68737,7 @@ GET https://three.ws/api/oracle/trades?mint=<mint>- Realized calibration per conviction band at `/api/oracle/calibration`: the fleet's actual win rate from real fills, next to what the band predicted, plus the bounded correction factor the scorer applies.- A dynamic 1200x630 OpenGraph conviction card (SVG) for sharing a coin at `/api/oracle/og`.-The write endpoints. Two are auth-scoped to the agent's owner: `GET·POST /api/oracle/watch` reads or arms an agent's watch config with server-side validation clamping every limit, and `POST /api/oracle/test-alert` sends a test alert. Two are public and IP rate-limited instead: `POST·DELETE /api/oracle/follow` subscribes a Telegram chat to an agent's signals (the chat id the caller supplies is the identity, so there is no session to scope to), and `POST /api/oracle/social` ingests tweets to additively boost virality (never downgrades an LLM read).+The write endpoints. Two are auth-scoped to the agent's owner: `GET·POST /api/oracle/watch` reads or arms an agent's watch config with server-side validation clamping every limit, and `POST /api/oracle/test-alert` sends a test alert. The clamps only ever move a number toward safety: a size above the ceiling is lowered, but arming `mode: "live"` with a `per_trade_sol` under the 0.001 SOL floor, or a `max_daily_sol` smaller than one trade, is a 400 rather than a silent round-up into real spending. Simulate runs keep the forgiving clamps. Two are public and IP rate-limited instead: `POST·DELETE /api/oracle/follow` subscribes a Telegram chat to an agent's signals (the chat id the caller supplies is the identity, so there is no session to scope to), and `POST /api/oracle/social` ingests tweets to additively boost virality (never downgrades an LLM read).### Through MCP@@ -68554,7 +68964,7 @@ guaranteed.> **Source:** `docs/package-extraction.md` · [↑ table of contents](#table-of-contents)-# Package extraction — breaking the monorepo into standalone repos+# Package extraction: breaking the monorepo into standalone reposWe are graduating the reusable packages out of the `three.ws` monorepo into theirown GitHub repos that publish to npm (or, for the VS Code extension, the@@ -68562,7 +68972,7 @@ Marketplace) independently. This is the playbook. **We start with the x402 famil## Why-The x402 packages (`@three-ws/x402-*`) are general-purpose — a buyer-side fetch+The x402 packages (`@three-ws/x402-*`) are general-purpose: a buyer-side fetchwrapper, a seller-side core, MCP servers, payment modals. They are useful farbeyond three.ws, they version on their own cadence, and bundling them in a 60+directory monorepo hides their issue tracker, inflates clone size, and couples@@ -68571,7 +68981,7 @@ their releases to unrelated platform commits. Standalone repos fix all four.## Decisions (locked)- **One repo per package** (polyrepo), not a shared x402 monorepo.-- **History preserved** via `git filter-repo --subdirectory-filter` — blame and+- **History preserved** via `git filter-repo --subdirectory-filter`, so blame andauthorship carry across.- **Scope/owner unchanged**: keep publishing as `@three-ws/*`, host under`github.com/nirholas`. No renames, no broken installs.@@ -68601,38 +69011,48 @@ monorepo first, then extract.All seven extract cleanly with full history. Six are npm packages already liveunder `@three-ws/*`; `vscode-x402` targets the VS Code Marketplace.+Versions move, so read this table as a snapshot and re-derive it before a+release: `npm view <pkg> version` for the live column, the package's own+`package.json` for the local one. Measured 2026-08-15.+| Package | Monorepo path | npm (live) | Local ver | Build | Tests | Notes ||---|---|---|---|---|---|---|-| `@three-ws/x402-fetch` | `packages/x402-fetch` | 1.0.1 | 1.0.1 | vite | 7 pass | buyer-side fetch wrapper |-| `@three-ws/x402-server` | `packages/x402-server` | 0.1.0 | 0.1.0 | — | pass | seller-side core |-| `@three-ws/x402-mcp` | `packages/x402-mcp` | 0.2.0 | 0.2.0 | ✓ | pass | MCP server |-| `@three-ws/ibm-x402-mcp` | `packages/ibm-x402-mcp` | 1.1.0 | 1.1.0 | ✓ | pass | IBM MCP variant |-| `@three-ws/x402-modal` | `x402-modal-sdk` | 0.2.0 | 0.2.0 | esbuild | pass | payment modal SDK |-| `@three-ws/x402-payment-modal` | `x402-payment-modal` | 1.1.0 | **1.2.0** | esbuild | 14 pass | publishes 1.2.0 (deps fixed — see below) |-| `@three-ws/vscode-x402` | `packages/vscode-x402` | — | 0.1.0 | esbuild | — | **Marketplace**, not npm; needs name/publisher fix |+| `@three-ws/x402-fetch` | `packages/x402-fetch` | 1.0.2 | **1.0.3** | vite | 7 pass | buyer-side fetch wrapper |+| `@three-ws/x402-server` | `packages/x402-server` | 0.1.2 | 0.1.2 | none | 24 pass | seller-side core |+| `@three-ws/x402-mcp` | `packages/x402-mcp` | 0.2.1 | **0.2.2** | none | 10 pass | MCP server |+| `@three-ws/ibm-x402-mcp` | `packages/ibm-x402-mcp` | 1.1.2 | **1.1.3** | none | 37 pass | IBM MCP variant |+| `@three-ws/x402-modal` | `x402-modal-sdk` | 0.2.1 | **0.3.0** | esbuild | 24 pass | payment modal SDK |+| `@three-ws/x402-payment-modal` | `x402-payment-modal` | 1.2.0 | **1.2.1** | esbuild | 20 pass, 2 skipped | deps fixed, see below |+| `@three-ws/vscode-x402` | `packages/vscode-x402` | not published | 0.2.0 | esbuild | none | **Marketplace**, not npm; needs a name fix |++A bolded local version is ahead of npm and publishes on its next tag. The two+MCP packages ship their sources directly and have no build step, so "none" in+that column is correct rather than missing.### Fixes the split surfaced (already applied to the monorepo)- **`x402-payment-modal/build.mjs`** imported esbuild via a hardcoded- `../node_modules/esbuild/lib/main.js` — coupled to the monorepo's hoisted- layout, broken in a standalone repo. Changed to a bare `import 'esbuild'`,- which resolves in both.+ `../node_modules/esbuild/lib/main.js`, coupling it to the monorepo's hoisted+ layout and breaking it in a standalone repo. Changed to a bare+ `import 'esbuild'`, which resolves in both.- **`x402-payment-modal/package.json`** shipped a `server/` adapter importing`@solana/web3.js`, `@solana/spl-token`, and `express` with **zero declared- dependencies** — the published package was broken for anyone using the server- subpath. Added them as optional `peerDependencies` (keeps the browser install- lean) plus the Solana pair as `devDependencies` so tests/CI run.+ dependencies**, so the published package was broken for anyone using the+ server subpath. Added them as optional `peerDependencies` (keeps the browser+ install lean) plus the Solana pair as `devDependencies` so tests run.-### vscode-x402 — extra step before Marketplace publish+### vscode-x402: extra step before Marketplace publish-VS Code extensions cannot use a scoped `name`. Before `vsce publish`:+VS Code extensions cannot use a scoped `name`, and the package is still named+`@three-ws/vscode-x402`. Before `vsce publish`:-- set `name` to a plain id (e.g. `vscode-x402`),-- add a `publisher` field matching a registered Marketplace publisher,-- the CI workflow already uses `vsce publish` + `ovsx publish` (Open VSX) and- expects `VSCE_PAT` / `OVSX_PAT` secrets.+- set `name` to a plain id (e.g. `vscode-x402`); this is the one blocker left,+- the `publisher` field is already set to `three-ws`, which must match a+ registered Marketplace publisher,+- the extracted repo's publish workflow already uses `vsce publish` ++ `ovsx publish` (Open VSX) and expects `VSCE_PAT` / `OVSX_PAT` secrets.-## Owner handoff — the two steps that need credentials+## Owner handoff: the two steps that need credentialsEverything up to the GitHub/npm boundary is automated and verified. The final twosteps need the owner's credentials and cannot run from a collaborator session:@@ -68652,20 +69072,20 @@ steps need the owner's credentials and cannot run from a collaborator session:x402-payment-modal x402-payment-modalPKGS```- (`vscode-x402` is handled separately — see the Marketplace note above.)+ (`vscode-x402` is handled separately: see the Marketplace note above.)2. **Set the publish-token secret** on each new repo so its workflow canauthenticate to npm (`NPM_TOKEN`) or the Marketplace (`VSCE_PAT`/`OVSX_PAT`).-Already-published versions (e.g. x402-fetch 1.0.1) republish only after a version-bump — the workflow tags and publishes the version in `package.json`, so bump it-when there's something new to ship. `x402-payment-modal` is at an unpublished-1.2.0 and will publish on first tag.+Already-published versions republish only after a version bump: the workflow tags+and publishes the version in `package.json`, so bump it when there's something+new to ship. Five of the six npm packages currently sit one version ahead of the+registry (the bolded local versions above) and publish on their next tag.## After a package is extractedThe monorepo copy can stay (the platform still imports it locally) or be replacedwith the published dependency. That cutover is tracked per-package and is **not**-part of the extraction itself — extract and publish first, swap the import later.+part of the extraction itself: extract and publish first, swap the import later.---@@ -69287,8 +69707,11 @@ What happens, in order:1. **Token check.** The token is verified against its stored hash.2. **Probe.** The endpoint is fetched (SSRF-guarded, 20 s timeout, redirects- not followed). If it responds with anything other than 402, you get the- response back with `"paid": false` and the session is not touched.+ not followed). If it answers with a success and no 402, the call was free:+ you get the response back with `"paid": false` and the session is not+ touched. If it answers with an error status and no 402, there was nothing to+ pay and nothing succeeded, so you get `502 endpoint_error` carrying the real+ `upstream_status` and `upstream_body`. The session is not touched either way.3. **Accept selection.** From the 402 challenge's `accepts[]`, the platformpicks a Solana USDC accept (the challenge must offer network `solana...`,asset USDC, and a `feePayer` in `extra`). Sessions created with@@ -69364,6 +69787,7 @@ Free endpoint (no 402 challenge):| 402 | `payment_rejected` | The service rejected the payment before settlement. | rolled back || 422 | `no_solana_accept`, `unsupported_asset`, `missing_fee_payer` | The challenge offers no payable Solana USDC option. | untouched || 502 | `endpoint_unreachable`, `invalid_challenge` | Could not reach the endpoint or parse its challenge. | untouched |+| 502 | `endpoint_error` | The endpoint answered an error status with no payment challenge. Carries `upstream_status` and `upstream_body`. | untouched || 502 | `build_failed` | Building the Solana transaction failed. | rolled back || 502 | `settle_uncertain` | Network failure after signing: chain state unknown. Do not retry immediately; check the session executions and wallet activity first. | kept reserved || 502 | `upstream_error` | The endpoint returned a non-402 error after payment. Check wallet activity before retrying. | kept reserved |@@ -69661,7 +70085,7 @@ curl -s 'https://three.ws/api/permissions/verify?hash=0x00&chainId=84532'| Method | Path | Auth | Description ||--------|------|------|-------------|| `POST` | `/api/permissions/grant` | Session cookie | Store a signed delegation + scope |-| `GET` | `/api/permissions/list` | Session cookie | List delegations (`?agentId=X&status=active`) |+| `GET` | `/api/permissions/list` | Public by `agentId`, session or bearer by `delegator` | List delegations (`?agentId=X&status=active`) || `POST` | `/api/permissions/revoke` | Session cookie | Mirror on-chain revocation to DB || `POST` | `/api/permissions/redeem` | Agent bearer token | Server-side redemption via relayer || `GET` | `/api/permissions/metadata` | Public (cached) | Public scope view for a given `agentId` |@@ -69669,6 +70093,26 @@ curl -s 'https://three.ws/api/permissions/verify?hash=0x00&chainId=84532'The `metadata` endpoint returns `{ ok, spec: "erc-7715/0.1", delegations: [...] }` with `Cache-Control: public` and `Access-Control-Allow-Origin: *` — it is safe to call from embed iframes.+### Retrying a relayer redemption safely++`POST /api/permissions/redeem` accepts an optional `Idempotency-Key` header. Send the same key when you retry a request whose response you never saw (a dropped connection, a client timeout) and the relayer replays the original `{ ok, txHash, receipt }` instead of broadcasting a second transaction:++```sh+curl -s -X POST https://three.ws/api/permissions/redeem \+ -H "authorization: Bearer $AGENT_TOKEN" \+ -H 'content-type: application/json' \+ -H 'idempotency-key: swap-run-42' \+ -d '{"id":"<delegation-uuid>","calls":[{"to":"0x1111111111111111111111111111111111111111","value":"0","data":"0xa9059cbb..."}]}'+```++What the key does and does not cover:++- **Scoped to the calling token's owner.** A replay only returns the cached result to the principal that made the original call. Another principal sending the same delegation id and key gets the normal ownership answer (`delegation_not_found`), never someone else's transaction hash.+- **Held in memory for 10 minutes**, per server instance. Treat it as a retry window for a request still in flight, not as a durable receipt store. After it lapses, or if the retry lands on a different instance, the request is redeemed again and the spend counts against `scope.maxAmount` a second time.+- **Only successful redemptions are cached.** A request rejected before submission (scope, expiry, ownership) leaves nothing behind, so fixing the request and retrying with the same key works.++Requests without the header are never deduplicated.+---## The DelegationManager contract@@ -70298,6 +70742,8 @@ The server verifies, at **finalized** commitment (reorg-safe):3. the treasury actually received ≥ the pinned amount of the right asset — SPL transfers are matched by instruction **and** by pre/post token-balance delta with an explicit mint check; native SOL by the recipient's lamport delta;4. one on-chain tx confirms at most one intent (unique index on `tx_hash`).+Both `checkout` and `confirm` take an optional `network` (`mainnet` by default). In production it is the only accepted value, on **both** endpoints: confirm picks the RPC it queries and the USDC mint it accepts from that field, so a mainnet-only checkout paired with a devnet-tolerant confirm would still settle a real plan against faucet USDC. `devnet` is accepted in non-production builds only, and `$THREE` is mainnet-only in every build.+On success, one atomic transaction claims the intent, upserts `subscriptions`, and sets `users.plan`.`tx_not_found` (422) usually means the tx hasn't finalized yet (~10–30 s) — retry; the built-in pricing UIs poll automatically. A payment sent just before the quote expired is still honored within a 1-hour grace window.@@ -70328,7 +70774,7 @@ On success, one atomic transaction claims the intent, upserts `subscriptions`, a| `SOLANA_RPC_URL` / `SOLANA_RPC_URL_DEVNET` | RPC endpoints — set a paid RPC in production || `SOLANA_USDC_MINT` | Override the USDC mint (defaults to mainnet USDC) |-Plan prices live in [api/payments/_config.js](../api/payments/_config.js) (`PLANS`) — the single source of truth; both pricing pages and the `plans` action read from it. The EVM (USDC-only) sibling path is [api/payments/evm/[action].js](../api/payments/evm/[action].js).+Plan prices live in [api/payments/_config.js](../api/payments/_config.js) (`PLANS`), the single source of truth: both pricing pages and the `plans` action read from it. The EVM (USDC-only) sibling path is [api/payments/evm/[action].js](../api/payments/evm/[action].js). It verifies the same way with two chain-specific differences: it waits for 12 confirmations before granting (EVM reorgs, versus Solana's `finalized` commitment), and because an ERC-20 transfer carries no memo it binds the payment to the account by requiring the payer address to be a wallet linked to that user. It honors the same 1-hour post-expiry grace window, which the confirmation wait makes necessary rather than merely kind.---@@ -75811,6 +76257,13 @@ The consequences, each detectable and pinpointed to a specific `seq`:That last check is the anchor: on a schedule, each agent's current chain head is written to Solana as a signed SPL-Memo transaction (kind `threews.ledger.v1`, recorded in `ledger_anchors`). Because the head commits to the whole prefix, anchoring one hash is a tamper proof for the entire history up to that point. Anchoring is best-effort by contract: without a funded attester key the commitment is recorded locally as pending, and the chain's cryptographic tamper-evidence holds regardless; only the independent on-chain timestamp is deferred.+Two very different things can leave a head un-anchored, and `/api/cron/reconcile-decisions` reports them apart:++- **`anchor_pending`**: no attester key is configured. Every agent's commitment is still recorded locally, and nobody is paged. This is the degraded mode described above.+- **`anchor_failed` + `anchor_outage`**: the memo was broadcast and rejected on-chain, for example when the attester wallet holds no SOL and every send comes back with `Attempt to debit an account but found no record of a prior credit`. That failure is identical for every agent in the run, so the tick stops after the first one, counts the rest under `anchor_skipped`, and raises an ops alert instead of re-simulating the same doomed transaction for every remaining agent, every ten minutes, in silence.++Fixing an `anchor_outage` means funding the `ATTEST_AGENT_SECRET_KEY` wallet; verification keeps working from the recomputed hash chain in the meantime, it just reports `unanchored` rather than `verified`.+## Verifying a ledger yourself```bash@@ -76422,6 +76875,31 @@ The funder needs roughly 0.02 SOL per run and is only ever debited to thethrowaway staker the run generates. If it is short, the proof says which accountholds how much and what it needs, rather than failing at a later stage.+### When there is no faucet and no funded keypair either++A local validator needs nothing external at all: `solana-test-validator` bundles+the same SPL Memo program the attestations and the settlement memo use, and it+airdrops without limit, so the whole contract runs offline.++```bash+solana-test-validator --reset --ledger /tmp/rsm-ledger &+solana-keygen new --no-bip39-passphrase --silent --outfile /tmp/rsm-funder.json+solana airdrop 20 "$(solana-keygen pubkey /tmp/rsm-funder.json)" --url http://127.0.0.1:8899++SOLANA_RPC_URL_DEVNET="http://127.0.0.1:8899/?cluster=devnet" \+REPUTATION_MARKET_PROOF_FUNDER_SECRET_KEY="$(cat /tmp/rsm-funder.json)" \+node scripts/reputation-market-proof.mjs+```++Two details in that command are load-bearing. The `?cluster=devnet` suffix is+how the RPC layer infers the cluster (`inferNetwork` in+[`api/_lib/solana/connection.js`](../api/_lib/solana/connection.js)); a bare+localhost URL reads as mainnet and would queue mainnet endpoints as fallbacks+behind it. And the funder rung is used rather than the faucet because+`requestAirdrop` confirms over a WebSocket subscription, which a local validator+serves on a port the derived URL does not point at; every other stage of the+proof confirms over HTTP polling and works untouched.+## HTTP surface| Endpoint | Method | Purpose |@@ -76989,7 +77467,7 @@ if (report.verdict.level === 'fail') {Every sample rig is linkable, which is how the failure states in this document can be checked against a live page rather than taken on faith:- [A Mixamo rig that fully animates](https://three.ws/rig-doctor?sample=/avatars/michelle.glb)-- [A halfbody avatar with frozen legs](https://three.ws/rig-doctor?sample=/avatars/realistic-halfbody.glb)+- [A halfbody avatar with frozen arms and legs](https://three.ws/rig-doctor?sample=/avatars/realistic-halfbody.glb)- [A skinned but non-humanoid rig](https://three.ws/rig-doctor?sample=/avatars/fox.glb)- [A static mesh with no skeleton](https://three.ws/rig-doctor?sample=/avatars/mannequin.glb)@@ -78167,9 +78645,9 @@ Every registered agent card requires a `model.sha256` field. The `<three-d-agent### Validator compromise (V4)-Validator keys are dedicated signing keys, not personal wallets. If a validator key is compromised, the registry owner calls `removeValidator(address)`. Indexers treat attestations from that validator as expired from the removal block onward.+Validator keys are dedicated signing keys, not personal wallets. The deployed `ValidationRegistry` has **no validator allowlist** (`removeValidator(address)` exists only on `contracts/src/ValidationRegistry.sol`, which is deployed nowhere), so revocation is not an on-chain call: any address can answer a request addressed to it. Containment for a compromised validator key is therefore to rotate it (`scripts/erc8004/provision-validator-key.mjs` reprovisions `VALIDATOR_PRIVATE_KEY` on the API service) and to have indexers and resolvers filter by validator address, treating attestations signed by the retired key as expired from the rotation block onward.-The registry owner is currently the deployer EOA. Migration to a 3-of-5 Safe on Base is planned before public registration opens — allow-list changes will require multisig approval.+That places the whole burden on key custody: see the platform-validator note in [contracts/DEPLOYMENTS.md](../contracts/DEPLOYMENTS.md) and [docs/erc8004/validation-attestation.md](#sec-186) for the operating rules.### Reputation gaming (V5)@@ -78373,6 +78851,7 @@ forge flow already trusts, then applies catalog-specific bounds on top.| Reason | Meaning | Default bound || --- | --- | --- || `not_valid_glb` | The bytes are not a binary glTF 2.0 at all | - |+| `degenerate_triangles` | Almost no triangle geometry; renders as nothing | `FORGE_QUALITY_MIN_TRIS` = 80 || `vertices_below_floor` | Too coarse to look like anything | `SEED_GATE_MIN_VERTICES` = 1,500 || `vertices_above_ceiling` | Runaway output | `SEED_GATE_MAX_VERTICES` = 1,500,000 || `file_too_small` | Structurally empty | `SEED_GATE_MIN_BYTES` = 20,000 |@@ -79159,7 +79638,7 @@ If you have `prefers-reduced-motion` turned on, the page never auto-plays: signiThe **Avatar** setting's third pill (`Your avatar…`) opens the three.ws avatar gallery: your own avatars and every public one. Pick one and it takes the hero's place immediately, keeping the speed and signing hand you already set.-It works because signs are anatomy, not coordinates. A sign says "index fingertip on the chin", and the solver measures your avatar's skeleton to find where its chin is, so the same entry lands correctly on a tall rig, a short one, long fingers or small hands. Nothing about the vocabulary is per-avatar, which is also why the [clips retarget](#how-it-works) instead of being rebuilt.+It works because signs are anatomy, not coordinates. A sign says "index fingertip on the chin", and the solver measures your avatar's skeleton to find where its chin is, so the same entry lands correctly on a tall rig, a short one, long fingers or small hands. Nothing about the vocabulary is per-avatar, which is also why the [clips retarget](#part-3-how-it-works) instead of being rebuilt.Once picked, the avatar is remembered on that device and is already on stage on [/asl-alphabet](https://three.ws/asl-alphabet) too. Click its pill again to swap to a different one; the built-in pills switch back without a trip through the gallery.@@ -79327,10 +79806,13 @@ const clip = buildFingerspellingClip('HELLO', { marks });## Install it as a package-The whole engine ships as [`@three-ws/sign-language`](https://www.npmjs.com/package/@three-ws/sign-language) with **zero runtime dependencies**: no three.js, no DOM, no network. It compiles signing in a browser, in Node, or in a worker.+The whole engine is packaged as `@three-ws/sign-language` with **zero runtime dependencies**: no three.js, no DOM, no network. It compiles signing in a browser, in Node, or in a worker.++The registry publish is still queued, so `npm install @three-ws/sign-language` resolves to nothing today. Until it lands, install the package directory out of a clone of this repository; the import path and every export below are already the published ones:```bash-npm install @three-ws/sign-language+git clone https://github.com/nirholas/three.ws+npm install ./three.ws/packages/sign-language``````js@@ -79363,9 +79845,9 @@ curl -s "https://three.ws/api/sign?text=happy+to+meet+you" | jq '.timeline'"letters": [ { "letter": "T", "start": 1.64, "end": 2.14 },{ "letter": "O", "start": 2.14, "end": 2.64 } ] },{ "word": "MEET", "signed": true, "gloss": "Two upright index fingers come together.",- "start": 2.82, "end": 3.98, "letters": null },+ "start": 2.82, "end": 3.58, "letters": null },{ "word": "YOU", "signed": true, "gloss": "Index finger points at the person addressed.",- "start": 4.16, "end": 5.0, "letters": null }+ "start": 3.76, "end": 4.64, "letters": null }]```@@ -79607,7 +80089,7 @@ None of this replaces a human interpreter. It makes an avatar legible to signers1. **Captured signs**: clips from real signers (commissioned, community capture through [Motion Swap](https://three.ws/motion-swap), permissively licensed video) replacing authored entries word by word, through the same dictionary interface.2. **Word-level sign recognition**: the current recognizer reads fingerspelling; a 250-sign vocabulary model (MIT architecture retrained on the CC BY 4.0 PopSign corpus) will let common signs be recognized directly.3. **Review by Deaf signers**: the vocabulary is authored, not validated. Growing it past a core set should follow review and capture, not more authoring.-4. **Standalone package**: the engines are platform-free by design and will ship as an npm package plus reference integration.+4. **Standalone package on npm**: the engine is already packaged and installable from a clone ([Install it as a package](#install-it-as-a-package)); publishing `@three-ws/sign-language` to the public registry is what remains.## Related@@ -79768,6 +80250,25 @@ Two things to know before reading a report:- **The score is not the byte count.** Performance is weighted Total Blocking Time 30%, Largest Contentful Paint 25%, Cumulative Layout Shift 25%, First Contentful Paint 10%, Speed Index 10%. A page can ship 4 MB and score well if none of it blocks; a page can ship 900 KB and score badly if all of it runs at once.- **Lighthouse 13 removed the audits everyone quotes.** `offscreen-images`, `uses-responsive-images`, `modern-image-formats` and `dom-size` are gone, replaced by the insight family: `image-delivery-insight`, `render-blocking-insight`, `cache-insight`, `legacy-javascript-insight`, `cls-culprits-insight`. A script that reads the old audit names throws on `undefined`.+## The 2026-08-14 baseline++Every page named in this table was measured against `https://three.ws` with Lighthouse 13.4.1 on 2026-08-14. **This is the baseline, not the current state**: the live build at the time was commit `0496089f0`, stamped `2026-08-14T01:24:52Z`, which predates rules 1, 2, 3 and the model-viewer half of rule 4, plus the chip fix in `a789c2f90`. Every one of those is committed and none of them was deployed when these numbers were taken, so treat the table as the problem statement each rule below was written against.++| Page | Desktop | Mobile | Desktop TBT | Desktop CLS | Desktop bytes |+|---|---|---|---|---|---|+| `/` | 33 | 25 | 19,340ms | 0.009 | 3,715 KiB |+| `/create` | 38 | 25 | 6,940ms | 0.013 | 1,892 KiB |+| `/forge` | 32 | 20 | 12,560ms | 0.232 | 4,243 KiB |+| `/marketplace` | 23 | 17 | 51,400ms | 0.178 | 4,748 KiB |+| `/play` | 31 | 25 | 5,870ms | 0 | 2,317 KiB |+| `/docs` | 39 | 35 | 4,490ms | 0.028 | 701 KiB |+| `/discover` | 54 | 44 | 11,010ms | 0.022 | 10,952 KiB |+| `/chat` | 28 | 25 | 6,390ms | 0.001 | 4,435 KiB |++Total blocking time is what holds every one of these scores down, and it is 30% of the weighting on its own. Read the table by that column, not by the score.++Two caveats worth knowing when you compare a later run against this one. The runs were taken on a shared build machine with other work in flight, so single-page scores move a few points between runs: `/create` measured 50 in a quieter run earlier the same day and 38 here. And `/marketplace` is heavy enough that Lighthouse itself gave up with `PROTOCOL_TIMEOUT` on the first attempt and needed a 90s `--max-wait-for-load` to complete at all, which is a finding in its own right.+---## 1. A grid never lays out what nobody can see@@ -79831,7 +80332,9 @@ All three are gated in [pages/home.html](../pages/home.html) with a `rootMargin:The same rule covers 3D viewers, and it needs its own mechanism because the platform default does not work. **`loading="lazy"` on a `<model-viewer>` is not enough on a page that renders many of them.** Slides in a carousel occupy one box and are hidden with opacity rather than `display`, so every one of them intersects the viewport at once and model-viewer's own lazy loading holds nothing back; a grid card is a different shape but the cost is the same once the cards are on screen.-So [src/marketplace.js](../src/marketplace.js) uses a `data-src` contract instead. A viewer ships `data-src` rather than `src`, and `observeCardModelViewers()` promotes it to `src` on first intersect at a 200px margin, adds `auto-rotate` there, and *removes* `auto-rotate` when the element leaves so an offscreen viewer is not running a raf loop. The grid cards and the hero carousel already worked this way. The themed-picks strip did not, and that made it the last eager viewer on the page. On `/marketplace`, `model-viewer` was the single most expensive script in the trace at **7,924ms of evaluation**.+So [src/marketplace.js](../src/marketplace.js) uses a `data-src` contract instead. A viewer ships `data-src` rather than `src`, and `observeCardModelViewers()` promotes it to `src` on first intersect at a 200px margin, adds `auto-rotate` there, and *removes* `auto-rotate` when the element leaves so an offscreen viewer is not running a raf loop. The grid cards and the hero carousel already worked this way. The themed-picks strip did not, and that made it the last eager viewer on the page. On `/marketplace`, `model-viewer` is the single most expensive script in the trace at **7,924ms of evaluation**, across the grid, the hero and the strip together.++Measured honestly, that last one is the smallest of the three: at 1350x940 the strip sits at y=137, above the fold, so the observer promotes all six viewers immediately and a desktop first load is unchanged. It pays on a narrow viewport that pushes the strip down, on a filtered view that moves it, and on the rotation that used to keep running after the visitor scrolled past. **Report a fix by what you measured it doing, not by the size of the number next to it.****A new `<model-viewer>` on a multi-viewer page ships `data-src`, or it is eager.** There is no third option, and the attribute that looks like it should handle this does not.@@ -79855,6 +80358,25 @@ The box is reserved by CSS rather than by `width`/`height` attributes, because t**A reserved box is not optional.** If you add a thumbnail whose container has no `aspect-ratio` and no fixed height, add one, or the late image will shift everything under it.+## 6. Whoever writes a node's text owns it, and i18n has to be told++**Invariant: JavaScript that replaces the text of an element carrying `data-i18n` removes the attribute in the same statement.**++`/forge` measured a CLS of 0.232 on desktop, and **0.1785 of it was a single shift**. A probe of the live page found the cause: at `DOMContentLoaded` the example-prompt chips held their randomized prompts and the row was 168px tall, and about a second later they had reverted to the static English labels from the HTML at 99px. That 69px collapse moved the quality tiles, the composer row, the Generate button and everything below them.++The mechanism is ownership. The static chips carry `data-i18n` keys so a visitor with no JavaScript still gets translated copy. `applyCatalog` in `src/i18n.js` walks every `[data-i18n]` node whenever a catalog loads or the locale changes, and writes the keyed string back. Once the randomizer has replaced a chip's label, the key no longer describes that node, so i18n was faithfully undoing the rotation on every single load. The layout shift was the visible half of a functional bug: the "fresh set every visit" promise silently did not hold.++The fix is one line next to the write, in `setChipPrompt()` in [src/forge-prompt-studio.js](../src/forge-prompt-studio.js):++```js+function setChipPrompt(chip, text) {+ chip.textContent = text;+ chip.removeAttribute('data-i18n');+}+```++**Any node whose text becomes dynamic loses its `data-i18n` at the point it becomes dynamic.** Not later, not in a cleanup pass. `src/i18n.js` uses the same guard for `data-auth-name` in the nav.+---## Open: directory thumbnails are served with no cache headers at all@@ -80941,7 +81463,7 @@ Three Solidity contracts make up the ERC-8004 registry system for three.ws ident| Contract | Source | Purpose ||---|---|---|-| `IdentityRegistry` | `contracts/src/IdentityRegistry.sol` | ERC-721 token registry — register and resolve three.ws identities on-chain |+| `IdentityRegistry` | `contracts/src/IdentityRegistry.sol` | ERC-721 token registry, register and resolve three.ws identities on-chain || `ReputationRegistry` | `contracts/src/ReputationRegistry.sol` | Submit and aggregate signed feedback scores for agents || `ValidationRegistry` | `contracts/src/ValidationRegistry.sol` | Record immutable attestations of off-chain validation results (glTF schema, behavioral tests, etc.) |@@ -80953,6 +81475,19 @@ All contracts are Solidity `^0.8.24`, compiled with the optimizer at 200 runs, aContracts are deployed at the same address on every supported EVM chain, using CREATE2 deterministic deployment. There are two address sets: mainnet and testnet.+> **The addresses below do not run this repository's source.** All three canonical registries are ERC-1967 proxies in front of the ERC-8004 **reference upgradeable** implementations. `contracts/src/*.sol` in this repo is a superset design that is deployed nowhere, so several members documented in the interface sections further down exist only if you deploy the repo contracts yourself. An `eth_call` sweep on 2026-08-15 against Base (8453) and Base Sepolia (84532) confirmed:+>+> | Member | Deployed registry | Repo source |+> |---|---|---|+> | `name`, `symbol`, `ownerOf`, `balanceOf`, `tokenURI`, `register`, `setAgentURI`, `setMetadata`, `setAgentWallet` | yes | yes |+> | `getMetadata`, `getAgentWallet`, `supportsInterface` | Base Sepolia only (the mainnet implementation is older) | yes |+> | `totalSupply`, `tokenOfOwnerByIndex` (ERC-721 Enumerable) | **no**, reverts | yes |+> | `isAgent`, `DOMAIN_SEPARATOR` | **no**, reverts | yes |+> | `deposit`, `withdraw`, `agentBalance`, `setSpendAllowance`, `spend` (ETH escrow) | **no**, reverts | yes |+> | every `ReputationRegistry` member documented below (`submitFeedback`, `getReputation`, `hasReviewed`, `getFeedbackCount`, `getFeedback`, `getFeedbackRange`, `stakeReputation`, `withdrawStake`) | **no**, reverts; the deployed reputation registry exposes the reference `readFeedback` / `getClients` interface instead | yes |+>+> Re-run the sweep before relying on any row: implementations sit behind upgradeable proxies and can change without the address changing. `contracts/DEPLOYMENTS.md` carries the per-chain liveness record.+### MainnetChains with confirmed bytecode: Ethereum (1), Optimism (10), BSC (56), Gnosis (100), Polygon (137), Mantle (5000), Base (8453), Arbitrum One (42161), Celo (42220), Avalanche (43114), Linea (59144), Scroll (534352).@@ -80984,7 +81519,7 @@ const { identityRegistry, reputationRegistry, validationRegistry } =REGISTRY_DEPLOYMENTS[chainId];```-### CREATE2 Factory — ThreeWSFactory+### CREATE2 Factory: ThreeWSFactoryVanity-prefixed CREATE2 deployer used to obtain matching addresses across chains.@@ -80994,7 +81529,7 @@ Vanity-prefixed CREATE2 deployer used to obtain matching addresses across chains| Base (8453) | `0x00000000D49195AE81759cd247cFeDD9D0B479df` | `0x4022de2D...C0564f402` || Arbitrum One (42161) | `0x00000000D49195AE81759cd247cFeDD9D0B479df` | `0x4022de2D...C0564f402` |-The 8-byte zero prefix (`0x00000000…`) saves calldata gas on every call. Source is `ThreeWSFactory.sol` (solc 0.8.35, optimizer 200 runs, MIT, verified on BscScan).+The 8-byte zero prefix (`0x00000000…`) saves calldata gas on every call. Source is [`contracts/ThreeWSFactory.sol`](../contracts/ThreeWSFactory.sol) (solc 0.8.35, optimizer 200 runs, MIT, verified on BscScan), with its test at `contracts/test/ThreeWSFactory.t.sol`.```solidityfunction deploy(bytes32 salt, bytes initCode) external returns (address);@@ -81008,14 +81543,16 @@ event Deployed(address indexed addr, bytes32 indexed salt);## IdentityRegistry-`IdentityRegistry` is the canonical on-chain registry for three.ws identities. Each agent is minted as an ERC-721 token; the token URI points to an ERC-8004 registration JSON (typically hosted on IPFS). The contract extends `ERC721Enumerable`, so all standard ERC-721 enumeration methods work.+`IdentityRegistry` is the canonical on-chain registry for three.ws identities. Each agent is minted as an ERC-721 token; the token URI points to an ERC-8004 registration JSON (typically hosted on IPFS).++This section describes `contracts/src/IdentityRegistry.sol`. It extends `ERC721Enumerable`, so on an instance you deploy yourself all standard ERC-721 enumeration methods work. The canonical deployed addresses run the reference implementation instead and expose no enumeration: see the deployment note above for exactly which members answer and which revert.### RegistrationThree overloads of `register()` are available depending on how much you want to set at mint time:```solidity-// Mint with no URI — set it later with setAgentURI+// Mint with no URI: set it later with setAgentURIfunction register() external returns (uint256 agentId)// Mint and set the agent URI in one transaction@@ -81028,7 +81565,7 @@ function register() external returns (uint256 agentId)```-`agentURI` should be a URL pointing to the ERC-8004 registration JSON — typically `ipfs://Qm...` or an HTTPS URL. The `MetadataEntry` array lets you attach arbitrary bytes under named keys:+`agentURI` should be a URL pointing to the ERC-8004 registration JSON, typically `ipfs://Qm...` or an HTTPS URL. The `MetadataEntry` array lets you attach arbitrary bytes under named keys:```soliditystruct MetadataEntry {@@ -81061,7 +81598,7 @@ event URIUpdated(uint256 indexed agentId, string newURI, address indexed updated### Arbitrary Metadata-Key/value metadata store per agent. Values are raw bytes — ABI-encode complex types before writing.+Key/value metadata store per agent. Values are raw bytes, ABI-encode complex types before writing.```solidity// Set a metadata value (owner only)@@ -81117,20 +81654,42 @@ SetAgentWallet(uint256 agentId, address newWallet, uint256 nonce, uint256 deadliDomain: `name = "ERC8004-IdentityRegistry"`, `version = "1"`.+### ETH escrow and spend delegation++Repo source only. An agent can hold ETH inside the registry, attributed per `agentId`, and its owner can authorize a spender (typically a delegated server key) to draw on that balance up to a cap. Bare transfers are rejected (`receive`/`fallback` revert with `DirectTransferRejected`) so ETH is always attributed to one agent rather than pooled.++```solidity+// Anyone may fund an agent; the balance is spendable only against that agent.+function deposit(uint256 agentId) external payable++// The NFT owner reclaims unspent deposits.+function withdraw(uint256 agentId, address payable recipient, uint256 amountWei) external++// The NFT owner caps what a spender may draw.+function setSpendAllowance(uint256 agentId, address spender, uint256 maxWei) external++// The spender pays out, bounded by both the allowance and the agent's own balance.+function spend(uint256 agentId, address payable recipient, uint256 amountWei, string calldata memo) external++// Public storage getters+function agentBalance(uint256 agentId) external view returns (uint256)+function spendAllowance(uint256 agentId, address spender) external view returns (uint256)+```++Emits `AgentDeposit`, `AgentWithdrawal`, `SpendAllowanceSet`, and `AgentPayment(agentId, spender, recipient, amountWei, memo)`. Additional errors: `ZeroDeposit`, `InsufficientAgentBalance`, `DirectTransferRejected`, `EthTransferFailed`, `ZeroRecipient`.+### Helpers```solidity-// Check whether an agentId exists-function isAgent(uint256 agentId) external view returns (bool)+// Standard ERC-721, present on every deployment+function balanceOf(address owner) external view returns (uint256)+function ownerOf(uint256 tokenId) external view returns (address)-// EIP-712 domain separator (useful for off-chain signature construction)+// Repo source only: these revert on the canonical deployed addresses+function isAgent(uint256 agentId) external view returns (bool)function DOMAIN_SEPARATOR() external view returns (bytes32)--// Standard ERC-721 Enumerablefunction totalSupply() external view returns (uint256)function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256)-function balanceOf(address owner) external view returns (uint256)-function ownerOf(uint256 tokenId) external view returns (address)```### Errors@@ -81159,20 +81718,33 @@ const registry = new ethers.Contract(const owner = await registry.ownerOf(42);const uri = await registry.tokenURI(42);-// List all agents owned by an address+// How many agents an address holdsconst balance = await registry.balanceOf('0xYourAddress');-const ids = [];-for (let i = 0; i < Number(balance); i++) {- ids.push(await registry.tokenOfOwnerByIndex('0xYourAddress', i));-}-// Check total registered agents-const total = await registry.totalSupply();+// Whether a given agentId is registered. ownerOf reverts for an unminted id,+// which is the portable existence check: isAgent() and totalSupply() are+// ERC721Enumerable/repo-source members and revert on the deployed registries.+const exists = await registry.ownerOf(42).then(() => true, () => false);+```++To list the ids an address owns, index the `Transfer` event rather than calling `tokenOfOwnerByIndex`. Public RPCs cap `eth_getLogs` at a 10,000-block range, so page it:-// Check whether a given agentId is registered-const exists = await registry.isAgent(42);+```js+const latest = await provider.getBlockNumber();+const STEP = 10_000;+const ids = new Set();+for (let to = latest; to > latest - 40_000; to -= STEP) {+ const events = await registry.queryFilter(+ registry.filters.Transfer(null, '0xYourAddress'),+ to - STEP + 1,+ to,+ );+ for (const e of events) ids.add(String(e.args.tokenId));+}```+Widen the window (or use an indexed provider) to cover the registry's full history rather than a recent slice.+### Registering from ethers.js```js@@ -81215,9 +81787,11 @@ await tx2.wait();## ReputationRegistry+**This section describes `contracts/src/ReputationRegistry.sol`, which is deployed nowhere.** The canonical `reputationRegistry` addresses run the ERC-8004 reference implementation, whose interface (`readFeedback`, `getClients`) shares no function with the one below: every call in this section reverts against them. Use it when you deploy the repo contracts yourself, and read the deployment note above before pointing it at a canonical address.+`ReputationRegistry` stores signed feedback about registered agents. Scores are integers in the range `[-100, 100]`: negative scores indicate poor experiences, positive scores indicate good ones. Each `(reviewer, agentId)` pair can only submit once; there is no update path. Agent owners cannot review their own agents. Alongside plain feedback, the contract also exposes an ETH-staked variant (`stakeReputation(uint256 agentId, uint8 score, string comment)` payable, refundable via `withdrawStake(uint256 agentId)`); `submitFeedback` is the path documented here.-The registry holds a reference to `IdentityRegistry` — submitting feedback for an unregistered agentId reverts with `UnknownAgent`.+The registry holds a reference to `IdentityRegistry`, submitting feedback for an unregistered agentId reverts with `UnknownAgent`.### Submitting Feedback@@ -81230,10 +81804,10 @@ function submitFeedback(```Reverts with:-- `ScoreOutOfRange` — if `score < -100 || score > 100`-- `UnknownAgent` — if `agentId` is not registered in IdentityRegistry-- `SelfReviewForbidden` — if caller is the agent's NFT owner-- `AlreadyReviewed` — if caller has already reviewed this agent+- `ScoreOutOfRange`: if `score < -100 || score > 100`+- `UnknownAgent`: if `agentId` is not registered in IdentityRegistry+- `SelfReviewForbidden`: if caller is the agent's NFT owner+- `AlreadyReviewed`: if caller has already reviewed this agentEmits:@@ -81249,7 +81823,7 @@ event FeedbackSubmitted(### Reading Reputation```solidity-// Returns (average * 100, count) — divide avgX100 by 100 to get the real average.+// Returns (average * 100, count): divide avgX100 by 100 to get the real average.// Returns (0, 0) for agents with no reviews.function getReputation(uint256 agentId)external view@@ -81524,7 +82098,7 @@ These are approximate costs at optimizer 200 runs. Actual cost depends on chain| `validationResponse` | ~60k | Updates the request in place || All `view` functions | 0 | Free off-chain reads |-On Base at typical gas prices (~0.001 gwei base fee), an agent registration runs to roughly $0.10–$0.25. The same transaction costs 20–50x more on Ethereum mainnet — use Base or another L2 for cost-sensitive flows.+On Base at typical gas prices (~0.001 gwei base fee), an agent registration runs to roughly $0.10-$0.25. The same transaction costs 20-50x more on Ethereum mainnet, use Base or another L2 for cost-sensitive flows.---@@ -82540,7 +83114,7 @@ Failing over is only half the contract. The other half is *how long* a lane stay| Plain rate limit (429, no quota wording) | 10 min | Transient burst throttling; the lane recovers on its own. || Bad or expired key (401, 403) | 30 min | An endpoint-wide credential problem. || Dead or misrouted URL (404, 410) | 30 min | Persistent misconfiguration, not a blip. |-| One refused *call shape* (403 + `Request blocked`) | 30 s | The lane is healthy; only this request is unwelcome. |+| One refused *call shape* (403 + `Request blocked`) | none for the lane | The lane is healthy; only this request is unwelcome, so the *method* is demoted on that endpoint (`markMethodDemotion`) and every other call shape keeps flowing. A caller that reaches `markEndpointCooldown` directly still gets the cheapest window, 30 s. || Provider 5xx | 2 min | Server-side wobble. || Fetch threw (DNS, connection) | 30 s | Network blip. |@@ -82553,7 +83127,7 @@ The second-to-last row is the subtle one, and it cost us a primary. Each provide"message": "Request blocked. Details: blocked parameter: params.1.programId" } }```-Read as a credential failure that benched the node for 30 minutes, and since token and USDC balance readers make that exact call constantly, a healthy primary evicted itself on its own routine traffic and the rotation cascaded onto whatever came next. So a 403 whose body names a blocked call shape now fails over for that one request and leaves the lane in service. A 403 that does *not* say so is still treated as a bad key and benched for the full 30 minutes. Both directions are covered by `tests/solana-rpc-priority-and-breaker.test.js`.+Read as a credential failure that benched the node for 30 minutes, and since token and USDC balance readers make that exact call constantly, a healthy primary evicted itself on its own routine traffic and the rotation cascaded onto whatever came next. So a 403 whose body names a blocked call shape now fails over for that one request and demotes only that method on that endpoint, leaving the lane serving everything else with no cooldown at all. A 403 that does *not* say so is still treated as a bad key and benched for the full 30 minutes. Both directions are covered by `tests/solana-rpc-priority-and-breaker.test.js`.The same distinction applies one layer up, to HTTP 200 responses carrying a JSON-RPC error. A provider refusing a call shape (PublicNode's `excluded from account secondary indexes`, Tatum's `available for paid plans only`) must rotate to the next lane, while a genuinely deterministic error (`invalid params`) must *not*, because every lane would fail it identically and rotating just multiplies one failure by the length of the chain.@@ -84076,8 +84650,11 @@ lands in ~8–15s. Make sure the micro-buy wallet holds enough SOL for fees:## Turning it on```bash-# 1. Apply the schema.-npm run db:migrate -- --apply+# 1. Apply the schema. db:migrate already hardcodes --apply and has no dry run,+# so read db:status first: db:migrate applies EVERY pending migration, not+# just this lane's (api/_lib/migrations/20260717233000_three_microbuy.sql).+npm run db:status+npm run db:migrate# 2. Fund a wallet with USDC (+ a little SOL for fees). Reuse the buyback wallet, or# set a dedicated key so the two lanes don't compete for the same USDC:@@ -85173,8 +85750,12 @@ table was rewritten to match them:5. **A capped-upside/uncapped-downside arm loses even when it wins.** Thegraduation-ride arm won 63% of 90 trades and still lost money with TP 20 /SL 15 against occasional -99% rugs. Reward must be a multiple of risk- everywhere: no arm keeps a TP below 2x its SL, and no arm trades with a null- TP (that arm went 0-for-24).+ everywhere: no arm keeps a TP below 2x its SL, and no *ladderless* arm trades+ with a null TP (that arm went 0-for-24). A null TP is still correct on a+ ladder arm, where the ladder takes the stake back at 2x and the trailing stop+ governs the moon bag, which is why the setup script below leaves+ `take_profit_pct` null. The failure was an uncapped bag with nothing at all+ scheduled to take profit, not the absence of a ceiling as such.The applied changes: six lifetime-negative `new_mint` spray arms disabled (thattrigger went 4-for-64, -0.17 SOL, worst in the fleet), TP set on all 14 arms@@ -85612,13 +86193,13 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix**Fix steps:**-1. Open DevTools → Console (F12). Look for red errors — a failed fetch or a Three.js parse error will be logged there.+1. Open DevTools → Console (F12). Look for red errors, a failed fetch or a Three.js parse error will be logged there.2. Open DevTools → Network. Find the GLB request. Check the HTTP status code:- - `404` — the URL is wrong. Verify `src` attribute.- - `403` / `401` — access is blocked. Make the file publicly readable.- - `200` with a CORS error in Console — see the CORS section below.+ - `404`: the URL is wrong. Verify `src` attribute.+ - `403` / `401`: access is blocked. Make the file publicly readable.+ - `200` with a CORS error in Console: see the CORS section below.3. Paste the GLB URL directly into a new browser tab. If it downloads or previews, the URL is valid.-4. Check file size. Models over ~100 MB can cause timeouts on slow connections. Compress with Draco (5–10× mesh size reduction). See "Model loads slowly" under Performance.+4. Check file size. Models over ~100 MB can cause timeouts on slow connections. Compress with Draco (5-10× mesh size reduction). See "Model loads slowly" under Performance.5. Verify the format. Only **glTF 2.0** (`.glb` or `.gltf`) is supported. glTF 1.0, OBJ, FBX, and USDZ are not. If you're exporting from Blender, use File → Export → glTF 2.0 with "Format: GLB".---@@ -85637,7 +86218,7 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix- **Apache:** `Header set Access-Control-Allow-Origin "*"` in `.htaccess`.- **AWS S3 / CloudFront:** Set a CORS policy on the bucket (allow all origins, GET method).- **Vercel / Netlify:** Add a `headers` rule in the config file.-2. If you can't modify the server, re-host the file somewhere that sends CORS headers: the platform's hosted storage (uploads via the Studio are CORS-configured automatically), or any CDN/bucket with a permissive CORS rule (Cloudflare R2, S3 + CORS policy). Note that the `key-proxy` attribute is **not** a fetch proxy — it points the element at your LLM API-key proxy endpoint (so the key never reaches the client) and has no effect on GLB loading.+2. If you can't modify the server, re-host the file somewhere that sends CORS headers: the platform's hosted storage (uploads via the Studio are CORS-configured automatically), or any CDN/bucket with a permissive CORS rule (Cloudflare R2, S3 + CORS policy). Note that the `key-proxy` attribute is **not** a fetch proxy, it points the element at your LLM API-key proxy endpoint (so the key never reaches the client) and has no effect on GLB loading.---@@ -85652,7 +86233,7 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix**Fix steps:**1. Open the file in a glTF viewer (e.g. [gltf.report](https://gltf.report)) to isolate the problem from the viewer itself.-2. If using `.gltf` (not `.glb`): texture PNG/JPG files must be served from the same origin as the JSON and referenced by relative path. The simplest fix is to re-export as `.glb` — this embeds all textures in one file.+2. If using `.gltf` (not `.glb`): texture PNG/JPG files must be served from the same origin as the JSON and referenced by relative path. The simplest fix is to re-export as `.glb`, this embeds all textures in one file.3. If using `.glb`: textures are embedded by default. If they're missing, the export settings may have excluded them. In Blender: tick "Include → Textures" when exporting.---@@ -85662,7 +86243,7 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix**Symptom:** Model appears but with black surfaces, missing reflections, or washed-out colors.**Likely causes:**-- No environment map — metallic materials need a reflection source+- No environment map: metallic materials need a reflection source- Metalness = 1.0 with no environment (renders black)- Inverted normal map@@ -85695,7 +86276,7 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix**Symptom:** Chat input works but no reply appears. The agent is silent.**Likely causes:**-- `brain` attribute not set on `<agent-3d>` — without it, the element uses `NullProvider` (a no-op)+- `brain` attribute not set on `<agent-3d>`: without it, the element uses `NullProvider` (a no-op)- Missing or invalid `ANTHROPIC_API_KEY`- Rate limit reached@@ -85707,9 +86288,9 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix```Without this attribute, `brain.provider` defaults to `none` and the agent uses `NullProvider`, which returns empty responses silently.2. Open DevTools → Network. Filter for `/api/chat` or `/api/llm`. Look at the response:- - `401` — the API key is missing or invalid.- - `429` — rate limited. Wait a minute and retry.- - `500` — server error. Check the server logs.+ - `401`: the API key is missing or invalid.+ - `429`: rate limited. Wait a minute and retry.+ - `500`: server error. Check the server logs.3. Verify `ANTHROPIC_API_KEY` is set in your server environment. On the production Cloud Run service:```bashgcloud run services update three-ws-api --region us-central1 \@@ -85728,7 +86309,7 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix1. Tighten the system prompt. A vague `instructions` field produces vague behavior. Be explicit: "You are a guide for [product]. You only discuss [topic]. If asked about anything else, say you can't help with that."2. Add a boundary statement to the instructions: "Never break character. Never discuss topics outside [domain]."-3. If you're loading instructions from a `.md` file via `brain.instructions`, verify the file is being fetched correctly — check the Network panel for the `.md` request.+3. If you're loading instructions from a `.md` file via `brain.instructions`, verify the file is being fetched correctly, check the Network panel for the `.md` request.---@@ -85745,7 +86326,7 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix1. Check the Console. The avatar module logs a warning if expected morph targets aren't found on load.2. Verify your GLB has morph targets named exactly as expected (case-sensitive). The emotion system maps to: `mouthSmile`, `mouthFrown`, `mouthOpen`, `cheekPuff`, `browInnerUp`, `browOuterUpLeft` / `browOuterUpRight`, `noseSneerLeft` / `noseSneerRight`, `eyeSquintLeft` / `eyeSquintRight`, `eyesClosed`. These are the standard ARKit / humanoid avatar blendshape names.3. For head tilt and lean, the skeleton needs a `Head` or `Neck` bone. Open the model in Blender and check the armature.-4. Confirm the avatar module is initialized: open DevTools Console and run `window.VIEWER?.agent_avatar`. If `undefined`, the avatar layer didn't boot — check for earlier errors in the console.+4. Confirm the avatar module is initialized: open DevTools Console and run `window.VIEWER?.agent_avatar`. If `undefined`, the avatar layer didn't boot, check for earlier errors in the console.---@@ -85785,9 +86366,9 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix**Fix steps:**1. Open DevTools → Network. Filter for `/api/tts` or `elevenlabs.io`. Check the response:- - `401` — `ELEVENLABS_API_KEY` is missing or wrong.- - `429` — rate limited. The free tier allows 10,000 characters/month.- - `422` — voice ID is invalid. Verify the `voiceId` in your manifest or config.+ - `401`: `ELEVENLABS_API_KEY` is missing or wrong.+ - `429`: rate limited. The free tier allows 10,000 characters/month.+ - `422`: voice ID is invalid. Verify the `voiceId` in your manifest or config.2. Confirm `ELEVENLABS_API_KEY` is set in your server environment variables.---@@ -85821,7 +86402,7 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix**Fix steps:**-1. Verify the `src` URL is correct — use the full HTTPS URL.+1. Verify the `src` URL is correct: use the full HTTPS URL.2. Do not use a URL that ends in `/edit` or `/dashboard`: those pages block framing for security. Use the agent's public embed URL (`/agent/<id>/embed`, `/w/<widget-id>`, or `/widget#widget=<id>`).3. Only the dedicated embed routes send a `frame-ancestors *` CSP header (set in the route table and applied by the server); regular pages send `frame-ancestors 'self'` and will refuse to load in your iframe. If an embed route is being blocked, the block is coming from the host page's own CSP, the agent's embed policy (domain allowlist), or a browser extension.@@ -85843,8 +86424,8 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix```3. Use the correct envelope shape. There are three related protocols, and none uses a type prefix like `3dagent:`:- The **agent iframe bridge** (`/agent/<id>/embed`) uses `{ type: 'agent:*', agentId, ... }`: send `{ type: 'agent:hello', agentId }` first, wait for `agent:ready`, then drive it with `{ type: 'agent:action', agentId, action: { type: 'speak', text: '...' } }`. Every message must carry the `agentId`. See example 9 in the [Examples gallery](/docs/examples).- - The **element bridge** (`src/embed-host-bridge.js`) wraps every message in `{ v: 1, source: 'agent-host' | 'agent-3d', id, kind, op, payload }` — e.g. a speak request is `{ v: 1, source: 'agent-host', id: '<uuid>', kind: 'request', op: 'speak', payload: { text: '...' } }`.- - The **host protocol** ([specs/EMBED_HOST_PROTOCOL.md](../specs/EMBED_HOST_PROTOCOL.md)) uses `{ v: 1, type: 'host.*' | 'embed.*', id, payload }` — e.g. `{ v: 1, type: 'host.chat.message', payload: { ... } }`.+ - The **element bridge** (`src/embed-host-bridge.js`) wraps every message in `{ v: 1, source: 'agent-host' | 'agent-3d', id, kind, op, payload }`, e.g. a speak request is `{ v: 1, source: 'agent-host', id: '<uuid>', kind: 'request', op: 'speak', payload: { text: '...' } }`.+ - The **host protocol** ([specs/EMBED_HOST_PROTOCOL.md](../specs/EMBED_HOST_PROTOCOL.md)) uses `{ v: 1, type: 'host.*' | 'embed.*', id, payload }`, e.g. `{ v: 1, type: 'host.chat.message', payload: { ... } }`.Messages that don't match the expected envelope (missing `agentId` or `v: 1`, wrong `source`/`type`) are silently ignored.4. For element embeds, use the `EmbedHostBridge` class (`src/embed-host-bridge.js`) rather than raw `postMessage`: it handles the handshake, queues requests until the iframe is ready, and correlates responses by `id`.@@ -85858,7 +86439,7 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix**Fix steps:**1. The element sets `z-index: 2147483000` internally via `:host([mode="floating"])`. If another element has a higher z-index, it will cover the agent.-2. Check parent elements for `overflow: hidden` — this can clip absolutely-positioned children even with a high z-index.+2. Check parent elements for `overflow: hidden`: this can clip absolutely-positioned children even with a high z-index.3. If the agent is inside a stacking context (e.g. a `position: relative` container with `z-index`), the z-index is relative to that context. Move `<agent-3d>` to a direct child of `<body>` if possible.---@@ -85875,12 +86456,12 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix```html<agent-3d style="width: 100%; height: 50vh;" ...></agent-3d>```-2. Avoid `display: inline` on the container — use `block` or `flex`.-3. For inline mode with automatic aspect ratio, add the `responsive` attribute:+2. Avoid `display: inline` on the container: use `block` or `flex`.+3. For inline mode with automatic aspect ratio, set the **`width` attribute** and omit `height`. Responsive sizing is on by default, so there is no `responsive` attribute to add:```html- <agent-3d responsive style="width: 100%;" ...></agent-3d>+ <agent-3d mode="inline" width="320" ...></agent-3d>```- This sets `aspect-ratio: 3/4` and lets height follow width.+ The element then sets `aspect-ratio: 3/4` and height follows width. Two things switch it off: an explicit `height` attribute, and `responsive="false"`. A CSS-only width (`style="width:100%"`) does not engage it, because the element reads the `width` attribute, not the computed style.---@@ -85908,7 +86489,7 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix**Fix steps:**1. Set `PUBLIC_APP_ORIGIN` to exactly the origin users are hitting (e.g. `https://www.yourdomain.com`). `www.yourdomain.com` and `yourdomain.com` are treated as different domains. In production this lives on the Cloud Run service (`gcloud run services update three-ws-api --region us-central1 --update-env-vars PUBLIC_APP_ORIGIN=...`).-2. For local development, any `localhost` domain is accepted automatically — you don't need to set `PUBLIC_APP_ORIGIN` for local dev.+2. For local development, any `localhost` domain is accepted automatically, you don't need to set `PUBLIC_APP_ORIGIN` for local dev.3. For forks deployed on Vercel, the deployment host injected as `VERCEL_URL` is automatically trusted alongside `PUBLIC_APP_ORIGIN`.---@@ -85921,7 +86502,7 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix**Fix steps:**-1. Set `JWT_SECRET` once and don't rotate it unless needed. In production it lives on the Cloud Run service env (`gcloud run services describe three-ws-api --region us-central1` to inspect) — it must be the same value across all revisions.+1. Set `JWT_SECRET` once and don't rotate it unless needed. In production it lives on the Cloud Run service env (`gcloud run services describe three-ws-api --region us-central1` to inspect), it must be the same value across all revisions.2. Session duration is 30 days. A session used when fewer than 7 days remain is rotated to a fresh 30-day token (a rolling refresh window), so actively returning users stay signed in indefinitely.---@@ -85932,7 +86513,7 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix**Fix steps:**-1. The key must be sent as `Authorization: Bearer <key>` — include the `Bearer ` prefix with a space.+1. The key must be sent as `Authorization: Bearer <key>`, include the `Bearer ` prefix with a space.2. Check if the key has been revoked in the dashboard (Settings → API Keys).3. Verify the key's scope includes the endpoint you're calling. For example, reading avatar data requires `avatars:read`; creating or updating requires `avatars:write`.@@ -85946,7 +86527,7 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix**Fix steps:**-1. Increase the gas limit by 20% — registration involves IPFS CID storage and can exceed estimates.+1. Increase the gas limit by 20%: registration involves IPFS CID storage and can exceed estimates.2. Check your ETH balance on Base. Bridge more if needed.3. Verify the manifest CID resolves on IPFS before calling the contract. A CID that doesn't resolve yet may cause the contract to reject it depending on the registry version.4. Confirm MetaMask is on the chain you intend to register on. The platform default is Base (chain ID 8453). The registry contracts are deployed at the same addresses on all major EVM chains, but your wallet must be on the chain the registration flow targets, with gas funds on that chain.@@ -85959,7 +86540,7 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix**Fix steps:**-1. Retry — IPFS providers go down occasionally. Wait a minute and try again.+1. Retry: IPFS providers go down occasionally. Wait a minute and try again.2. Check `PINATA_JWT` (or your configured IPFS provider key) in your environment variables.3. The default backend uses R2 storage (via `/api/erc8004/pin`). If you're supplying a Pinata JWT directly to the client, verify the token is valid and not expired in the Pinata dashboard.@@ -85971,8 +86552,8 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix**Fix steps:**-1. Wait 1–2 minutes. The indexer polls the chain periodically.-2. Access the agent directly by URL: `https://three.ws/a/<chainId>/<agentId>` — this bypasses the index.+1. Wait 1-2 minutes. The indexer polls the chain periodically.+2. Access the agent directly by URL: `https://three.ws/a/<chainId>/<agentId>`, this bypasses the index.3. Confirm the transaction was actually confirmed (not just submitted) on the block explorer for Base.---@@ -85998,7 +86579,7 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix**Symptom:** The agent starts fresh with no memory of previous conversations.**Likely causes:**-- Memory mode is `"none"` — conversations are never persisted+- Memory mode is `"none"`: conversations are never persisted- localStorage was cleared**Fix steps:**@@ -86028,8 +86609,8 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix**Fix steps:**1. Check file size. Over 10 MB is noticeable on mobile; over 50 MB is slow on most connections.-2. Enable Draco compression on export. In Blender's glTF exporter: Geometry → Compression → enable. This typically reduces mesh data by 5–10×.-3. Scale down textures. 4096×4096 textures are rarely necessary — 1024×1024 is fine for most avatars. Use KTX2 format for GPU-compressed textures that decompress on the GPU rather than in JavaScript.+2. Enable Draco compression on export. In Blender's glTF exporter: Geometry → Compression → enable. This typically reduces mesh data by 5-10×.+3. Scale down textures. 4096×4096 textures are rarely necessary, 1024×1024 is fine for most avatars. Use KTX2 format for GPU-compressed textures that decompress on the GPU rather than in JavaScript.4. Merge meshes in Blender before exporting. Fewer objects = fewer draw calls = faster load.---@@ -86040,10 +86621,10 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix**Fix steps:**-1. Open the stats panel (visible in the dat.gui panel on the right side of the viewer). Check which metric is the bottleneck — GPU time or JavaScript time.+1. Open the stats panel (visible in the dat.gui panel on the right side of the viewer). Check which metric is the bottleneck, GPU time or JavaScript time.2. Reduce polygon count. Under 100k triangles renders at 60fps on most desktop GPUs; under 50k for mobile.-3. Disable environment maps on mobile — IBL (image-based lighting) is GPU-expensive. Set `preset="none"` or use a simple directional light preset.-4. Limit the number of `<agent-3d>` elements on a single page. Each one creates a WebGL context. Most browsers cap WebGL contexts at 8–16; 4–6 is a safe limit, fewer on mobile.+3. Disable environment maps on mobile: IBL (image-based lighting) is GPU-expensive. Set `preset="none"` or use a simple directional light preset.+4. Limit the number of `<agent-3d>` elements on a single page. Each one creates a WebGL context. Most browsers cap WebGL contexts at 8-16; 4-6 is a safe limit, fewer on mobile.---@@ -86055,9 +86636,9 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix**Fix steps:**-1. Compress with Draco — the WASM decoder is more efficient and has less UI thread impact than uncompressed mesh parsing.+1. Compress with Draco: the WASM decoder is more efficient and has less UI thread impact than uncompressed mesh parsing.2. Split the model into multiple smaller files if possible, and load non-essential parts after the main avatar appears.-3. Moving model loading to a Web Worker is technically possible but requires custom viewer configuration — advanced use case.+3. Moving model loading to a Web Worker is technically possible but requires custom viewer configuration, advanced use case.---@@ -86082,9 +86663,9 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix**Symptom:** API routes and crons throw `NeonDbError: relation "agent_custody_events" does not exist` (or `forge_creations`, `x_triggers`, `club_tips`, `unstoppable_activity`, …). Often hundreds or thousands of identical errors.-**Cause:** The database was provisioned with only part of the schema — typically `apply-schema.mjs` was run but the incremental migrations under `api/_lib/migrations/` were not. The base schema does **not** create migration-defined tables.+**Cause:** The database was provisioned with only part of the schema, typically `apply-schema.mjs` was run but the incremental migrations under `api/_lib/migrations/` were not. The base schema does **not** create migration-defined tables.-**Fix:** Point `DATABASE_URL` at the affected database and run the complete bootstrap. It is idempotent — it only creates what is missing:+**Fix:** Point `DATABASE_URL` at the affected database and run the complete bootstrap. It is idempotent, it only creates what is missing:```bashDATABASE_URL=<prod connection string> npm run db:bootstrap```@@ -86103,7 +86684,7 @@ Run `npm run db:status` first to preview which migrations are pending.gcloud logging read 'resource.type="cloud_run_revision" resource.labels.service_name="three-ws-api" severity>=ERROR' \--freshness=1h --limit 20 --format="value(textPayload)"```- Deploys ship via `npm run deploy:gcp` (run `npm run build` first for frontend changes) — the full runbook lives in the repo at `docs/ops/gcp-production.md`. On a self-hosted fork, check whatever your host surfaces as function/process logs.+ Deploys ship via `npm run deploy:gcp` (run `npm run build` first for frontend changes), the full runbook lives in the repo at `docs/ops/gcp-production.md`. On a self-hosted fork, check whatever your host surfaces as function/process logs.2. The most common cause is a missing environment variable. All required vars must be set: `DATABASE_URL`, `JWT_SECRET`, `PUBLIC_APP_ORIGIN`. The `env.js` module throws on startup if required vars are absent. In production, inspect and set them on the Cloud Run service: `gcloud run services describe three-ws-api --region us-central1` / `gcloud run services update three-ws-api --region us-central1 --update-env-vars KEY=value`.---@@ -86116,7 +86697,7 @@ Run `npm run db:status` first to preview which migrations are pending.1. Hard-refresh: Ctrl+Shift+R (Windows/Linux) or Cmd+Shift+R (Mac).2. Clear the service worker manually: DevTools → Application → Service Workers → "Unregister", then DevTools → Application → Clear Storage → "Clear site data".-3. Service workers cache aggressively and can serve stale content for up to 24 hours. This is expected behavior — users will update automatically when the SW checks for a new version.+3. Service workers cache aggressively and can serve stale content for up to 24 hours. This is expected behavior, users will update automatically when the SW checks for a new version.---@@ -86126,17 +86707,17 @@ Run `npm run db:status` first to preview which migrations are pending.**Symptom:** The `<agent-3d ar>` element renders correctly, but no AR button is visible on an iPhone or Android phone.-**Check 1 — `ar` attribute is present:**+**Check 1: `ar` attribute is present:**```html<agent-3d id="..." ar></agent-3d>```Without `ar`, the button is never rendered, even on supported devices.-**Check 2 — correct browser:**+**Check 2: correct browser:**- iPhone: must be **Safari**. Chrome, Firefox, and all other iOS browsers use WebKit but lack the Quick Look integration that triggers AR. The button is hidden for non-Safari iOS browsers.- Android: must be **Chrome** (or a Chromium-based browser with ARCore). Firefox on Android does not support Scene Viewer or WebXR AR.-**Check 3 — inside an iframe:**+**Check 3: inside an iframe:**Add `allow="xr-spatial-tracking"` to the `<iframe>` element. Without it, the browser blocks `navigator.xr` inside the frame.```html@@ -86146,17 +86727,17 @@ Add `allow="xr-spatial-tracking"` to the `<iframe>` element. Without it, the bro></iframe>```-**Check 4 — model not yet loaded:**+**Check 4: model not yet loaded:**The AR button is only shown after the GLB finishes loading. If the model is large or on a slow connection, the button appears late. Check the console for load errors.-**Check 5 — HTTP origin:**+**Check 5: HTTP origin:**`navigator.xr` is `undefined` on `http://` origins. All AR methods require HTTPS for the page or the model URL. Use an ngrok tunnel or a deployed HTTPS environment during development.---### AR button appears but tapping it does nothing-**iOS:** The model URL is `http://`. Quick Look silently refuses non-HTTPS model URLs — it opens briefly then closes immediately, or never opens. Use an HTTPS URL for both the page and the GLB.+**iOS:** The model URL is `http://`. Quick Look silently refuses non-HTTPS model URLs, it opens briefly then closes immediately, or never opens. Use an HTTPS URL for both the page and the GLB.**Android:** ARCore is not installed. Chrome shows a "Get ARCore" prompt on first use; if dismissed, nothing happens. Direct the user to install ARCore from the Play Store, then try again.@@ -86168,16 +86749,16 @@ The AR button is only shown after the GLB finishes loading. If the model is largAlmost always a model problem:-1. **File too large.** Quick Look on older devices struggles above ~15 MB. Compress textures and simplify geometry — see [model optimization](/docs/ar#model-size-and-compatibility).-2. **Draco-compressed GLB.** Quick Look doesn't include a Draco decoder — the file may load partially then fail. Decompress it: `npx @gltf-transform/cli optimize model.glb out.glb --no-draco`.+1. **File too large.** Quick Look on older devices struggles above ~15 MB. Compress textures and simplify geometry, see [model optimization](ar.md#model-optimization-for-ar).+2. **Draco-compressed GLB.** Quick Look doesn't include a Draco decoder, the file may load partially then fail. Decompress it: `npx @gltf-transform/cli optimize model.glb out.glb --no-draco`.3. **CORS missing on the model URL.** Quick Look fetches the file separately from the browser, and CORS failures are silent. Verify `Access-Control-Allow-Origin: *` is present on the response headers for the GLB URL.-4. **USDZ conversion failed.** Check the browser console for errors *before* Quick Look opens — the in-browser USDZExporter logs any failures. A corrupt or oversize USDZ causes immediate dismissal.+4. **USDZ conversion failed.** Check the browser console for errors *before* Quick Look opens, the in-browser USDZExporter logs any failures. A corrupt or oversize USDZ causes immediate dismissal.---### The model is invisible or floating in WebXR-**Background not cleared:** Verify the scene background is `null` when the XR session starts. If it's opaque, it occludes the camera passthrough — the agent is there but hidden behind the background color.+**Background not cleared:** Verify the scene background is `null` when the XR session starts. If it's opaque, it occludes the camera passthrough, the agent is there but hidden behind the background color.**Agent placed off-screen:** If `activateAR()` is called before the agent is positioned in the viewport, the model may be anchored outside the camera frustum. Ensure the agent is visible in the standard 3D view before activating AR.@@ -86187,11 +86768,11 @@ Almost always a model problem:### USDZ conversion is slow or fails-The in-browser GLB → USDZ conversion runs in the main thread and can take 5–15 seconds for complex models. If it fails:+The in-browser GLB → USDZ conversion runs in the main thread and can take 5-15 seconds for complex models. If it fails:- Check the browser console for errors from `USDZExporter`.-- Try the model in the [glTF Validator](/validation) first — invalid GLBs often cause export failures.-- Skinned/rigged meshes export as static poses in USDZ (animations are lost — this is expected).+- Try the model in the [glTF Validator](/validation) first, invalid GLBs often cause export failures.+- Skinned/rigged meshes export as static poses in USDZ (animations are lost, this is expected).- Models over ~30 MB may time out or exhaust memory during conversion on mobile. Reduce the model size before attempting Quick Look.Pre-generate USDZ files on the server and set `ios-src` to skip in-browser conversion entirely.@@ -86202,15 +86783,15 @@ Pre-generate USDZ files on the server and set `ios-src` to skip in-browser conveAll three AR methods require HTTPS. `navigator.xr` is undefined on insecure origins; Quick Look and Scene Viewer require the model URL to be HTTPS regardless of the page origin.-**Option 1 — ngrok:**+**Option 1: ngrok:**```bashnpm run dev # starts dev server on port 3000ngrok http 3000 # creates an HTTPS tunnel# Open the ngrok URL on your phone```-**Option 2 — a deployed HTTPS environment:**-Deploy your change and test against the live HTTPS URL. There are no per-branch preview deployments in the production flow — three.ws production deploys with `npm run deploy:gcp` to Cloud Run. A fork hosted on Vercel or Netlify does get an HTTPS URL per deploy, which works the same way for AR testing.+**Option 2: a deployed HTTPS environment:**+Deploy your change and test against the live HTTPS URL. There are no per-branch preview deployments in the production flow, three.ws production deploys with `npm run deploy:gcp` to Cloud Run. A fork hosted on Vercel or Netlify does get an HTTPS URL per deploy, which works the same way for AR testing.**Chrome WebXR emulator (desktop testing):**Chrome 127+ includes a WebXR device simulator under DevTools → More Tools → WebXR. It won't show camera passthrough but lets you test the session lifecycle and model placement logic without a physical device.@@ -86223,19 +86804,19 @@ See the [AR & WebXR guide](/docs/ar) for the full platform compatibility matrix**Is three.ws free?**-The core platform is free. API usage costs (Anthropic for LLM, ElevenLabs for TTS) are charged at cost — you supply your own API keys. IPFS pinning for on-chain registration requires a Pinata JWT or uses the default R2 backend.+The core platform is free. API usage costs (Anthropic for LLM, ElevenLabs for TTS) are charged at cost, you supply your own API keys. IPFS pinning for on-chain registration requires a Pinata JWT or uses the default R2 backend.**Can I use any 3D model, or does it have to be a humanoid?**-Any glTF 2.0 / GLB model works. Humanoid models with the correct skeleton and morph targets unlock the full emotion system (facial expressions, head movement). Non-humanoid models display and animate fine — they just won't show emotions.+Any glTF 2.0 / GLB model works. Humanoid models with the correct skeleton and morph targets unlock the full emotion system (facial expressions, head movement). Non-humanoid models display and animate fine, they just won't show emotions.**Does the agent work without an Anthropic API key?**-The 3D viewer, animations, and widget system all work without a key. The LLM conversation feature requires setting the `brain` attribute on the element and a valid API key. If no key is configured, the element uses `NullProvider` (no-op) — it won't respond to chat messages.+The 3D viewer, animations, and widget system all work without a key. The LLM conversation feature requires setting the `brain` attribute on the element and a valid API key. If no key is configured, the element uses `NullProvider` (no-op), it won't respond to chat messages.**Can I self-host without Vercel?**-Yes — production itself doesn't run on Vercel. Since 2026-07-07, three.ws production is a single container on Google Cloud Run: `server/index.mjs` serves the static frontend and every `api/**` handler, and reads `vercel.json`'s route table at runtime as its routing config. That server is the reference implementation for self-hosting on any Node.js host. If you'd rather use your own routing layer (Express routes, Nginx `proxy_pass`, etc.), replicate the `vercel.json` rewrite rules there — the API routes are standard Node.js async functions. Deploying a fork to Vercel also still works.+Yes: production itself doesn't run on Vercel. Since 2026-07-07, three.ws production is a single container on Google Cloud Run: `server/index.mjs` serves the static frontend and every `api/**` handler, and reads `vercel.json`'s route table at runtime as its routing config. That server is the reference implementation for self-hosting on any Node.js host. If you'd rather use your own routing layer (Express routes, Nginx `proxy_pass`, etc.), replicate the `vercel.json` rewrite rules there, the API routes are standard Node.js async functions. Deploying a fork to Vercel also still works.**Is the agent data private?**@@ -87599,7 +88180,7 @@ curl -s $BASE/api/pay/execute \{"ok": true,"paid": false,- "note": "Endpoint served response without a 402 - no payment needed.",+ "note": "Endpoint served response without a 402. No payment needed.","status": 200,"result": { "ok": true, "method": "GET", "headers": { "...": "..." }, "body": null, "ts": "..." }}@@ -87995,7 +88576,6 @@ curl -X PUT https://three.ws/api/agents/$AGENT_ID/animations \-H "authorization: Bearer $THREE_WS_TOKEN" \-H 'content-type: application/json' \-d '{- "animations": [],"animationSlots": {"dance": "av-offabean-dance","celebrate": "av-cheering",@@ -88007,7 +88587,9 @@ curl -X PUT https://three.ws/api/agents/$AGENT_ID/animations \Anything not listed keeps the platform default, so a map is only as long as the changes you want. `"animationSlots": {}` clears every override. The map is stored on the agent at `meta.edits.animations` and published on its public manifest as `animationSlots`, so an `<agent-3d>` embed of that agent plays its body language too.-Two things the endpoint will reject rather than silently accept: a slot name outside the vocabulary (a typo would create a gesture nothing ever plays) and a clip name that is not a plain name. `animations` is the agent's clip list and is required by that endpoint; send `[]` only if you do not use it, since the field replaces what is there.+Every field on that endpoint is optional and follows one rule: **present means replace this, absent means leave it alone.** Send `animationSlots` on its own and the agent's clip list, animation graph and choreographies are untouched. Do not pad the body with `"animations": []` to satisfy the schema, because an empty array is a real value and wipes the clip list. The body only has to carry at least one of `animations`, `animationGraph`, `animationSlots` or `choreographies`, or you get a `400`.++Two things the endpoint will reject rather than silently accept: a slot name outside the vocabulary (a typo would create a gesture nothing ever plays) and a clip name that is not a plain alphanumeric name.Any of the 112 clip names in [`/animations/manifest.json`](https://three.ws/animations/manifest.json) is valid. Browse them with previews at [three.ws/animations](https://three.ws/animations).@@ -88058,7 +88640,7 @@ The full attribute and method surface is in the [embedding guide](/docs/embeddin## 5. Player-driven gestures on /walk-There is a second gesture library for avatars a person is driving rather than an agent: open [three.ws/walk](https://three.ws/walk), move with `WASD`, and press `1`-`8` for a gesture.+There is a second gesture library for avatars a person is driving rather than an agent: open [three.ws/walk](https://three.ws/walk), move with `WASD`, and press `1`-`8` for a gesture. Those eight keys are `wave`, `dance`, `sit`, `point`, `cheer`, `agree`, `disagree` and `talking`, in that order. The library holds four more (`nod`, `shrug`, `jog`, `celebrate`) with no quick key: hold `G` for the gesture wheel, or call `window.walk.playGesture('shrug')`.The difference that matters is the layer. `wave`, `point`, `nod` and `shrug` are **upper-body overlays**: the legs keep the walk cycle, so your avatar waves while it walks. `dance`, `sit`, `jog` and `celebrate` are **full-body**, so movement is suppressed until they end. Try waving while walking, then dancing while walking, and the distinction is obvious in one second.@@ -88079,9 +88661,9 @@ The difference that matters is the layer. `wave`, `point`, `nod` and `shrug` are# Animate your avatar-By the end of this tutorial you'll be able to take any rigged avatar, browse the three.ws clip library, apply a motion to it live, control its speed and looping, and export an animated GLB you can use anywhere. You'll also understand *why* a clip authored for one skeleton plays correctly on yours — the runtime retargeting that makes the library universal.+By the end of this tutorial you'll be able to take any rigged avatar, browse the three.ws clip library, apply a motion to it live, control its speed and looping, and export an animated GLB you can use anywhere. You'll also understand *why* a clip authored for one skeleton plays correctly on yours, the runtime retargeting that makes the library universal.-**Prerequisites:** a three.ws account and at least one rigged avatar ([create one](/create), or load any public avatar). No code required — everything here happens in the browser. Light JavaScript familiarity helps only for the optional "how retargeting works" section.+**Prerequisites:** a three.ws account and at least one rigged avatar ([create one](/create), or load any public avatar). No code required, everything here happens in the browser. Light JavaScript familiarity helps only for the optional "how retargeting works" section.---@@ -88095,7 +88677,7 @@ Pick an avatar ──► Browse the clip library ──► Click a cliptune speed / loop ──► export animated GLB```-You don't author motion from scratch (you can — that's the keyframe timeline, a separate workflow). Here you *apply* and *remix* the shared library: dozens of pre-baked clips — idle, walk, dances, gestures, reactions — that drive **any** humanoid rig without manual bone mapping.+You don't author motion from scratch (you can: that's the keyframe timeline, a separate workflow). Here you *apply* and *remix* the shared library: dozens of pre-baked clips, idle, walk, dances, gestures, reactions, that drive **any** humanoid rig without manual bone mapping.Two surfaces do this, and they're connected:@@ -88112,18 +88694,18 @@ The Gallery is where you *discover* a clip; the Studio is where you *apply* it.The thing that makes the library work is that **motion and body are stored separately**.-- An avatar is a **GLB** — geometry, skeleton, skin, textures.-- A motion is a **clip JSON** — keyframe tracks only, no geometry. One clip can play on every avatar.+- An avatar is a **GLB**: geometry, skeleton, skin, textures.+- A motion is a **clip JSON**: keyframe tracks only, no geometry. One clip can play on every avatar.-A clip's tracks are named against a **canonical skeleton** — a 53-bone humanoid set (`Hips → Spine → Spine1 → Spine2 → Neck → Head`, both arms `Shoulder → Arm → ForeArm → Hand` with finger chains, both legs `UpLeg → Leg → Foot → ToeBase`). Every clip in [public/animations/clips](../public/animations/clips) is baked against the reference rig `public/avatars/cz.glb`.+A clip's tracks are named against a **canonical skeleton**, the 52-bone humanoid set exported as `CANONICAL_BONES` (`Hips → Spine → Spine1 → Spine2 → Neck → Head`, both arms `Shoulder → Arm → ForeArm → Hand` with finger chains, both legs `UpLeg → Leg → Foot → ToeBase`). Every clip in [public/animations/clips](../public/animations/clips) is baked against the reference rig `public/avatars/cz.glb`.-Your avatar almost certainly names its bones differently — `mixamorig:Hips`, `DEF-spine`, `J_Bip_C_Hips`, `pelvis`, `leftUpperArm`. Two runtime modules bridge that gap:+Your avatar almost certainly names its bones differently, `mixamorig:Hips`, `DEF-spine`, `J_Bip_C_Hips`, `pelvis`, `leftUpperArm`. Two runtime modules bridge that gap:-1. **Bone-name canonicalization** ([src/glb-canonicalize.js](../src/glb-canonicalize.js)) recognizes the common skeleton conventions — Mixamo (`mixamorig:`), Blender (`Armature_`, `.L`/`.R`), Rigify (`DEF-`/`ORG-`), Unreal (`upperarm_l`), VRM/VRoid (`J_Bip_L_UpperArm`), VRM 1.0 (`leftUpperArm`), Daz/Genesis (`lShldr`), MakeHuman, and simple rigs (`shoulderL`) — and maps each bone to its canonical name.+1. **Bone-name canonicalization** ([src/glb-canonicalize.js](../src/glb-canonicalize.js)) recognizes the common skeleton conventions, Mixamo (`mixamorig:`), Blender (`Armature_`, `.L`/`.R`), Rigify (`DEF-`/`ORG-`), Unreal (`upperarm_l`), VRM/VRoid (`J_Bip_L_UpperArm`), VRM 1.0 (`leftUpperArm`), Daz/Genesis (`lShldr`), MakeHuman, and simple rigs (`shoulderL`), and maps each bone to its canonical name.2. **Retargeting** ([src/animation-retarget.js](../src/animation-retarget.js)) rewrites each track onto your rig's actual bone names, applies a per-bone bind-pose correction (so an A-pose clip plays right on a T-pose rig, and a hip baked at −90°X doesn't tip the body over), and rescales hip translation by your avatar's height so root motion lands where it should.-**There is no rig allowlist.** Any humanoid avatar drives the library through this canonicalize-then-retarget path. The only gates are sanity thresholds: a rig needs **≥8** recognizable humanoid bones, and a clip must map **≥50%** of its tracks onto the rig to land. Below that the motion would read as a few twitching joints, so the Studio refuses it with an actionable message instead of playing garbage. If you hit a brand-new skeleton convention the canonicalizer doesn't know, the fix is to add its bone-name mapping to `glb-canonicalize.js` — never to hardcode a curated list of supported rigs.+**There is no rig allowlist.** Any humanoid avatar drives the library through this canonicalize-then-retarget path. The only gates are sanity thresholds: a rig needs **≥8** recognizable humanoid bones, and a clip must map **≥50%** of its tracks onto the rig to land. Below that the motion would read as a few twitching joints, so the Studio refuses it with an actionable message instead of playing garbage. If you hit a brand-new skeleton convention the canonicalizer doesn't know, the fix is to add its bone-name mapping to `glb-canonicalize.js`, never to hardcode a curated list of supported rigs.---@@ -88131,7 +88713,7 @@ Your avatar almost certainly names its bones differently — `mixamorig:Hips`, `-Open **[/pose](/pose)**. You'll land on the built-in **mannequin** — a primitive figure for FK/IK posing. The mannequin has no skinned skeleton to export, so the preset library stays locked until you load a real avatar.+Open **[/pose](/pose)**. You'll land on the built-in **mannequin**, a primitive figure for FK/IK posing. The mannequin has no skinned skeleton to export, so the preset library stays locked until you load a real avatar.@@ -88145,7 +88727,7 @@ If you'd rather skip the picker, deep-link directly:The Studio reads `?avatar=` on boot and loads it for you (swap in your own avatar's id from its `/avatars/<id>` page). Add `&anim=<clip-id>` and it also opens that saved clip; this is exactly what the Gallery's **Open in Studio** button does.-If the right panel shows **"Load a rigged avatar to animate"**, you're still on the mannequin — load an avatar. If it shows **"This rig can't be retargeted,"** the model exposes fewer than 8 recognizable humanoid bones (see Troubleshooting).+If the right panel shows **"Load a rigged avatar to animate"**, you're still on the mannequin, load an avatar. If it shows **"This rig can't be retargeted,"** the model exposes fewer than 8 recognizable humanoid bones (see Troubleshooting).---@@ -88157,7 +88739,7 @@ With an avatar loaded, the **Animation** section on the right fills with a searc- **Search** ("Search animations…") matches clip labels and names as you type.- Each **card** shows an icon, a label, and a **loop** / **once** badge so you know up front whether a clip cycles forever or plays a single shot.-The library covers a wide range — idle breaths, walks, dances, celebrations, reactions, sitting and crouching poses, and more. Browse by category, or search for what you want (e.g. `dance`, `wave`, `idle`).+The library covers a wide range: idle breaths, walks, dances, celebrations, reactions, sitting and crouching poses, and more. Browse by category, or search for what you want (e.g. `dance`, `wave`, `idle`).> Want to browse the *full* community catalog first? Open the **[Animation Gallery](/animations)** in another tab. It lists public clips with hover-to-preview on a live avatar, a loop/one-shot filter, and infinite scroll. When you find one you like, click **Open in Studio** and it lands back here applied to your avatar.@@ -88171,32 +88753,32 @@ Click any card. The Studio:2. Retargets it onto your loaded rig (rewrites bone names, corrects the bind pose, scales the hips).3. Plays it live on the figure in the viewport.-The shared 3D stage **is** the preview — one figure performing the motion, the way Mixamo previews look, rather than a wall of video thumbnails. The active card gets a "now playing" equalizer animation and a highlighted border.+The shared 3D stage **is** the preview: one figure performing the motion, the way Mixamo previews look, rather than a wall of video thumbnails. The active card gets a "now playing" equalizer animation and a highlighted border.The status line at the bottom of the stage confirms the retarget, e.g.:```-Playing "Cheering" — 96% retargeted (51/53 bones matched).+Playing "Cheering": 96% retargeted (51/53 bones matched).```-That percentage is the coverage — how many of the clip's tracks found a home on your rig. A couple of dropped bones (often fingers a simpler rig lacks) is normal and fine. If coverage falls below 50%, the clip won't apply and the status explains why (see Troubleshooting).+That percentage is the coverage: how many of the clip's tracks found a home on your rig. (The counter is tracks, which the status line labels "bones": a full library clip carries 53 of them, one rotation track per canonical bone plus the hips' position track.) A couple of dropped bones (often fingers a simpler rig lacks) is normal and fine. If coverage falls below 50%, the clip won't apply and the status explains why (see Troubleshooting).Clips marked **once** play a single shot and hold the final frame; **loop** clips cycle until you stop them or pick another.----## Step 4: Control playback — speed and loop+## Step 4: Control playback: speed and loopOnce a clip is playing, a **transport bar** appears under the gallery:- A pulsing **now-playing** indicator with the clip's name.-- A **Speed** slider, `0.25×` to `2.5×`. Drag it to taste — `1.8×` turns a walk into something close to a jog; `0.5×` slows a gesture down for emphasis. The value updates live.+- A **Speed** slider, `0.25×` to `2.5×`. Drag it to taste, `1.8×` turns a walk into something close to a jog; `0.5×` slows a gesture down for emphasis. The value updates live.- **⏹ Stop** ends the preview and hands the figure back to a clean rest pose.- **Export animated GLB** (covered next).-Looping follows the clip's own `loop` flag (the **loop** / **once** badge). Speed is a live preview control *and* it's baked into the export — the GLB you download carries the tempo you previewed, not a default one.+Looping follows the clip's own `loop` flag (the **loop** / **once** badge). Speed is a live preview control *and* it's baked into the export, the GLB you download carries the tempo you previewed, not a default one.-To swap clips, just click a different card — the new motion retargets and replaces the old one. To compare two dances, apply one, watch it, then click the other; the transport always reflects what's currently playing.+To swap clips, just click a different card: the new motion retargets and replaces the old one. To compare two dances, apply one, watch it, then click the other; the transport always reflects what's currently playing.---@@ -88205,10 +88787,10 @@ To swap clips, just click a different card — the new motion retargets and replThe preset library is finite; your imagination isn't. At the top of the **Animation** section is a text-to-motion box:```-Generate a motion — "waving confidently" [ ✨ Generate ]+Generate a motion: "waving confidently" [ ✨ Generate ]```-Type a short description (e.g. `waving confidently`, `a slow bow`, `excited jumping`) and click **Generate**. The Studio submits a motion job, polls until the clip is ready (typically ~10–30s on a warm GPU; up to ~90s), then **retargets and plays it on your rig through the exact same path as a preset.** A generated motion behaves identically — same transport, speed slider, loop, and export. The status line counts the seconds while it works.+Type a short description (e.g. `waving confidently`, `a slow bow`, `excited jumping`) and click **Generate**. The Studio submits a motion job, polls until the clip is ready (typically ~10-30s on a warm GPU; up to ~90s), then **retargets and plays it on your rig through the exact same path as a preset.** A generated motion behaves identically, same transport, speed slider, loop, and export. The status line counts the seconds while it works.If the deployment hasn't enabled text-to-animation, you'll get a clear "isn't enabled on this deployment yet" message rather than a hang. Either way, the preset library is always available.@@ -88218,7 +88800,7 @@ If the deployment hasn't enabled text-to-animation, you'll get a clear "isn't enWhen a clip looks right, click **Export animated GLB** in the transport bar.-The Studio bakes the retargeted clip — at your chosen speed — onto your avatar's rig and downloads a single self-contained file:+The Studio bakes the retargeted clip: at your chosen speed, onto your avatar's rig and downloads a single self-contained file:```<avatar-name>-<clip-name>.glb@@ -88226,9 +88808,9 @@ The Studio bakes the retargeted clip — at your chosen speed — onto your avatThis closes the loop: you started with a GLB (body) and a separate clip (motion), and you end with **one GLB that has the motion embedded.** It loads in any standard glTF viewer or in any three.ws surface, no retargeting required at play time.-The figure is parked on the clip's first frame before export, so the file's rest pose is the animation's actual start — not wherever the live preview happened to pause.+The figure is parked on the clip's first frame before export, so the file's rest pose is the animation's actual start, not wherever the live preview happened to pause.-> The Studio can also export **clip JSON** (motion only, reusable on other rigs) and a **PNG screenshot** from the top bar, and — if you author your own motion on the keyframe timeline — save it to your account and list it. Those are adjacent workflows; this tutorial is the apply-and-remix path.+> The Studio can also export **clip JSON** (motion only, reusable on other rigs) and a **PNG screenshot** from the top bar, and, if you author your own motion on the keyframe timeline, save it to your account and list it. Those are adjacent workflows; this tutorial is the apply-and-remix path.---@@ -88237,7 +88819,7 @@ The figure is parked on the clip's first frame before export, so the file's restThe **[Animation Gallery](/animations)** is the social, browse-first side of the same system. It lists public, community-authored clips:- **Search** and a **loop / one-shot** filter narrow the grid.-- **Hover or click a card** to launch a live preview — an embedded viewer plays the clip on the reference CZ avatar, so you see real motion, not a static thumbnail.+- **Hover or click a card** to launch a live preview: an embedded viewer plays the clip on the reference CZ avatar, so you see real motion, not a static thumbnail.- **Open in Studio** deep-links to `/pose?anim=<id>`, dropping the clip into the Studio so you can apply it to *your* avatar, tune its speed, and export.This is the remix loop: find a motion someone else published, open it in the Studio, retarget it onto your own avatar, adjust it, export. Because every clip is format-light JSON addressed by canonical bone names, the same clip that previewed on the CZ avatar drives your custom rig with no extra work.@@ -88246,38 +88828,38 @@ This is the remix loop: find a motion someone else published, open it in the Stu## Emotion and expression on the live agent-Applying clips in the Studio is the **authoring** side. On a *running* agent, the same library drives emotion and gesture automatically through two channels that share one emotional state — the avatar's **Empathy Layer** ([src/agent-avatar.js](../src/agent-avatar.js)):+Applying clips in the Studio is the **authoring** side. On a *running* agent, the same library drives emotion and gesture automatically through two channels that share one emotional state, the avatar's **Empathy Layer** ([src/agent-avatar.js](../src/agent-avatar.js)):-**Gesture slots** ([src/runtime/animation-slots.js](../src/runtime/animation-slots.js)) — a fixed emotional vocabulary the agent plays in conversation: `idle`, `wave`, `nod`, `shake`, `think`, `celebrate`, `concern`, `bow`, `point`, `shrug`, `dance`. Each slot resolves to a concrete library clip at runtime (e.g. `celebrate` → the `celebrate` clip, `think` → `pray`). An agent picks a slot when the moment calls for it; the clip retargets onto that agent's avatar exactly as in the Studio. You can override any slot per agent via `meta.edits.animations` — point `wave` at a different clip, or map a slot to a motion you authored yourself.+**Gesture slots** ([src/runtime/animation-slots.js](../src/runtime/animation-slots.js)), a fixed vocabulary the agent plays in conversation. The conversational slots are `idle`, `wave`, `nod`, `shake`, `think`, `celebrate`, `concern`, `bow`, `point`, `shrug`, `fidget`, `dance`; a second group exists because skills emit the matching hint: `inspect`, `present`, `sign`, `curiosity`, `patience`, `manipulate`, `conjure`. Each slot resolves to a concrete library clip at runtime through `DEFAULT_ANIMATION_MAP`, most map to the clip of the same name (`celebrate` → `celebrate`, `think` → `think`), and a few borrow the closest baked motion where no dedicated clip exists yet (`concern` → `defeated`, `bow` → `sitclap`, `dance` → `rumba`). An agent picks a slot when the moment calls for it; the clip retargets onto that agent's avatar exactly as in the Studio. You can override any slot per agent via `meta.edits.animations`, point `wave` at a different clip, or map a slot to a motion you authored yourself.-**Facial expression** ([src/runtime/arkit52.js](../src/runtime/arkit52.js)) — driven from the same blend of morph targets as the gesture layer, not a separate track. If your avatar carries ARKit-52 blendshapes (most modern avatar-platform exports do, as do VRoid models), the runtime resolves those morph targets and drives expression and lip-sync directly on the face. A skeletal clip plays the body; the blendshape layer plays the eyes, brows, and mouth on top.+**Facial expression** ([src/runtime/arkit52.js](../src/runtime/arkit52.js)), driven from the same blend of morph targets as the gesture layer, not a separate track. If your avatar carries ARKit-52 blendshapes (most modern avatar-platform exports do, as do VRoid models), the runtime resolves those morph targets and drives expression and lip-sync directly on the face. A skeletal clip plays the body; the blendshape layer plays the eyes, brows, and mouth on top.The two channels are wired to the *same* emotional state, at two different timescales, so the body and the face never disagree:-- **Momentary events** (an error just happened, a skill just finished) inject a transient emotion spike — `concern`, `celebration`, `curiosity`, and friends — that decays over seconds. A spike crossing threshold both reshapes the face immediately *and* biases the gesture slot the avatar plays next (e.g. sustained `celebration` picks the `celebrate` slot).-- **Sustained mood** — the agent's resting valence/arousal, set via `setMood()` (see [docs/tutorials/emotion-from-data.md](#sec-432)) — is the continuous baseline between events. It biases the resting face (a soft smile at high valence, a worried brow at low) and posture (lean, gaze) every frame, and, once nothing more urgent claims the gesture slot, biases *which* ambient gesture plays too: a sustained up-and-energetic mood leans toward the `celebrate` slot, a sustained down-and-subdued mood toward `concern` — the opposite bias, never the energetic one. A momentary event always takes priority over the ambient mood bias, and slot overrides via `meta.edits.animations` apply identically whether the trigger was a spike or the resting mood.+- **Momentary events** (an error just happened, a skill just finished) inject a transient emotion spike, `concern`, `celebration`, `curiosity`, and friends, that decays over seconds. A spike crossing threshold both reshapes the face immediately *and* biases the gesture slot the avatar plays next (e.g. sustained `celebration` picks the `celebrate` slot).+- **Sustained mood**: the agent's resting valence/arousal, set via `setMood()` (see [docs/tutorials/emotion-from-data.md](#sec-432)), is the continuous baseline between events. It biases the resting face (a soft smile at high valence, a worried brow at low) and posture (lean, gaze) every frame, and, once nothing more urgent claims the gesture slot, biases *which* ambient gesture plays too: a sustained up-and-energetic mood leans toward the `celebrate` slot, a sustained down-and-subdued mood toward `concern`, the opposite bias, never the energetic one. A momentary event always takes priority over the ambient mood bias, and slot overrides via `meta.edits.animations` apply identically whether the trigger was a spike or the resting mood.-The division of labor: **clips move the body, blendshapes move the face, slots choose *which* body motion fits the emotion — and one emotional state, not two independent tracks, drives all of it.** All three ride the same universal-rig foundation — name your bones (and your blendshapes) in a convention the resolvers know, and everything just works.+The division of labor: **clips move the body, blendshapes move the face, slots choose *which* body motion fits the emotion, and one emotional state, not two independent tracks, drives all of it.** All three ride the same universal-rig foundation, name your bones (and your blendshapes) in a convention the resolvers know, and everything just works.---## Troubleshooting-- **The Animation section says "Load a rigged avatar to animate."** You're on the built-in mannequin. The mannequin has no skinned skeleton to retarget or export — click **Load avatar** in the top bar (or open `/pose?avatar=<id>`).+- **The Animation section says "Load a rigged avatar to animate."** You're on the built-in mannequin. The mannequin has no skinned skeleton to retarget or export, click **Load avatar** in the top bar (or open `/pose?avatar=<id>`).-- **"This rig can't be retargeted — only N recognizable humanoid bones."** The model exposes fewer than 8 canonical bones. It's likely non-humanoid, a static prop, or a rig whose bone names the canonicalizer doesn't recognize. Re-export it as a standard humanoid (Mixamo, VRM, or any common avatar-platform export all work), or auto-rig a rig-less mesh first.+- **"This rig can't be retargeted: only N recognizable humanoid bones."** The model exposes fewer than 8 canonical bones. It's likely non-humanoid, a static prop, or a rig whose bone names the canonicalizer doesn't recognize. Re-export it as a standard humanoid (Mixamo, VRM, or any common avatar-platform export all work), or auto-rig a rig-less mesh first.-- **A clip won't apply: "can't retarget to this rig — only X/Y tracks mapped."** Coverage fell below 50%. The rig is missing too many of the clip's bones (often a stripped-down skeleton with no spine subdivisions or no fingers). Try a clip that uses fewer bones, or use a more complete humanoid rig. The fix for a recurring convention is to add its bone-name mapping in [src/glb-canonicalize.js](../src/glb-canonicalize.js) — never a hardcoded allowlist.+- **A clip won't apply: "can't retarget to this rig: only X/Y tracks mapped."** Coverage fell below 50%. The rig is missing too many of the clip's bones (often a stripped-down skeleton with no spine subdivisions or no fingers). Try a clip that uses fewer bones, or use a more complete humanoid rig. The fix for a recurring convention is to add its bone-name mapping in [src/glb-canonicalize.js](../src/glb-canonicalize.js), never a hardcoded allowlist.- **The motion plays but limbs look skewed or the body lies down.** This is the symptom the bind-pose correction exists to prevent, so it should be rare. It usually means the rig rests in an unusual pose the canonicalizer mapped but couldn't fully correct. Verify the avatar imports upright and T- or A-posed; re-export from the source tool if it doesn't.-- **A few bones are "not on this rig" but it still plays.** Expected. The status note (`51/53 bones · 2 not on this rig`) just lists dropped tracks — usually fingers or toes a simpler rig lacks. As long as coverage is ≥50% the performance reads correctly.+- **A few bones are "not on this rig" but it still plays.** Expected. The status note (`51/53 bones · 2 not on this rig`) just lists dropped tracks, usually fingers or toes a simpler rig lacks. As long as coverage is ≥50% the performance reads correctly.- **"Text-to-animation isn't enabled on this deployment yet."** The motion generator isn't configured on this instance. Use the preset library, which is always available.- **Generation times out.** The job exceeded the poll window. Try a shorter, simpler prompt.-- **Export downloads nothing / fails.** Make sure a clip is actively playing (the transport bar is visible) before clicking **Export animated GLB** — export bakes the *currently previewing* clip onto the rig.+- **Export downloads nothing / fails.** Make sure a clip is actively playing (the transport bar is visible) before clicking **Export animated GLB**, export bakes the *currently previewing* clip onto the rig.---@@ -88285,18 +88867,18 @@ The division of labor: **clips move the body, blendshapes move the face, slots cYou learned the apply-and-remix workflow for motion on three.ws:-- **The library is universal.** Motion is stored as canonical-skeleton clip JSON, separate from the avatar GLB. [glb-canonicalize.js](../src/glb-canonicalize.js) maps any humanoid's bone names to canonical; [animation-retarget.js](../src/animation-retarget.js) rewrites tracks, corrects the bind pose, and scales the hips so one clip drives every rig. No rig allowlist — only an 8-bone / 50%-coverage sanity gate.-- **[/pose](/pose) is where you apply.** Load a rigged avatar, browse or search the categorized gallery, click to retarget and preview live, tune speed (0.25×–2.5×) and loop in the transport bar, and **export an animated GLB** with the motion baked in.+- **The library is universal.** Motion is stored as canonical-skeleton clip JSON, separate from the avatar GLB. [glb-canonicalize.js](../src/glb-canonicalize.js) maps any humanoid's bone names to canonical; [animation-retarget.js](../src/animation-retarget.js) rewrites tracks, corrects the bind pose, and scales the hips so one clip drives every rig. No rig allowlist, only an 8-bone / 50%-coverage sanity gate.+- **[/pose](/pose) is where you apply.** Load a rigged avatar, browse or search the categorized gallery, click to retarget and preview live, tune speed (0.25×-2.5×) and loop in the transport bar, and **export an animated GLB** with the motion baked in.- **[/animations](/animations) is where you discover.** Browse public community clips with live hover-preview, then **Open in Studio** to apply any of them to your own avatar.- **Generate what doesn't exist.** Text-to-motion synthesizes a brand-new clip and runs it through the identical retarget-and-apply path as a preset.-- **On a live agent**, the same clips drive emotion through gesture **slots**, while **ARKit-52 blendshapes** drive facial expression independently — clips move the body, blendshapes move the face.+- **On a live agent**, the same clips drive emotion through gesture **slots**, while **ARKit-52 blendshapes** drive facial expression independently, clips move the body, blendshapes move the face.**See also:**-- [docs/animations.md](#sec-093) — the runtime animation registry, manifest, and agent slot reference.-- [docs/3d-asset-pipeline.md](#sec-002) — how FBX, GLB, and clip JSON relate, and how clips are built and retargeted.-- [docs/tutorials/swap-avatar-in-studio.md](#sec-470) — loading and switching avatars in the Studio.-- [docs/tutorials/upload-custom-glb.md](#sec-473) — getting a Mixamo or custom rig into three.ws as a clean, animatable GLB.+- [docs/animations.md](#sec-093): the runtime animation registry, manifest, and agent slot reference.+- [docs/3d-asset-pipeline.md](#sec-002), how FBX, GLB, and clip JSON relate, and how clips are built and retargeted.+- [docs/tutorials/swap-avatar-in-studio.md](#sec-470), loading and switching avatars in the Studio.+- [docs/tutorials/upload-custom-glb.md](#sec-473), getting a Mixamo or custom rig into three.ws as a clean, animatable GLB.Primary call to action: open **[/pose](/pose)**, load an avatar, and apply your first clip.@@ -88374,14 +88956,16 @@ That is 0.05 SOL per trade, at most 0.2 SOL per day, one position at a time. `GE## Step 3: Know your exit ladder-Exits are decided by a pure function in strict priority order, so behavior is exactly predictable:+Exits are decided by a pure function in strict priority order, so behavior is exactly predictable. The first rule that matches wins:1. **Stop-loss** (`stop_loss_pct`): value falls 30% below entry, sell everything, always checked first.-2. **Trailing stop** (`trailing_stop_pct`): value falls 25% off its peak since entry, sell.-3. **Take-profit** (`take_profit_pct`): value reaches entry plus 60%, sell.-4. **Timeout** (`max_hold_seconds`): the clock wins no matter what the PnL is.+2. **Signal flip**: only if you armed paid sentiment intel and the position is underwater. A bearish flip closes it rather than waiting for the stop. Off unless you turn it on.+3. **Trailing stop** (`trailing_stop_pct`): value falls 25% off its peak, sell. **It arms only once the position has actually been green** (the peak has to clear entry). Armed underwater a trail just converts recoverable dips into locked losses, and the hard stop-loss above already caps the downside.+4. **Take-initials** (`initials_out_multiple`): the laddered mode's first profit event, fired once, described below.+5. **Take-profit** (`take_profit_pct`): value reaches entry plus 60%, sell. With a ladder armed this applies only after the initials are out, so the ceiling can never pre-empt the ladder.+6. **Timeout** (`max_hold_seconds`): the clock wins no matter what the PnL is.-There is also a laddered mode (`initials_out_multiple`, `moonbag_min_pct`): recover your initial cost when the position hits a multiple, then let the remaining moon bag ride the trailing stop.+The laddered mode (`initials_out_multiple`, `moonbag_min_pct`) is rungs 4 and 5 working together: recover your initial cost when the position hits a multiple, then let the remaining moon bag ride the trailing stop up to the take-profit ceiling.## Step 4: The lesson from the first live trade: set `take_profit_pct`@@ -89789,152 +90373,153 @@ See also:# Connect Anthropic, OpenAI, or xAI (Grok) as the brain-The agent's body is the avatar. The agent's voice is the TTS. The agent's *brain* is whatever LLM is generating its replies. By default the platform routes through a managed Claude endpoint, which works out of the box but bills against your free tier. The moment you want real production traffic, full control over which model runs, or your own usage observability, you bring your own API key.+The agent's body is the avatar. The agent's voice is the TTS. The agent's *brain* is whatever LLM is generating its replies. By default an embedded agent runs on a **free open-weight lane** (`openai/gpt-oss-20b:free`, routed through OpenRouter on the platform's key), which works out of the box at no cost to you. The moment you want a frontier model, full control over which one runs, or your own usage observability, you bring your own API key.-This tutorial covers the whole brain layer. Where the LLM call actually happens (and why your key never ends up in HTML), how to attach your Anthropic or OpenAI key in My Agents, choosing between Claude Sonnet 4.6, Claude Opus 4.7, the GPT-5.6 family, and the smaller models, the latency and cost tradeoffs, configuring streaming and system prompts, tool-use support per model, and where to watch your token spend. The embed snippet doesn't change when you switch models — every config is on the agent record.+This tutorial covers the whole brain layer. Where the LLM call actually happens (and why your key never ends up in HTML), how to attach your Anthropic, OpenAI, or xAI key, choosing between the Claude 5 family, the GPT-5.x family, Grok, and the free lanes, the latency and cost tradeoffs, how streaming and system prompts are configured, tool-use support per model, and where to watch your spend. The embed snippet doesn't change when you switch models, the model lives on the agent's embed policy, not in your HTML.**What you'll build:**-- An agent powered by your own Anthropic key, with model selection-- An agent powered by your own OpenAI key, switchable across the GPT-5.6 family+- An agent powered by your own Anthropic, OpenAI, or xAI key- A working understanding of which model fits which use case (cost, latency, capability)-- A streaming-enabled brain so replies feel responsive-- An observability dashboard you can use to monitor spend per agent+- An embed policy that pins the model, the monthly quota, and the per-minute rate limit+- A concrete read on what your agents are actually spending**Prerequisites:** You have an agent at [three.ws/my-agents](https://three.ws/my-agents). You have an API key from Anthropic ([console.anthropic.com](https://console.anthropic.com)), OpenAI ([platform.openai.com](https://platform.openai.com)), or xAI ([console.x.ai](https://console.x.ai)). Familiarity with the concept of system prompts (see [agent personality](/tutorials/agent-personality)).----## Step 1 — Where the LLM call actually happens+## Step 1: Where the LLM call actually happensThe single most important architectural detail: **the LLM call is server-side, always**. The browser never talks to Anthropic or OpenAI directly. Your API key never leaves the platform's backend.When the agent on the page calls `agent.say('hi')`, the flow is:-1. The browser sends the user's message, the agent ID, and a session token to `three.ws/api/chat`.-2. The platform looks up the agent's brain configuration (provider, model, system prompt, attached tools).-3. The platform looks up the agent owner's stored API key for that provider (or falls back to the managed free-tier credit).-4. The platform makes the LLM call from the server, streams the response back over Server-Sent Events to the browser.-5. The browser fires `brain:stream` events with chunks and a final `brain:message` event with the complete reply.+1. The browser posts an Anthropic-shape body (`{ model, system, messages, tools, stream }`) to `three.ws/api/llm/anthropic?agent=<agentId>` (`api/llm/anthropic.js`).+2. The proxy reads that agent's **embed policy** and checks the referring origin against its allowlist, its per-minute rate limit, and its monthly quota, all before a single upstream token is spent.+3. It resolves which model actually runs (see the clamp below), looks up the matching upstream credential, and calls the provider from the server.+4. The response streams back as Anthropic-shape Server-Sent Events, whatever the upstream was, Groq, OpenRouter, NVIDIA, Mistral, xAI, and Vertex are all translated into that one wire format so the browser parser never changes.+5. The runtime fires `brain:stream` events with chunks and a final `brain:message` event with the complete reply. Both are re-dispatched on the `<agent-3d>` host element, so you listen on the element.-This matters for three reasons:+This matters for four reasons:-- **Keys stay secret.** Even a "view source" attack on your page reveals nothing. The key lives only in the platform's key store.-- **Rate-limit shaping happens once, server-side.** The platform manages backoff and retries for you.-- **The embed snippet doesn't know which model is running.** You can swap from Claude Sonnet 4.6 to GPT-5.6 Sol in My Agents and every page that embeds your agent picks up the change on next load. No code edits anywhere.+- **Keys stay secret.** Even a "view source" attack on your page reveals nothing. Keys live only on the server.+- **Rate-limit shaping and quota happen once, server-side**, per agent, from the embed policy.+- **A visitor cannot escalate you onto a paid model.** The proxy clamps the requested model: a caller may pick freely among the free lanes, but any model billed to a first-party vendor key (every Claude and every Grok id) is forced back to whatever the *owner* configured in `policy.brain.model`. The response echoes the model actually used, so a clamped caller can see what it got.+- **The embed snippet doesn't know which model is running.** Change `policy.brain.model` and every page that embeds your agent picks up the change on next load. No code edits anywhere.-The corollary: setting `api-key="sk-ant-..."` directly on the `<agent-3d>` tag is supported but discouraged. It exposes your key in DOM. Use it only for local prototypes that never get deployed. Production agents store their key on the platform side.+There is also a lane-failover chain: if the configured model's upstream returns a quota/billing/rate-limit error mid-request, the proxy retries down a chain of free fallbacks rather than failing the turn, and the response reports the model it landed on.++The corollary: setting `api-key="sk-ant-..."` directly on the `<agent-3d>` tag is supported but discouraged. It exposes your key in the DOM. Use it only for local prototypes that never get deployed. Production agents keep their key server-side.----## Step 2 — Add your API key in My Agents+## Step 2: Add your API key in My Agents-The key store is per-account, not per-agent — once you've added a key, every agent you own can use it.+Keys live at **[/dashboard/account](https://three.ws/dashboard/account)**, in the **AI Provider Keys** panel. The store is per-account, not per-agent, once you've added a key, every agent you own can use it.For Anthropic:1. Open [console.anthropic.com](https://console.anthropic.com).2. **Settings → API Keys → Create Key.** Give it a label like "three.ws production".3. Copy the key (it starts with `sk-ant-`). You won't see it again.-4. Open [three.ws/my-agents](https://three.ws/my-agents).-5. Click the gear icon → **API Keys → Anthropic → Add key.**-6. Paste, save.+4. Open [/dashboard/account](https://three.ws/dashboard/account) → **AI Provider Keys**.+5. Paste it into **Anthropic (Claude)** and save.For OpenAI:1. Open [platform.openai.com/api-keys](https://platform.openai.com/api-keys).2. **Create new secret key.** Label it.-3. Copy (starts with `sk-`).-4. In three.ws My Agents, **API Keys → OpenAI → Add key.**-5. Paste, save.+3. Copy it (starts with `sk-proj-`).+4. Paste it into **OpenAI (GPT-4)** in the same panel and save.For xAI (Grok):1. Open [console.x.ai](https://console.x.ai).2. **API Keys → Create API key.** Label it.-3. Copy (starts with `xai-`).-4. In three.ws My Agents, **API Keys → Grok (xAI) → Add key.**-5. Paste, save.+3. Copy it (starts with `xai-`).+4. Paste it into **Grok (xAI)** in the same panel and save.-You can store all three keys at once and route different agents to different providers.+You can store all three at once. The same panel also holds keys for the non-LLM providers the platform can call on your behalf (Meshy, Tripo, Rodin, Stability, Replicate, ElevenLabs).-After saving, the keys are stored encrypted at rest. The dashboard shows the last four characters and a creation timestamp; the full key is never displayed back. If you suspect a leak, rotate the key on the provider side and replace it in the dashboard — the platform invalidates the old one immediately.+Under the hood this is `GET`/`PATCH /api/user/provider-keys`. The `GET` returns only which providers are set, never a value, and a `PATCH` with `null` for a provider deletes that key. Keys are stored encrypted at rest and are never displayed back. If you suspect a leak, rotate it on the provider side and replace it here.----## Step 3 — Pick a model+## Step 3: Pick a model-Each agent has a single active brain at a time. You change it in the agent's settings panel under **Brain → Model**.+Each agent has a single active brain at a time, pinned as `brain.model` on its embed policy (Step 8 covers changing it). To compare models interactively before you commit, the **model grid and multi-model playground at [/dashboard/brain](https://three.ws/dashboard/brain)** streams the same prompt across several models side by side. That page reads its roster from `GET /api/brain/chat`, which reports every model and whether it is currently available, so it is the live source of truth rather than a hardcoded list.-The current production-ready models, with the tradeoffs that actually matter for agent use:+Prices below are USD per million tokens (input / output) from the platform's own price table (`api/_lib/llm-pricing.js`).### Anthropic models-**Claude Sonnet 4.6** (`claude-sonnet-4-6`) — the default for most agents.+**Claude Sonnet 5** (`claude-sonnet-5`): the default recommendation.-- **Cost:** Low. Roughly $3 per million input tokens, $15 per million output. For a typical 20-turn chat this is fractions of a cent.-- **Latency:** First token in ~600ms. Full reply for a 2-sentence answer in 1.2-2 seconds.-- **Capability:** Excellent at tool use, structured output, and following system prompts. The right default for support, sales, concierge, and personal agents.+- **Cost:** $3 / $15. For a typical 20-turn chat this is fractions of a cent.+- **Capability:** Near-Opus quality on coding and agentic work at Sonnet cost. The right default for support, sales, concierge, and personal agents.- **Context window:** 200K tokens. Plenty of room for long system prompts and memory.-**Claude Opus 4.7** (`claude-opus-4-7`) — when you need the smartest model.+**Claude Opus 5** (`claude-opus-5`): when you need depth.++- **Cost:** $5 / $25.+- **Capability:** Deep reasoning, agentic and long-horizon work. **Thinks by default**, which is the tradeoff: better answers on hard questions, more latency and more billed output tokens on easy ones.+- **Context window:** 200K tokens.++**Claude Fable 5** (`claude-fable-5`): the most capable model on the platform.-- **Cost:** ~5x Sonnet. Worth it for high-stakes agents (legal, medical, financial assistants) and complex reasoning chains.-- **Latency:** First token in ~1.2s. Full reply 2.5-4s for a typical turn.-- **Capability:** Best-in-class at multi-step reasoning, ambiguous instruction handling, and long-context retrieval. Holds character better under adversarial pressure.-- **Context window:** 200K tokens. Same headroom as Sonnet — the upgrade is depth of reasoning, not window size.+- **Cost:** $10 / $50.+- **Capability:** State-of-the-art reasoning, long-horizon agentic work, knowledge work, and vision. Reach for it when a specific quality gap survives prompt iteration on Opus.+- **Note:** thinking is always on and is not configurable; the proxy strips any non-adaptive `thinking` config rather than letting the upstream reject the call.-**Claude Haiku 4.5** (`claude-haiku-4-5-20251001`) — when latency matters more than depth.+**Claude Haiku 4.5** (`claude-haiku-4-5`): when latency matters more than depth.-- **Cost:** ~1/3 of Sonnet.-- **Latency:** First token in ~250ms. Full reply in well under a second.+- **Cost:** $1 / $5, a third of Sonnet.- **Capability:** Good for FAQ-style agents, lookups, and short interactions. Drops noticeably below Sonnet on long context or nuanced tone.-- **Use it when:** you have an agent that handles many short turns (a wave-and-greet, a status-check agent) and you want it to feel instant.+- **Use it when:** you have an agent handling many short turns (a wave-and-greet, a status-check agent) and you want it to feel instant.++The previous generation stays selectable and priced identically to its successor tier: **Claude Opus 4.7** (`claude-opus-4-7`, $5 / $25) and **Claude Sonnet 4.6** (`claude-sonnet-4-6`, $3 / $15). There is no reason to start a new agent on them, but existing agents keep working untouched.++> Both Opus 4.7+ and the whole Claude 5 family reject sampling parameters upstream. The proxy strips `temperature` for those models and upgrades a `budget_tokens`-style `thinking` config to the adaptive form, so an embed that ships its SDK's defaults doesn't draw an avoidable 400. You don't have to do anything; just don't expect `temperature` to change a Claude 5 reply.### OpenAI models-**GPT-5.6 Terra** (`gpt-5.6-terra`) is the comparable peer to Sonnet 4.6.+**GPT-5.6 Terra** (`gpt-5.6-terra`) is the balanced peer to Sonnet.-- **Cost:** $2.50 per million input, $15 per million output. The same band as Sonnet.-- **Latency:** First token in ~700ms.+- **Cost:** $2.50 / $15. The same band as Sonnet.- **Capability:** Strong at multimodal input and general chat. Tool use is reliable. The right OpenAI default for support, sales, and concierge agents.- **Context window:** 1M tokens.-**GPT-5.6 Sol** (`gpt-5.6-sol`) is the reasoning-grade OpenAI flagship, comparable to Opus.+**GPT-5.6 Sol** (`gpt-5.6-sol`) is the reasoning-grade OpenAI flagship.-- **Cost:** Premium ($5 per million input, $30 per million output). Comparable to Opus per token.-- **Latency:** Higher than Terra; first token in ~1.5s, more if reasoning is engaged.+- **Cost:** $5 / $30.- **Capability:** Frontier reasoning, coding, and agentic work. Excellent at hard tasks, math, and complex tool chains. Overkill for casual chat.- **Context window:** 1M tokens.**GPT-5.6 Luna** (`gpt-5.6-luna`) is the budget pick of the 5.6 family.-- **Cost:** $1 per million input, $6 per million output.-- **Latency:** Fast.-- **Capability:** Vision-capable, and roughly comparable to Haiku for short interactions. Less coherent on long conversations.+- **Cost:** $1 / $6.+- **Capability:** Vision-capable, roughly comparable to Haiku for short interactions. Less coherent on long conversations.- **Context window:** 1M tokens.**o3** (`o3`) is the reasoning specialist, with `o3-pro` above it.- **Cost:** Reasoning tokens bill as output, so replies cost more than their visible length suggests.-- **Latency:** Variable; it thinks before the first token arrives.- **Capability:** Deep chain-of-thought for math, logic, and structured planning. Not a general chat pick; reach for it when the agent's job is to reason, not to converse.-The platform also carries the wider OpenAI lineup: GPT-5.5 and GPT-5.5 Pro, the more affordable GPT-5.4 tier (`gpt-5.4`, `gpt-5.4-pro`, `gpt-5.4-mini`, `gpt-5.4-nano`, the cheapest current GPT), and GPT-5.3 Codex (`gpt-5.3-codex`) for code-centric agents. The three 5.6 models above cover almost every agent use case; the rest are there when you want a specific cost or capability point.+The platform also carries GPT-5.5 and GPT-5.5 Pro, the more affordable GPT-5.4 tier (`gpt-5.4`, `gpt-5.4-pro`, `gpt-5.4-mini`, `gpt-5.4-nano`, the cheapest current GPT), and GPT-5.3 Codex (`gpt-5.3-codex`) for code-centric agents.Legacy ids keep working: `gpt-4o`, `gpt-4o-mini`, and `o3-mini` are accepted as aliases and resolve to `gpt-5.6-sol`, `gpt-5.6-luna`, and `o3` (the GPT-4o family was deprecated upstream in July 2026), so existing agents upgrade in place with no config change.### xAI (Grok) models-**Grok 4.5** (`grok-4.5`) is the xAI flagship.+**Grok 4.5** (`grok-4.5`) is the xAI flagship: $2 / $6, cheaper than Sonnet per token, with a 500K context window. Frontier reasoning and strong real-time knowledge of X. A good pick for agents that discuss current events or social sentiment.++**Grok 4.3** (`grok-4.3`) is the long-context option: $1.25 / $2.50, 1M-token window. Reach for it when the agent carries very large system prompts or memory.-- **Cost:** $2 per million input, $6 per million output. Cheaper than Sonnet per token.-- **Latency:** First token in roughly a second.-- **Capability:** Frontier reasoning with strong real-time knowledge of X. Tool use is reliable. A good pick for agents that discuss current events or social sentiment.-- **Context window:** 500K tokens.+**Grok 4.1 Fast** (`grok-4.1-fast`) is the budget workhorse on paper ($0.20 / $0.50, 2M-token window), but check availability before you pin it: OpenRouter dropped it from its catalog, so it only runs when a first-party `GROK_API_KEY` is configured. `GET /api/brain/chat` reports it as unavailable otherwise.-**Grok 4.3** (`grok-4.3`) is the long-context option ($1.25 in / $2.50 out, 1M-token window). Reach for it when the agent carries very large system prompts or memory.+### Free lanes (no key, no bill)-**Grok 4.1 Fast** (`grok-4.1-fast`) is the budget workhorse ($0.20 in / $0.50 out, 2M-token window). Comparable to Haiku for short interactions and dramatically cheaper.+The embed default, `openai/gpt-oss-20b:free`, costs nothing and is tool-call capable. Signed-out callers are restricted to these free lanes on purpose, so an unauthenticated script can't drain the server's billed keys. Alongside GPT-OSS the platform carries free NVIDIA NIM models (Nemotron, DeepSeek, Kimi K2, Llama 4 Maverick, MiniMax M2), Groq's sub-second Llama lanes, SambaNova, Mistral's experiment tier, and Z.AI's GLM Flash. They are the fallback rungs the proxy walks when a paid lane errors, and they are perfectly serviceable as a primary brain for a low-stakes agent.### Picking a model@@ -89942,23 +90527,28 @@ A practical rule of thumb:| Use case | Recommended model ||---|---|-| Support / FAQ agent for a SaaS | Sonnet 4.6 or GPT-5.6 Terra |-| Personal-website-me agent | Sonnet 4.6 |-| Onboarding co-pilot, sales bot | Sonnet 4.6 |-| Museum tour guide, long-form domain agent | Sonnet 4.6, escalate to Opus only if needed |-| Legal, medical, financial assistant | Opus 4.7 or GPT-5.6 Sol |+| Kicking the tyres, low-stakes embed | `openai/gpt-oss-20b:free` (the default, no key, no bill) |+| Support / FAQ agent for a SaaS | Sonnet 5 or GPT-5.6 Terra |+| Personal-website-me agent | Sonnet 5 |+| Onboarding co-pilot, sales bot | Sonnet 5 |+| Museum tour guide, long-form domain agent | Sonnet 5, escalate to Opus 5 only if needed |+| Legal, medical, financial assistant | Opus 5 or GPT-5.6 Sol |+| Hardest reasoning, vision-heavy knowledge work | Fable 5 || Status-check, wave-and-greet, micro-interaction | Haiku 4.5 or GPT-5.6 Luna |-| Multi-step tool chains, code assistance | Opus 4.7 or GPT-5.6 Sol |+| Multi-step tool chains, code assistance | Opus 5 or GPT-5.6 Sol |+| Current events, social sentiment | Grok 4.5 |-Start at Sonnet 4.6 for almost everything. Move to Haiku if latency is the bottleneck. Move to Opus or GPT-5.6 Sol only when you have a specific quality issue that the smaller model can't fix with prompt iteration.+Start at Sonnet 5 for almost everything. Move to Haiku if latency is the bottleneck. Move to Opus 5, Fable 5, or GPT-5.6 Sol only when you have a specific quality issue that the smaller model can't fix with prompt iteration.----## Step 4 — Configure the system prompt+## Step 4: Configure the system promptThe system prompt and the model are configured separately. You can swap models without touching the prompt, and vice versa.-In **Brain → System prompt**, paste your full prompt. The same prompt works across all the models above, with one caveat: smaller models (Haiku, GPT-5.6 Luna) follow instructions less precisely, so prompts written for them benefit from being shorter and more explicit. A 600-word prompt that Sonnet handles cleanly may overflow Haiku's instruction-following budget.+The prompt lives on the agent's persona, which you build in the **Brain Studio** panel of the agent editor. It is an interview, not a text box: you direct a character with trait sliders and sample exchanges, and the studio extracts the system prompt from that. Read the extracted prompt back with `GET /api/agents/:id/persona`.++The same prompt works across all the models above, with one caveat: smaller models (Haiku, GPT-5.6 Luna) follow instructions less precisely, so prompts written for them benefit from being shorter and more explicit. A 600-word prompt that Sonnet handles cleanly may overflow Haiku's instruction-following budget.If you're targeting Haiku or GPT-5.6 Luna specifically, trim:@@ -89968,20 +90558,19 @@ If you're targeting Haiku or GPT-5.6 Luna specifically, trim:For Sonnet, Opus, GPT-5.6 Terra, and GPT-5.6 Sol, the full prompt template from the [agent personality](/tutorials/agent-personality) tutorial works without modification.-A few configuration knobs alongside the prompt:+**Sampling knobs are set on the client, not in a dashboard.** The runtime's provider takes them when it is constructed, and the `<agent-3d>` element passes them through from the agent manifest's `brain` block:-| Setting | What it does | Recommended |-|---|---|---|-| **Temperature** | 0-2 range, controls randomness | 0.7-0.9 for chat agents, 0.3-0.5 for FAQ |-| **Max tokens** | Hard cap on reply length | 512 for voice agents, 1024 for text-mode |-| **Top-p** | Nucleus sampling threshold | Leave at default unless you have a specific reason |-| **Stream** | Whether to stream tokens as they arrive | On — see Step 5 |+| Setting | Where it lives | Default | Notes |+|---|---|---|---|+| `temperature` | `manifest.brain.temperature` | `0.7` | 0.8 is a safe centre for a conversational agent. **Silently stripped for Opus 4.7+ and the whole Claude 5 family**, which reject sampling parameters upstream. |+| `maxTokens` | `manifest.brain.maxTokens` | `4096` | The proxy defaults a missing value to 4096, and floors thinking-by-default models at 4096 so the visible reply isn't squeezed out by thinking tokens. |+| `thinking` | `manifest.brain.thinking` | `'auto'` | `'always'` requests extended thinking. Coerced to the adaptive form on models that demand it. |-The temperature setting is the second-most impactful knob after the prompt itself. Too low and the agent becomes mechanical; too high and it goes off-script. 0.8 is a safe centre for any conversational agent.+There is no top-p knob and no streaming toggle: the client always requests `stream: true` (see Step 5). A long, stable system prompt gets a prompt-cache breakpoint added automatically once it clears the per-model length threshold, which bills repeat turns at roughly a tenth of the input price. You don't opt in.----## Step 5 — Streaming responses+## Step 5: Streaming responsesBy default the platform streams responses from the model as they generate. The browser receives tokens in `brain:stream` events and the full message arrives in `brain:message` once the model finishes.@@ -89991,7 +90580,7 @@ You can see this in action:const agent = document.querySelector('agent-3d');agent.addEventListener('brain:stream', (e) => {- // e.detail.chunk is a small string — usually 1-5 tokens+ // e.detail.chunk is a small string: usually 1-5 tokensconsole.log('chunk:', e.detail.chunk);});@@ -90002,55 +90591,71 @@ agent.addEventListener('brain:message', (e) => {});```-For a custom chat UI, build incremental rendering on `brain:stream` so the user sees text arriving instead of waiting for the whole reply. The built-in chat input already does this — assistant messages fill in word by word.+For a custom chat UI, build incremental rendering on `brain:stream` so the user sees text arriving instead of waiting for the whole reply. The built-in chat input already does this, assistant messages fill in word by word.-To turn streaming off (rarely useful, but available if you're piping the output somewhere that can only handle complete messages), set **Brain → Stream → off** in the agent settings. You'll get a single `brain:message` event with the whole reply and no `brain:stream` events.+There is no streaming off-switch: the runtime always requests `stream: true`. If you need whole messages only, ignore `brain:stream` and read `brain:message`, which fires once with the complete reply, the same end state, with no wiring change.Streaming impacts perceived latency *much* more than actual end-to-end latency. A reply that takes 2 seconds to fully generate feels nearly instant with streaming on; without streaming, the same 2-second wait feels like the agent is broken.----## Step 6 — Tool use per model+## Step 6: Tool use per model-Tool use (the model invoking a function you've defined — a `searchProducts(query)` skill, a `lookupOrder(id)` skill) is supported across all the models above, but the quality varies.+Tool use (the model invoking a function you've defined, a `searchProducts(query)` skill, a `lookupOrder(id)` skill) is supported across all the models above, but the quality varies.| Model | Tool use quality ||---|---|-| Claude Opus 4.7 | Excellent. Handles complex multi-tool chains and ambiguous tool selection cleanly. |-| Claude Sonnet 4.6 | Excellent. Indistinguishable from Opus for most tool flows. The default recommendation. |+| Claude Fable 5 | Excellent. The strongest option for long, ambiguous tool chains. |+| Claude Opus 5 | Excellent. Handles complex multi-tool chains and ambiguous tool selection cleanly. |+| Claude Sonnet 5 | Excellent. Indistinguishable from Opus for most tool flows. The default recommendation. || Claude Haiku 4.5 | Good for single-tool flows. Struggles with chains that require 3+ sequential tool calls. || GPT-5.6 Sol | Excellent, similar to Opus. Strong at parallel tool calls. || GPT-5.6 Terra | Very good. Slightly more prone to mis-formatting tool arguments than Sonnet. || GPT-5.6 Luna | Functional. Avoid for anything with 2+ tools or non-trivial schemas. |+| Grok 4.5 | Reliable. A fair substitute for Terra when you also want current-events knowledge. |+| Free lanes (GPT-OSS, NVIDIA NIM, Groq) | Tool-call capable, that is why they are the fallback rungs, but noticeably weaker at picking the right tool. Fine for one or two tools with simple schemas. |-If you're building a skill-heavy agent — one that needs to look up products, check inventory, search documentation, and place orders, all in one conversation — pick Sonnet or GPT-5.6 Terra at minimum. Haiku and Luna are acceptable for single-purpose lookups but get confused on chains.+If you're building a skill-heavy agent: one that needs to look up products, check inventory, search documentation, and place orders, all in one conversation, pick Sonnet 5 or GPT-5.6 Terra at minimum. Haiku and Luna are acceptable for single-purpose lookups but get confused on chains.++The runtime caps a single turn at 8 tool iterations, so a chain that can't resolve inside 8 round trips returns whatever it has rather than looping forever.See the [custom skill tutorial](/tutorials/custom-skill) for the full skill-writing workflow.----## Step 7 — Observability and cost+## Step 7: Observability and costEvery chat turn costs tokens. For agents handling real traffic, you need to know where your spend is going.-The dashboard at [three.ws/my-agents](https://three.ws/my-agents) → your agent → **Usage** tab shows:+**The per-agent read.** `GET /api/agents/:id/usage` (owner-only) returns that agent's brain usage:++```js+const usage = await (await fetch(`/api/agents/${agentId}/usage`, { credentials: 'include' })).json();+// → {+// agentId,+// monthlyQuota, // from the agent's embed policy; null = unlimited+// currentMonthCalls, // LLM calls this calendar month+// dailyBreakdown: [{ day, calls }] // last 30 days+// }+```++Note what this is and isn't: it counts **calls**, not tokens, and it is the same counter the proxy enforces `monthly_quota` against. It is the number to watch for "is this agent about to hit its cap", not for a dollar figure.-- **Total tokens** by day, separated into input and output-- **Estimated cost** at the rate of your selected model-- **Per-agent breakdown** if you have multiple agents-- **Top conversations** by token spend (useful for finding runaway prompt loops)+**The account read.** `GET /api/usage/summary` returns your account-level numbers (plan quotas, avatar count and bytes, MCP tool calls in the last 24h, total events in the last 30 days).++**Cost.** The platform prices every call server-side through `api/_lib/llm-pricing.js` and records it, so the spend cap in `checkUserLlmSpendCap` is enforced on real numbers. What there is *not* today is a self-serve token-and-dollar breakdown chart per conversation, nor threshold email alerts. Budget with `monthly_quota` and `rate_limit_per_min` on the embed policy (Step 8), those are hard, enforced-before-spend limits, which is a stronger control than an after-the-fact alert.Two specific things to watch:-**Input-token growth across a session.** Long conversations accumulate context — every turn includes the full conversation history as input to the next turn. By turn 50 of a chat, your input tokens per turn might be 20x what they were at turn 1. If you're seeing surprisingly large bills, this is usually the cause. The fix is either tighter session-end heuristics (clear memory after N minutes idle) or summarising older turns into a single context message.+**Input-token growth across a session.** Long conversations accumulate context, every turn includes the full conversation history as input to the next turn. By turn 50 of a chat, your input tokens per turn might be 20x what they were at turn 1. If you're seeing surprisingly large bills, this is usually the cause. The fix is either tighter session-end heuristics (clear memory after N minutes idle) or summarising older turns into a single context message.**Tool-call expansion.** A tool that returns 5000 tokens of JSON balloons the next-turn input. If you have a skill that returns large data, summarise the response before it goes back to the model rather than passing the raw payload through.-For agents handling 1000+ chats per day, you can set up **usage alerts** under **Account → Billing → Alerts**. Pick a threshold (a daily spend or a token count); the platform emails you when you cross it.+For agents handling real volume, set `monthly_quota` deliberately rather than leaving the 1000-call default: once an agent crosses it the proxy stops serving paid lanes for the rest of the month, which is a blunt but effective ceiling. Pair it with a tight `origins` allowlist so nobody else's site can spend your quota in the first place.----## Step 8 — Switch models without changing your embed+## Step 8: Switch models without changing your embedThis is the part that often surprises people: the embed snippet on your website doesn't know which model is running. Everything is on the agent record.@@ -90061,26 +90666,57 @@ If you have:<agent-3d agent-id="YOUR_AGENT_ID" id="agent"></agent-3d>```-…on a thousand pages, you can switch the brain from Sonnet to Opus to GPT-5.6 Sol entirely from the dashboard. No deploy. No code edit. The next page load picks up the new model.+…on a thousand pages, you can switch the brain from Sonnet 5 to Opus 5 to GPT-5.6 Sol by changing one field. No deploy. No code edit. The next page load picks up the new model.++That field is `brain.model` on the agent's **embed policy**, read and written at `GET`/`PUT /api/agents/:id/embed-policy`. The `PUT` takes the whole policy document, so read it first, change the one field, and write it back:++```js+const { policy } = await (await fetch(`/api/agents/${agentId}/embed-policy`, {+ credentials: 'include',+})).json();++await fetch(`/api/agents/${agentId}/embed-policy`, {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ credentials: 'include', // the dashboard's own helper attaches the CSRF token+ body: JSON.stringify({+ ...policy,+ brain: { ...policy.brain, model: 'claude-sonnet-5' },+ }),+});+```++The whole `brain` block is what you tune here:++| Field | Default | What it does |+|---|---|---|+| `mode` | `'we-pay'` | `we-pay` uses the platform's credential. `key-proxy` calls your endpoint for a key (Step 9) and requires `proxy_url`. `wallet-gated` and `none` close the lane. |+| `model` | `'openai/gpt-oss-20b:free'` | The model the agent actually runs, and the ceiling a visitor is clamped to. |+| `monthly_quota` | `1000` | LLM calls per calendar month before the lane closes. `null` = unlimited. |+| `rate_limit_per_min` | `10` | Per-minute request cap. |++The `origins` block on the same document is the other half of cost control: with `mode: 'allowlist'` and your own hosts, a request from anywhere else is rejected *before* your model budget is touched. The [/dashboard/api](https://three.ws/dashboard/api) page has an editor for that allowlist.This makes A/B testing painless. Common patterns:-- **Cost optimisation pass.** Move a low-stakes agent from Sonnet to Haiku, watch the quality and spend for a week, decide whether to keep the change.-- **Capability spike.** Promote an agent to Opus for a busy week (a launch, a marketing campaign), then dial back down to Sonnet for steady-state.-- **Provider failover.** If Anthropic has a brief outage, you can switch the agent to GPT-5.6 Terra in the dashboard and keep traffic moving while you wait. Both keys are stored, both providers are reachable from the same agent record.+- **Cost optimisation pass.** Move a low-stakes agent from Sonnet 5 to Haiku, watch the quality and spend for a week, decide whether to keep the change.+- **Capability spike.** Promote an agent to Opus 5 for a busy week (a launch, a marketing campaign), then dial back down to Sonnet 5 for steady-state.+- **Provider failover.** If one vendor has a brief outage, switch `brain.model` to a peer on another provider and keep traffic moving. You don't have to do this for transient errors, though: the proxy already walks a free-lane fallback chain on a quota/billing/rate-limit failure mid-request.-The trick to making this work cleanly is to write your system prompt in a model-agnostic style. Prompts that lean hard on Claude-specific quirks ("respond in XML tags") can produce slightly different output on GPT. The prompt template in the [agent personality](/tutorials/agent-personality) tutorial is intentionally portable across providers — use that style and your switch-day surprises are minimal.+The trick to making this work cleanly is to write your system prompt in a model-agnostic style. Prompts that lean hard on Claude-specific quirks ("respond in XML tags") can produce slightly different output on GPT. The prompt template in the [agent personality](/tutorials/agent-personality) tutorial is intentionally portable across providers, use that style and your switch-day surprises are minimal.----## Step 9 — Self-hosted keys via key-proxy (advanced)+## Step 9: Self-hosted keys via key-proxy (advanced)The standard path is to store your key in the platform dashboard. If you have a stricter security posture and want to keep the key on infrastructure you control entirely, the platform supports a **key proxy** pattern: you run a tiny endpoint that vends short-lived, scoped tokens, and the platform calls your endpoint instead of holding the long-lived key.The flow:1. You run an endpoint at, say, `https://your-domain.com/api/llm-key`. It returns a JSON response with a short-lived API key (or a session token usable as one), valid for some window you control.-2. You set the `key-proxy` attribute on your `<agent-3d>` element or in the agent's dashboard settings:+2. You point the agent at it. Two places, and they do different things:+ - The **`key-proxy` attribute** on `<agent-3d>` replaces the platform proxy entirely: the runtime sends its Anthropic-shape request straight to your URL instead of `/api/llm/anthropic`. Your endpoint is then responsible for the upstream call and for streaming Anthropic-shape SSE back.+ - **`brain.mode: 'key-proxy'`** with a `proxy_url` on the embed policy declares the same intent server-side, which is what closes the platform's own we-pay lane. The policy schema rejects `key-proxy` mode without a `proxy_url`, so the two can't drift apart.```html<agent-3d@@ -90089,9 +90725,9 @@ The flow:></agent-3d>```-3. When the platform needs to make an LLM call for this agent, it calls your endpoint first to get a fresh key, then uses that key for the LLM request.+3. Every LLM call for this agent goes through your endpoint, so the long-lived key never leaves your infrastructure.-This is genuinely advanced — most teams don't need it. The reasons to reach for it:+This is genuinely advanced: most teams don't need it. The reasons to reach for it:- Compliance requirements that prohibit storing third-party API keys outside your infrastructure- Multi-tenant SaaS where each customer brings their own key and you don't want to pool them into a single account@@ -90101,19 +90737,19 @@ For everything else, the dashboard key store is the right answer.----## Step 10 — A concrete switch: walk through+## Step 10: A concrete switch: walk through-To make this concrete, here's the actual sequence for moving a production agent from the managed free tier to your own Anthropic key, then upgrading the model from Sonnet to Opus.+To make this concrete, here's the actual sequence for moving a production agent off the free lane and onto Claude, then upgrading it.1. **Get your key.** [console.anthropic.com](https://console.anthropic.com) → API Keys → Create Key. Label it "three.ws production".-2. **Add to platform.** [three.ws/my-agents](https://three.ws/my-agents) → gear icon → API Keys → Anthropic → paste, save.-3. **Switch the agent's brain provider.** Open your agent. **Brain → Provider → Anthropic.** Verify the dropdown for **Use my key** is selected, not **Use managed credit**.-4. **Test.** Open any page that embeds the agent. Send a message. Check the Usage tab — input/output tokens should be incrementing against your key, not the managed credit.-5. **Upgrade the model.** **Brain → Model → Claude Opus 4.7.** Save.-6. **Test again.** Notice the reply time is slightly slower (~1.5s first token vs ~600ms) and the responses are noticeably more thoughtful on hard questions.-7. **Set a budget alert.** Account → Billing → Alerts → $20 / day. You'll get an email if Opus pushes your spend up faster than expected.+2. **Add it to the platform.** [/dashboard/account](https://three.ws/dashboard/account) → **AI Provider Keys** → **Anthropic (Claude)** → paste, save.+3. **Compare before you commit.** Open [/dashboard/brain](https://three.ws/dashboard/brain), select Sonnet 5 and one alternative, and run the same prompt through both in the playground.+4. **Pin the model.** `PUT /api/agents/:id/embed-policy` with `brain.model` set to `claude-sonnet-5` (the read-modify-write in Step 8). While you're there, set `monthly_quota` and lock `origins` to your own hosts.+5. **Test.** Open any page that embeds the agent and send a message. `GET /api/agents/:id/usage` should show `currentMonthCalls` incrementing.+6. **Upgrade if needed.** Repeat step 4 with `claude-opus-5`. Expect slower first tokens (it thinks by default) and better answers on hard questions. Fable 5 is the rung above that.+7. **Confirm the ceiling.** Re-read the policy and check `monthly_quota` and `rate_limit_per_min` are the numbers you meant. These are enforced before spend, so they are your real budget control.-Total time: under five minutes. The agent IDs in your existing embeds don't change. Visitors notice the smarter replies but the front-end is identical.+Total time: under ten minutes. The agent IDs in your existing embeds don't change. Visitors notice the smarter replies but the front-end is identical.---@@ -90121,22 +90757,23 @@ Total time: under five minutes. The agent IDs in your existing embeds don't chanThe brain layer in full:-- LLM calls happen server-side; your key never leaves the platform's backend-- Keys are stored per-account in My Agents; one key serves all your agents from that provider-- Sonnet 4.6 is the default; Opus 4.7 and GPT-5.6 Sol are the reasoning-grade upgrades; Haiku and GPT-5.6 Luna are the latency picks-- Streaming is on by default and matters more than total latency for perceived speed-- Tool-use quality varies by model — pick Sonnet or larger for skill-heavy agents-- Usage and cost are visible in the dashboard, with alerts available for spend caps-- Switching models is a dashboard toggle; the embed snippet never needs to change+- LLM calls happen server-side through `/api/llm/anthropic`; your key never leaves the backend+- Keys are stored per-account at [/dashboard/account](https://three.ws/dashboard/account) → AI Provider Keys; one key serves all your agents from that provider+- The embed default is a free open-weight lane. Sonnet 5 is the recommended paid default; Opus 5 and GPT-5.6 Sol are the reasoning-grade upgrades, Fable 5 the ceiling; Haiku 4.5 and GPT-5.6 Luna are the latency picks+- Streaming is always on and matters more than total latency for perceived speed+- A visitor can never escalate you onto a paid model: the proxy clamps any first-party-billed model back to the owner's configured one+- Tool-use quality varies by model: pick Sonnet 5 or larger for skill-heavy agents+- `monthly_quota` and `rate_limit_per_min` on the embed policy are the real budget controls, enforced before spend; `GET /api/agents/:id/usage` is the counter to watch+- Switching models is one field on the embed policy; the embed snippet never needs to change- Key proxies are an advanced option for compliance-heavy setups-The brain is the part of the agent you'll iterate on most after the system prompt. Pick a sensible default (Sonnet 4.6), ship, and only upgrade once you've identified a specific quality gap that prompt iteration can't close.+The brain is the part of the agent you'll iterate on most after the system prompt. Pick a sensible default (Sonnet 5), ship, and only upgrade once you've identified a specific quality gap that prompt iteration can't close.## Next steps-- [Give your agent a personality](/tutorials/agent-personality) — write a system prompt that holds across thousands of chats-- [Add a custom skill](/tutorials/custom-skill) — give the brain tools to use-- [Trigger the agent from page events](/tutorials/trigger-from-page-events) — wire the brain into your product flow+- [Give your agent a personality](/tutorials/agent-personality), write a system prompt that holds across thousands of chats+- [Add a custom skill](/tutorials/custom-skill): give the brain tools to use+- [Trigger the agent from page events](/tutorials/trigger-from-page-events), wire the brain into your product flow---@@ -90467,7 +91104,7 @@ The leverage is in *enhancement*: the right type, one fact per memory, tags, del# Build a Custom Skill-By the end of this tutorial you will have a working **weather skill** that an agent can use to answer questions like "What's the weather in Tokyo?" — with the agent calling a live API and responding naturally in conversation.+By the end of this tutorial you will have a working **weather skill** that an agent can use to answer questions like "What's the weather in Tokyo?", with the agent calling a live API and responding naturally in conversation.Along the way you'll understand the skill bundle format, how the LLM decides when to invoke your tool, and how to reach back into the agent through the context API.@@ -90484,13 +91121,13 @@ Agent: "Tokyo is currently 18°C with overcast skies and light rain.Might want to pack an umbrella!"```-The agent doesn't hardcode weather logic. It reads your skill's tool description, decides when the user is asking about weather, and calls `get_weather` — your handler fetches live data and returns structured results that the agent narrates naturally.+The agent doesn't hardcode weather logic. It reads your skill's tool description, decides when the user is asking about weather, and calls `get_weather`, your handler fetches live data and returns structured results that the agent narrates naturally.---## How skills work (two minutes of theory)-A skill is a static file bundle — no server, no build step. It has four parts:+A skill is a static file bundle: no server, no build step. It has four parts:| File | Purpose ||---|---|@@ -90504,7 +91141,7 @@ When the runtime loads your skill it:1. Fetches and validates `manifest.json`2. Merges your tools from `tools.json` into the LLM's tool list3. Injects `SKILL.md` into the system prompt as a `<skill>` block-4. Runs `handlers.js` in a **sandboxed Web Worker** — it has no DOM access, no `window`, no direct network; everything goes through the `ctx` API+4. Runs `handlers.js` in a **sandboxed Web Worker**, it has no DOM access, no `window`, no direct network; everything goes through the `ctx` APIThe sandbox is the key safety primitive. Your handler can't accidentally read cookies or touch page state. All side effects go through `ctx.*` methods that the runtime validates and dispatches.@@ -90526,7 +91163,7 @@ Create the folder and four empty files. Everything below fills them in.## Step 2: Write manifest.json-The manifest declares your skill's identity, what rig types it works with, and what tools it provides. It does **not** embed tool schemas — those live in `tools.json`.+The manifest declares your skill's identity, what rig types it works with, and what tools it provides. It does **not** embed tool schemas, those live in `tools.json`.```json{@@ -90550,11 +91187,11 @@ The manifest declares your skill's identity, what rig types it works with, and wKey fields:-- **`spec`** — always `"skill/0.1"` for the current format-- **`provides.tools`** — names that must exactly match function exports in `handlers.js` and entries in `tools.json`-- **`provides.triggers`** — semantic tags for skill discovery; the runtime can surface your skill when a user query matches these-- **`requires.rig`** — which avatar rigs this skill supports; `"any"` works everywhere; use `"mixamo"` if your skill plays Mixamo-specific animation clips-- **`author`** — optional, but used for the `owned-only` trust policy (see the security section)+- **`spec`**: always `"skill/0.1"` for the current format+- **`provides.tools`**: names that must exactly match function exports in `handlers.js` and entries in `tools.json`+- **`provides.triggers`**: semantic tags for skill discovery; the runtime can surface your skill when a user query matches these+- **`requires.rig`**: which avatar rigs this skill supports; `"any"` works everywhere; use `"mixamo"` if your skill plays Mixamo-specific animation clips+- **`author`**: optional, but used for the `owned-only` trust policy (see the security section)---@@ -90582,7 +91219,7 @@ Use `get_weather` whenever the user asks about:- Whether to bring an umbrella, coat, or sunscreen- What the weather is like anywhere in the world-When you receive weather data, respond conversationally — don't just repeat+When you receive weather data, respond conversationally, don't just repeatthe raw fields. Mention conditions, temperature, and any useful context(e.g. "perfect for a walk" or "might want to stay indoors").@@ -90591,7 +91228,7 @@ If the user doesn't specify units, use celsius by default.The frontmatter `cost: low` tells the runtime this is a cheap skill to load eagerly. For skills that load heavy assets, use `medium` or `high` to defer loading.-The markdown body is your behavioral contract with the LLM. Write it like you'd write a Claude system prompt — clear, specific about when to invoke the tool, and with guidance on how to present the results.+The markdown body is your behavioral contract with the LLM. Write it like you'd write a Claude system prompt, clear, specific about when to invoke the tool, and with guidance on how to present the results.---@@ -90628,8 +91265,8 @@ This is what the LLM actually sees as a callable function. The format follows thThe `description` field is doing real work here. The LLM reads it to decide **when** to call `get_weather`. Compare:-- **Too vague:** `"Get weather"` — the agent might not connect this to "should I bring a jacket?"-- **Right:** `"Get current weather conditions and temperature for a specific city. Use this when the user asks about weather, temperature, climate, or what to wear."` — the agent knows both the capability and the intent signals+- **Too vague:** `"Get weather"`: the agent might not connect this to "should I bring a jacket?"+- **Right:** `"Get current weather conditions and temperature for a specific city. Use this when the user asks about weather, temperature, climate, or what to wear."`, the agent knows both the capability and the intent signalsEvery hour you spend writing a good tool description pays back in fewer missed invocations.@@ -90647,9 +91284,14 @@ const WEATHER_API_BASE = 'https://wttr.in';export async function get_weather({ city, units = 'celsius' }, ctx) {try {// wttr.in is a free weather API, no key needed.- // Format string: condition + temperature + wind + precipitation- const fmt = units === 'celsius' ? '%C+%t+%w+%p' : '%C+%f+%w+%p';- const url = `${WEATHER_API_BASE}/${encodeURIComponent(city)}?format=${encodeURIComponent(fmt)}&lang=en`;+ // Format string: condition | temperature | wind | precipitation.+ // Pipe, not '+', because %t renders a signed value ("+27°C") and a+ // '+' delimiter would split that sign into its own empty field.+ // Units come from the `m` (metric) / `u` (USCS) flag, not the format+ // string: %f is "feels like", not Fahrenheit.+ const fmt = '%C|%t|%w|%p';+ const unitFlag = units === 'celsius' ? 'm' : 'u';+ const url = `${WEATHER_API_BASE}/${encodeURIComponent(city)}?format=${encodeURIComponent(fmt)}&lang=en&${unitFlag}`;const res = await ctx.fetch(url);if (!res.ok) {@@ -90657,7 +91299,7 @@ export async function get_weather({ city, units = 'celsius' }, ctx) {}const text = (await res.text()).trim();- const [condition, temp, wind, precipitation] = text.split('+');+ const [condition, temp, wind, precipitation] = text.split('|');return {ok: true,@@ -90676,19 +91318,19 @@ export async function get_weather({ city, units = 'celsius' }, ctx) {Walk through what's happening:-**`({ city, units = 'celsius' }, ctx)`** — the first argument is the validated parameters object the LLM passed; the second is the context object. Always destructure with defaults for optional params.+**`({ city, units = 'celsius' }, ctx)`**: the first argument is the validated parameters object the LLM passed; the second is the context object. Always destructure with defaults for optional params.-**`ctx.fetch(url)`** — this is the only way to make network calls from a handler. It's the worker's native `fetch` with standard CORS rules applied. You can't reach `window.fetch` directly (the handler runs in a Worker with no `window`).+**`ctx.fetch(url)`**: this is the only way to make network calls from a handler. It's the worker's native `fetch` with standard CORS rules applied. You can't reach `window.fetch` directly (the handler runs in a Worker with no `window`).-**`{ ok: true, ...data }` / `{ ok: false, error: "..." }`** — the runtime expects this shape. On `ok: false`, the runtime surfaces the error cleanly in the LLM conversation without crashing.+**`{ ok: true, ...data }` / `{ ok: false, error: "..." }`**, the runtime expects this shape. On `ok: false`, the runtime surfaces the error cleanly in the LLM conversation without crashing.-**No imports** — because the handler runs inside a sandboxed Web Worker loaded from a `blob:` URL, there's no module resolution context. You can't `import` external packages. Everything you need must come from `ctx.*` or be self-contained in the file.+**No imports**: because the handler runs inside a sandboxed Web Worker loaded from a `blob:` URL, there's no module resolution context. You can't `import` external packages. Everything you need must come from `ctx.*` or be self-contained in the file.---## Step 6: Host the skill-Skills must be accessible over HTTPS. They're static files — any static host works.+Skills must be accessible over HTTPS. They're static files, any static host works.**GitHub Pages (free, permanent URL):**```bash@@ -90706,7 +91348,7 @@ git push -u origin main```bashcd weather-skillnpx vercel-# Follow the prompts — done in about 30 seconds+# Follow the prompts: done in about 30 seconds# Your manifest URL: https://weather-skill-abc123.vercel.app/manifest.json```@@ -90717,12 +91359,12 @@ npx serve .# Terminal 2: expose itnpx ngrok http 3000-# Copy the https://... URL — use it as your manifest URL+# Copy the https://... URL: use it as your manifest URL```One thing to check after deploying: open the manifest URL directly in your browser. You should see raw JSON. If you see an error page or HTML, something's wrong with the hosting setup before you go further.-Also verify that your host is sending CORS headers (`Access-Control-Allow-Origin: *`). GitHub Pages and Vercel do this by default. If you're using a custom server, add the header — the runtime's `fetch` calls will fail silently otherwise.+Also verify that your host is sending CORS headers (`Access-Control-Allow-Origin: *`). GitHub Pages and Vercel do this by default. If you're using a custom server, add the header, the runtime's `fetch` calls will fail silently otherwise.---@@ -90745,7 +91387,7 @@ There are three ways, depending on how you're working.}```-The `uri` points to the **directory**, not the manifest file. The runtime appends `manifest.json`, `SKILL.md`, `tools.json`, and `handlers.js` automatically. Make sure the URI ends with a trailing slash — the runtime uses it as a base for relative asset resolution.+The `uri` points to the **directory**, not the manifest file. The runtime appends `manifest.json`, `SKILL.md`, `tools.json`, and `handlers.js` automatically. Make sure the URI ends with a trailing slash, the runtime uses it as a base for relative asset resolution.**In the web component attribute** (comma-separated skill URIs, installed on top of any manifest skills):@@ -90772,19 +91414,19 @@ With the agent running, type: **"What's the weather in Tokyo?"**Watch what happens in DevTools → Network: you should see a fetch to `wttr.in` originating from the worker. The agent will receive the structured data back, and respond with something like:-> "Tokyo is currently 18°C with overcast skies and wind at 15 km/h. Looks a bit grey today — maybe a good day for an indoor museum."+> "Tokyo is currently 18°C with overcast skies and wind at 15 km/h. Looks a bit grey today, maybe a good day for an indoor museum."If it doesn't invoke the tool:- **Check the console** for skill load errors. A 404 on any of the four files silently skips the tool registration.- **Verify the manifest URL** returns valid JSON when opened directly in a browser.-- **Check CORS** — if the browser blocks the `manifest.json` fetch, the skill won't load.-- **Check handler function name** — `get_weather` in `handlers.js` must match `"get_weather"` in `tools.json` and `provides.tools` in `manifest.json`. One character off and the tool silently fails.+- **Check CORS**: if the browser blocks the `manifest.json` fetch, the skill won't load.+- **Check handler function name**: `get_weather` in `handlers.js` must match `"get_weather"` in `tools.json` and `provides.tools` in `manifest.json`. One character off and the tool silently fails.If the tool calls but returns an error:- The wttr.in API is free and generally reliable, but city names need to be recognizable. Try a major city like `London` first.-- Check that the worker can reach `wttr.in` — some corporate networks block unusual hostnames.+- Check that the worker can reach `wttr.in`: some corporate networks block unusual hostnames.---@@ -90794,8 +91436,8 @@ Once you've confirmed the happy path, sharpen the tool description to handle edgThe LLM currently calls `get_weather` when it sees words like "weather" or "temperature." But what about:-- "Should I pack a coat for my trip to Oslo next week?" — intent is weather, but the word isn't there-- "Is it a good beach day in Sydney?" — the user wants weather but asked about activities+- "Should I pack a coat for my trip to Oslo next week?", intent is weather, but the word isn't there+- "Is it a good beach day in Sydney?": the user wants weather but asked about activitiesUpdate `tools.json`:@@ -90833,9 +91475,9 @@ Add to `tools.json`:"days": {"type": "integer","minimum": 1,- "maximum": 7,+ "maximum": 3,"default": 3,- "description": "Number of forecast days"+ "description": "Number of forecast days (wttr.in returns at most 3)"}},"required": ["city"]@@ -90872,7 +91514,7 @@ export async function get_forecast({ city, days = 3 }, ctx) {}```-One skill, two tools. The LLM picks `get_weather` for "what's the weather now" and `get_forecast` for "what will the weather be like this week" — because the descriptions tell it to.+One skill, two tools. The LLM picks `get_weather` for "what's the weather now" and `get_forecast` for "what will the weather be like this week", because the descriptions tell it to.---@@ -90905,27 +91547,27 @@ export async function get_weather({ city, units = 'celsius' }, ctx) {The full context surface:```-ctx.fetch(url) — safe network call (CORS applies)-ctx.memory.read(key) — read a stored value-ctx.memory.write(key, val) — write a value-ctx.memory.note(type, data) — append to a timeline (good for history)-ctx.memory.recall(query) — substring search over notes-ctx.speak(text) — make the agent say something mid-tool-ctx.listen() — wait for user voice/text input-ctx.call(toolName, args) — invoke another tool (cross-skill calls)-ctx.loadGLB(uri) — load a 3D model-ctx.loadClip(uri) — load an animation clip-ctx.loadJSON(uri) — load a JSON file from a URL-ctx.viewer.play(clip) — play a loaded clip on the avatar-ctx.viewer.setExpression(p) — set facial expression preset-ctx.viewer.lookAt(target) — direct the avatar's gaze-ctx.llm.complete(prompt) — call the LLM directly (advanced)-ctx.skillBaseURI — base URL of this skill bundle+ctx.fetch(url) : safe network call (CORS applies)+ctx.memory.read(key) : read a stored value+ctx.memory.write(key, val) : write a value+ctx.memory.note(type, data): append to a timeline (good for history)+ctx.memory.recall(query) : substring search over notes+ctx.speak(text) : make the agent say something mid-tool+ctx.listen() : wait for user voice/text input+ctx.call(toolName, args) : invoke another tool (cross-skill calls)+ctx.loadGLB(uri) : load a 3D model+ctx.loadClip(uri) : load an animation clip+ctx.loadJSON(uri) : load a JSON file from a URL+ctx.viewer.play(clip) : play a loaded clip on the avatar+ctx.viewer.setExpression(p): set facial expression preset+ctx.viewer.lookAt(target) : direct the avatar's gaze+ctx.llm.complete(prompt) : call the LLM directly (advanced)+ctx.skillBaseURI : base URL of this skill bundle```-`ctx.memory.note` is useful for building history without explicit keys — it appends to an internal timeline that you can later query with `ctx.memory.recall('weather')`. Good for tracking what the user has asked about across a session.+`ctx.memory.note` is useful for building history without explicit keys, it appends to an internal timeline that you can later query with `ctx.memory.recall('weather')`. Good for tracking what the user has asked about across a session.-`ctx.speak` runs mid-handler, before you return. Use it to give the user feedback when a fetch might take a moment. Don't overdo it — a quick `"Let me check..."` is good; narrating every internal step is annoying.+`ctx.speak` runs mid-handler, before you return. Use it to give the user feedback when a fetch might take a moment. Don't overdo it, a quick `"Let me check..."` is good; narrating every internal step is annoying.---@@ -90939,7 +91581,7 @@ Understanding the sandbox helps you write handlers that work with it rather than**No imports.** Because handlers load from a `blob:` URL with no base URL context, relative `import` statements silently fail. All logic must be self-contained in `handlers.js`. If you need utilities, inline them.-**`trusted-main-thread` opt-out.** Owner-signed skills that need direct Three.js access can set `"sandboxPolicy": "trusted-main-thread"` in `manifest.json`. This runs the handler in the main thread. Only meaningful for skills that pass the agent's trust policy — default is `owned-only`, which requires `manifest.json`'s `author` to match the agent owner's wallet address.+**`trusted-main-thread` opt-out.** Owner-signed skills that need direct Three.js access can set `"sandboxPolicy": "trusted-main-thread"` in `manifest.json`. This runs the handler in the main thread. Only meaningful for skills that pass the agent's trust policy, default is `owned-only`, which requires `manifest.json`'s `author` to match the agent owner's wallet address.For the weather skill and most API-integration skills, the default sandbox is all you need.@@ -90951,11 +91593,11 @@ Your weather skill is a template for any external API integration. The pattern iGood skills to build next:-- **Financial data** — token prices, portfolio values, DCA calculations-- **GitHub integration** — open PRs, recent commits, issue status-- **Spotify** — currently playing, queue management-- **Notion / Linear** — read and write tickets or docs-- **Domain knowledge** — a skill that's pure `SKILL.md` with no tools, injecting specialized context (legal, medical, culinary)+- **Financial data**: token prices, portfolio values, DCA calculations+- **GitHub integration**: open PRs, recent commits, issue status+- **Spotify**: currently playing, queue management+- **Notion / Linear**: read and write tickets or docs+- **Domain knowledge**: a skill that's pure `SKILL.md` with no tools, injecting specialized context (legal, medical, culinary)Sharing your skill is as simple as posting the manifest URL. Add the topic `3dagent-skill` to your GitHub repo so others can find it, and browse what the community has built on the [Skills Marketplace](/skills).@@ -90965,10 +91607,10 @@ Sharing your skill is as simple as posting the manifest URL. Add the topic `3dagYou built a weather skill with these four files:-- **`manifest.json`** — declares identity, rig compatibility, and what tools the skill provides-- **`SKILL.md`** — the behavioral contract injected into the LLM's system prompt; tells the agent *when* and *how* to use the tool-- **`tools.json`** — the tool schema the LLM invokes; `input_schema` in Anthropic format; the `description` is prompt-engineered-- **`handlers.js`** — exports one function per tool; runs sandboxed in a Web Worker; all I/O through `ctx.*`+- **`manifest.json`**: declares identity, rig compatibility, and what tools the skill provides+- **`SKILL.md`**: the behavioral contract injected into the LLM's system prompt; tells the agent *when* and *how* to use the tool+- **`tools.json`**: the tool schema the LLM invokes; `input_schema` in Anthropic format; the `description` is prompt-engineered+- **`handlers.js`**: exports one function per tool; runs sandboxed in a Web Worker; all I/O through `ctx.*`The skill installs via a URI in the agent manifest, runs entirely client-side, and adds new capabilities to any compatible agent without modifying the agent itself. That's the composability primitive: agents are extensible at runtime through content-addressed skill bundles.@@ -91484,11 +92126,13 @@ The repo ships a `vercel.json`. Read it once so you know what's working for you.{"buildCommand": "npm run build:vercel","outputDirectory": "dist",- "public": true,- "installCommand": "npm ci --prefer-offline --no-audit --no-fund",+ "installCommand": "PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 PUPPETEER_SKIP_DOWNLOAD=1 npm ci --no-audit --no-fund","env": { "NODE_OPTIONS": "--no-deprecation" },"functions": {- "api/**/*.js": { "includeFiles": "node_modules/@zauthx402/sdk/dist/**" }+ "api/**/*.js": {+ "includeFiles": "{data/pages.json,sdk/src/sas-config.json}",+ "maxDuration": 30+ }},"routes": [{ "src": "/openapi\\.json", "dest": "/api/openapi-json" },@@ -91498,10 +92142,11 @@ The repo ships a `vercel.json`. Read it once so you know what's working for you.}```-Three things worth understanding:+Four things worth understanding:- **`buildCommand: npm run build:vercel`** runs the production build, including the prebuild step that generates the page index. The local `npm run dev` uses Vite directly; `build:vercel` is the optimized path that ships.- **`outputDirectory: dist`** is what Vercel serves as static files. After `npm run build`, `dist/` contains `index.html`, hashed JS bundles, the `cdn/` folder, sub-apps under `dist/chat/`, etc.+- **`functions`** sets per-route bundling and timeouts. The `api/**/*.js` entry above is the catch-all fallback; the real file layers dozens of more specific globs before it, giving slow routes (forge, streams, crons) a longer `maxDuration` and pulling in the data files each one reads. Add your own entry above the catch-all when a route needs more than 30 seconds.- **`routes`** rewrites specific paths to specific function files. The well-known routes (`/.well-known/x402.json` → `/api/wk?name=x402-discovery`) are how the platform exposes machine-readable discovery surfaces at the URLs the spec mandates.You shouldn't need to edit `vercel.json` for the basic deploy. The repo's defaults are tuned for the platform's actual route set.@@ -91904,7 +92549,7 @@ In rough order of likelihood:**The build breaks because Node version drifts.** Confirm `engines.node` in `package.json` matches what Vercel installs. The repo pins to `24.x`; Vercel respects this. If it ever stops, set `NODE_VERSION=24` in your project's env vars (build-time scope).-**A migration runs out of order.** Your `migrations/` directory is the source of truth — if two engineers add migrations on parallel branches, the lexically-earlier one applies first regardless of merge order. The fix: timestamp filenames (`20260514120000_add_x.sql`), don't number them (`002_add_x.sql`).+**A migration runs out of order.** Your `api/_lib/migrations/` directory is the source of truth: if two engineers add migrations on parallel branches, the lexically-earlier one applies first regardless of merge order. The fix: timestamp filenames (`20260514120000_add_x.sql`), don't number them (`002_add_x.sql`).**The CDN bundle gets stale at edges.** Vercel's edge respects `Cache-Control` headers. Make sure your build emits hashed filenames (`agent-3d.<hash>.js`) and your script tag references the canonical URL that always rewrites to the latest hash. The repo handles this; if you customize the build pipeline, don't break the hashing.@@ -92173,10 +92818,10 @@ Open [https://three.ws/create](https://three.ws/create) in a new tab. The editorIf you want to ship something working as fast as possible, skip every panel for now and click **Save** in the top-right of the editor. The platform creates an agent with the default body, the default personality, and a default greeting. Once saved, the URL in your browser's address bar becomes something like:```-https://three.ws/agent/0xabc123…def+https://three.ws/agent/d94d2a50-86fa-4d2e-b87b-580f7517aa4c```-The string after `/agent/` is your agent ID. Copy it. You will paste it into the `<agent-3d>` tag in the next step.+The string after `/agent/` is your agent ID: a UUID, assigned once and never reissued. Copy it. You will paste it into the `<agent-3d>` tag in the next step.### Path B — Customise first, then save@@ -92262,7 +92907,7 @@ When the browser hits these lines:5. Once the avatar is loaded, the element dispatches a `agent:ready` event you can listen to. The agent then begins its idle animation and waits for interaction.Notice what is *not* on this list:-- No iframe. The agent renders directly in your page's DOM, which means it inherits your site's CSS scope intentionally (we'll cover styling shadows in the customisation tutorial).+- No iframe. `<agent-3d>` is a real element in your page's DOM, so it participates in your layout like any other block. Its internals live in an open shadow root, so your site's stylesheet cannot accidentally break the chat chrome, and the chrome cannot leak styles back into your page. You still theme it deliberately, through inherited CSS custom properties and `::part()` selectors: the customisation tutorial covers both.- No second script tag. You don't need to load Three.js separately. You don't need to bundle anything.- No build step. The script is plain JavaScript, served minified from a CDN edge.@@ -92306,7 +92951,7 @@ Open developer tools (F12 or right-click → Inspect → Console). You should seIn the Network tab, filter by `three.ws`. You should see:-- `agent-3d.js` (the bundle, around 1–2 MB gzipped)+- `agent-3d.js` (the bundle, under 1 MB gzipped)- A request to the agents API with your agent ID- A request for the avatar GLB- A few smaller assets (animations, textures)@@ -92933,27 +93578,27 @@ Squarespace's developer preview and published output can differ. Try adding the# Animations from data: wire your agent's gestures to real APIs and AI-An agent that just idles is furniture. An agent that visibly *reacts* — dances when something spikes, flinches when something drops, celebrates a milestone — reads as alive. three.ws ships a full animation library (idle, wave, dance, celebrate, jump, dozens more — browse them at [/animations](/animations)) and a public JS API to trigger any of it on command. This tutorial shows you how to point that at data you actually have: a live feed, a webhook, or a real AI model classifying arbitrary text.+An agent that just idles is furniture. An agent that visibly *reacts*, dances when something spikes, flinches when something drops, celebrates a milestone, reads as alive. three.ws ships a full animation library (idle, wave, dance, celebrate, jump, dozens more, browse them at [/animations](/animations)) and a public JS API to trigger any of it on command. This tutorial shows you how to point that at data you actually have: a live feed, a webhook, or a real AI model classifying arbitrary text.-You'll build two working pipelines — one with zero AI (a lexicon sentiment score, free, no key, triggering a real body animation), one with a real model in the loop (IBM Granite classifying arbitrary documents, feeding a wider set of gestures) — plus the cooldown pattern that keeps an automated agent from spamming animations every tick.+You'll build two working pipelines. One uses zero AI (a lexicon sentiment score, free, no key, triggering a real body animation), one puts a real model in the loop (IBM Granite reading arbitrary documents, feeding a graded set of gestures). Both use the cooldown pattern that keeps an automated agent from spamming animations every tick.**What you'll build:**- An agent that plays a real body animation (celebrate, dance, flinch) driven by a live sentiment feed, using only `<agent-3d>`'s public JS API-- A second pipeline where an actual AI model reads arbitrary text — reviews, tickets, chat logs, anything — and picks the matching gesture from a wider library, not just a three-way keyword split+- A second pipeline where an actual AI model reads arbitrary text (reviews, tickets, chat logs, anything) and picks the matching gesture from a graded score plus its risk flags, not just a keyword match- A cooldown/dedupe pattern so a fast-moving data source doesn't retrigger the same animation every poll- The two real, documented entry points for animation: `agent.play(clipName)` (exact clip) and `agent.playEmote(name)` (semantic, with a fallback chain)-**Prerequisites:** You've completed [first agent](/tutorials/first-agent) or have an `<agent-3d>` element on a page, and ideally [the JS API tutorial](/tutorials/js-api-events) (Step 5 covers the animation basics this one builds on). For the AI lane, a small amount of USDC and familiarity with the [x402 payment flow](/tutorials/pay-for-x402-service) — the call costs $0.04.+**Prerequisites:** You've completed [first agent](/tutorials/first-agent) or have an `<agent-3d>` element on a page, and ideally [the JS API tutorial](/tutorials/js-api-events) (Step 5 covers the animation basics this one builds on). For the AI lane, a small amount of USDC and familiarity with the [x402 payment flow](/tutorials/pay-for-x402-service), the call costs $0.04.----## Step 1 — The two animation entry points+## Step 1: The two animation entry points-Every `<agent-3d>` element exposes two public methods for triggering body animation, and — per the [JS API tutorial](/tutorials/js-api-events#step-5--animations-exact-name-vs-hint) — they answer different questions.+Every `<agent-3d>` element exposes two public methods for triggering body animation, and, per the [JS API tutorial](/tutorials/js-api-events#step-5-animations-exact-clip-vs-emote), they answer different questions.-**`agent.play(clipName)`** — plays the clip with that *exact* name from the loaded library or GLB. Case-sensitive; if the name isn't found, nothing plays. Use this once you know what's actually in the rig — e.g. `agent.play('rumba')`, `agent.play('thriller')`, `agent.play('celebrate')`. The full catalog (idle, locomotion, dance, gesture, action, sport, reaction, fitness — every clip a real, retargetable library entry, never hardcoded per-rig) is browsable at [/animations](/animations).+**`agent.play(clipName)`**: plays the clip with that *exact* name from the loaded library or GLB. Case-sensitive; if the name isn't found, nothing plays. Use this once you know what's actually in the rig, e.g. `agent.play('rumba')`, `agent.play('thriller')`, `agent.play('celebrate')`. The full catalog (idle, locomotion, dance, gesture, action, sport, reaction, fitness, every clip a real, retargetable library entry, never hardcoded per-rig) is browsable at [/animations](/animations).-**`agent.playEmote(name)`** — a higher-level wrapper for the small set of product-moment reactions with a built-in fallback chain, so it's guaranteed to do *something* regardless of which clips the loaded rig actually has:+**`agent.playEmote(name)`**: a higher-level wrapper for the small set of product-moment reactions with a built-in fallback chain, so it's guaranteed to do *something* regardless of which clips the loaded rig actually has:```jsagent.playEmote('celebrate'); // celebrate → wave@@ -92961,17 +93606,17 @@ agent.playEmote('cheer'); // cheer → celebrate → waveagent.playEmote('flinch'); // flinch → defeated → concern → shake```-If none of a chain's names exist on the rig, `playEmote` falls back to a small head-bob rather than doing nothing — so it's the safe default for "react to this event" code, and `play()` is for "I know exactly which clip I want."+If none of a chain's names exist on the rig, `playEmote` falls back to a small head-bob rather than doing nothing, so it's the safe default for "react to this event" code, and `play()` is for "I know exactly which clip I want."Convenience shortcut: `agent.wave()`.-The pattern for "animation from data" is: **your data source picks a discrete outcome** (celebrate / flinch / a specific dance), and you call `playEmote()` or `play()` with that name. Unlike the sustained facial-mood layer (`setMood()` — covered separately, see the note at the end), these are one-shot performances that play out and settle back to idle on their own.+The pattern for "animation from data" is: **your data source picks a discrete outcome** (celebrate / flinch / a specific dance), and you call `playEmote()` or `play()` with that name. Unlike the sustained facial-mood layer (`setMood()`, covered separately, see the note at the end), these are one-shot performances that play out and settle back to idle on their own.----## Step 2 — The free lane: sentiment → animation, no AI required+## Step 2: The free lane: sentiment → animation, no AI required-The platform runs a public, unauthenticated sentiment scorer over live pump.fun token chat: [`POST /api/social/sentiment-pulse`](../api/social/sentiment-pulse.js). It pulls recent comments for a token and scores them with an in-repo lexicon (no LLM call, no key) — good enough to prove the wiring before you reach for a model.+The platform runs a public, unauthenticated sentiment scorer over live pump.fun token chat: [`POST /api/social/sentiment-pulse`](../api/social/sentiment-pulse.js). It pulls recent comments for a token and scores them with an in-repo lexicon (no LLM call, no key), good enough to prove the wiring before you reach for a model.```html<!DOCTYPE html>@@ -93002,7 +93647,7 @@ The platform runs a public, unauthenticated sentiment scorer over live pump.funfunction reactTo(overall) {// scoreSentiment() returns score in [-1, 1] and posPct/negPct/count.- // Require both a strong score AND enough chatter to trust it — a+ // Require both a strong score AND enough chatter to trust it, a// single glowing comment shouldn't trigger a full celebration.const confident = overall.count >= 5;const now = performance.now();@@ -93032,34 +93677,41 @@ The platform runs a public, unauthenticated sentiment scorer over live pump.fun</html>```-Save that as `index.html` and open it — no build step, no server, no wallet. Swap `TOKEN` for any Solana mint and the agent physically celebrates or flinches as that token's live chat swings.+Save that as `index.html` and open it: no build step, no server, no wallet. Swap `TOKEN` for any Solana mint and the agent physically celebrates or flinches as that token's live chat swings.----## Step 3 — The AI lane: real classification over arbitrary data, richer gestures+## Step 3: The AI lane: real classification over arbitrary data, richer gestures++A lexicon scorer only works on short, informal text, and it only fires on words it already knows. For real documents (support tickets, product reviews, meeting transcripts, incident reports) you want a model that actually reads the thing and returns *structured* output: a graded sentiment score plus the findings and risk flags behind it, so the reaction tracks the document's real tone instead of its vocabulary. `ibm_granite_analyze` (part of the [IBM Granite x402 MCP suite](#sec-248)) does exactly this for $0.04/call, no IBM account needed: you pay in USDC, it pays IBM.-A lexicon scorer only works on short, informal text and only gives you positive/negative. For real documents — support tickets, product reviews, meeting transcripts, incident reports — you want a model that returns *structured* emotion: a sentiment score plus a breakdown across joy, anger, fear, sadness, surprise, and disgust, so you can pick a more specific reaction than a binary celebrate/flinch. `ibm_granite_analyze` (part of the [IBM Granite x402 MCP suite](#sec-248)) does exactly this for $0.04/call, no IBM account needed — you pay in USDC, it pays IBM.+The tool returns a fixed set of keys: `summary`, `entities`, `sentiment` (`{ overall, score }`, score in -1..1), `key_findings`, `risk_flags` (each with a `severity`), and `next_steps`. The two the animation layer cares about are `sentiment.score` and `risk_flags`.-This is a server-side call (it needs a wallet to sign the payment), so it lives behind a small endpoint you host yourself and the browser polls. The `@three-ws/x402-fetch` package does the 402 → sign → retry dance for you — see [pay-for-x402-service](/tutorials/pay-for-x402-service) for the full protocol if you want the mechanics.+This is a server-side call (it needs a wallet to sign the payment), so it lives behind a small endpoint you host yourself and the browser polls. The `@three-ws/x402-fetch` package does the 402 → sign → retry dance for you, see [pay-for-x402-service](/tutorials/pay-for-x402-service) for the full protocol if you want the mechanics.```js-// gesture-from-ai.js — run with `node gesture-from-ai.js`, or drop the body of+// gesture-from-ai.js: run with `node gesture-from-ai.js`, or drop the body of// gestureFor() into any serverless handler (Vercel/Cloud Run/etc).import { withX402, privateKeyToWallet } from '@three-ws/x402-fetch';const wallet = privateKeyToWallet(process.env.SOLANA_PRIVATE_KEY); // funds the $0.04 callsconst fetchWithPay = withX402(fetch, wallet);-// Dominant emotion → the richest matching clip. exact-name clips (agent.play)+// Score band → the richest matching clip. exact-name clips (agent.play)// give a bigger, more specific performance than the 3-way emote chain.-const GESTURE_FOR = {- joy: 'celebrate',- surprise: 'silly',- anger: 'shake',- fear: 'defeated',- sadness: 'defeated',- disgust: 'angry',-};+// Bands, not a binary: a mildly positive review gets a wave, a glowing+// one gets a full celebrate.+const GESTURE_FOR_SCORE = [+ { min: 0.6, clip: 'celebrate' },+ { min: 0.25, clip: 'wave' },+ { min: -0.25, clip: null }, // middling: leave idle alone+ { min: -0.6, clip: 'concern' },+ { min: -1, clip: 'defeated' },+];++function clipForScore(score) {+ return GESTURE_FOR_SCORE.find((band) => score >= band.min)?.clip ?? null;+}async function gestureFor(document) {const res = await fetchWithPay('https://three.ws/api/ibm-mcp', {@@ -93078,17 +93730,23 @@ async function gestureFor(document) {const { result } = await res.json();const analysis = JSON.parse(result.content[0].text);- const breakdown = analysis.emotion_breakdown || {};- const [dominant, strength] = Object.entries(breakdown).sort((a, b) => b[1] - a[1])[0] || ['joy', 0];+ // A high-severity risk flag outranks the score: an incident report can read+ // as calm prose and still be the thing you want the agent to react to.+ const alarming = (analysis.risk_flags || []).some((f) => f.severity === 'high');+ if (alarming) return { clip: 'concern', strength: 1, summary: analysis.summary };++ const score = analysis.sentiment?.score;+ if (typeof score !== 'number') return null; // model returned no usable score// Below this, the signal is too weak to justify interrupting idle.+ const strength = Math.abs(score);if (strength < 0.3) return null;- return { clip: GESTURE_FOR[dominant] || null, strength, summary: analysis.summary };+ return { clip: clipForScore(score), strength, summary: analysis.summary };}```-Wire that into a one-route endpoint (`GET /gesture?text=...` returning the JSON above), and the browser side reuses the same cooldown-gated `reactTo()` shape from Step 2 — swap the fetch call and the trigger:+Wire that into a one-route endpoint (`GET /gesture?text=...` returning the JSON above), and the browser side reuses the same cooldown-gated `reactTo()` shape from Step 2, swap the fetch call and the trigger:```jsasync function tick() {@@ -93102,16 +93760,16 @@ async function tick() {}```-Now anything you can turn into a string — a webhook payload, a scraped page, a batch of reviews — can drive a specific, visible body performance instead of a static idle loop.+Now anything you can turn into a string: a webhook payload, a scraped page, a batch of reviews, can drive a specific, visible body performance instead of a static idle loop.----## Step 4 — Don't let fast data spam the animation queue+## Step 4: Don't let fast data spam the animation queue-Two rules worth copying from the platform's own production reaction engine ([`src/widgets/pumpfun-reactions.js`](../src/widgets/pumpfun-reactions.js) — the pump.fun live-trade avatar reactor, 23 distinct clips across dozens of event shapes):+Two rules worth copying from the platform's own production reaction engine ([`src/widgets/pumpfun-reactions.js`](../src/widgets/pumpfun-reactions.js), the pump.fun live-trade avatar reactor, 23 distinct clips across dozens of event shapes):-1. **Cooldown, not "react to every event."** A fast feed (trades, comments, ticks) will fire far more often than a physical performance can play out. Gate triggers behind a minimum interval (`COOLDOWN_MS` above) — the production reactor goes further and queues lower-priority events behind an in-flight gesture instead of dropping or interrupting it.-2. **Require confidence before you interrupt idle.** A single data point (one comment, one weak signal) shouldn't yank the avatar out of idle. Both examples above gate on a minimum sample size / signal strength (`overall.count >= 5`, `strength >= 0.3`) — tune the threshold to your own data's noise floor.+1. **Cooldown, not "react to every event."** A fast feed (trades, comments, ticks) will fire far more often than a physical performance can play out. Gate triggers behind a minimum interval (`COOLDOWN_MS` above), the production reactor goes further and queues lower-priority events behind an in-flight gesture instead of dropping or interrupting it.+2. **Require confidence before you interrupt idle.** A single data point (one comment, one weak signal) shouldn't yank the avatar out of idle. Both examples above gate on a minimum sample size / signal strength (`overall.count >= 5`, `strength >= 0.3`), tune the threshold to your own data's noise floor.```jslet lastFired = 0;@@ -93130,28 +93788,29 @@ function reactIfConfident(clipOrEmoteName, { confident, useExactClip = false } =## A note on the facial layer-`agent.play()` / `agent.playEmote()` drive the *body* directly — the skeleton, via the shared animation-clip library, for a one-shot performance you chose explicitly. `agent.setMood(valence, arousal)` / `agent.expressEmotion(trigger, weight)` primarily drive the *face* — ARKit-52 blendshapes (smile, brow, gaze) on avatars that carry them, without touching the skeleton. They're still distinct APIs for distinct calls (`play`/`playEmote` for "perform this exact gesture now" vs. `setMood`/`expressEmotion` for "this is how the agent feels"), but they're not fully independent: once nothing more urgent (like a `play()`/`playEmote()` call or a fresh `expressEmotion()` spike) already claims the ambient gesture slot, a *sustained* `setMood()` also lightly biases which idle-time gesture the body reaches for — energetic-positive moods lean toward `celebrate`, subdued-negative moods toward `concern` — so a happy agent doesn't just smile while standing dead still. See [Animate your avatar → Emotion and expression on the live agent](tutorials/animate-your-avatar.md#emotion-and-expression-on-the-live-agent) for the full wiring. This tutorial covers explicit body triggers; if you want the face (and the ambient body bias) to track data too, the same fetch/cooldown pattern above applies, just swapping in `setMood()`/`expressEmotion()`.+`agent.play()` / `agent.playEmote()` drive the *body* directly, the skeleton, via the shared animation-clip library, for a one-shot performance you chose explicitly. `agent.setMood(valence, arousal)` / `agent.expressEmotion(trigger, weight)` primarily drive the *face*, ARKit-52 blendshapes (smile, brow, gaze) on avatars that carry them, without touching the skeleton. They're still distinct APIs for distinct calls (`play`/`playEmote` for "perform this exact gesture now" vs. `setMood`/`expressEmotion` for "this is how the agent feels"), but they're not fully independent: once nothing more urgent (like a `play()`/`playEmote()` call or a fresh `expressEmotion()` spike) already claims the ambient gesture slot, a *sustained* `setMood()` also lightly biases which idle-time gesture the body reaches for, energetic-positive moods lean toward `celebrate`, subdued-negative moods toward `concern`, so a happy agent doesn't just smile while standing dead still. See [Animate your avatar → Emotion and expression on the live agent](tutorials/animate-your-avatar.md#emotion-and-expression-on-the-live-agent) for the full wiring. This tutorial covers explicit body triggers; if you want the face (and the ambient body bias) to track data too, the same fetch/cooldown pattern above applies, just swapping in `setMood()`/`expressEmotion()`.---## Troubleshooting-- **Nothing plays.** Confirm `agent:ready` fired before your first `play()`/`playEmote()` call — calling either before boot is silently a no-op. Wrap your first tick in the `agent:ready` listener as shown in Step 2.-- **`agent.play('someClip')` does nothing.** The name is case-sensitive and must match a clip actually present on the rig — check the exact name at [/animations](/animations) or fall back to `playEmote()`, which degrades gracefully instead of silently failing.+- **Nothing plays.** Confirm `agent:ready` fired before your first `play()`/`playEmote()` call, calling either before boot is silently a no-op. Wrap your first tick in the `agent:ready` listener as shown in Step 2.+- **`agent.play('someClip')` does nothing.** The name is case-sensitive and must match a clip actually present on the rig, check the exact name at [/animations](/animations) or fall back to `playEmote()`, which degrades gracefully instead of silently failing.- **The agent keeps re-celebrating every poll.** You skipped the cooldown gate in Step 4, or your confidence threshold is too low for a noisy feed. Widen `COOLDOWN_MS` or raise the sample-size/strength floor.-- **AI lane 402 loop / never resolves.** Your `SOLANA_PRIVATE_KEY` wallet has no USDC. Fund it with a few cents — see the [x402 payment flow](/tutorials/pay-for-x402-service).-- **`analysis.emotion_breakdown` is undefined.** You passed `analysis_type` other than `sentiment` — only that type returns the per-emotion breakdown; the other five types return type-specific fields instead (see [ibm-x402-mcp](#sec-248)).+- **AI lane 402 loop / never resolves.** Your `SOLANA_PRIVATE_KEY` wallet has no USDC. Fund it with a few cents, see the [x402 payment flow](/tutorials/pay-for-x402-service).+- **`analysis.sentiment` is undefined.** Granite returned something that wasn't a clean JSON analysis object; the tool falls back to `{ ok: true, raw_response, parse_error }` in that case. Log `analysis.parse_error` and `analysis.raw_response` to see what came back. The `gestureFor()` above already treats a missing score as "no gesture" rather than crashing.+- **Every document scores middling and nothing ever plays.** `analysis_type: 'sentiment'` tunes the model toward tone; the other five types (`general`, `contract`, `financial`, `technical`, `medical`) return the same keys but reason about different things, so a contract analyzed as `general` often lands near 0. Match the type to your data (see [ibm-x402-mcp](#sec-248)).---## Recap-- `agent.play(clipName)` for an exact clip, `agent.playEmote(name)` for a safer semantic trigger with a fallback chain — both are public methods on every `<agent-3d>` element, no library beyond the CDN script.+- `agent.play(clipName)` for an exact clip, `agent.playEmote(name)` for a safer semantic trigger with a fallback chain, both are public methods on every `<agent-3d>` element, no library beyond the CDN script.- The free lane (`/api/social/sentiment-pulse`) proves the wiring with zero AI and zero cost.-- The AI lane (`ibm_granite_analyze` over x402) turns arbitrary documents into a richer emotion breakdown, unlocking more of the animation library than a simple positive/negative split.-- Gate every automated trigger behind a cooldown and a confidence floor — [`pumpfun-reactions.js`](../src/widgets/pumpfun-reactions.js) is the production-grade version of this exact pattern, queueing and prioritizing real trade-feed events across 23 distinct clips.+- The AI lane (`ibm_granite_analyze` over x402) turns arbitrary documents into a graded sentiment score plus risk flags, which drives more of the animation library than a lexicon's positive/negative split can reach.+- Gate every automated trigger behind a cooldown and a confidence floor, [`pumpfun-reactions.js`](../src/widgets/pumpfun-reactions.js) is the production-grade version of this exact pattern, queueing and prioritizing real trade-feed events across 23 distinct clips.-**Related tutorials:** [The JS API — animations, exact name vs. hint](/tutorials/js-api-events) · [Trigger the agent from page events](/tutorials/trigger-from-page-events) · [Animate your avatar](/tutorials/animate-your-avatar) · [Discover and pay for an x402 service](/tutorials/pay-for-x402-service)+**Related tutorials:** [The JS API: animations, exact name vs. hint](/tutorials/js-api-events) · [Trigger the agent from page events](/tutorials/trigger-from-page-events) · [Animate your avatar](/tutorials/animate-your-avatar) · [Discover and pay for an x402 service](/tutorials/pay-for-x402-service)---@@ -93203,13 +93862,24 @@ https://three.ws/docs/world#forge## 4. Use the index instead of walking-The **☰ Index** chip (top left) lists all fourteen sections. Picking one teleports you to its pavilion and opens its page list. This is also the fully keyboard-accessible path through the world: Tab to the chip, Enter, arrow through the list.+The **☰ Index** chip (top left) lists all fourteen sections. Picking one teleports you to its pavilion and opens its page list. This is also a fully keyboard-accessible path through the world: Tab to the chip, Enter, arrow through the list.++## 5. Search when you already know the page++Walking is the point of this surface, but hunting fourteen pavilions for a page you can already name is not. Press `/` (or Ctrl+K, Cmd+K on a Mac) anywhere in the world and a search palette opens over the scene, ranking every documented page. Typos are tolerated: the palette uses the same fuzzy scorer as the rest of the platform, so `marketpalce` still finds the marketplace page.++Each result offers two actions:-## 5. Change the camera+- **Enter** reads the page now, and stands your avatar at its pavilion so closing the reader leaves you where that page lives.+- **Shift+Enter** has the world walk you there, routing around the other pavilions and opening the page on arrival.++Pages you opened recently are listed first when the box is empty.++## 6. Change the cameraPress C (or the camera chip, top right) to cycle the four platform camera modes: Follow, Cinematic, First Person, Top Down. These are the same modes `/walk` and `/play` use, and your choice is remembered.-## 6. Bring your own avatar+## 7. Bring your own avatarBy default you walk as the base mannequin. Any rigged humanoid GLB can replace it via the `avatar` query parameter:@@ -93283,12 +93953,17 @@ curl -s 'https://three.ws/api/sniper/exit-lab?window=all&limit=500' \```json{- "scanned": 239,- "replayable": 234,+ "scanned": 313,+ "replayable": 306,"excluded": ["laddered"]}```+Those counts grow every time the fleet closes a position, so yours will be+larger. The shape is the part that matters: `scanned` is every closed position+the corpus reached, `replayable` is how many survived the exclusions, and+`excluded` names why the rest were dropped.+**The first thing to notice is that "net result" and "actually booked" are notthe same number, and they are not supposed to be.**@@ -93421,8 +94096,8 @@ https://three.ws/exit-lab?stopLossPct=15&trailingStopPct=10&takeProfitPct=off&inThat link is the unit of a useful argument about exits. Instead of "I think thestop is too wide", you can send a page that shows what a tighter stop would have-returned over 234 real trades, with the caveats attached and the underlying-transactions one click away.+returned over every replayable trade in the corpus, with the caveats attached and+the underlying transactions one click away.If you run your own agent, the same parameters are what[`/api/sniper/strategy`](#sec-096) accepts, so a finding here maps@@ -93706,11 +94381,11 @@ Then add your own input below the element:const agent = document.querySelector('agent-3d');const input = document.getElementById('msg');- async function send() {+ function send() {const text = input.value.trim();if (!text) return;input.value = '';- await agent.say(text);+ agent.say(text);}// Submit on Enter@@ -93730,8 +94405,8 @@ Then add your own input below the element:| Method | What it does ||--------|--------------|-| `agent.say(text)` | Sends a message and returns the reply. The agent also speaks and animates. |-| `agent.ask(text)` | Same as `say()`, but returns the reply text as a string. |+| `agent.say(text)` | Sends a message the way the built-in chat input does. Fire-and-forget: the reply renders in the bubble, and the agent speaks and animates, but nothing is returned. |+| `agent.ask(text)` | Same turn as `say()`, but returns a promise that resolves with the reply text once the response has finished (and rejects if the brain call fails). || `agent.wave()` | Triggers the wave animation directly. || `agent.lookAt(target)` | `'camera'`, `'model'`, or `'user'` — the agent turns to look. || `agent.play(clipName)` | Plays a named animation clip from the GLB. |@@ -93744,7 +94419,7 @@ Then add your own input below the element:|-------|--------------|----------------|| `agent:ready` | Agent fully booted | `{ agent, manifest }` || `brain:message` | Each turn of conversation | `{ role, content }` |-| `brain:thinking` | LLM call started | — |+| `brain:thinking` | LLM call started, and again when it ends | `{ thinking }` || `skill:tool-called` | Agent used a tool/skill | `{ tool, args, result }` || `voice:transcript` | STT produced a transcript | `{ text, final }` |@@ -93756,10 +94431,10 @@ Make Aria say hello as soon as the page loads. Add this after the script block f```html<script>- agent.addEventListener('agent:ready', async () => {+ agent.addEventListener('agent:ready', () => {// Short pause so the avatar settles in before speaking- setTimeout(async () => {- await agent.say('Hello! I\'m Aria. How can I help you today?');+ setTimeout(() => {+ agent.say('Hello! I\'m Aria. How can I help you today?');}, 1200);});</script>@@ -93921,11 +94596,11 @@ Here's the complete `index.html` all in one place:const agent = document.querySelector('agent-3d');const input = document.getElementById('msg');- async function send() {+ function send() {const text = input.value.trim();if (!text) return;input.value = '';- await agent.say(text);+ agent.say(text);}input.addEventListener('keydown', e => {@@ -94552,6 +95227,8 @@ Two things worth knowing about this snippet:That's a working greeting. The rest of this tutorial is about doing it well rather than doing it at all.+> **The editor's "Greeting" field is a different thing.** The agent editor has a **Greeting (demo first message)** field, and it is easy to assume filling it in makes your embed talk. It does not. That field is the opening line published in the agent's signed manifest and shown on platform surfaces that demo the agent (its marketplace card, a Widget Studio talking-agent widget, an exported agent JSON). `<agent-3d>` does not read it. On your own page, the greeting is the JavaScript below.+---## Step 2 — When the greeting fires@@ -95129,22 +95806,22 @@ The URL path and the file-upload path converge on the same avatar record and the# Drive the agent with the JavaScript API-The script tag is the easy mode. It drops a 3D agent on your page, gives it a chat input, and walks away. That's enough for a contact widget. But once you start treating the agent like a real part of your product — something that reacts to clicks, scroll position, form submits, and checkout success — you need the JavaScript API.+The script tag is the easy mode. It drops a 3D agent on your page, gives it a chat input, and walks away. That's enough for a contact widget. But once you start treating the agent like a real part of your product, something that reacts to clicks, scroll position, form submits, and checkout success, you need the JavaScript API.-This tutorial covers the full handle-to-event lifecycle. By the end you will know how to grab the agent element, wait for it to be truly ready, fire animations and speech in response to user actions, listen for the events the agent emits back, and chain everything together into a real product moment — a checkout celebration sequence that fires on a successful order.+This tutorial covers the full handle-to-event lifecycle. By the end you will know how to grab the agent element, wait for it to be truly ready, fire animations and speech in response to user actions, listen for the events the agent emits back, and chain everything together into a real product moment, a checkout celebration sequence that fires on a successful order.**What you'll build:**- A live page where the agent reacts to clicks and form events- A "wait until ready" pattern that never tries to drive an unbooted agent- A queue that chains `ask`, `play`, and `lookAt` without overlap- A listener that reads back every word the agent says-- A checkout celebration flow — submit a form, the agent cheers, narrates, and goes idle+- A checkout celebration flow: submit a form, the agent cheers, narrates, and goes idle**Prerequisites:** Comfort with vanilla DOM APIs (`querySelector`, `addEventListener`), promises, and async/await. You should have completed the [first-agent tutorial](/tutorials/first-agent) or have an agent ID from [three.ws/my-agents](https://three.ws/my-agents).----## Step 1 — Drop the agent on the page+## Step 1: Drop the agent on the pageStart with the simplest possible embed. Create `index.html` and paste this:@@ -95212,13 +95889,13 @@ function logLine(text) {logLine('Page loaded. Waiting for agent to boot...');```-Serve it locally — `python3 -m http.server 8080` works — and open `http://localhost:8080`. The agent appears. Nothing else does. Good.+Serve it locally: `python3 -m http.server 8080` works, and open `http://localhost:8080`. The agent appears. Nothing else does. Good.----## Step 2 — Get a handle to the agent+## Step 2: Get a handle to the agent-The `<agent-3d>` element is a custom element. `document.getElementById('agent')` gives you back an `Agent3DElement` instance with the full API attached — the CDN script's only job is registering that element, so every `<agent-3d>` tag on the page is a live API handle.+The `<agent-3d>` element is a custom element. `document.getElementById('agent')` gives you back an `Agent3DElement` instance with the full API attached, the CDN script's only job is registering that element, so every `<agent-3d>` tag on the page is a live API handle.If you didn't put an `id` on the tag (or you're writing code that runs on pages you don't control), grab the first agent on the page instead:@@ -95230,7 +95907,7 @@ Either lookup returns the same element with the same JavaScript API from this po----## Step 3 — Wait for ready, always+## Step 3: Wait for ready, alwaysThis is the rule that prevents 90% of the headaches you would otherwise hit. The agent does a lot at boot: fetches the manifest, downloads a GLB body (often several megabytes), warms up the runtime, registers skills, and resolves the brain. None of `.speak()`, `.wave()`, or `.say()` will do anything useful until that finishes.@@ -95242,7 +95919,7 @@ agent.addEventListener('agent:ready', (e) => {});```-`e.detail.manifest` contains the resolved manifest — name, description, body URL, brain config, the lot. If you need anything from it, grab it here.+`e.detail.manifest` contains the resolved manifest, name, description, body URL, brain config, the lot. If you need anything from it, grab it here.But what if you have code that runs *after* the page might have already booted? A common case: a button handler that fires whenever the user clicks, where the click could happen before or after boot. You need a promise that resolves when the agent is ready, no matter when you call it.@@ -95261,7 +95938,7 @@ function whenReady(el) {}```-The `_mounted` flag is set by the runtime once boot finishes, so if the agent is already ready the promise resolves immediately. Otherwise it waits for the event. This pattern is in the element's own `_waitForReady` helper — we're just exposing it as a public utility.+The `_mounted` flag is set by the runtime once boot finishes, so if the agent is already ready the promise resolves immediately. Otherwise it waits for the event. This pattern is in the element's own `_waitForReady` helper, we're just exposing it as a public utility.Now every action handler starts the same way:@@ -95276,15 +95953,15 @@ No race conditions, no "I clicked but nothing happened on the first try" bugs.----## Step 4 — The two ways to speak+## Step 4: The two ways to speakThe agent has two methods that look similar but do different things. Picking the right one matters.-**`agent.speak(text)`** — plays a talking *gesture* sized to the length of the text (roughly 0.3s per word, minimum 1.5s). It is silent: no LLM, no audio, no chat bubble. Use it to add life to a scripted moment where the page itself supplies the words on screen. Cheap, instant, deterministic.+**`agent.speak(text)`**: plays a talking *gesture* sized to the length of the text (roughly 0.3s per word, minimum 1.5s). It is silent: no LLM, no audio, no chat bubble. Use it to add life to a scripted moment where the page itself supplies the words on screen. Cheap, instant, deterministic.-**`agent.say(text)`** — sends `text` to the brain as a user message. The reply renders in the chat bubble and is spoken aloud when the `voice` attribute is set. This is what the built-in chat input calls. It's fire-and-forget: it returns immediately, and if you call it again while a turn is in flight, the newest message replaces the queued one.+**`agent.say(text)`**: sends `text` to the brain as a user message. The reply renders in the chat bubble and is spoken aloud when the `voice` attribute is set. This is what the built-in chat input calls. It's fire-and-forget: it returns immediately, and if you call it again while a turn is in flight, the newest message replaces the queued one.-**`agent.ask(text)`** — same brain turn as `say`, but returns a promise that resolves with the reply text once the response (and its speech, if voice is on) has finished. Reach for it whenever you need to await the turn or use the reply.+**`agent.ask(text)`**: same brain turn as `say`, but returns a promise that resolves with the reply text once the response (and its speech, if voice is on) has finished. Reach for it whenever you need to await the turn or use the reply.Most page-driven interactions want `say` or `ask`. Use `speak` when all you need is the gesture.@@ -95293,13 +95970,13 @@ Wire up two buttons:```jsdocument.getElementById('btn-greet').addEventListener('click', async () => {await whenReady(agent);- // Silent talking gesture — pair it with your own on-page caption.+ // Silent talking gesture: pair it with your own on-page caption.agent.speak('Hey there. Glad you stopped by.');});document.getElementById('btn-think').addEventListener('click', async () => {await whenReady(agent);- // Goes through the LLM — the model decides what to say.+ // Goes through the LLM: the model decides what to say.agent.say('Tell me a one-sentence fun fact.');});```@@ -95308,13 +95985,13 @@ Click both. The first animates instantly and makes no sound. The second pauses b----## Step 5 — Animations: exact clip vs emote+## Step 5: Animations: exact clip vs emoteThe agent has two ways to pick an animation clip. They map to two different mental models.-**`agent.play(name)`** — plays the clip with that name from the loaded rig (an exact match, falling back to a case-insensitive one). If the clip isn't in the model, it returns `false` and nothing plays. Use this when you know what's in the rig — for instance, if you've baked a `WaveLoop` clip yourself.+**`agent.play(name)`**: plays the clip with that name from the loaded rig: an exact match first, then a case-insensitive one, then a case-insensitive substring match. If the GLB carries no such clip, it looks the name up in the shared animation library instead, and only returns `false` when neither source can supply it. Use this when you know what's in the rig, for instance, if you've baked a `WaveLoop` clip yourself.-**`agent.playEmote(name)`** — the resilient one. Instead of a clip name it takes an intent — `'celebrate'`, `'cheer'`, or `'flinch'` — and walks a fallback chain of clips until one exists in the rig (`celebrate` → `wave`; `cheer` → `celebrate` → `wave`; `flinch` → `defeated` → `concern` → `shake`). If none of them are present, it finishes with a small head-bob, so it's guaranteed to do *something* regardless of the rig.+**`agent.playEmote(name)`**: the resilient one. Instead of a clip name it takes an intent, `'celebrate'`, `'cheer'`, or `'flinch'`, and walks a fallback chain of clips until one exists in the rig (`celebrate` → `wave`; `cheer` → `celebrate` → `wave`; `flinch` → `defeated` → `concern` → `shake`). If none of them are present, it finishes with a small head-bob, so it's guaranteed to do *something* regardless of the rig.For product moments, prefer the emote version:@@ -95344,9 +96021,9 @@ document.getElementById('btn-clear').addEventListener('click', async () => {----## Step 6 — Listen back: the event lifecycle+## Step 6: Listen back: the event lifecycle-So far we've been issuing commands. The agent also emits events you can listen for — and they're the foundation of most useful integrations.+So far we've been issuing commands. The agent also emits events you can listen for, and they're the foundation of most useful integrations.Here are the events that actually fire, in the order you'll usually see them in one chat turn:@@ -95356,11 +96033,11 @@ Here are the events that actually fire, in the order you'll usually see them in| `brain:thinking` | An LLM call has started | `{ thinking: true | false }` || `brain:stream` | A chunk of a streamed response arrived | `{ chunk: string }` || `brain:message` | A complete message landed (user or assistant) | `{ role, content, sentiment? }` |-| `skill:tool-start` | A tool/skill is about to run | `{ tool }` |-| `skill:tool-called` | A tool returned | `{ name, args, result }` |+| `skill:tool-start` | A tool/skill is about to run | `{ tool, args }` |+| `skill:tool-called` | A tool returned | `{ tool, args, result }` || `voice:speech-start` | The agent began speaking out loud | `{ text }` |-| `voice:speech-end` | The agent finished speaking | — |-| `voice:transcript` | Mic input was transcribed | `{ text }` |+| `voice:speech-end` | The agent finished speaking | - |+| `voice:transcript` | Mic input was transcribed | `{ text, final }` || `memory:write` | Something was written to memory | `{ scope, key, value }` |Wire a logger to see them flow:@@ -95391,18 +96068,18 @@ Click "Think about something" and watch the order. Boot → ready → thinking sEvery one of these is a hook for your app. A few common patterns:-- **Show a typing indicator** — switch a CSS class on `brain:thinking` and clear it on `brain:message`.-- **Mirror chat to your own UI** — listen to `brain:message` and append `e.detail.content` to your message log when `role === 'assistant'`.-- **Track skill usage** — `skill:tool-called` tells you which skill ran, with what arguments, and what came back. Log it to your analytics.-- **React to speech state** — disable an input while `voice:speech-start` is active, re-enable on `voice:speech-end`. Stops the user from interrupting the agent mid-sentence.+- **Show a typing indicator**: switch a CSS class on `brain:thinking` and clear it on `brain:message`.+- **Mirror chat to your own UI**: listen to `brain:message` and append `e.detail.content` to your message log when `role === 'assistant'`.+- **Track skill usage**: `skill:tool-called` tells you which skill ran (`e.detail.tool`), with what arguments, and what came back. Log it to your analytics.+- **React to speech state**: disable an input while `voice:speech-start` is active, re-enable on `voice:speech-end`. Stops the user from interrupting the agent mid-sentence.----## Step 7 — Sequencing: do A, then B, then C+## Step 7: Sequencing: do A, then B, then CA common pitfall: fire `speak` and `play` back-to-back, and they overlap. The second clip steps on the talking gesture and things look broken.-For LLM turns the clean fix is `ask()` — it resolves only after the reply is complete (including its speech, when `voice` is on), so a plain `await` sequences everything:+For LLM turns the clean fix is `ask()`: it resolves only after the reply is complete (including its speech, when `voice` is on), so a plain `await` sequences everything:```jsasync function intro() {@@ -95415,9 +96092,9 @@ async function intro() {}```-Each line waits for the previous one to land before the next runs. The result feels deliberate — not a stuttering pile-up.+Each line waits for the previous one to land before the next runs. The result feels deliberate, not a stuttering pile-up.-For the silent `speak()` gesture there is no completion event — but its duration is deterministic (0.3s per word, minimum 1.5s), so you can mirror it:+For the silent `speak()` gesture there is no completion event, but its duration is deterministic (0.3s per word, minimum 1.5s), so you can mirror it:```jsfunction gestureAndWait(el, text) {@@ -95427,7 +96104,7 @@ function gestureAndWait(el, text) {}```-And if you're reacting to real speech (an LLM reply being voiced), `voice:speech-end` is still the event to wait on — it fires when the spoken sentence is done:+And if you're reacting to real speech (an LLM reply being voiced), `voice:speech-end` is still the event to wait on, it fires when the spoken sentence is done:```jsfunction nextSpeechEnd(el) {@@ -95439,7 +96116,7 @@ function nextSpeechEnd(el) {----## Step 8 — Error patterns+## Step 8: Error patternsThe bulk of mistakes fall into three buckets.@@ -95457,9 +96134,9 @@ function getAgent() {}```-Or use a small reactive wrapper if you're inside a framework — see the [Web Component end-to-end tutorial](/tutorials/web-component-end-to-end) for React and Vue patterns.+Or use a small reactive wrapper if you're inside a framework, see the [Web Component end-to-end tutorial](/tutorials/web-component-end-to-end) for React and Vue patterns.-**LLM errors during a turn.** Network glitch, brain provider rate-limit, no API key. `say()` never rejects — it shows the error in the chat bubble and fires an `agent:error` event. When you need to handle the failure programmatically, use `ask()`, which rejects:+**LLM errors during a turn.** Network glitch, brain provider rate-limit, no API key. `say()` never rejects, it shows the error in the chat bubble and fires an `agent:error` event. When you need to handle the failure programmatically, use `ask()`, which rejects:```jstry {@@ -95471,11 +96148,11 @@ try {}```-The fallback `agent.speak(...)` does *not* go through the brain (it's a silent gesture), so it works even when the LLM path is broken — pair it with your own on-page error message for the words.+The fallback `agent.speak(...)` does *not* go through the brain (it's a silent gesture), so it works even when the LLM path is broken, pair it with your own on-page error message for the words.----## Step 9 — The checkout celebration flow+## Step 9: The checkout celebration flowTime to put it all together. You run a Shopify store, a Stripe checkout, or any form-driven flow. When a user submits a successful order, you want the agent to celebrate, narrate, and settle back to idle. The whole sequence should run on the success page.@@ -95544,12 +96221,12 @@ async function placeOrder({ name, item }) {A few things this gets right:- The form submit is intercepted with `preventDefault` so we control the flow.-- The real network call is awaited before the celebration runs — no fake confetti on a failed order.+- The real network call is awaited before the celebration runs, no fake confetti on a failed order.- An explicit error branch speaks an apology if the order didn't go through.- The celebration sequences animation → speech → animation cleanly, so each beat lands.- `whenReady` is called even though we expect the agent to already be booted by submit time. Cheap insurance.-If you also wanted to log the celebration upstream — to your analytics, to a CRM — you'd subscribe to `voice:speech-end` once and fire an event:+If you also wanted to log the celebration upstream, to your analytics, to a CRM, you'd subscribe to `voice:speech-end` once and fire an event:```jsagent.addEventListener('voice:speech-end', () => {@@ -95583,9 +96260,9 @@ The `whenReady`, awaited-`ask()`, and try/catch patterns are small but they remo## Next steps-- [Use the <agent-3d> web component end-to-end](/tutorials/web-component-end-to-end) — same API, in React, Vue, and your component system-- [Trigger the agent from page events](/tutorials/trigger-from-page-events) — scroll, route changes, idle time, onboarding flows-- [Give your agent a personality](/tutorials/agent-personality) — write a system prompt that holds across thousands of chats+- [Use the <agent-3d> web component end-to-end](/tutorials/web-component-end-to-end), same API, in React, Vue, and your component system+- [Trigger the agent from page events](/tutorials/trigger-from-page-events), scroll, route changes, idle time, onboarding flows+- [Give your agent a personality](/tutorials/agent-personality), write a system prompt that holds across thousands of chats---@@ -96074,12 +96751,21 @@ The shape:{"resource": "https://three.ws/api/mcp","authorization_servers": ["https://three.ws"],- "scopes_supported": ["mcp", "mcp:tools", "mcp:resources"],"bearer_methods_supported": ["header"],- "resource_documentation": "https://three.ws/docs/mcp"+ "resource_documentation": "https://three.ws/docs/mcp",+ "scopes_supported": [+ "avatars:read", "avatars:write", "avatars:delete",+ "profile", "offline_access",+ "memory:read", "memory:write",+ "agents:read", "agents:write",+ "wallet:read", "wallet:write",+ "services:write"+ ]}```+Note the scopes are per-capability, not one blanket `mcp` scope. A client asks for exactly what it needs (`avatars:read` to render, `memory:write` to store a memory), so a token that leaks cannot do more than the tool it was minted for.+To wire this on your own server, add `api/wk-oauth-protected-resource.js`:```js@@ -96522,9 +97208,9 @@ The protocol itself is fully specified in [docs/PROTOCOL-vanity.md](#sec-005), a# Mint an Agent Token on Pump.fun-By the end of this tutorial your agent has a live, tradable token on Solana — bonded to its three.ws identity, indexed by the platform's live mint stream, and discoverable from your agent's profile card. The token is real. The bonding curve is real. The Pump.fun graduation event, if it happens, is real.+By the end of this tutorial your agent has a live, tradable token on Solana, bonded to its three.ws identity, indexed by the platform's live mint stream, and discoverable from your agent's profile card. The token is real. The bonding curve is real. The Pump.fun graduation event, if it happens, is real.-This is the canonical path for turning a 3D agent into a community-owned asset. It does not make your agent more capable. It makes your agent **owned** — by its holders, transparently, on a chain anyone can read.+This is the canonical path for turning a 3D agent into a community-owned asset. It does not make your agent more capable. It makes your agent **owned**, by its holders, transparently, on a chain anyone can read.**What you'll build:**@@ -96540,22 +97226,22 @@ This is the canonical path for turning a 3D agent into a community-owned asset.- A Solana wallet. Phantom, Solflare, or any wallet that supports Solana mainnet works. Email-based embedded wallets created on three.ws are also acceptable for this flow.- Approximately **0.05 SOL** in that wallet on Solana mainnet. This covers Pump.fun's mint fee, a small initial dev buy, and rent + transaction fees with a healthy margin for retries.- A square image (PNG or JPG, 512x512 minimum, under 1 MB) to use as the token icon. Pump.fun uploads it to its CDN and bakes it into the mint metadata.-- A clear name and ticker symbol you have already verified is available — Step 2 covers how.+- A clear name and ticker symbol you have already verified is available, Step 2 covers how.- Familiarity with the fact that **tokens minted on Pump.fun are public, immutable, and economically real**. Read the legal note at the end of this tutorial before launching anything you'd regret.----## Step 1 — Understand what Pump.fun actually is+## Step 1: Understand what Pump.fun actually is-Pump.fun is a Solana token launch protocol. Every token launched on Pump.fun starts on a **fair-launch bonding curve** — no presale, no team allocation, no insider rounds. The first buyer pays the lowest price; every subsequent buyer pays slightly more along a deterministic curve. The curve holds the SOL collected on the buy side and the unsold token supply on the sell side. Selling burns the position and returns SOL.+Pump.fun is a Solana token launch protocol. Every token launched on Pump.fun starts on a **fair-launch bonding curve**, no presale, no team allocation, no insider rounds. The first buyer pays the lowest price; every subsequent buyer pays slightly more along a deterministic curve. The curve holds the SOL collected on the buy side and the unsold token supply on the sell side. Selling burns the position and returns SOL.There are three states a Pump.fun token can be in:-1. **Bonding** — the curve is active, trades route through the Pump.fun program, prices follow the curve formula. This is the first life of every token. Almost all activity happens here.-2. **Graduated** — the curve has accumulated enough SOL (currently around 85 SOL at the time of writing; Pump.fun adjusts this threshold). The protocol burns the remaining curve supply, takes the collected SOL, and seeds a Raydium liquidity pool. From then on the token trades like any other Solana SPL token on the open market.-3. **Stalled** — the curve never fills. The token continues to trade on the curve indefinitely. No timer. No expiry. It will sit there at whatever price the last trade left it.+1. **Bonding**: the curve is active, trades route through the Pump.fun program, prices follow the curve formula. This is the first life of every token. Almost all activity happens here.+2. **Graduated**: the curve has accumulated enough SOL (currently around 85 SOL at the time of writing; Pump.fun adjusts this threshold). The protocol burns the remaining curve supply, takes the collected SOL, and seeds a Raydium liquidity pool. From then on the token trades like any other Solana SPL token on the open market.+3. **Stalled**: the curve never fills. The token continues to trade on the curve indefinitely. No timer. No expiry. It will sit there at whatever price the last trade left it.-The vast majority of tokens stall. Graduation is rare. This tutorial assumes the bonding stage is the destination, not a milestone. Building real utility into your agent is what gives the curve a reason to fill — not the launch itself.+The vast majority of tokens stall. Graduation is rare. This tutorial assumes the bonding stage is the destination, not a milestone. Building real utility into your agent is what gives the curve a reason to fill, not the launch itself.**Why bond a token to your agent?**@@ -96563,20 +97249,20 @@ A few legitimate reasons:- **Skin in the game for skill authors.** If your agent is monetized via paid skills or x402 endpoints, holders of the token participate in the upside of usage growth. See [paid-x402-endpoint](/tutorials/paid-x402-endpoint).- **Community ownership.** Anyone can buy. There is no allowlist, no KYC, no permission required. The set of holders becomes a public record on Solana.-- **A canonical pointer.** The mint address becomes the single canonical identifier for "this agent's token" — useful for treasury tools, voting, or distribution.+- **A canonical pointer.** The mint address becomes the single canonical identifier for "this agent's token", useful for treasury tools, voting, or distribution.- **Curiosity-driven distribution.** The three.ws Pump.fun feed surfaces new agent mints in real time, sending eyeballs to your agent page.None of these justify launching a token if your agent does not yet do anything users want. The launch is the easy part. The token is a wrapper around whatever utility already exists.----## Step 2 — Lock down name, ticker, and image+## Step 2: Lock down name, ticker, and imageBefore the launch dialog opens, decide three things and verify them.-**Name** — readable, related to your agent. If your agent's name is `Atlas Concierge`, a token name like `Atlas Concierge Token` or `Atlas` is fine. Names are not unique on Pump.fun; collisions are common. Don't fight over a generic name.+**Name**: readable, related to your agent. If your agent's name is `Atlas Concierge`, a token name like `Atlas Concierge Token` or `Atlas` is fine. Names are not unique on Pump.fun; collisions are common. Don't fight over a generic name.-**Ticker symbol** — 3 to 10 uppercase letters, ideally 3–5. The ticker is what traders type. `$ATLAS` is good; `$ACAGENTTOKEN` is bad.+**Ticker symbol**: 3 to 10 uppercase letters, ideally 3-5. The ticker is what traders type. `$ATLAS` is good; `$ACAGENTTOKEN` is bad.**Symbol availability check.** Pump.fun does not enforce ticker uniqueness, but the three.ws agent registry warns when a ticker is already used by another listed agent. Hit the platform's symbol-availability endpoint from your terminal:@@ -96586,31 +97272,31 @@ curl 'https://three.ws/api/x402/symbol-availability?symbol=ATLAS' \-H 'accept: application/json'```-The first call returns a 402 because the endpoint is paid (see [paid-x402-endpoint](/tutorials/paid-x402-endpoint) for the full flow). For a one-off check, the agent dashboard at `https://three.ws/dashboard` runs the same query for free against the cached symbol index — open your agent's settings, the Pump.fun tab includes an inline availability indicator.+The first call returns a 402 because the endpoint is paid (see [paid-x402-endpoint](/tutorials/paid-x402-endpoint) for the full flow). For a one-off check, the agent dashboard at `https://three.ws/dashboard` runs the same query for free against the cached symbol index, open your agent's settings, the Pump.fun tab includes an inline availability indicator.-**Image** — a square PNG or JPG, at least 512x512 pixels. This becomes the token's permanent icon on every Solana wallet, explorer, and aggregator. Once minted, you cannot change it. Use a stable, high-contrast asset; avoid text that gets crushed at 24px favicon sizes.+**Image**: a square PNG or JPG, at least 512x512 pixels. This becomes the token's permanent icon on every Solana wallet, explorer, and aggregator. Once minted, you cannot change it. Use a stable, high-contrast asset; avoid text that gets crushed at 24px favicon sizes.The image is uploaded to Pump.fun's storage and pinned. The CID is written into the SPL token's metadata account.----## Step 3 — Fund the wallet you'll launch from+## Step 3: Fund the wallet you'll launch fromOpen Phantom (or your wallet of choice). Switch the network to **Solana Mainnet**. Confirm the balance shows at least 0.05 SOL.If you need to fund the wallet:-- **From a centralized exchange** — Coinbase, Binance, Kraken, and most others let you withdraw SOL to a Solana address. Confirm you're withdrawing to **Solana mainnet** (not Wormhole-wrapped, not BSC, not Polygon). Withdrawals usually confirm in under a minute.-- **From another Solana wallet** — standard SPL transfer to your launch wallet's public key.-- **From a card** — Phantom and Solflare both support on-ramp via MoonPay / Coinbase Pay. Slower and more expensive (3–5% fee) but works in two minutes.+- **From a centralized exchange**: Coinbase, Binance, Kraken, and most others let you withdraw SOL to a Solana address. Confirm you're withdrawing to **Solana mainnet** (not Wormhole-wrapped, not BSC, not Polygon). Withdrawals usually confirm in under a minute.+- **From another Solana wallet**: standard SPL transfer to your launch wallet's public key.+- **From a card**: Phantom and Solflare both support on-ramp via MoonPay / Coinbase Pay. Slower and more expensive (3-5% fee) but works in two minutes.-Pump.fun charges a flat **0.02 SOL creation fee** plus a small Solana rent allocation (~0.003 SOL). The dev buy is optional but recommended — see Step 5. Reserve 0.005 SOL on top for transaction signing buffer.+Pump.fun charges a flat **0.02 SOL creation fee** plus a small Solana rent allocation (~0.003 SOL). The dev buy is optional but recommended, see Step 5. Reserve 0.005 SOL on top for transaction signing buffer.Once funded, **double-check the wallet's public key** matches the wallet you plan to connect to three.ws. The mint will be authored by whichever wallet signs the launch transaction. If that wallet is different from the one that owns your three.ws account, bonding the mint to the agent in Step 7 requires an extra signature linking the two.----## Step 4 — Open the Pump.fun launch flow on three.ws+## Step 4: Open the Pump.fun launch flow on three.wsNavigate to:@@ -96618,17 +97304,17 @@ Navigate to:https://three.ws/pumpfun```-This is the live Pump.fun feed. It shows every Pump.fun mint on Solana mainnet in real time, plus a separate ribbon for agent-bonded mints originating from three.ws agents. Watch the feed for thirty seconds — you will see new tokens scroll past every few seconds. Most are noise. The ribbon at the top is where your token will appear after launch.+This is the live Pump.fun feed. It shows every Pump.fun mint on Solana mainnet in real time, plus a separate ribbon for agent-bonded mints originating from three.ws agents. Watch the feed for thirty seconds, you will see new tokens scroll past every few seconds. Most are noise. The ribbon at the top is where your token will appear after launch.In the upper right of that page is a button **Launch your agent's token**. Click it.-You can also reach the same launch dialog from your dashboard at `https://three.ws/dashboard` — pick an agent, open its detail panel, and click **Mint Pump.fun token** on the right-side action rail. Both paths open the same modal.+You can also reach the same launch dialog from your dashboard at `https://three.ws/dashboard`, pick an agent, open its detail panel, and click **Mint Pump.fun token** on the right-side action rail. Both paths open the same modal.----## Step 5 — Fill in the launch form+## Step 5: Fill in the launch form-The launch modal has six fields. Fill them in deliberately — once the mint transaction confirms, none of them can be changed.+The launch modal has six fields. Fill them in deliberately, once the mint transaction confirms, none of them can be changed.**1. Agent.** A dropdown of your saved agents. Pick the one you want to bond the token to. The agent's name, avatar, and on-chain ID (if registered) appear in the preview pane on the right.@@ -96640,7 +97326,7 @@ The launch modal has six fields. Fill them in deliberately — once the mint tra**5. Description.** A 280-character bio that gets written into Pump.fun's token page. Treat this like a tweet. State what the agent does and link to its three.ws page if it has a public profile.-**6. Initial dev buy (optional).** A small SOL amount the form will use to immediately buy your own token after the mint succeeds. Setting this to **0.01–0.05 SOL** is conventional. Two reasons it helps:+**6. Initial dev buy (optional).** A small SOL amount the form will use to immediately buy your own token after the mint succeeds. Setting this to **0.01-0.05 SOL** is conventional. Two reasons it helps:- It sets a non-zero floor on the curve. A token with a zero-buy initial state looks abandoned in the feed and is easier to ignore.- It registers you as a holder. Some downstream tools (treasury dashboards, holder leaderboards) treat zero-balance creators differently from non-zero-balance creators.@@ -96651,9 +97337,9 @@ When everything looks right, click **Continue**.----## Step 6 — Sign the mint transaction+## Step 6: Sign the mint transaction-Phantom (or your connected wallet) pops a transaction prompt. It will be a complex transaction with multiple instructions — at minimum:+Phantom (or your connected wallet) pops a transaction prompt. It will be a complex transaction with multiple instructions, at minimum:1. Create the SPL mint account2. Initialize the Metaplex metadata account@@ -96661,16 +97347,16 @@ Phantom (or your connected wallet) pops a transaction prompt. It will be a compl4. Initialize the curve with the protocol's defaults5. If you set a dev buy: a buy instruction against the just-created curve-Phantom shows estimated SOL changes (negative — leaving your wallet) and the program IDs being invoked. The two you should expect to see are:+Phantom shows estimated SOL changes (negative: leaving your wallet) and the program IDs being invoked. The two you should expect to see are:- The Pump.fun program (a Solana mainnet program well-known to wallets; Phantom usually labels it)- The Metaplex Token Metadata programConfirm. The transaction signs and broadcasts. Pump.fun's program rents the mint account, initializes the curve, and returns the new mint address.-Confirmation on Solana mainnet typically lands in 5–10 seconds at the current slot time. The launch modal flips to a success state and displays:+Confirmation on Solana mainnet typically lands in 5-10 seconds at the current slot time. The launch modal flips to a success state and displays:-- The **mint address** (a base58 public key, 43–44 chars)+- The **mint address** (a base58 public key, 43-44 chars)- A link to **pump.fun** for the new token page- A link to **Solscan** for the mint account- A button **Bond this mint to your agent on three.ws**@@ -96679,13 +97365,13 @@ Copy the mint address. You'll want it.----## Step 7 — Bond the mint into the agent manifest+## Step 7: Bond the mint into the agent manifestThis is the step that makes the token *your agent's* token rather than a free-floating SPL mint that happens to share a name. Bonding writes the mint address into your agent's manifest under a `tokens.pumpfun` entry.Click **Bond this mint to your agent**.-If the wallet that signed the mint matches the wallet on your three.ws account, the modal writes the manifest server-side immediately. The agent's manifest is re-pinned and (if the agent is registered on-chain via ERC-8004) you'll be prompted to also update its on-chain `tokenURI` — see [register-onchain](/tutorials/register-onchain) for the registration mechanics.+If the wallet that signed the mint matches the wallet on your three.ws account, the modal writes the manifest server-side immediately. The agent's manifest is re-pinned and (if the agent is registered on-chain via ERC-8004) you'll be prompted to also update its on-chain `tokenURI`, see [register-onchain](/tutorials/register-onchain) for the registration mechanics.If the launching wallet is **different** from your three.ws account wallet (common when you launch from a hot wallet but the agent was created under your hardware wallet, for example), the modal asks for a **link signature**: a short SIWS (Sign-In With Solana) signature from the launching wallet proving you control the mint authority. Approve the signature in Phantom. The link costs no gas.@@ -96717,9 +97403,9 @@ The `graduated` field is updated automatically by a cron job that polls the bond----## Step 8 — Verify the listing in the feed+## Step 8: Verify the listing in the feed-Open `https://three.ws/pumpfun` again. Your token should appear in the **Agent-bonded** ribbon within thirty seconds — the feed is driven by a Helius webhook on the Pump.fun program plus a server-side filter that joins against bonded mints.+Open `https://three.ws/pumpfun` again. Your token should appear in the **Agent-bonded** ribbon within thirty seconds, the feed is driven by a Helius webhook on the Pump.fun program plus a server-side filter that joins against bonded mints.Click your token. The detail panel shows:@@ -96743,28 +97429,28 @@ This is the same data surfaced on the per-agent dashboard at:https://three.ws/pump-dashboard.html?agent=<your-agent-id>```-Open that page too. The pump-dashboard is the operator view — it shows aggregate trade volume, holder distribution (top holders, concentration warnings), and a chart of price + curve fill over time. Bookmark it.+Open that page too. The pump-dashboard is the operator view, it shows aggregate trade volume, holder distribution (top holders, concentration warnings), and a chart of price + curve fill over time. Bookmark it.----## Step 9 — Tell people the token exists+## Step 9: Tell people the token existsA token that nobody knows about does nothing. The launch is not the announcement.A reasonable sequence on launch day:1. **Update the agent's public card.** The three.ws agent page already shows the Pump.fun panel after bonding, but check it in an incognito tab to confirm.-2. **Post the agent URL** (not the bare Pump.fun URL — the agent URL frames it correctly). Example: "Just bonded a token to my agent. mint and chart on the page → https://three.ws/a/<chain>/<agentId>".+2. **Post the agent URL** (not the bare Pump.fun URL, the agent URL frames it correctly). Example: "Just bonded a token to my agent. mint and chart on the page → `https://three.ws/a/<chain>/<agentId>`".3. **Cross-post the Pump.fun link.** Some communities prefer the raw pump.fun page. Both are valid.4. **Pin the post.** Make it findable.-The three.ws feed handles in-platform discovery automatically — there's nothing extra to do to appear in the agent-bonded ribbon. External discovery (Twitter, Telegram, Farcaster) is on you.+The three.ws feed handles in-platform discovery automatically, there's nothing extra to do to appear in the agent-bonded ribbon. External discovery (Twitter, Telegram, Farcaster) is on you.What not to do: brigade groupchats begging for buys. Tokens that ride this pattern reliably stall and burn the creator's reputation.----## Step 10 — What graduation actually means+## Step 10: What graduation actually meansA Pump.fun token graduates when the bonding curve accumulates the protocol's graduation threshold of collected SOL. At that moment, atomically:@@ -96779,22 +97465,22 @@ The Pump.fun page for the token flips to a **Graduated** state and points to the----## Step 11 — Operate the token, don't promote it+## Step 11: Operate the token, don't promote itThe most useful thing you can do with a bonded agent token is make the agent more valuable. Concretely:- Ship more skills. Each new skill is a reason for an existing holder to keep holding and a new user to discover the agent. See [custom-skill](/tutorials/custom-skill) and [skill-with-database-auth](/tutorials/skill-with-database-auth).- Add a paid x402 endpoint that your agent calls and that you charge for. Revenue accrues to the operator wallet. See [paid-x402-endpoint](/tutorials/paid-x402-endpoint).- Register the agent on-chain via ERC-8004 so the token's holders have a verifiable identity to anchor reputation to. See [register-onchain](/tutorials/register-onchain).-- Surface the agent in more places. Embed it on your own site at a real domain — see [deploy-to-vercel-custom-domain](/tutorials/deploy-to-vercel-custom-domain).+- Surface the agent in more places. Embed it on your own site at a real domain, see [deploy-to-vercel-custom-domain](/tutorials/deploy-to-vercel-custom-domain).The token will follow the utility, not the other way around. A creator who keeps the agent improving keeps the holders interested.----## Step 12 — Reading the bonding curve programmatically+## Step 12: Reading the bonding curve programmatically-If you want to build something on top of your token — a trading bot, a holder-gated chat, an automated buyback funded by skill revenue — you'll need to read the curve state directly.+If you want to build something on top of your token, a trading bot, a holder-gated chat, an automated buyback funded by skill revenue, you'll need to read the curve state directly.The three.ws API exposes a normalized view of any bonded curve at:@@ -96824,11 +97510,11 @@ The response includes the curve account's raw fields plus computed helpers:`graduationProgress` is a float between 0 and 1; multiply by 100 for a percentage. `complete` flips to `true` after graduation and stays there. For a holder count, hit `https://three.ws/api/pump/dashboard?agent=<agentId>`.-If you need raw on-chain reads, point any Solana RPC client (Helius, Triton, or the public mainnet RPC for low-volume use) at the Pump.fun program ID and decode the bonding curve account with the program's published IDL. The three.ws endpoint is just a normalized, rate-limit-friendly convenience layer over that same on-chain data — every field is derivable yourself if you don't want to depend on the platform.+If you need raw on-chain reads, point any Solana RPC client (Helius, Triton, or the public mainnet RPC for low-volume use) at the Pump.fun program ID and decode the bonding curve account with the program's published IDL. The three.ws endpoint is just a normalized, rate-limit-friendly convenience layer over that same on-chain data, every field is derivable yourself if you don't want to depend on the platform.----## Step 13 — Sell pressure, doxx pressure, and other things to be ready for+## Step 13: Sell pressure, doxx pressure, and other things to be ready forA few realities of operating a public token, in roughly the order you'll encounter them:@@ -96836,7 +97522,7 @@ A few realities of operating a public token, in roughly the order you'll encount**Concentration.** If a single wallet holds more than ~5% of the supply, watch it. The pump-dashboard surfaces top holders. If the concentration moves into worrying territory, decide whether to do anything about it (typically: nothing).-**Impersonation.** Other creators may mint tokens with your agent's name or ticker. Pump.fun does not enforce uniqueness. Your agent's three.ws card is the canonical link — point people there.+**Impersonation.** Other creators may mint tokens with your agent's name or ticker. Pump.fun does not enforce uniqueness. Your agent's three.ws card is the canonical link, point people there.**Telegram/Discord requests for "calls."** Trading communities will ask you to coordinate buys. Don't. It is securities-promotion-adjacent in many jurisdictions, and it produces short-lived spikes followed by long drawdowns.@@ -96846,14 +97532,14 @@ A few realities of operating a public token, in roughly the order you'll encount## Legal note (read this)-Pump.fun tokens trade on a permissionless protocol. Once launched, the token exists, anyone can buy or sell it, and nobody — including you, Pump.fun, or three.ws — can pause it, reverse trades, or recall supply. The platform is a launchpad, not a gatekeeper.+Pump.fun tokens trade on a permissionless protocol. Once launched, the token exists, anyone can buy or sell it, and nobody, including you, Pump.fun, or three.ws, can pause it, reverse trades, or recall supply. The platform is a launchpad, not a gatekeeper.Some practical implications:- **You are responsible for what you launch.** Three.ws does not vet token names, descriptions, or claims attached to a bonded mint. If you launch a token impersonating someone, promising returns, or otherwise breaking the law of your jurisdiction, that is on you.- **Tokens are not securities offerings by us.** Three.ws is software that integrates with the Pump.fun protocol. We do not custody, broker, or guarantee anything about any token launched through that integration. The same is true of the Pump.fun protocol itself.- **Some jurisdictions restrict promotion.** Even talking about "buying $TICKER" online, in some jurisdictions, can be regulated. Especially if you are paid to do so. Read the rules where you live.-- **Reversibility is zero.** A typo in the ticker is permanent. A wrong image is permanent. The mint authority is, by default, retained by the creator wallet and can be renounced — many creators renounce immediately to signal they cannot mint more supply. Renouncing is irreversible.+- **Reversibility is zero.** A typo in the ticker is permanent. A wrong image is permanent. The mint authority is, by default, retained by the creator wallet and can be renounced, many creators renounce immediately to signal they cannot mint more supply. Renouncing is irreversible.If you have a lawyer, talk to them before launching. If you don't, default to the conservative interpretation: launch a token only if your agent is providing genuine, ongoing utility, and only if you're comfortable with all of the above being permanent and public.@@ -96866,14 +97552,14 @@ If you have a lawyer, talk to them before launching. If you don't, default to th- How the bonded mint surfaces in the live feed, the agent's public card, and the dashboard- How to read curve state programmatically via `https://three.ws/api/pump/curve`- The operational realities of owning a public, irreversible, permissionless token-- The legal posture you should adopt — not legal advice, but a reasonable default+- The legal posture you should adopt: not legal advice, but a reasonable default## Next steps-- Register the agent on-chain so the token has a verified identity anchor — [register-onchain](/tutorials/register-onchain).-- Add a paid x402 endpoint and route revenue to the token's operator wallet — [paid-x402-endpoint](/tutorials/paid-x402-endpoint).-- Build a database-backed skill that uses the token as an access gate — [skill-with-database-auth](/tutorials/skill-with-database-auth).-- Coordinate the agent with a second one for richer interactions — [multi-agent-coordination](/tutorials/multi-agent-coordination).+- Register the agent on-chain so the token has a verified identity anchor, [register-onchain](/tutorials/register-onchain).+- Add a paid x402 endpoint and route revenue to the token's operator wallet, [paid-x402-endpoint](/tutorials/paid-x402-endpoint).+- Build a database-backed skill that uses the token as an access gate, [skill-with-database-auth](/tutorials/skill-with-database-auth).+- Coordinate the agent with a second one for richer interactions, [multi-agent-coordination](/tutorials/multi-agent-coordination).---@@ -97282,12 +97968,12 @@ A two-agent layout where both characters are always visible. Riley on the left,<div class="stage"><div id="riley-stage" class="active"><h3>Riley · Sales</h3>- <agent-3d id="riley" agent-id="<RILEY_AGENT_ID>" avatar-chat="off" voice eager+ <agent-3d id="riley" agent-id="<RILEY_AGENT_ID>" chat="off" voice eagerstyle="width:100%;height:100%"></agent-3d></div><div id="devon-stage"><h3>Devon · Engineering</h3>- <agent-3d id="devon" agent-id="<DEVON_AGENT_ID>" avatar-chat="off" voice eager+ <agent-3d id="devon" agent-id="<DEVON_AGENT_ID>" chat="off" voice eagerstyle="width:100%;height:100%"></agent-3d></div></div>@@ -97300,7 +97986,7 @@ A two-agent layout where both characters are always visible. Riley on the left,</html>```-One loader `<script>` in the `<head>` registers the `<agent-3d>` element; two tags with `agent-id` attributes point at your saved agents. Three attribute choices matter here: `avatar-chat="off"` hides each agent's built-in chat input (this page has its own shared composer), `voice` enables text-to-speech so the avatars actually speak their replies (and fire the `voice:speech-start`/`voice:speech-end` events we lean on later), and `eager` boots both agents immediately instead of waiting for them to scroll into view. `coordinator.js` is the file we'll write next.+One loader `<script>` in the `<head>` registers the `<agent-3d>` element; two tags with `agent-id` attributes point at your saved agents. Three attribute choices matter here: `chat="off"` renders each agent as a bare avatar with no built-in chat shell (this page has its own shared composer), `voice` enables text-to-speech so the avatars actually speak their replies (and fire the `voice:speech-start`/`voice:speech-end` events we lean on later), and `eager` boots both agents immediately instead of waiting for them to scroll into view. `coordinator.js` is the file we'll write next.Replace `<RILEY_AGENT_ID>` and `<DEVON_AGENT_ID>` with the actual agent IDs from your dashboard. They're displayed under each agent in `https://three.ws/dashboard`.@@ -97494,7 +98180,7 @@ function buildBrief(scratch, target) {}```-`targetEl.say(brief)` pushes the brief into the target agent's conversation as an ordinary message — there is no separate system-role channel, which is exactly why `buildBrief` wraps the transcript in an explicit `[Stage director: …]` framing: the model reads the bracketed preamble as direction rather than visitor speech, and responds with its next visitor-facing message. Because both elements run with `avatar-chat="off"`, the brief never renders anywhere the visitor can see; the only transcript on the page is the one your `brain:message` handler builds in the log.+`targetEl.say(brief)` pushes the brief into the target agent's conversation as an ordinary message. There is no separate system-role channel, which is exactly why `buildBrief` wraps the transcript in an explicit `[Stage director: …]` framing: the model reads the bracketed preamble as direction rather than visitor speech, and responds with its next visitor-facing message. Because both elements run with `chat="off"`, the brief never renders anywhere the visitor can see; the only transcript on the page is the one your `brain:message` handler builds in the log.---@@ -98125,7 +98811,7 @@ Good candidates in 2026, with concrete examples already running in production:- **Reputation lookup.** `/api/x402/agent-reputation` — pulls an ERC-8004 agent's review history from on-chain and returns aggregate scores.- **Symbol availability.** `/api/x402/symbol-availability` — checks whether a Pump.fun ticker is already used by another agent in the registry.-This tutorial builds **a simplified model-check endpoint**. The full production version is at `/workspaces/three.ws/api/x402/model-check.js` in the three.ws repo — read it for reference. We'll build a leaner version end-to-end that's easier to follow.+This tutorial builds **a simplified model-check endpoint**. The full production version is at [`api/x402/model-check.js`](https://github.com/nirholas/three.ws/blob/main/api/x402/model-check.js) in the three.ws repo. Read it for reference. We'll build a leaner version end-to-end that's easier to follow.The work: take a `?url=` query param pointing at a glTF or GLB file, fetch it, count primitives and materials, return JSON. Price: $0.001 USDC per call (1000 micro-USDC).@@ -100129,14 +100815,28 @@ that never fills is not being cautious, it is stuck.## Step 7: Verify anything you doubt on-chainEvery fill is signed by the agent's own wallet, so nothing here has to be taken-on trust. The leaderboard exposes each agent's wallet and an explorer link:+on trust. The same response carries a `trades` array, and every trade links both+legs straight to Solscan:```bashcurl -s 'https://three.ws/api/sniper/leaderboard?window=all' \- | jq '.leaderboard[] | {agent_name, wallet, wallet_explorer_url}'+ | jq '.trades[] | {agent_name, symbol, pnl_sol, exit_reason, buy_url, sell_url}'```-Open the explorer link and the transactions are there in the order the platform+To go the other way, from an agent to its whole on-chain history, take the wallet+off the leaderboard row and open it in an explorer:++```bash+curl -s 'https://three.ws/api/sniper/leaderboard?window=all' \+ | jq -r '.leaderboard[] | select(.wallet and .wallet != "pending")+ | "\(.agent_name)\thttps://solscan.io/account/\(.wallet)"'+```++That filter is not decoration. An agent whose wallet has not been provisioned yet+reports `null`, and one mid-provision reports the literal string `"pending"`.+Both would otherwise build an explorer URL that resolves to nothing.++Open either link and the transactions are there in the order the platformclaims. If a number on a three.ws page ever disagrees with the chain, the chain isright and it is a bug worth reporting.@@ -100901,10 +101601,11 @@ curl -sL -D - -o small.glb "$REMY" | grep -i 'x-three-ws'```x-three-ws-source-bytes: 20566060-x-three-ws-output-bytes: 1737840+x-three-ws-output-bytes: 1479972+x-three-ws-optimize: none```-20.6 MB down to 1.7 MB, a 92% cut, mostly from capping textures at 512px and dropping non-ARKit morph targets. `textureSize` accepts `128`, `256`, `512`, `1024`, `2048`; `lod=1` or `lod=2` adds progressively more aggressive welding; `morphs=arkit52` drops every morph target outside the standard set. `src` must be on a three.ws-controlled origin (the app origin or the CDN host), otherwise it is `400 untrusted_source`. Full parameter list in the [Media & Render API reference](/docs/media-api.md).+20.6 MB down to 1.5 MB, better than a 90% cut, mostly from capping textures at 512px and dropping non-ARKit morph targets. Read the two byte headers rather than the numbers printed here: the exact output size moves as the pipeline improves. `x-three-ws-optimize` names the mesh-compression scheme that survived (`draco`, `meshopt`, `none`, or `source` when the pipeline could not beat the original and handed the source bytes back untouched); `none` here means the saving came from textures and morphs alone. `textureSize` accepts `128`, `256`, `512`, `1024`, `2048`; `lod=1` or `lod=2` adds progressively more aggressive welding; `morphs=arkit52` drops every morph target outside the standard set. `src` must be on a three.ws-controlled origin (the app origin or the CDN host), otherwise it is `400 untrusted_source`. Full parameter list in the [Media & Render API reference](/docs/media-api.md).Best part: the optimizer's own URL is a public https URL, so you can hand it straight to the renderer and never store an intermediate file.@@ -101077,9 +101778,9 @@ This is the heaviest tutorial in the Advanced tier. It's worth doing in full if**What you'll build:**-- A local development setup running the full stack (front-end + Vercel functions + Cloudflare workers + database)+- A local development setup running the full stack (front-end + Vercel functions + database + object storage)- A production deployment on Vercel under a custom domain-- Cloudflare workers proxying Anthropic and OpenAI traffic with your own keys+- Anthropic and OpenAI served from your own keys, held server-side in your deployment- An `agent-3d.js` embed script served from your CDN, so embeds on third-party sites point at *your* infrastructure- The full set of environment variables wired correctly across local, preview, and production- A hardening pass: CORS, rate limiting, secret hygiene, audit logging@@ -101109,10 +101810,12 @@ The platform is intentionally composed of small, independently deployable servic**Serverless functions (Vercel).** Everything under `api/`. Each `.js` file is a Vercel function. These handle: agent CRUD, MCP server endpoint, x402 paid endpoints, ERC-8004 prep/confirm flows, Pump.fun integration, OAuth callbacks, signed-URL avatar storage, etc. The file path is the route — `api/agents.js` becomes `/api/agents`.-**Cloudflare workers (`workers/`).** Edge proxies in front of model providers. The two important ones are:+**Workers (`workers/`).** Everything that doesn't fit in a serverless function. Two distinct kinds live here:++- **The Pump.fun MCP worker** (`workers/pump-fun-mcp/`), the one Cloudflare Worker in the tree. It maintains live websocket connections to the Pump.fun program, which Vercel functions can't hold cheaply.+- **GPU model workers** (`workers/model-trellis/`, `workers/rig/`, `workers/remesh/`, and about two dozen more), containers that run 3D generation, rigging, and mesh processing. Each deploys from its own `cloudbuild.yaml` and is only needed if you want the Forge feature it backs.-- A general LLM proxy that fronts Anthropic and OpenAI: rate-limits per agent, redacts logs, and lets you swap keys without redeploying the platform-- A Pump.fun MCP worker that maintains live websocket connections to the Pump.fun program (Vercel functions can't hold long-lived sockets cheaply)+Model-provider traffic does *not* go through a worker: Anthropic and OpenAI are called directly from the serverless functions, with the keys held in the deployment env.**Database (Postgres).** Stores agents, manifests, accounts, sessions, audit logs, skill access grants, x402 receipts. Schema is checked in.@@ -101122,7 +101825,7 @@ The platform is intentionally composed of small, independently deployable servic**Embed bundle (`/agent-3d/<version>/agent-3d.js`, also `/dist-lib/agent-3d.js`).** The `<agent-3d>` custom-element bundle, built by `npm run build:lib` from `src/lib.js` into `dist-lib/` and served from the same deployment. Third-party sites load this script tag and your domain ends up in their `<script src="...">`.-Everything except the database and Cloudflare workers can live on a single Vercel project. The minimum production deployment is: 1 Vercel project, 1 Cloudflare worker, 1 Postgres database, 1 R2 bucket.+Everything except the database, object storage, and the workers can live on a single Vercel project. The minimum production deployment is: 1 Vercel project, 1 Postgres database, 1 bucket. No worker is required for the core agent loop; add them only for the Pump.fun feed and the Forge.---@@ -101185,19 +101888,21 @@ Copy the connection string. It looks like `postgresql://user:pass@host/db?sslmod**Supabase.** Works fine; use the "transaction" pooler URL, not the direct URL, to avoid connection limits in serverless.-Once you have a connection string, run the schema:+Once you have a connection string, put it in your env file as `DATABASE_URL` and bootstrap the database:```bash-psql "$DATABASE_URL" -f api/_lib/schema.sql+npm run db:bootstrap```+Do not apply `api/_lib/schema.sql` by hand. The core schema is only the first of four steps: `db:bootstrap` runs `api/_lib/schema.sql`, then `specs/schema/indexer_state.sql`, then `specs/schema/agent_delegations.sql`, then every incremental migration in `api/_lib/migrations/`. The order matters because later migrations `ALTER` tables the base files create, and a `psql -f schema.sql` alone leaves you with a database that is missing most tables. Every step is idempotent, so re-running it on a live database is a no-op.+Confirm the tables exist:```bashpsql "$DATABASE_URL" -c "\dt"```-You should see tables like `agents`, `accounts`, `sessions`, `audit_log`, `x402_receipts`, `skill_grants`, etc.+You should see tables like `users`, `sessions`, `avatars`, `agent_identities`, `usage_events`, `audit_log`, and `x402_receipts`, plus everything the migrations add (`forge_creations`, `agent_custody_events`, and so on).---@@ -101232,19 +101937,18 @@ cp .env.example .env.developmentOpen `.env.development` and fill in the values. The file is long; here's the irreducible minimum to get local dev running:-```env-# Front-end-VITE_API_BASE=http://localhost:3000+There is deliberately no front-end API-base variable. The embed bundle derives its API origin from the script's own URL at runtime (Step 11), so nothing about the front-end is baked in at build time.+```env# DatabaseDATABASE_URL=postgresql://...-# Object storage-R2_ENDPOINT=https://<account-id>.r2.cloudflarestorage.com-R2_BUCKET=three-ws-fork-assets-R2_ACCESS_KEY_ID=<from cloudflare>-R2_SECRET_ACCESS_KEY=<from cloudflare>-R2_PUBLIC_BASE=https://pub-<id>.r2.dev # the bucket's public hostname+# Object storage (S3-compatible; R2 is just one provider that fits)+S3_ENDPOINT=https://<account-id>.r2.cloudflarestorage.com+S3_BUCKET=three-ws-fork-assets+S3_ACCESS_KEY_ID=<from cloudflare>+S3_SECRET_ACCESS_KEY=<from cloudflare>+S3_PUBLIC_DOMAIN=https://pub-<id>.r2.dev # the bucket's public hostname# Model providers (used by the chat function and the worker proxy)ANTHROPIC_API_KEY=sk-ant-...@@ -101260,19 +101964,16 @@ X402_ASSET_ADDRESS_BASE=0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913X402_MAX_AMOUNT_REQUIRED=1000CDP_API_KEY_ID=CDP_API_KEY_SECRET=-X402_CDP_FACILITATOR_URL=https://api.cdp.coinbase.com/platform/v2/x402+X402_CDP_FACILITATOR_URL=https://api.cdp.coinbase.com/platform/v2/x402/facilitatorX402_FACILITATOR_URL_BASE=https://facilitator.payai.networkX402_FACILITATOR_URL_SOLANA=https://facilitator.payai.network-# Session/CSRF secrets — generate fresh with `openssl rand -hex 32`+# Session secret. Generate fresh with `openssl rand -hex 32`SESSION_SECRET=<random hex>-CSRF_SECRET=<random hex>--# Cloudflare worker URLs (set after Step 7)-LLM_WORKER_URL=-PUMPFUN_MCP_WORKER_URL=```+CSRF protection is on by default and derives its token from the session, so there is no separate CSRF secret to set. `CSRF_DISABLED=1` exists as a local-debugging escape hatch; never set it in a deployed environment.+The exhaustive list of env vars is in `.env.example`. Most are optional — you can leave them empty until you need the feature they unlock. For example, you don't need `HELIUS_API_KEY` to run an agent; you only need it if you're enabling the Pump.fun live feed.Do **not** commit `.env.development`. It's in `.gitignore` already; double-check with `git status`.@@ -101293,7 +101994,7 @@ In another terminal, sanity-check the API:curl http://localhost:3000/api/healthz```-You should see `{"ok": true}` or similar.+You should get a JSON body starting `{"status":"ok","service":"3d-agent",...}`, with `uptime`, the resolved `version`, and a per-subsystem readiness block (`x402`, mail, and so on). Anything other than `"status":"ok"` names the subsystem that is unhappy.Now open `http://localhost:3000` in a browser. You should land on the platform's home page. Click into the editor — drag any GLB onto it — confirm the avatar loads. Open DevTools → Console. **There should be no red errors.** If there are, the most common causes:@@ -101307,38 +102008,27 @@ If the avatar loads and you can send a chat message that gets a real model respo## Step 7 — Deploy the Cloudflare workers-The LLM proxy worker lives at `workers/` (alongside the strategy executor). The proxy is responsible for:--- Holding the production Anthropic/OpenAI keys server-side-- Rate-limiting per agent (so a runaway agent doesn't bankrupt your provider budget)-- Streaming responses back to the browser-- Stripping or appending headers as required+**There is no LLM proxy worker to deploy.** Model traffic is served by the platform's own serverless functions: `api/chat.js` and `api/brain/chat.js` route through `api/_lib/llm.js` and `api/llm/anthropic.js`, reading `ANTHROPIC_API_KEY` and `OPENAI_API_KEY` from the deployment env. Keys stay server-side, rate limiting is enforced by `api/_lib/rate-limit.js` (Step 13), and streaming is handled in the function. Setting those two keys in Step 5 is all the wiring the chat path needs, so this step is optional.-Configure and deploy:+The one Cloudflare worker in the tree is the Pump.fun MCP worker, which exists because Vercel functions cannot hold long-lived websockets cheaply. Deploy it only if you want the Pump.fun live feed:```bash-cd workers-cp wrangler.example.toml wrangler.toml+cd workers/pump-fun-mcp```-Edit `wrangler.toml` and fill in your worker name and the secrets bindings. The example file lists the required vars: `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, plus optional Helius keys for the Pump.fun worker.--Set secrets via wrangler (don't put them in `wrangler.toml`):+Its `wrangler.toml` is committed and already configured; every variable is optional and documented in the comment block at the top of that file and in its `README.md`. Set the ones you want as secrets rather than editing them into the file:```bash-wrangler secret put ANTHROPIC_API_KEY-wrangler secret put OPENAI_API_KEY+npx wrangler@4 secret put SOLANA_RPC_URL```Deploy:```bash-wrangler deploy+npx wrangler@4 deploy```-You'll get a URL like `https://three-ws-llm.<account>.workers.dev`. Put that into your `.env.development` and (later) your Vercel project as `LLM_WORKER_URL`.--If you're running the Pump.fun feed, repeat for `workers/pump-fun-mcp/`.+You'll get a URL like `https://pump-fun-mcp.<account>.workers.dev`. The worker is reached directly by the surfaces that use it; there is no worker-URL env var to thread back into the platform.---@@ -101359,13 +102049,7 @@ This builds:- The `<agent-3d>` embed bundle into `dist-lib/agent-3d.js` (ES module; `npm run build:lib:full` adds the UMD build)- The chat sub-app into `dist/chat/` (via `npm run build:chat`)-Look at `dist/` — there should be an `index.html`, hashed bundles, and the various sub-apps, with the embed bundle in `dist-lib/`. If the build prints warnings about missing env vars (e.g., `VITE_*` vars that the front-end reads at build time), set them before re-running:--```bash-VITE_API_BASE=https://<your-domain>.vercel.app npm run build-```--For preview/staging builds the API base can point at the preview deployment; for production, point it at the final domain.+Look at `dist/`. There should be an `index.html`, hashed bundles, and the various sub-apps, with the embed bundle in `dist-lib/`. Nothing about the API origin is baked in at build time, so the same `dist/` is valid on preview and production alike; the bundle resolves its origin at runtime (Step 11). The handful of `VITE_*` vars that *are* read at build time are third-party client IDs (`VITE_PRIVY_APP_ID`, `VITE_WALLETCONNECT_PROJECT_ID`, `VITE_AVATURN_DEVELOPER_ID`), and each only gates the feature it belongs to. Set the ones whose features you want before re-running the build.---@@ -101391,8 +102075,8 @@ cat .env.production | vercel env import productionA few env vars that have to be set per-environment:-- `VITE_API_BASE` — must be the public URL of *that* environment (preview, production, etc.)-- `SESSION_SECRET`, `CSRF_SECRET` — use **different secrets per environment**. Don't reuse production secrets in preview.+- `DATABASE_URL`: point preview at a Neon branch database, never at the production one+- `SESSION_SECRET`: use a **different secret per environment**. Don't reuse the production secret in preview.- `X402_PAY_TO_BASE` — use **different wallets per environment** so you can identify which environment generated which receipt.Deploy a preview to validate:@@ -101507,7 +102191,7 @@ Without Redis, the in-memory fallback works for a single Vercel function instancA few non-negotiables for the env vars you just set:- **Never commit any of them.** `.env.development`, `.env.preview`, `.env.production` are all gitignored. Confirm with `git check-ignore .env.production`.-- **Rotate on personnel changes.** If anyone with access leaves the project, rotate `SESSION_SECRET`, `CSRF_SECRET`, the LLM keys, and the wallet private keys.+- **Rotate on personnel changes.** If anyone with access leaves the project, rotate `SESSION_SECRET`, the LLM keys, and the wallet private keys.- **Use separate keys per environment.** Don't share `ANTHROPIC_API_KEY` between local dev and production — it makes log attribution impossible and one buggy local script can torch the production rate-limit window.- **Sweep wallet balances.** `X402_PAY_TO_BASE` receives USDC. Sweep to a cold address daily or set up an automated sweep transaction.- **CDP keys are sensitive.** Treat them like AWS keys. Coinbase rotates them via the dashboard at any time.@@ -101516,22 +102200,25 @@ A few non-negotiables for the env vars you just set:## Step 15 — Hardening: audit logging-`api/_lib/audit.js` writes structured records to the `audit_log` table. The platform already writes audit entries for: agent creation, manifest changes, on-chain registrations, x402 payments, skill grants, account-level writes.+`api/_lib/audit.js` writes structured records to the `audit_log` table (created by `api/_lib/migrations/2026-05-01-audit-log.sql`, which `db:bootstrap` applied in Step 3).-In your fork, you'll add audit entries for your own routes:+In your fork, you'll add audit entries for your own routes. `logAudit` is fire-and-forget: it never throws and never adds database latency to the response.```js-import { audit } from './_lib/audit.js';--await audit({- actor: auth.userId, // or wallet address, or null for unauthenticated- action: 'custom.action',- target: targetId,- meta: { request: summarize(req.body) },+import { logAudit } from './_lib/audit.js';++logAudit({+ userId: auth.userId, // null when the actor is unknown or the system+ action: 'delete_avatar', // short kebab-case verb+ resourceId: targetId,+ meta: { reason }, // small JSON blob; avoid PII+ req, // captures IP + user agent});```-Hard rule: every mutation to a user-visible record must produce an audit row. The point isn't compliance for its own sake — it's that when something weird happens (a manifest gets corrupted, a wallet drains, an admin role is granted), the audit trail is the only artifact that survives.+There is an awaitable twin, `logAuditNow(entry)`, which resolves `true` when the row landed and `false` when it was dropped. Use it only where the row itself is the deliverable and the caller reports that outcome (the legal-acceptance endpoints do); everything else wants `logAudit`.++The policy the platform follows: log sensitive state changes that need an after-the-fact "who did what, when" trail: deletions, revocations, ownership transfers. Reads, idempotent updates, and analytics belong in `usage_events` instead, so the audit trail stays legible. The point isn't compliance for its own sake. It's that when something weird happens (a manifest gets corrupted, a wallet drains, an admin role is granted), the audit trail is the only artifact that survives.Export the audit log to long-term storage if your compliance demands it. The schema is plain Postgres; `pg_dump` works.@@ -101570,7 +102257,7 @@ npm run build # confirm it still buildsgit push origin main```-Vercel auto-redeploys. New schema migrations (if any) land in `api/_lib/migrations/` — re-run them against your database. The repo uses simple forward-only SQL migrations; check the directory's README for the runner script.+Vercel auto-redeploys. New schema migrations (if any) land in `api/_lib/migrations/` as forward-only SQL. Preview what an upstream merge brought in with `npm run db:status`, then apply it with `npm run db:migrate`. Read the status output first: `db:migrate` applies immediately with no dry run, and it applies *every* pending migration, not just the ones you were expecting.If you've forked aggressively and diverged, you may want to keep your changes in a long-running `your-company/main` branch and merge from `upstream/main` periodically with a clear strategy (e.g., quarterly cadence, with a dedicated "merge upstream" PR).@@ -101584,9 +102271,8 @@ Before you point real traffic at your deployment, walk through this list. If any- `npm run build` passes locally with production env- `/api/healthz` returns 200 on the production URL- A test agent can be created, edited, saved, and embedded-- The LLM proxy worker is deployed and `LLM_WORKER_URL` points to it-- A test chat message gets a real model response in production-- Database schema matches `api/_lib/schema.sql` (run `pg_dump --schema-only` and diff)+- `ANTHROPIC_API_KEY` and `OPENAI_API_KEY` are set in production, and a test chat message gets a real model response there+- `npm run db:status` reports no pending migrations against the production database- Upstash rate-limiting is wired (or you have a clear plan for when to add it)- `X402_PAY_TO_BASE` is a wallet you control and the private key is held securely (hardware wallet, KMS, or equivalent — *not* in plaintext anywhere)- CDP keys are set so x402 settlements route through CDP (otherwise endpoints don't get cataloged in agentic.market)@@ -101605,7 +102291,9 @@ A few things you should know going in:**Some upstream features require platform-only secrets.** The hosted three.ws has access to API keys and wallets that aren't published. If you fork, those features (e.g., the platform-managed agent treasury) won't work as-is — you'll either disable them or wire your own equivalents. The code paths that depend on platform secrets are clearly conditional on env-var presence; if your env var is empty, the feature is hidden in the UI.-**You become responsible for security patches.** Vercel handles its own infrastructure. You handle the application code. Subscribe to GitHub Dependabot alerts on your fork. The repo lists Apache-2.0 as its license — you can ship patches yourself, but you should also feed them upstream if they're not specific to your deployment.+**Check the license before you deploy anything.** The repo's `LICENSE` is proprietary, not open source: "All rights reserved", with use, copying, modification, and distribution requiring the copyright owner's express written permission. Reading the source is not the same as being licensed to run a fork of it, so get that permission in writing before you stand up a deployment. Everything below assumes you have it.++**You become responsible for security patches.** Vercel handles its own infrastructure. You handle the application code. Subscribe to GitHub Dependabot alerts on your fork, and feed fixes back upstream when they aren't specific to your deployment.**Cost shapes:**@@ -101622,7 +102310,7 @@ A self-hosted instance with light traffic runs at $20–50/month all-in. The dom## What you learned-- The component breakdown: front-end, Vercel functions, Cloudflare workers, Postgres, R2, CDN+- The component breakdown: front-end, Vercel functions, workers, Postgres, object storage, CDN- How to bring up a development instance with a real database, real model providers, and real wallets- How to deploy to production on Vercel with your own domain and CDN- How to swap the CDN base so third-party embeds point at your infrastructure@@ -101840,7 +102528,8 @@ Because the output is a clean, rigged glTF 2.0 file, it isn't locked to three.ws- **Animate it** in the [Animation Studio](/pose) — load it, browse the clip gallery, and retarget motion onto it live. It works because it's rigged.- **Download the GLB** from the avatar page to use it in Unity, Unreal, Blender, or any glTF-aware tool.- **Embed it** on a website with the web component — see [Embed in 30 seconds](/tutorials/embed-in-30-seconds).-- **Refine the look** with [Customize your agent's appearance](/tutorials/customize-appearance) — clothing, accessories, and more layer on without re-rigging.+- **Refine the look** in the avatar editor at `/avatars/<id>/edit`. Clothing and accessories layer on top of the GLB without re-rigging it; [Avatar Creation](#sec-108) documents how that layering works.+- **Tune how it looks on your site** with [Customize size, position and background](/tutorials/customize-appearance), which covers the embed's layout, framing, and backdrop.---@@ -101889,7 +102578,7 @@ The result is a standard `.glb` that animates in the [Animation Studio](/pose),- [Turn Photos into a 3D Model](/tutorials/image-to-3d) — reconstruct an *object* (not a person) from a few photos in the Forge.- [Animate your avatar](/tutorials/animate-your-avatar) — apply and tune motion on the rigged avatar you just built.- [Avatar Creation](#sec-108) — the full reference: every creation path, rig requirements, and accessories.-- [Customize your agent's appearance](/tutorials/customize-appearance) — clothing, accessories, and styling on top of your avatar.+- [Customize size, position and background](/tutorials/customize-appearance): how the finished avatar is framed and placed once it is embedded on a page.- [Give your agent a personality](/tutorials/agent-personality) — turn the body into a character.---@@ -102135,18 +102824,18 @@ Go to [https://three.ws/my-agents](https://three.ws/my-agents). Sign in if you'rYou see a grid of every agent you own. Click the agent you want to share. The agent's profile page opens at a URL of this shape:```-https://three.ws/agent/<id>+https://three.ws/agent/d94d2a50-86fa-4d2e-b87b-580f7517aa4c```-The `<id>` is your agent's permanent identifier. It looks like a hex string or a slugified handle, depending on how the agent was created. Copy the full URL from the browser's address bar — that's the canonical public link.+The `<id>` is your agent's permanent identifier: a UUID, assigned when the agent is first saved. Copy the full URL from the browser's address bar and it works forever.A few practical notes:- **The URL is permanent.** It does not change when you update the agent's body, personality, name, or skills. Embeds, QR codes, business cards, and conference badges you produce today remain valid indefinitely.-- **The URL is public.** Anyone with the link can open it. There is no login required to talk to a public agent.-- **The URL is canonical.** Even if the platform's user-facing URL structure ever evolves, the agent ID itself is a stable platform reference. Old links continue to redirect.+- **The URL is public.** Anyone with the link can open it. There is no login required to talk to an agent.+- **`/agent/<id>` redirects to `/agents/<id>`.** The profile page's canonical address is the plural form, and the singular one issues a permanent redirect to it. Both are safe to hand out; links printed years ago keep resolving.-If you ever forget the URL, the "Copy share link" button on the agent profile page copies the canonical version to your clipboard.+There is a **Share** button on the profile page: one floating above the fold on the hero, one in the action row. Either opens a share panel that shows the exact card your link will unfurl as, with **Copy link**, **Share on X**, **Share on Farcaster**, and **Remix in three.ws**. The link it copies is the share URL from Step 3, not the bare profile URL, because that is the one carrying the rich preview.Every public agent is also in the platform's own directory, which is a plain open endpoint. Press the button and you are looking at the live directory, portrait and all, the way it exists as you read this:@@ -102218,57 +102907,81 @@ Don't tint both foreground and background; the contrast will drop too low and scWhen you paste your agent URL into iMessage, WhatsApp, Slack, Discord, Telegram, Twitter / X, LinkedIn, Bluesky, Mastodon — every modern chat and social platform fetches the URL, extracts a preview, and shows the recipient a card with a title, description, and image. The right preview can be the difference between a recipient clicking the link and ignoring it.-three.ws sets Open Graph and Twitter Card meta tags automatically on every agent page. You do not need to configure anything for the previews to work — they ship by default.+three.ws builds those tags automatically. You do not configure anything for the previews to work, but you do need to share the right URL.++### Share the `/share` URL, not the bare profile URL++The agent profile page at `/agent/<id>` is a JavaScript app. Its HTML carries the generic three.ws card, because at the moment a crawler fetches it, the page has not yet loaded which agent it is about. So the platform serves a second, server-rendered address purely for crawlers:++```+https://three.ws/agent/<id>/share+```++That page is plain HTML with your agent's real meta baked into the `<head>`, and a redirect that sends a human straight on to `/agent/<id>`. A recipient who taps the link never sees it; the unfurler does. This is the URL the Share button copies, and the one to paste anywhere a preview matters.### What the previews contain-When a platform fetches `https://three.ws/agent/<id>`, it sees:+When a platform fetches `https://three.ws/agent/<id>/share`, it sees:-- **og:title** — Your agent's name. Example: "Iris".-- **og:description** — Your agent's one-line description from the editor. Example: "Personal AI guide for Lumen customers."-- **og:image** — A pre-rendered preview image of the agent. This is generated automatically the first time someone shares the URL, then cached on the platform CDN.-- **og:url** — The canonical public URL of the agent.-- **og:type** — `website`.-- **twitter:card** — `summary_large_image`, so the Twitter preview shows the big-image card.-- **twitter:title**, **twitter:description**, **twitter:image** — Twitter-specific duplicates of the OG fields.+- **og:title**: `<agent name> · 3D AI Agent · three.ws`, or `<agent name> · 3D AI Agent on <chain> · three.ws` when the agent has been deployed on-chain.+- **og:description**: Your agent's description (first 120 characters), the chain it is deployed on if any, then `3D AI Agent on three.ws`.+- **og:image**: Your avatar's rendered thumbnail when the avatar's visibility is public or unlisted. Otherwise a generated SVG card from `/api/og/agent?id=<id>` carrying the agent's name and its chain badge.+- **og:url**: The `/share` URL itself. **og:type** is `profile`.+- **twitter:card**: `summary_large_image`, so X renders the big-image card, alongside `twitter:title`, `twitter:description`, and `twitter:image`.+- A **Farcaster Frame** block, so the same link renders as a frame in Farcaster clients.+- A **link rel="alternate" oEmbed** pointer at `/api/oembed`, so embedders that speak oEmbed can resolve the agent without scraping.-The preview image is a still render of your agent — same body, same lighting as the live page, framed for the 1200×630 standard OG image aspect. The agent's name is composited onto the corner of the image. The whole thing reads as "this is an agent you can talk to" without the recipient having to open the link first.+Both image paths target the 1200x630 standard OG aspect.-### How the preview image is generated+There is also a wallet variant, `/agent/<id>/share?wallet=1`, which swaps the copy and the deep link over to the agent's wallet view and always uses the generated card (the card is what carries the wallet identity). Use it when the thing you are sharing is the agent's wallet rather than the agent.-When an OG-fetcher (iMessage's link-unfurler, Slack's link preview service, Twitter's card scraper) hits your agent's URL for the first time, the platform spins up a headless WebGL renderer, loads the agent's GLB, renders a single high-quality frame against a neutral background, composites the name on top, and saves the result to the CDN. The whole render takes about two seconds.+### Preview freshness-After that first render, the image is cached on the CDN for ~24 hours. So:+Nothing is pre-rendered and nothing needs purging. The share page is generated per request from the agent's current row in the database, and the generated card is drawn on demand:-- The first share of a brand-new agent will see a "loading" image for a few seconds (most platforms show their own placeholder during this window)-- Subsequent shares within ~24 hours are instant — the cached image is served-- After 24 hours, the next share triggers a re-render. This is useful: if you've swapped the agent's body in Studio, the new body shows up in social previews within a day automatically+- The share page is cached `max-age=60` in the browser and `s-maxage=600` at the edge, with a one-hour stale-while-revalidate window.+- The generated SVG card is cached `max-age=180` / `s-maxage=900`, with a two-minute stale-while-revalidate window.-If you need an instant re-render — say, you've changed the agent's body for a launch and want fresh previews — there's a "Refresh preview image" button on the agent profile page that purges the CDN cache and forces a fresh render on the next share.+So a rename, a description edit, or a body swap shows up in new previews within minutes, with no button to press. The lag you are more likely to hit is on the other side: X, Slack, and Facebook each cache what they scraped, sometimes for days. That is what the debuggers below are for.### Verifying the preview before sharing-Don't ship a link without testing the preview first. Run the URL through a debugger:+Don't ship a link without testing the preview first. There are three levels of check, cheapest first.-- [Twitter Card Validator](https://cards-dev.twitter.com/validator) — Paste the URL, see the preview Twitter will render.-- [Facebook Sharing Debugger](https://developers.facebook.com/tools/debug/) — Same for Facebook, Messenger, WhatsApp, and Instagram.-- [LinkedIn Post Inspector](https://www.linkedin.com/post-inspector/) — Same for LinkedIn.+**The share panel.** Open your agent's profile page and click **Share**. The panel renders the real card image at the top, so you see what the link unfurls as before you send it anywhere.-Run your agent URL through at least Twitter and Facebook before a big share. If a preview looks wrong, the most common causes are:+**Read the tags yourself.** One command, no third party, no cache in the way:++```bash+curl -s https://three.ws/agent/YOUR_AGENT_ID/share \+ | grep -o '<meta[^>]*og:[^>]*>'+```-- The agent's name or description is unset in the editor → set them-- The preview image hasn't generated yet → wait one minute and retry-- A platform has cached an old version → use the platform's debugger (each tool above has a "re-scrape" button)+You should see your agent's name in `og:title` and a real image URL in `og:image`. If `og:title` says "Agent" and nothing else, the agent's name is unset.++**Platform debuggers**, for when a specific network is showing something stale:++- [Facebook Sharing Debugger](https://developers.facebook.com/tools/debug/): Facebook, Messenger, WhatsApp, and Instagram. Has a "Scrape Again" button.+- [LinkedIn Post Inspector](https://www.linkedin.com/post-inspector/): LinkedIn, with the same re-inspect behaviour.+- [Twitter Card Validator](https://cards-dev.twitter.com/validator): X's card preview. It now requires a logged-in developer account, so the `curl` check above is usually faster.++If a preview looks wrong, the causes in order of likelihood are:++- **You shared `/agent/<id>` instead of `/agent/<id>/share`.** That gets the generic three.ws card. This is by far the most common one.+- **The agent's name or description is unset** → set them in the editor and re-check.+- **The avatar is private**, so the card falls back to the generated SVG rather than your avatar's thumbnail → set the avatar's visibility to unlisted or public in the [avatar dashboard](/dashboard/avatars).+- **A platform cached an old version** → use its debugger's re-scrape button.### Customising the preview-Most agents look right with the default preview. If you want to customise:+The card is assembled from the agent's own record, so you customise it by editing the agent, not by editing a preview setting:-- The **name** is read from the agent's name field in the editor.-- The **description** is read from the agent's description field in the editor.-- The **image background** can be set per agent in the editor's Brand panel: a solid colour, a gradient, or a fixed background image upload. The agent body composites in front.+- The **name** is the agent's name field in the editor. It becomes `og:title`.+- The **description** is the agent's description field. It becomes `og:description`, truncated to the first 120 characters, so put the point first.+- The **image** is your avatar's thumbnail when the avatar's visibility is public or unlisted. Swap the agent's body (see [Pick and swap an avatar in Studio](/tutorials/swap-avatar-in-studio)) and the card follows within minutes.+- The **chain badge** appears by itself once the agent is deployed on-chain, both in the title and on the generated card.-Keep the name short (under 30 characters) and the description specific (under 120 characters). Both render onto the image; long strings overflow and the platform clips them.+Keep the name short and the description specific and front-loaded. Long strings are clipped, not wrapped.---@@ -102281,7 +102994,7 @@ Each platform has its own conventions. Here is what works on each.A line of plain text at the bottom of your email signature is the most under-used share context for personal agents.```-Talk to my AI: https://three.ws/agent/YOUR_AGENT_ID+Talk to my AI: https://three.ws/agent/YOUR_AGENT_ID/share```The recipient sees the link and the email client unfurls a preview card if it supports OG (Gmail, Apple Mail, Outlook all do). For agents that represent you personally, this is a way to let every email recipient interact with your AI persona without an explicit invite.@@ -102291,7 +103004,7 @@ The recipient sees the link and the email client unfurls a preview card if it suA simple post with the URL works, but the engagement is higher if you give context:```-Built a 3D AI agent that knows my work. Ask it anything → https://three.ws/agent/YOUR_AGENT_ID+Built a 3D AI agent that knows my work. Ask it anything → https://three.ws/agent/YOUR_AGENT_ID/share```X expands the URL into a large image card. The agent's preview image shows. Don't add a screenshot — let the auto-preview do the work; otherwise the platform sometimes hides the card.@@ -102303,7 +103016,7 @@ LinkedIn's link unfurling is conservative. The post performs better if you write```I built a personal AI assistant that visitors can talk to instead of reading my "About me" page. It knows my work, my availability, and what I'm building right now.-Try it: https://three.ws/agent/YOUR_AGENT_ID+Try it: https://three.ws/agent/YOUR_AGENT_ID/share```LinkedIn shows the preview card below your post. Engagement is highest within the first few hours, so post during your network's morning timezone.@@ -102387,7 +103100,7 @@ Your share strategy:1. **Embed on your portfolio site** — Following [Embed in 30 seconds](/tutorials/embed-in-30-seconds), you've added the one-line embed to the home page of your portfolio. Visitors can talk to Mara without leaving your site.-2. **Public link in your email signature** — At the bottom of every email you send: "Available 24/7 to chat about projects → https://three.ws/agent/mara-uxconsultant". Recipients can talk to Mara even when you're asleep.+2. **Public link in your email signature.** At the bottom of every email you send: "Available 24/7 to chat about projects → https://three.ws/agent/<MARA_ID>/share". Recipients can talk to Mara even when you're asleep, and the mail client unfurls her card inline.3. **QR on the back of your business card** — At networking events, instead of "I'll email you next week", you say "Scan my card, ask Mara about my work, and book a call directly through her if it's a fit". The conversation happens on your terms, on her schedule.@@ -102411,19 +103124,25 @@ A few practical implications:- **Tell the agent what it can and cannot say.** A line like "Never share my home address, phone number, or contract rates" in the system prompt is followed reliably by modern LLMs.- **Memory is private to your agent's record on the platform.** It's not shared with other agents and not visible to other users. But you, the owner, can see conversation logs in the editor.-If you want a private agent — one that only lives on a specific embed and isn't reachable from a public URL — toggle the "Public profile" switch off in the editor's settings panel. The agent ID still works for embeds; the public profile URL returns a 404. This is the right setting for internal tools, B2B-only embeds, and any agent that should not be discoverable.+**There is no private-profile switch, and this matters.** Every saved agent has a reachable profile page. What you *can* control is discoverability and assets, which are two separate settings:++- **Marketplace listing.** An agent is unpublished until you publish it, and only published agents appear in the [marketplace](/marketplace) and its category browsing. Unpublishing removes an agent from the directory; it does not close the profile URL.+- **Avatar visibility.** Your avatar has its own private / unlisted / public setting in the [avatar dashboard](/dashboard/avatars). A private avatar is not served from any public endpoint, which is also why the agent's social card falls back to the generated SVG rather than the avatar's thumbnail.++So plan on the URL being reachable by anyone who has it. For genuinely internal tooling, do not put the knowledge in a hosted agent's system prompt at all.---## What you learned-- Every agent has a permanent public URL at `https://three.ws/agent/<id>`+- Every agent has a permanent public URL at `https://three.ws/agent/<id>`, where the id is a UUID- The URL is stable across body swaps, system prompt updates, and skill changes+- Rich previews come from `https://three.ws/agent/<id>/share`, a server-rendered page that carries the agent's real Open Graph, Twitter Card, and Farcaster Frame meta and forwards humans to the profile+- The Share button on the profile page shows that card and copies the `/share` link for you+- Nothing is pre-rendered and nothing needs purging: edits appear in new previews within minutes, and the stale copy you see is usually the sharing platform's own cache- A QR code generated from any standard service points to that URL for offline share-- Open Graph and Twitter Card meta tags are set automatically, with a pre-rendered preview image-- Social preview images are generated on first share, cached 24 hours, and can be force-refreshed- The three share formats — embed, link, QR — are complementary; a complete strategy uses all three-- Public agents are genuinely public; configure the system prompt and skills accordingly, or toggle the public profile off for private use cases+- Every agent profile is reachable by anyone with the link; discoverability is controlled by marketplace publishing, and asset exposure by avatar visibilityThe agent's URL is the durable handle. Embed it, link it, print it. The agent shows up everywhere, identical, maintained from a single source of truth.@@ -104478,7 +105197,7 @@ Click **⬇ Get the code**. Because a partner template targets a real, already-b**2. Drop the tag on the page.** Paste the generated `<script>` tag right before `</body>`, swapping the placeholder URL for the one from step 1:```html-<script src="https://unpkg.com/@three-ws/[email protected]/dist/tour.global.js"+<script src="https://unpkg.com/@three-ws/[email protected]/dist/tour.global.js"data-tourdata-curriculum="https://cdn.sperax.io/tour/curriculum.json"defer></script>@@ -104604,252 +105323,186 @@ This is covered by an automated test — [`tour-sdk/test/director.test.mjs`](htt# Pick & swap an avatar in Studio-Your agent has a mind: a name, a personality, a set of skills, memory, and a wallet. Separately, your agent has a body: a 3D model that visitors see and interact with. The platform keeps these two things distinct on purpose. The mind is the durable identity. The body is a presentation choice that you can change at any time without affecting the rest.+Your agent has a mind: a name, a personality, a set of skills, memory, and a wallet. Separately, your agent has a body: a 3D model that visitors see and interact with. The platform keeps these two things distinct on purpose. The mind is the durable identity. The body is a presentation choice you can change at any time without affecting the rest.-Widget Studio is where you make that choice. You open it, browse the gallery, preview the candidate bodies on top of your agent's actual brain, and pick the one you want live. The snippet you've already embedded on your customer's site does not change. The next time the page loads, the new body is what visitors see.--This tutorial walks through the full Studio flow, explains what changes server-side versus snippet-side when you swap, and shows you how to maintain a small library of swappable bodies for the same agent.+This tutorial covers both halves of that. You swap the body in the agent editor's **Outfit** panel, in one click. Then you take the result into **Widget Studio**, which is a different surface with a different job: turning any avatar into an embeddable widget.**What you'll build:**-- A working understanding of how Studio fits between editor and embed-- A swap of your agent's body to a different avatar, live, in under five minutes+- A swap of your agent's body to a different avatar, live, in under a minute- A small personal library of avatars you can rotate between for seasons, campaigns, or audiences+- A widget built in Studio from the avatar you picked- The mental model for separating identity (the agent) from presentation (the avatar)**Prerequisites:** A saved agent on three.ws. If you've worked through [Embed in 30 seconds](/tutorials/embed-in-30-seconds), you already have one.----## Step 1 — Open Widget Studio--Go to [https://three.ws/studio](https://three.ws/studio). Sign in if you're not already.+## Step 1: Know which surface does what-Studio opens with a split layout. On the left is your agent — already loaded, animating, ready. On the right is the avatar gallery: a grid of 3D bodies the platform hosts, your own uploads, and any community-published avatars you can use freely.+Two surfaces have "studio" energy and they are often confused. They do not overlap:-If you have more than one agent in your account, there's an agent selector at the top of the left panel. Pick the one you want to modify; the rest of the page updates to show that agent's current body.+| Surface | Where | What it changes |+| --- | --- | --- |+| **Agent editor, Outfit panel** | `/agent/<id>/edit` | The agent's own body, animation set, and animation states. This is where a swap happens. |+| **Widget Studio** | [/studio](/studio) | Builds a standalone embeddable widget from an avatar. Does not modify any agent. |+| **Avatar dashboard** | [/dashboard/avatars](/dashboard/avatars) | Creates, names, deletes avatars, and sets each one's visibility. |-> The studio is genuinely a "studio" rather than a settings page. You can spend ten minutes in here just trying bodies on, the same way you'd browse outfits in a fitting room. Nothing is final until you save.+If you are trying to change what your embedded agent looks like, you want the first row. Studio is Step 6.----## Step 2 — Understand the gallery's structure--The avatar gallery has a few visible sections worth knowing about. They control what shows up when you search and where new avatars come from over time.--### Platform avatars--The default tab. These are bodies the three.ws team curates: a balanced set of styles (realistic, stylised, abstract), gender presentations, ethnicities, and aesthetic moods. They're stored on the platform's CDN, optimised for fast load, and tested for animation compatibility — every animation in the standard library plays correctly on every platform avatar.+## Step 2: Open the Outfit panel-You can filter by:+Open [https://three.ws/my-agents](https://three.ws/my-agents) and click the agent you want to change. On its profile page, click **✏ Edit Agent** (visible to you as the owner). That lands you on `/agent/<id>/edit`.-- **Style** — realistic, stylised, low-poly, geometric, abstract-- **Use case** — support, hero, mascot, narrator, professional-- **Polygon count** — useful if you're embedding on a low-end-device-heavy site+Scroll to the **Outfit** panel. It has three sections stacked in order:-Click any tile to preview the avatar on your agent — the left panel updates in real time, and your agent's actual greeting and idle animations play on the new body.+- **Avatar**: the grid of bodies you can put on this agent. This is the one this tutorial is about.+- **Animations**: which clips from the three.ws animation library this agent is allowed to play. Changing this needs an explicit **Save selection**.+- **Animation states**: which clip plays in each behaviour state, so the avatar crossfades sensibly as it speaks, walks, and reacts. Saved with **Save states**.-### Your uploads--If you've ever uploaded a GLB through the editor or the upload flow, those files appear here under "Your avatars". The platform stores them on its CDN with the right CORS headers so the embed loader can fetch them from anywhere.--If you haven't uploaded anything yet, this section is empty and the studio shows a hint pointing to the upload flow. Custom uploads are covered in their own tutorial — for this one, we stick with platform and community avatars.--### Community avatars--Avatars that other three.ws users have published as freely usable. This section grows over time. Each tile shows the creator's handle and a license note (most community avatars are CC-BY or CC0). Click the creator handle to see their full set.+A live 3D preview of the agent sits in the left column, so you are always looking at the current body while you work.----## Step 3 — Preview before committing+## Step 3: Read the avatar grid-This is the single most important habit to form when working with Widget Studio: preview every candidate body fully before saving. Click on each candidate and let it run for at least twenty seconds in the preview panel. You'll notice things you'd otherwise miss.+The grid lists the avatars on your account, newest first, up to fifty. Each tile shows the avatar's thumbnail and name. The body currently on this agent carries a **Current** badge, so you never have to guess which one is live.-The preview panel runs your agent's actual configuration on the new body. So you see:+Two things sit alongside the grid:-- How the avatar holds its head while idle-- How it gestures when speaking-- How the wave clip looks (try clicking "Wave" in the preview controls)-- How the talk-mouth animation reads — some stylised characters have very expressive mouth shapes, others almost none-- Whether the lighting in the scene flatters this particular model+- A **Create new** tile (the `+`). It opens a menu with the four real ways to get a new body: **three.ws Studio** (the in-browser builder for hair, clothing, and body), **three.ws Selfie** (a photo becomes a photoreal avatar, covered in [Turn a selfie into a 3D avatar](/tutorials/selfie-to-avatar)), **Upload GLB** (bring your own model), and **Browse public gallery** (pick from community avatars).+- A **Manage in dashboard ›** link to [/dashboard/avatars](/dashboard/avatars), where you rename, delete, and set visibility.-A few practical checks that pay off:+If you have no avatars yet, the grid says so and points you at the dashboard instead of showing an empty box.-- **Wave test** — Every avatar should be able to wave. If the wave looks broken (arm goes through the chest, hand stays at the side), the avatar's rig is incomplete; pick a different one.-- **Talk test** — Type a sentence into the preview chat input. The avatar should move its mouth and gesture lightly. If it doesn't, the talk animation isn't bound; pick a different one.-- **Idle test** — Watch the avatar for twenty seconds with no input. The idle should feel natural, not robotic. Notice the breathing, the small head turns, the weight shifts.+----When something feels right, you'll know — the preview panel feels like a real conversation rather than a mannequin.+## Step 4: Perform the swap----+Click a tile. That is the whole interaction.-## Step 4 — What happens when you swap+There is no confirmation dialog and no separate save button for the avatar: the click sends the change immediately, the status line under the heading reads `Saving…` and then `Saved.`, the **Current** badge moves to the tile you picked, and the 3D preview reloads on the new body. If something goes wrong, the same line shows the error rather than failing silently.-This is the part most people get wrong on their first try, and the part the studio is most useful for clarifying. Here is what changes — and, just as importantly, what does *not* change — when you save a new body.+Under the hood that click is one request:-### Server-side: the agent record updates+```+PUT /api/agents/<agent-id>+Content-Type: application/json-The platform stores each agent as a record. The record has:+{ "avatar_id": "<the avatar you clicked>" }+```-- An agent ID (permanent, never changes)-- A name-- A personality / system prompt-- A skills list-- A memory configuration-- A wallet-- And a pointer to a body — that pointer is a URL of a GLB file+The call is owner-scoped, so you can only re-body agents you own.-When you save a new body in Studio, the only field that changes in that record is the body URL. Everything else — name, personality, skills, memory, wallet, the ID — stays exactly as it was. The agent is the same entity. It just dresses differently.+### What changes, and what does not-### Snippet-side: nothing changes+The platform stores each agent as a record holding its ID, name, personality, skills, memory configuration, wallet, and a pointer to a body. **A swap changes only the body pointer.** Name, personality, skills, memory, wallet, and the agent ID are untouched. The agent is the same entity, and a returning visitor's conversation history is still there. It just dresses differently.-This is the crucial property. Your embed snippet is:+Your embed snippet does not change either:```html<script type="module" src="https://three.ws/agent-3d/latest/agent-3d.js"></script><agent-3d agent-id="YOUR_AGENT_ID" mode="floating"></agent-3d>```-There is no body URL in this snippet. The `<agent-3d>` element references the agent by its ID, and the embed runtime fetches the current body URL from the platform every time a visitor loads the page. When you swap the body in Studio, the next page load returns the new body. The customer site doesn't need to be re-deployed, the snippet doesn't need to be edited, the cached HTML on Cloudflare doesn't need to be purged.--This is by design and it's worth pausing on, because it changes how you operate at scale. You can:+There is no body URL in that snippet. The `<agent-3d>` element references the agent by ID and resolves the current body from the platform on every page load. Swap the body and the next page load shows it: no redeploy, no snippet edit, no cache purge on the customer's site.-- Run a seasonal avatar swap across hundreds of customer sites in one click-- A/B test two different bodies for the same brain across two agent IDs without touching any client code-- Replace a corrupted GLB at the source and have every embed self-heal on next page load-- Move from a placeholder avatar to a final-art avatar mid-campaign without coordinating a single deploy+This is what makes the pattern useful at scale. You can run a seasonal swap across every site that embeds you in one click, replace a broken GLB at the source and have every embed self-heal on the next load, or move from a placeholder body to final art mid-campaign without coordinating a single deploy.-Once the snippet is in place, the body lives entirely in the platform's control.+### Why there is nothing to purge-### What about cached GLBs?+Two caching facts make the swap effectively instant, and it is worth knowing them so you do not go hunting for a cache-busting button that does not exist:-The platform serves GLBs with reasonable cache headers — typically a few hours of freshness, then revalidate. When you save a swap in Studio, visitors who already have the page open keep the old body until they refresh. Visitors who arrive after the swap get the new body within at most an hour or two (and usually immediately, because most CDN edges revalidate on every miss).+- The agent record is served `Cache-Control: no-store`, so a page load always reads the current body pointer. There is no stale-manifest window.+- Each avatar is a distinct object at a distinct URL, so a swap points at a different file rather than replacing the bytes behind one. GLBs are served long-lived on purpose (`public, max-age=604800, stale-while-revalidate=2592000`), with `Access-Control-Allow-Origin: *` and `Content-Type: model/gltf-binary`, so the old body stays cached for the visitors still on it and the new body is fetched fresh.-If you need an instant swap — say, you're fixing a visibly broken avatar for an important demo — the platform exposes a "Bust cache" button in Studio's save dialog. Use it sparingly; it forces every CDN edge to refetch.+The only visitors who keep seeing the old body are the ones with the page already open, and only until they refresh.----## Step 5 — Perform a swap+## Step 5: Build a personal avatar library-Time to do the thing. With the studio open and your agent loaded:--1. **Pick a candidate.** Browse the gallery, click an avatar that matches the mood you want.-2. **Preview thoroughly.** Use the controls under the preview panel — Wave, Idle, Greet, Talk — and try at least the first three.-3. **Click Save** in the preview panel's footer. A confirmation dialog appears with two options: **Save** (default cache behaviour, fast and free) or **Save and bust cache** (instant propagation, use only when needed).-4. **Click Save.** The platform updates the agent record. The dialog closes.-5. **Open your embedded page in a new tab.** The new body appears.--That's the whole flow. In practice, on a real connection, a swap takes about ten seconds from click to live.-------## Step 6 — Build a personal avatar library--Studio is not just for one-off swaps; it's also where you maintain a small library of bodies you cycle between for different contexts. A few patterns that pay off.+The Outfit grid is your library, so it pays to keep a few deliberate bodies in it rather than one.### Seasonal swaps-Holiday avatars are a small detail that visitors notice. A "winter outfit" body for December and January, a "summer / outdoor" body for the warmer months, a "back to school" body in September. The brain is unchanged — your agent's personality persists across seasons. Only the appearance shifts. Use Studio's preview to make sure the seasonal avatar still feels like the same character (similar build, hair colour, posture); otherwise visitors will feel a discontinuity.+Holiday avatars are a small detail visitors notice: a winter body for December and January, a summer body for the warmer months. The brain is unchanged, so your agent's personality persists across seasons. Use the live preview to check the seasonal body still reads as the same character (similar build, hair colour, posture), otherwise visitors feel a discontinuity.### Campaign avatars-If you run product launches, your agent can wear a launch-themed body for the launch week. Examples: a body holding the new product, a body wearing the launch t-shirt, a body in the launch's colour palette.--### Audience-specific avatars+If you run product launches, your agent can wear a launch-themed body for launch week: holding the new product, wearing the launch shirt, or in the launch's colour palette.-You can run two agents with the same brain and different bodies, embedded on different pages:+### Audience-specific agents-- `agent_dev_id` — wears a developer-coded body, embedded on your docs and changelog-- `agent_sales_id` — wears a polished body, embedded on your marketing and pricing pages+Run two agents with the same personality and different bodies, embedded on different pages: a developer-coded body on your docs and changelog, a polished one on marketing and pricing. Same brain, different perceived audience. Create the second agent from [My Agents](/my-agents), then set its body here.-Both agents have the same personality, the same memory, the same skills. Only the body — and therefore the perceived audience — differs. The split is set up by duplicating the agent in My Agents at [https://three.ws/my-agents](https://three.ws/my-agents) and then using Studio to pick the right body for each clone.+### A test body-### Test bodies--It's useful to keep one "test" body in your library — something visually distinct, like a bright-coloured low-poly character — that you swap to when you're verifying a deployment. You can tell at a glance whether the page is showing the test body (deployment worked, cache busted, embed is live) or the production body (it's serving stale).+Keep one visually unmistakable body, such as a bright low-poly character, and swap to it when you are verifying a deployment. You can tell at a glance whether a page is serving the new build or a stale one.----## Step 7 — How the platform serves avatars+## Step 6: Take the avatar into Widget Studio-A short technical note for engineers, in case it matters for your stack.+[Widget Studio](/studio) is the other half of the story. It does not touch your agents; it turns an avatar into a self-contained embeddable widget with its own URL and snippet. It runs as four numbered steps across three columns.-Every platform avatar and every user upload is stored in the three.ws CDN, served from edge nodes globally. The URL format is approximately:+**1. Pick avatar.** Your own avatars appear here, but only the ones whose visibility is public or unlisted (a widget is served to strangers, so a private avatar cannot back one). Set visibility in the [avatar dashboard](/dashboard/avatars). There is also a search box for browsing public avatars, and a demo agent is pre-loaded so you can try the studio before signing in.-```-https://three.ws/cdn/avatars/<hash>.glb-```+**2. Pick widget type.** Each type is a different layout, not a different avatar:-The hash is a content-addressable digest, which means the same GLB always has the same URL, and uploading a new version generates a new URL. The agent record stores the current URL; Studio updates that pointer when you swap.+- **Turntable Showcase**: hero banner, auto-rotate, no UI.+- **Animation Gallery**: click through every clip on a rigged avatar.+- **Talking Agent**: embodied chat, your agent on your site.+- **ERC-8004 Passport**: on-chain identity card for any agent.+- **Hotspot Tour**: annotated 3D scene with clickable points of interest.+- **Walking Avatar**: a roaming avatar visitors steer with a joystick or the keyboard.+- **Pump.fun Live Feed**, **Smart Money Feed**, **Live Trades Canvas**, **Bonding Curve**: live market surfaces narrated or visualised by the avatar.-Headers served on every GLB:+**3. Brand.** Colours, environment, captions, and behaviour, with the middle column previewing every change live. The preview has a desktop / tablet / mobile switcher, and a **Use current view** button that locks whatever camera angle you have dragged to as the widget's default framing.-- `Access-Control-Allow-Origin: *` — so the embed loader can fetch the file from any customer domain-- `Cache-Control: public, max-age=86400, must-revalidate` — one-day freshness with revalidation-- `Content-Type: model/gltf-binary` — correct MIME type for GLB+Then **Generate**. A modal opens with the widget's live URL, a width and height, and two copy-ready snippets: an `<iframe>` and a script tag. **Save draft** keeps work in progress without publishing.-Files are not gzipped (GLBs are already binary-packed and don't benefit) but textures inside the GLB are compressed using KTX2 / Basis when present.--The "Bust cache" save option in Studio sends a purge signal to the edge network, which clears the cached object on every edge node usually within ten seconds.--This matters in two cases:--- You're embedding on a customer site with a strict CSP. Add `https://three.ws` to `connect-src` and you're done.-- You're embedding on a site behind a corporate proxy that strips `Access-Control-Allow-Origin`. The proxy needs to be configured to let three.ws responses through unmodified.+The important distinction: a widget built here is pinned to the avatar you chose. Swapping your *agent's* body in Step 4 does not re-point an existing widget. If you want the widget to follow the agent, use the **Talking Agent** type, which is backed by the agent rather than by a bare avatar.----## Step 8 — A worked example+## Step 7: A worked example-Let's run through a realistic scenario end to end.+You run an online cooking school called "Hearth", with a single agent named "Chef Olive" embedded on your home page, course catalogue, and pricing page. The current body is a stylised character in chef's whites.-Imagine you're running an online cooking school called "Hearth". You have a single agent named "Chef Olive" — friendly, knowledgeable, helps visitors pick the right course. Your agent is embedded on three pages: the home page, the course catalogue, and the pricing page. The current avatar is a stylised character in chef's whites — clean, professional, on-brand.+For a spring promotion you want a green-apron variant: same character build, same posture, clearly springtime. Olive's voice, personality, course knowledge, and memory all stay the same.-For your spring promotion, you want to swap the avatar to one wearing a green apron with a fresh-greens basket — same character build, same posture, same hair, but a clearly springtime variant. The agent's voice, personality, course knowledge, and memory of past conversations all stay the same.+1. Open [My Agents](/my-agents), click Chef Olive, click **✏ Edit Agent**.+2. Scroll to **Outfit**. The current whites tile carries the **Current** badge.+3. Click the spring-apron tile. The status line reads `Saved.` and the preview reloads on the new body.+4. Open your live home page in a private window. Olive is in the spring apron.-Here's the flow:+Total elapsed time is a few seconds, and no client code was touched. When the promotion ends, click the whites tile again.-1. Open [https://three.ws/studio](https://three.ws/studio). Select Chef Olive in the agent selector.-2. In the gallery, type "chef" in the search box. A handful of chef-style avatars surface, including the current production one.-3. Click the spring-apron candidate. The preview panel updates. Chef Olive — same voice, same greeting — appears in the new body.-4. Run the previews: wave, idle, talk. They all read well.-5. Click **Save**. Choose normal save (no cache bust — your spring campaign isn't time-critical).-6. Open the live home page in a private window. Chef Olive appears in the spring apron.--Visitors who land on the page during the next hour see the new body. Past conversation history is unchanged — a returning visitor who chats again finds Olive remembers their previous questions, just dressed differently for the season.--When the promotion ends, you return to Studio, swap back to the original whites, and save. The agent is back in its everyday outfit. No client code touched. No customer notified. No deploy run.-------## Step 9 — When to use Studio versus the full editor--A small clarification, because new users often conflate the two surfaces.--The **editor** at [https://three.ws/create](https://three.ws/create) is where you set the agent's identity: name, personality, skills, memory, wallet, voice. It's a designer surface for the brain.--**Studio** at [https://three.ws/studio](https://three.ws/studio) is where you tune the agent's appearance: the body and the embed presentation. It's a designer surface for the visual layer.--There is some overlap — Studio shows you which body is currently set, and the editor shows you a preview of the agent — but the principle is: brain in editor, body in studio. If you find yourself trying to write a system prompt in Studio or pick a body from the editor, you've taken the long way; switch surfaces and the right controls appear.+Note what did *not* happen: no deploy, no cache purge, no customer notified, and no loss of conversation history. A returning visitor finds Olive remembers their previous questions, just dressed differently.---## What you learned-- Widget Studio at [https://three.ws/studio](https://three.ws/studio) is the home for swapping an agent's body-- The platform separates the agent (mind, identity, wallet, memory) from the avatar (3D body, presentation)-- A swap updates one field on the server-side agent record and changes nothing about the embed snippet on customer sites-- Cache propagation is automatic within an hour, or instant with the "Bust cache" option-- A small personal library of avatars — seasonal, campaign, audience-specific, test — pays off for any agent you run beyond a single use case-- Avatars are served from the three.ws CDN with the right CORS and cache headers for embed use+- The body swap lives in the agent editor's **Outfit** panel at `/agent/<id>/edit`, not in Widget Studio+- Clicking an avatar tile saves immediately: one `PUT /api/agents/<id>` carrying `avatar_id`, with the **Current** badge and the live preview confirming it+- A swap changes one field. Name, personality, skills, memory, wallet, and the agent ID are untouched+- The embed snippet never changes, because `<agent-3d agent-id="…">` resolves the current body on every page load+- Nothing needs purging: the agent record is `no-store`, and each avatar is a distinct long-lived object+- **Widget Studio** at [/studio](/studio) is a separate surface that builds standalone widgets from an avatar, across ten widget types+- Avatar visibility (private / unlisted / public) is set in the [avatar dashboard](/dashboard/avatars) and gates whether an avatar can back a widget or a social card-The key insight is the snippet's stability. Once embedded, your customers' pages never need to change. You can update the body monthly, weekly, daily — visitors always see the current version, and the integration on the customer site keeps working without re-deploys.+The key insight is the snippet's stability. Once embedded, your customers' pages never need to change. You can update the body monthly, weekly, or daily, and visitors always see the current version.---## Next steps- [Customize size, position and background](/tutorials/customize-appearance) — once the body is right, tune the embed presentation-- [Embed in 30 seconds](/tutorials/embed-in-30-seconds) — revisit the one-line embed if you skipped it+- [Turn a selfie into a 3D avatar](/tutorials/selfie-to-avatar): put a real likeness in the Outfit grid+- [Embed in 30 seconds](/tutorials/embed-in-30-seconds): revisit the two-tag embed if you skipped it- [Add a greeting and first speech line](/tutorials/greeting-and-first-speech) — give every visitor a spoken welcome- [Share your agent](/tutorials/share-your-agent) — generate a public URL, QR code, and social previews- [Build your first agent](/tutorials/first-agent) — drop down to the manifest and skill level if you want full control@@ -105177,7 +105830,7 @@ async function setupSignupCelebration() {setupSignupCelebration();```-`playEmote` falls through a chain of clip names (`celebrate` → `cheer` → `wave`, or `flinch` → `concern`), so the reaction works regardless of what's baked into the loaded GLB.+`playEmote` falls through a chain of clip names (`celebrate` → `wave`, `cheer` → `celebrate` → `wave`, `flinch` → `defeated` → `concern` → `shake`), so the reaction works regardless of what's baked into the loaded GLB. If no clip in the chain exists, it falls back to a procedural head bob rather than doing nothing, and returns `false` so you can tell a real clip fired from the fallback.The pattern generalises: any form on your page — newsletter signup, contact form, lead capture, checkout — fits the same shape. Real fetch, branch on result, agent reacts.@@ -105496,41 +106149,43 @@ The pattern under all of these is the same: every recipe starts with `whenReady(# Upload a custom GLB avatar-The sample avatar is fine for learning, but at some point you want your agent to look like *yours* — a brand mascot, a stylised version of you, a museum guide in period dress, a character your designer built in Blender. That means uploading a custom GLB.+The sample avatar is fine for learning, but at some point you want your agent to look like *yours*, a brand mascot, a stylised version of you, a museum guide in period dress, a character your designer built in Blender. That means uploading a custom GLB.This tutorial covers the whole pipeline. Where compatible GLBs come from, what makes one compatible (and what makes one quietly fail), how to validate before you upload, what the validator output actually tells you, and how to fix the four or five problems that account for almost every upload failure. We'll end-to-end a Mixamo character, the most reliable starting point.**What you'll build:**- A custom, rigged 3D avatar running on your live agent- A workflow for validating GLBs before upload so failures happen in your editor, not in production-- A fix-list for the common failure modes (no idle clip, broken skinning, unsupported materials, oversize files)+- A fix-list for the common failure modes (a rig that won't canonicalize, mis-named clips, broken skinning, unsupported materials, oversize files)- A baked, draco-compressed GLB that loads fast on mobile**Prerequisites:** Comfort with a file manager and the command line. Some familiarity with Blender helps for the optional baking step but is not required. You should have an existing agent in [three.ws/my-agents](https://three.ws/my-agents) to swap a body into.----## Step 1 — Understand what the runtime expects+## Step 1: Understand what the runtime expects-A GLB is just a binary glTF — a 3D scene packaged in a single file. The runtime accepts any valid glTF 2.0 GLB, but to function as a *conversational agent body* it needs three things on top of the basic geometry:+A GLB is just a binary glTF: a 3D scene packaged in a single file. The runtime accepts any valid glTF 2.0 GLB. To function as a *conversational agent body*, the one thing that really matters on top of the basic geometry is:-1. **A skeleton (armature) the runtime can read.** The bones should follow a humanoid pattern — head, neck, spine, two arms, two legs. Mixamo and most humanoid avatar pipelines output skeletons that the runtime understands directly.-2. **An idle animation clip.** Without an idle, the avatar stands in T-pose between turns, which looks like a broken model. Any clip whose name contains "idle" (case-insensitive) works.-3. **At least one talk-style clip.** Used while the agent is speaking. Names containing "talk", "yes", or "wave" all match the runtime's hint search.+**A humanoid skeleton (armature) the runtime can name-map.** Bones following a humanoid pattern, head, neck, spine, two arms, two legs. There is no rig allowlist: `src/glb-canonicalize.js` maps the common conventions (Mixamo, Avaturn, Unreal, VRM/VRoid, VRM 1.0, Daz/Genesis, MakeHuman, Blender `.L` suffixes, simple `shoulderL` rigs) onto one canonical bone set.-That's the *minimum*. A great avatar also has:+**You do not have to ship animation clips.** Once the skeleton canonicalizes, `src/animation-retarget.js` retargets the platform's pre-baked clip library (idle, walk, and the emotes) onto your rig, legs included. A rig that genuinely can't be skeleton-driven, no skin, a non-humanoid prop, falls back to the default rig rather than freezing. And if only *some* bones name-map, `relaxUndrivenArms()` swings the un-driven arms down to a relaxed rest, so an avatar never reads as a broken bind-pose T-pose.++Baking your own clips in is therefore an *upgrade*, not a requirement. Do it when you want motion the shared library doesn't have, a brand-specific gesture, a costume-driven idle. Clips are matched by a case-insensitive substring search on the clip name, so `idle`, `idle_loop`, and `IdleBreathing` all satisfy an "idle" lookup; `talk`, `yes`, and `wave` all match the talk-style hint.++Beyond the rig, a great avatar has:- A wave clip (`wave`, `WaveLoop`, etc.) for greetings- Emote clips (`celebrate`, `cheer`, `flinch`, `concern`) for product moments-- Sensible material setup — PBR (`pbrMetallicRoughness`) materials, no unsupported extensions-- Textures sized for the web — 1024×1024 or 2048×2048 at most, JPEG or WebP rather than PNG where possible-- Draco compression, bringing the file under ~10 MB+- Sensible material setup: PBR (`pbrMetallicRoughness`) materials, no unsupported extensions+- Textures sized for the web: 1024×1024 or 2048×2048 at most, JPEG or WebP rather than PNG where possible+- Compressed geometry, bringing the file under ~10 MB-If your GLB is missing the bare minimum, you'll see it in T-pose. If it lacks the niceties, it works but feels heavy and pops in slowly on mobile.+If it lacks the niceties, it works but feels heavy and pops in slowly on mobile.----## Step 2 — Where compatible GLBs come from+## Step 2: Where compatible GLBs come fromFour reliable sources, ranked by how much work they need from you.@@ -105544,19 +106199,19 @@ Workflow:2. Click **Characters**, pick one.3. Click **Animations**, find an "idle", a "talk" (search for "talking"), a "wave", and any emotes you want.4. For each animation, click **Download**. Format: **FBX for Unity**. Skin: **With Skin** for the first download (the character), **Without Skin** for every subsequent one (you're just downloading the motion).-5. Convert the FBXs to a single GLB with a tool — see Step 4.+5. Convert the FBXs to a single GLB with a tool: see Step 4.Mixamo characters work *out of the box* with the runtime. This is the recommended path if you don't already have a model.-### three.ws Studio+### Avatar Studio-[three.ws Studio](https://studio.three.ws) lets you create a stylised avatar in minutes with full body customisation. The download is a single GLB with a clean skeleton and Mixamo-compatible rig.+[Avatar Studio](https://three.ws/avatar-studio) lets you create a stylised avatar in minutes with full body customisation (body, hair, face, clothing, accessories). The export is a single GLB with a clean skeleton and Mixamo-compatible rig. It is also reachable at [/create/studio](https://three.ws/create/studio), and the [Forge](https://three.ws/create) opens it in a modal. (Don't confuse it with [/studio](https://three.ws/studio), which is Widget Studio, the embed-snippet builder.)Workflow:-1. Open [three.ws Studio](https://studio.three.ws).-2. Customise your avatar and click **Export**.-3. The GLB has the body and skin but no animations baked in — you'll need to add at least an idle clip. See Step 5 for adding clips with `gltf-transform`.+1. Open [Avatar Studio](https://three.ws/avatar-studio).+2. Customise your avatar and click **Save Avatar**.+3. The GLB has the body and skin but no bespoke animation clips baked in. You don't have to add any: the platform retargets its pre-baked idle/walk/emote library onto any humanoid rig it can canonicalize, so a Studio avatar animates as soon as it is on an agent. Bake your own clips into the file only when you want motion the library doesn't have, Step 4 covers merging clips in.### Photo-to-avatar@@ -105567,17 +106222,17 @@ The three.ws photo pipeline generates a realistic humanoid avatar from three facIf you have a model you built or commissioned in Blender:1. Make sure your armature is a Mixamo-style humanoid rig, or rename your bones to match (`mixamorigHead`, `mixamorigSpine`, etc.).-2. Bake your animations down into NLA strips with sensible names — `Idle`, `Talk`, `Wave`.+2. Bake your animations down into NLA strips with sensible names, `Idle`, `Talk`, `Wave`.3. Export as glTF 2.0 (Binary) (`.glb`).4. In the export dialog, check **Include → Selected Objects** if you only want the character, **Animation → Always Sample Animations**, and **Compression → Draco mesh compression**.-Blender exports are the most flexible path but also the most error-prone — most upload failures we see in the wild come from Blender exports with missing or misconfigured animation tracks.+Blender exports are the most flexible path but also the most error-prone, most upload failures we see in the wild come from Blender exports with missing or misconfigured animation tracks.----## Step 3 — Run the validator before you upload+## Step 3: Run the validator before you upload-The single best habit you can build is validating *every* GLB before upload. The validator at [three.ws/validation](https://three.ws/validation) wraps the official Khronos glTF Validator with additional runtime-specific checks — does the file have an idle clip, is the skeleton humanoid, are the materials supported.+The single best habit you can build is validating *every* GLB before upload. The validator at [three.ws/validation](https://three.ws/validation) wraps the official Khronos glTF Validator with additional runtime-specific checks, does the file have an idle clip, is the skeleton humanoid, are the materials supported.Workflow:@@ -105591,7 +106246,7 @@ What to look for in the report:|---|---|| **Errors** | Any errors mean the file will fail to load. Fix them all before uploading. || **Warnings** | Most are cosmetic. Texture-size warnings ("3.4 MB PNG") and "unused material" warnings are worth fixing for performance, but won't break the agent. |-| **Animations** | The clip list. Look for at least one clip whose name contains "idle". Click each one to preview. |+| **Animations** | The clip list. If you baked your own clips in, confirm at least one name contains "idle" so the hint search finds it. A file with no clips is fine: the platform's own library retargets onto the rig. Click each one to preview. || **Skeleton** | Reports whether the rig is humanoid. A "non-humanoid skeleton" message means the runtime won't be able to drive head-look or wave gestures. || **Materials** | Lists each material's type. PBR (`pbrMetallicRoughness`) is the safe one. Any extension flagged with "unsupported" means that material will render as a fallback grey. || **File size** | The full size and a breakdown. Mesh + textures over ~10 MB is too heavy for mobile. |@@ -105602,11 +106257,11 @@ If there are errors, they almost always fall into the four buckets in Step 4.----## Step 4 — Convert Mixamo FBX to GLB+## Step 4: Convert Mixamo FBX to GLBMixamo's "Download" button gives you FBX. The runtime wants GLB. The conversion is a one-line command.-If you're working inside the repo, use the built-in converter — it's backed by FBX2glTF and preserves the skeleton, skin weights, animation, and textures, then prints a summary so you can confirm the rig survived:+If you're working inside the repo, use the built-in converter, it's backed by FBX2glTF and preserves the skeleton, skin weights, animation, and textures, then prints a summary so you can confirm the rig survived:```bash# One character FBX with its baked-in animation → public/avatars/<name>.glb:@@ -105616,49 +106271,87 @@ npm run convert:fbx -- your-character.fbxnpm run optimize:glb -- public/avatars/your-character.glb```-> **`optimize:glb` uses WebP, not Draco.** The avatar runtime *does* decode Draco — the viewer and the avatar body loaders wire a `DRACOLoader` pointed at the vendored `/three/draco/` decoder, so a Draco-compressed GLB loads fine (that's Step 5). `optimize:glb` itself deliberately stays within plain glTF 2.0 and leans on WebP textures for its ~90% size win, so its output needs no decoder at all. See [docs/3d-asset-pipeline.md](#sec-002) for the full format and pipeline reference.+> **`optimize:glb` uses WebP, not Draco.** The avatar runtime *does* decode Draco, the viewer and the avatar body loaders wire a `DRACOLoader` pointed at the vendored `/three/draco/` decoder, so a Draco-compressed GLB loads fine (that's Step 5). `optimize:glb` itself deliberately stays within plain glTF 2.0 and leans on WebP textures for its ~90% size win, so its output needs no decoder at all. See [docs/3d-asset-pipeline.md](#sec-002) for the full format and pipeline reference.-Outside the repo, [gltf-transform](https://gltf-transform.dev) is a Node-based CLI maintained as part of the glTF ecosystem that also handles the conversion:+Outside the repo, install the same converter directly. [FBX2glTF](https://github.com/facebookincubator/FBX2glTF) (Meta's converter) ships as a prebuilt binary inside the `fbx2gltf` npm package, and it is exactly what `npm run convert:fbx` wraps:```bash-# One character FBX with one baked-in animation:-npx @gltf-transform/cli@latest fbx2glb your-character.fbx your-character.glb+npm i -D fbx2gltf```-If you downloaded several animations separately (idle, talk, wave as standalone FBXs), merge them into a single GLB with named clips:+The package exports a function, not a CLI shim: there is no `npx fbx2gltf`. Call it from a small script:-```bash-# Convert each FBX into a GLB first-npx @gltf-transform/cli@latest fbx2glb idle.fbx idle.glb-npx @gltf-transform/cli@latest fbx2glb talk.fbx talk.glb-npx @gltf-transform/cli@latest fbx2glb wave.fbx wave.glb+```js+// convert.mjs: node convert.mjs your-character.fbx your-character.glb+import { createRequire } from 'node:module';+import { renameSync } from 'node:fs';-# Merge animations into the character GLB-npx @gltf-transform/cli@latest merge your-character.glb idle.glb talk.glb wave.glb out.glb+const convert = createRequire(import.meta.url)('fbx2gltf');+const [input, output] = process.argv.slice(2);-# Rename animation clips so the runtime's hint search picks them up-npx @gltf-transform/cli@latest rename --map "mixamo.com=Talk" out.glb out-named.glb+// A destination ending in .glb yields binary glTF. Some builds write to a+// slightly different path and return it, so normalize to what you asked for.+const written = await convert(input, output, ['--pbr-metallic-roughness']);+if (written && written !== output) renameSync(written, output);+console.log(`wrote ${output}`);```-The `rename` step matters. Mixamo names every clip `mixamo.com` by default, which is useless for the runtime's name-based hint matching. Set deliberate names — `Idle`, `Talk`, `Wave`, `Celebrate` — so `playAnimationByHint('idle')` and friends find the right clip.+PBR metallic-roughness materials, the skeleton, skin weights, animation clips, and textures all survive the conversion. If you would rather drive the binary straight from a shell, it is at `node_modules/fbx2gltf/bin/<Darwin|Linux|Windows_NT>/FBX2glTF`; run it with `--help` to see the flags (note that its `-o` takes a path *without* a suffix, which is why the wrapper above normalizes the result).++> **`gltf-transform` cannot read FBX.** It is a glTF-to-glTF toolkit, every command it exposes takes a `.glb`/`.gltf` in and writes one out, so there is no `fbx2glb`. Use it for the *optimization* steps below, after FBX2glTF has produced a GLB. It also has no `rename` and no `script` subcommand; renaming clips is a Blender or Document-API job (below).-A faster workflow if you have several clips: open the merged GLB in Blender, manually rename each animation in the NLA editor, re-export. Either approach works.+If you downloaded several animations separately (idle, talk, wave as standalone FBXs), convert each with the script above and merge them into a single GLB:++```bash+# Merge the animation GLBs into the character GLB+npx @gltf-transform/cli@latest merge your-character.glb idle.glb talk.glb wave.glb out.glb+```++Then rename the clips. Mixamo names every clip `mixamo.com` by default, which is useless for the runtime's name-based hint matching. Set deliberate names, `Idle`, `Talk`, `Wave`, `Celebrate`, so `playAnimationByHint('idle')` and friends find the right clip. Two ways:++- **Blender (no code):** open the merged GLB, rename each action in the NLA editor, re-export. This is the faster path for a handful of clips.+- **The glTF Transform Document API (scriptable):** the library is a normal npm package, so write a tiny Node script against it. There is no CLI subcommand for this.++```js+// rename-clips.mjs: node rename-clips.mjs merged.glb renamed.glb+import { NodeIO } from '@gltf-transform/core';+import { ALL_EXTENSIONS } from '@gltf-transform/extensions';+import { MeshoptDecoder, MeshoptEncoder } from 'meshoptimizer';++const NAMES = ['Idle', 'Talk', 'Wave', 'Cheer'];+const [input, output] = process.argv.slice(2);++// Registering the extensions is not optional: most three.ws avatars ship+// EXT_meshopt_compression, and a bare NodeIO throws+// `Missing required extension, "EXT_meshopt_compression"` on read.+const io = new NodeIO()+ .registerExtensions(ALL_EXTENSIONS)+ .registerDependencies({ 'meshopt.decoder': MeshoptDecoder, 'meshopt.encoder': MeshoptEncoder });++const document = await io.read(input);+document.getRoot().listAnimations().forEach((anim, i) => {+ if (NAMES[i]) anim.setName(NAMES[i]);+});+await io.write(output, document);+```++Install its three dependencies first: `npm i -D @gltf-transform/core @gltf-transform/extensions meshoptimizer`. Clip order follows merge order, so pass the animation GLBs to `merge` in the order you list them in `NAMES`.----## Step 5 — Draco-compress the file+## Step 5: Draco-compress the file-Draco is a mesh-compression format that shrinks vertex data by 5–10x with no visible quality loss. A 14 MB raw GLB drops to 2 MB compressed, which is the difference between a 6-second mobile load and an instant one.+Draco is a mesh-compression format that shrinks vertex data by 5-10x with no visible quality loss. A 14 MB raw GLB drops to 2 MB compressed, which is the difference between a 6-second mobile load and an instant one.-The runtime ships with the Draco decoder baked in, so compressed GLBs load transparently — no special attributes or flags needed on the agent side.+The runtime ships with the Draco decoder baked in, so compressed GLBs load transparently, no special attributes or flags needed on the agent side.To compress:```bash-npx @gltf-transform/cli@latest draco --quantization 14 your.glb your-draco.glb+npx @gltf-transform/cli@latest draco --quantize-position 14 your.glb your-draco.glb```-The `--quantization 14` flag balances size against visual quality. The default (14 for position, 12 for normals) is fine for almost all humanoid avatars. If you're seeing visible warping in the mesh after compression, bump it to 16. Anything above 16 stops shrinking the file usefully.+Quantization is per-attribute, not one global flag: `--quantize-position` (default 14), `--quantize-normal` (10), `--quantize-texcoord` (12), `--quantize-color` (8), and `--quantize-generic` (12), each accepting 1-16 bits. The defaults are fine for almost all humanoid avatars, so the command above is really just being explicit. If you see visible warping in the mesh after compression, raise `--quantize-position` to 16, which is the ceiling, there is nothing above it.Compare before/after sizes:@@ -105670,7 +106363,7 @@ A 12 MB → 2 MB drop is typical for a Mixamo character with three animation cli----## Step 6 — Resize textures+## Step 6: Resize texturesThe biggest GLBs we see in production are 90% textures. A character with three 4K textures (diffuse, normal, ARM) is 50 MB before you've added a single bone.@@ -105682,46 +106375,51 @@ npx @gltf-transform/cli@latest resize --width 1024 --height 1024 your.glb your-1The careful way: open the GLB in [three.ws/validation](https://three.ws/validation), find the largest textures in the report, and resize *just* those in an image editor before repackaging. For faces and skin, keep the diffuse at 2K and downsample the normal/roughness maps to 1K.-For most product-page avatars, 1K diffuse textures are plenty. The avatar is rendered at 280–400px on screen; 2K texels mostly average out before they hit a pixel.+For most product-page avatars, 1K diffuse textures are plenty. The avatar is rendered at 280-400px on screen; 2K texels mostly average out before they hit a pixel.JPEG and WebP are dramatically smaller than PNG for diffuse and ARM maps. PNG is only worth keeping for normal maps where banding shows up otherwise.----## Step 7 — Upload via the dashboard+## Step 7: Upload via the dashboard++With a validated, compressed GLB in hand, this is two steps: get the file into your avatar library, then point an agent at it.-With a validated, compressed GLB in hand:+**Upload the GLB**-1. Go to [three.ws/my-agents](https://three.ws/my-agents).-2. Select the agent you want to give a new body, or click **New agent**.-3. Open the **Body** tab.-4. Drag the GLB onto the drop zone, or click **Upload** and pick the file.-5. The dashboard runs the validator again as part of the upload, then renders a preview in the right pane.-6. Click **Save body**.+1. Go to [three.ws/create](https://three.ws/create).+2. Pick the **Upload your own GLB** card.+3. Drop the `.glb` file, or click to choose it. The header is checked before anything uploads, so a mis-renamed file is rejected immediately rather than half-saved.+4. The avatar lands in your library at [/dashboard/avatars](https://three.ws/dashboard/avatars).-The dashboard stores the GLB on the platform CDN with the right CORS headers and `Cache-Control` for fast subsequent loads. No further hosting steps needed.+**Attach it to an agent**-Once the body is saved, every embed of that agent — `<agent-3d agent-id="...">`, script-tag embeds, iframe widgets — picks up the new body on next page load. No code changes anywhere.+1. Open the agent in the editor and go to its **Outfit** panel.+2. Under **Avatar**, pick the avatar you just uploaded. Upload progress and a **Cancel** control show inline; the selection is saved to the agent as soon as the attach completes.+3. The same panel is where you pick which clips from the three.ws library the agent uses (**Animations**), which clip plays per behaviour (**Animation states**), and its **Gesture slots**.++The platform stores the GLB on its CDN with the right CORS headers and `Cache-Control` for fast subsequent loads. No further hosting steps needed.++Once the body is saved, every embed of that agent, `<agent-3d agent-id="...">`, script-tag embeds, iframe widgets, picks up the new body on next page load. No code changes anywhere.----## Step 8 — The five failure modes (and fixes)+## Step 8: The five failure modes (and fixes)Almost every upload failure falls into one of these categories. The validator catches them, but knowing what each one means cuts your debug time dramatically.-### Failure A: T-pose, no animation playing+### Failure A: frozen, no animation playing-**Symptom:** Body loads fine, but stands frozen in T-pose.+**Symptom:** Body loads fine, but stands frozen instead of breathing.-**Cause:** No clip whose name matches the runtime's idle hint. The runtime searches case-insensitively for `idle` in clip names.+**Cause:** Two different ones, and they need different fixes.-**Fix:** Rename your idle clip to include "idle" — `Idle`, `idle_loop`, `IdleBreathing` all match.+1. **The skeleton didn't canonicalize.** The retargeting layer couldn't name-map the rig, so the shared clip library has nothing to drive. This is the real failure, and it shows in the validator as a non-humanoid skeleton.+2. **You baked in clips but named them badly.** If the GLB ships its own clips, the runtime prefers them and searches case-insensitively for `idle` in the names. `mixamo.com` matches nothing.-```bash-npx @gltf-transform/cli@latest rename --map "mixamo.com=Idle" your.glb out.glb-```+**Fix for (1):** rename the bones to a convention `glb-canonicalize.js` knows, Mixamo (`mixamorigHead`), VRM, Avaturn, Unreal, Daz, MakeHuman, or Blender `.L`/`.R` suffixes. Hitting a genuinely new skeleton convention is a gap worth reporting rather than working around.-Or rename in Blender's NLA editor and re-export.+**Fix for (2):** rename your idle clip to include "idle", `Idle`, `idle_loop`, `IdleBreathing` all match. Use Blender's NLA editor or the `rename-clips.mjs` script from Step 4; `gltf-transform` has no `rename` command.### Failure B: Animation plays but the mesh deforms wrong@@ -105743,7 +106441,7 @@ But genuinely broken skinning needs a fresh export.**Symptom:** Avatar loads, but everything is matte grey or unnaturally bright.-**Cause:** Unsupported material extension. The most common culprits are `KHR_materials_pbrSpecularGlossiness` (the old material spec — runtime falls back to default PBR), or `KHR_materials_volume` / `KHR_materials_transmission` (advanced extensions some loaders skip).+**Cause:** Unsupported material extension. The most common culprits are `KHR_materials_pbrSpecularGlossiness` (the old material spec, runtime falls back to default PBR), or `KHR_materials_volume` / `KHR_materials_transmission` (advanced extensions some loaders skip).**Fix:** Convert the materials to standard PBR (`pbrMetallicRoughness`). In Blender, swap any "Specular BSDF" or "Glass BSDF" nodes for "Principled BSDF" and re-export. In `gltf-transform`:@@ -105755,11 +106453,11 @@ This converts `pbrSpecularGlossiness` materials to `pbrMetallicRoughness` automa### Failure D: File too large, slow to load-**Symptom:** Avatar loads, but takes 5–15 seconds to appear, especially on mobile. Initial page paint is fine; the avatar pops in late.+**Symptom:** Avatar loads, but takes 5-15 seconds to appear, especially on mobile. Initial page paint is fine; the avatar pops in late.**Cause:** Uncompressed mesh, oversized textures, or both.-**Fix:** Apply Steps 5 and 6 — Draco compression and texture resizing. A combined `transform` invocation does both in one pass:+**Fix:** Apply Steps 5 and 6: Draco compression and texture resizing. A combined `transform` invocation does both in one pass:```bashnpx @gltf-transform/cli@latest optimize \@@ -105769,7 +106467,7 @@ npx @gltf-transform/cli@latest optimize \your.glb optimized.glb```-The `optimize` command bundles draco, texture resize, image format change, and mesh simplification. For aggressive size reduction it usually drops a 15 MB GLB to 2–3 MB.+The `optimize` command bundles geometry compression, texture resize, image format change, and mesh simplification. Note its default compression is **meshopt**, not Draco: pass `--compress draco` if you specifically want Draco (or `--compress quantize`, or `false` to skip it). For aggressive size reduction it usually drops a 15 MB GLB to 2-3 MB.### Failure E: Validator complains "node has no skin"@@ -105781,7 +106479,7 @@ The `optimize` command bundles draco, texture resize, image format change, and m----## Step 9 — Complete Mixamo workflow+## Step 9: Complete Mixamo workflowHere's the end-to-end. Pick a Mixamo character, ship it as a custom agent body.@@ -105792,12 +106490,13 @@ Here's the end-to-end. Pick a Mixamo character, ship it as a custom agent body.# - Waving.fbx (Without Skin)# - Cheering.fbx (Without Skin)-# 2. Convert each FBX to GLB+# 2. Convert each FBX to GLB with the convert.mjs wrapper from Step 4for f in *.fbx; do- npx @gltf-transform/cli@latest fbx2glb "$f" "${f%.fbx}.glb"+ node convert.mjs "$f" "${f%.fbx}.glb"done-# 3. Merge the character GLB with the animation GLBs+# 3. Merge the character GLB with the animation GLBs.+# Merge order sets clip order, which the rename step relies on.npx @gltf-transform/cli@latest merge \"your-character.glb" \"Breathing Idle.glb" \@@ -105807,23 +106506,9 @@ npx @gltf-transform/cli@latest merge \merged.glb# 4. Rename clips so the runtime's hint search picks them up.-# Mixamo names everything "mixamo.com" by default — fix that.-# Use a glTF editor (Blender or Gestaltor) to rename, or:-npx @gltf-transform/cli@latest script renames.js merged.glb renamed.glb-```--For the rename script (`renames.js`), `gltf-transform` lets you write a small node program against its Document API. The simplest version:--```js-// renames.js-const animationNames = ['Idle', 'Talk', 'Wave', 'Cheer'];--module.exports = (document) => {- const root = document.getRoot();- root.listAnimations().forEach((anim, i) => {- if (animationNames[i]) anim.setName(animationNames[i]);- });-};+# Mixamo names everything "mixamo.com" by default: fix that.+# Use a glTF editor (Blender or Gestaltor), or the Step 4 script:+node rename-clips.mjs merged.glb renamed.glb``````bash@@ -105837,20 +106522,20 @@ npx @gltf-transform/cli@latest optimize \# Drag final.glb onto https://three.ws/validation# Confirm: file < 5 MB, animations named correctly, no errors.-# 7. Upload at https://three.ws/my-agents+# 7. Upload at https://three.ws/create, then attach it in the agent editor's Outfit panel```-Total: 15–25 minutes the first time, 5 minutes once you've done it. The script-based renames step is the only fiddly part; everything else is one-line commands.+Total: 15-25 minutes the first time, 5 minutes once you've done it. The script-based renames step is the only fiddly part; everything else is one-line commands.----## Step 10 — Verify on the live agent+## Step 10: Verify on the live agentOnce uploaded:-1. Open any page that embeds the agent (your homepage, the studio preview, [three.ws/my-agents](https://three.ws/my-agents) → preview).-2. Confirm the new body loads — no T-pose, no warped limbs.-3. Send a chat message — the agent should switch to the talk clip while replying.+1. Open any page that embeds the agent (your homepage, or the live preview in the agent editor's Outfit panel).+2. Confirm the new body loads: no T-pose, no warped limbs.+3. Send a chat message: the agent should switch to the talk clip while replying.4. In a browser console, fire each clip by name:```js@@ -105861,7 +106546,7 @@ agent.play('Talk');agent.play('Idle');```-Each one should trigger the corresponding clip. If a clip you expect doesn't fire, run `agent._scene.clips.map(c => c.name)` in the console — that prints the actual clip names the runtime sees. Compare against the names you set in Step 9.+Each one should trigger the corresponding clip. If a clip you expect doesn't fire, run `agent._scene.clips.map(c => c.name)` in the console, that prints the actual clip names the runtime sees. Compare against the names you set in Step 9.---@@ -105869,20 +106554,20 @@ Each one should trigger the corresponding clip. If a clip you expect doesn't firThe full custom-GLB pipeline:-- Compatible avatars come from Mixamo, three.ws Studio, the photo pipeline, or Blender — all produce something the runtime understands+- Compatible avatars come from Mixamo, three.ws Studio, the photo pipeline, or Blender, all produce something the runtime understands- The runtime needs a humanoid skeleton, an idle clip, and a talk clip; it likes a wave and a celebrate too- The validator at [three.ws/validation](https://three.ws/validation) catches every common failure before upload- Mixamo's `mixamo.com` clip names need renaming so the hint search finds them-- `gltf-transform optimize` is the one command that handles draco, resize, and simplify in one pass-- The dashboard upload path stores the GLB with correct CORS — no separate hosting work needed+- `gltf-transform optimize` is the one command that handles geometry compression, resize, and simplify in one pass (meshopt by default; `--compress draco` for Draco)+- The dashboard upload path stores the GLB with correct CORS, no separate hosting work neededOnce the body is on the platform, the embed snippet doesn't change. The same `<agent-3d agent-id="...">` tag picks up the new body automatically.## Next steps-- [Swap the avatar in Studio](/tutorials/swap-avatar-in-studio) — preview body swaps with no code-- [Build a personal AI website](/tutorials/personal-ai-site) — put your custom avatar at the centre of a homepage-- [Give your agent a personality](/tutorials/agent-personality) — match the brain to the new body+- [Swap the avatar in Studio](/tutorials/swap-avatar-in-studio), preview body swaps with no code+- [Build a personal AI website](/tutorials/personal-ai-site), put your custom avatar at the centre of a homepage+- [Give your agent a personality](/tutorials/agent-personality), match the brain to the new body---@@ -105995,13 +106680,15 @@ If you're using the iframe embed, add `xr-spatial-tracking` to the `allow` attri```html<iframe- src="https://three.ws/embed/avatar/13f259c7-7024-4d68-b1f0-dbbf52c06209"+ src="https://three.ws/embed/avatar?id=13f259c7-7024-4d68-b1f0-dbbf52c06209"allow="microphone; camera; xr-spatial-tracking; fullscreen"width="400"height="500"></iframe>```+An avatar id goes in the `id` query parameter, as above. The shorter path form, `/embed/avatar/<handle>`, is for a claimed handle (3 to 30 characters), not for a UUID.+Without `xr-spatial-tracking`, the browser blocks `navigator.xr` inside the frame and the AR button won't appear.---@@ -106330,9 +107017,9 @@ The leverage is that the avatar drives its mouth from the *audio it actually pla# Add the Walk Companion to your site-By the end of this tutorial you'll have a **3D avatar walking across your own website** — a corner mascot that idles, follows the cursor, and waves on navigation, plus a full-page playground the visitor can steer with WASD or a touch joystick. You'll add it two ways: a zero-build iframe you can paste onto any page, and the `@three-ws/walk` npm package when you want the real site-wide companion.+By the end of this tutorial you'll have a **3D avatar walking across your own website**, a corner mascot that idles, follows the cursor, and waves on navigation, plus a full-page playground the visitor can steer with WASD or a touch joystick. You'll add it two ways: a zero-build iframe you can paste onto any page, and the `@three-ws/walk` npm package when you want the real site-wide companion.-Along the way you'll see what the [/walk](/walk) product offers — live demos across six environments, the one-tag embed, the Chrome extension that walks the whole web, and the distance leaderboard — and exactly which attributes and APIs are real.+Along the way you'll see what the [/walk](/walk) product offers, live demos across six environments, the one-tag embed, the Chrome extension that walks the whole web, and the distance leaderboard, and exactly which attributes and APIs are real.**Prerequisites:** a website you can edit and a WebGL-capable browser. The iframe path needs no tooling at all; the npm path assumes light JavaScript familiarity and that you already bundle [Three.js](https://threejs.org) (>= 0.150).@@ -106352,7 +107039,7 @@ Corner companion Full-page playground└───────────────┘ └───────────────────────────┘```-The companion mounts in a corner and stays out of the way: it idles, turns to follow the cursor, waves when the visitor navigates, and greets each page. Click it and it **detaches into a full-page playground** — the visitor steers across the page from a gentle aerial view, or platforms across your real DOM with gravity and jumps. Walk onto a link and it opens like a doorway into the next page.+The companion mounts in a corner and stays out of the way: it idles, turns to follow the cursor, waves when the visitor navigates, and greets each page. Click it and it **detaches into a full-page playground**, the visitor steers across the page from a gentle aerial view, or platforms across your real DOM with gravity and jumps. Walk onto a link and it opens like a doorway into the next page.This is the same engine that powers the walking companion on three.ws, published as the `@three-ws/walk` package.@@ -106360,7 +107047,7 @@ This is the same engine that powers the walking companion on three.ws, published## The /walk product (two minutes)-Before you embed it, it helps to know what the live [/walk](/walk) page exposes — every piece below is something you can link to or reuse:+Before you embed it, it helps to know what the live [/walk](/walk) page exposes, every piece below is something you can link to or reuse:| Surface | Route | What it is ||---|---|---|@@ -106368,7 +107055,7 @@ Before you embed it, it helps to know what the live [/walk](/walk) page exposes| Live demos | embedded on [/walk](/walk) | Real (not video) iframes for `beach`, `night`, `grid`, and more || One-tag embed | [/walk-embed](/walk-embed) | The chrome-less iframe you drop on any site || Chrome extension | presented on [/walk](/walk) | Your avatar walks over every page you visit, reading them aloud |-| Distance leaderboard | [/walk-leaderboard](/walk-leaderboard) | The longest strolls on three.ws — daily, weekly, all-time |+| Distance leaderboard | [/walk-leaderboard](/walk-leaderboard) | The longest strolls on three.ws, daily, weekly, all-time |The six built-in environments are fixed and need no HDRI downloads: `studio`, `void`, `beach`, `sunset`, `night`, `grid`. You select one with the `env` query param.@@ -106376,10 +107063,10 @@ The six built-in environments are fixed and need no HDRI downloads: `studio`, `v## Step 1: The one-tag embed (no build step)-The fastest way to put a walking avatar on a page is the [/walk-embed](/walk-embed) iframe. It's intentionally chrome-less — no nav, no footer — so it drops cleanly into a card or a corner.+The fastest way to put a walking avatar on a page is the [/walk-embed](/walk-embed) iframe. It's intentionally chrome-less, no nav, no footer, so it drops cleanly into a card or a corner.```html-<!-- three.ws Walk — drop in anywhere -->+<!-- three.ws Walk: drop in anywhere --><iframesrc="https://three.ws/walk-embed?env=void&autoplay=true"width="360" height="480"@@ -106395,7 +107082,7 @@ The embed reads its world and controls from the URL. The verified params:| Param | Values | Effect ||---|---|---|-| `env` | `studio` `void` `beach` `sunset` `night` `grid` | The environment (default scene if omitted) |+| `env` | `studio` `void` `beach` `sunset` `night` `grid` | The environment (`studio` if omitted) || `autoplay` | `true` | Start animating immediately || `controls` | `joystick` `keyboard` `none` | How (or whether) the visitor steers || `orbit` | `true` `false` | Allow drag-to-orbit the camera |@@ -106428,7 +107115,7 @@ The `allow="accelerometer; gyroscope"` attribute lets the joystick respond to de## Step 2: Drive the embed from the host page (postMessage)-The embed isn't a black box — it speaks a versioned `postMessage` contract so your page can tell the avatar where to walk, what to say, and which environment to show. The contract is defined in [src/walk-embed-events.js](../src/walk-embed-events.js) and documented interactively at [/docs/walk-embed-api](/docs/walk-embed-api).+The embed isn't a black box: it speaks a versioned `postMessage` contract so your page can tell the avatar where to walk, what to say, and which environment to show. The contract is defined in [src/walk-embed-events.js](../src/walk-embed-events.js) and documented interactively at [/docs/walk-embed-api](/docs/walk-embed-api).Every message is namespaced to the `three-walk` channel and carries a protocol version, so it never collides with other `message` listeners on your page.@@ -106449,7 +107136,7 @@ Every message is namespaced to the `three-walk` channel and carries a protocol vif (!msg || msg.channel !== 'three-walk') return;if (msg.type === 'walk:ready') {- send('walk:say', { text: 'Hi — thanks for visiting.' });+ send('walk:say', { text: 'Hi: thanks for visiting.' });send('walk:goto', { x: 4, z: 0 }); // walk to a world spot}if (msg.type === 'walk:position') {@@ -106463,10 +107150,10 @@ The commands a host can send (inbound) and the events the iframe emits (outbound| Direction | Message | Payload ||---|---|---|-| host → iframe | `walk:goto` | `{ x, z }` — walk to a world position, then stop |-| host → iframe | `walk:gesture` | `{ gesture }` — one of `idle` `walk` `run` `wave` `jump` |+| host → iframe | `walk:goto` | `{ x, z }`: walk to a world position, then stop |+| host → iframe | `walk:gesture` | `{ gesture }`: one of `idle` `walk` `run` `wave` `jump` || host → iframe | `walk:say` | `{ text, voice?, durationMs? }` |-| host → iframe | `walk:env` | `{ env }` — one of the six environments |+| host → iframe | `walk:env` | `{ env }`: one of the six environments || host → iframe | `walk:avatar` | `{ avatarId }` || host → iframe | `walk:config` | `{ speed?, bg?, controls? }` || iframe → host | `walk:ready` | `{ avatarId, env }` (fires once, when loaded) |@@ -106492,7 +107179,7 @@ The iframe is great for a fixed card. For the actual corner-mascot-plus-playgrounpm install @three-ws/walk three```-`three` is a **peer dependency** — the package brings none of its own; you supply >= 0.150 from your app.+`three` is a **peer dependency**: the package brings none of its own; you supply >= 0.150 from your app.```jsimport { createWalkCompanion } from '@three-ws/walk';@@ -106501,7 +107188,7 @@ const walk = createWalkCompanion();walk.bootstrap();```-`createWalkCompanion` is **side-effect free on import** — nothing touches the DOM, and no Three.js is fetched, until you call `bootstrap()` or `enable()`. A page that never turns the companion on pays nothing for shipping the import.+`createWalkCompanion` is **side-effect free on import**, nothing touches the DOM, and no Three.js is fetched, until you call `bootstrap()` or `enable()`. A page that never turns the companion on pays nothing for shipping the import.`bootstrap()` is the app-style entry: it auto-mounts based on the visitor's saved preference, honors `?walk=` deep links, and resumes the playground after a page "dive." If you'd rather drive it yourself:@@ -106531,10 +107218,10 @@ walk.instance // the live companion (or null)Once `bootstrap()` is wired, these query params work on any page:-- `?walk=1` — force the companion on-- `?walk=0` — force it off-- `?walk=play` — deep-link straight into the full-page playground-- `?avatar=<id>` — load a specific avatar (a roster id, or one of your own)+- `?walk=1`: force the companion on+- `?walk=0`: force it off+- `?walk=play`: deep-link straight into the full-page playground+- `?avatar=<id>`: load a specific avatar (a roster id, or one of your own)---@@ -106558,9 +107245,9 @@ Other options worth knowing: `excludedRoutes` (path prefixes where the companion----## Step 5: Choose who walks — the roster+## Step 5: Choose who walks: the roster-Every visitor can pick who walks with them from a built-in roster: a robot mascot, humanoids, a fox, dancers, and showpieces. Each entry declares a rig strategy so it **always moves** — nothing freezes in a bind/T-pose:+Every visitor can pick who walks with them from a built-in roster: a robot mascot, humanoids, a fox, dancers, and showpieces. Each entry declares a rig strategy so it **always moves**, nothing freezes in a bind/T-pose:| `rig` | Used for | How it animates ||---|---|---|@@ -106589,52 +107276,52 @@ createWalkCompanion({}).bootstrap();```-User-generated avatars served by the GLB proxy (`/api/avatars/<id>/glb`) resolve at runtime via `makeApiAvatarEntry(id)` — you don't have to list them.+User-generated avatars served by the GLB proxy (`/api/avatars/<id>/glb`) resolve at runtime via `makeApiAvatarEntry(id)`, you don't have to list them.----## Step 6: Walk the whole web — the Chrome extension+## Step 6: Walk the whole web: the Chrome extensionThe embed and SDK put the avatar on *your* site. The Chrome extension puts it on *every* site the visitor opens. Link to [/walk](/walk) from your page, or just point people there.What the extension does, per the product page:-- The avatar walks over any page the user visits — articles, docs, social feeds.-- It reads pages aloud as it strolls — a living browsing companion.+- The avatar walks over any page the user visits: articles, docs, social feeds.+- It reads pages aloud as it strolls: a living browsing companion.- The visitor picks any of their three.ws avatars from the popup and switches in one click.- Minimal permissions, no tracking. Privacy details are on [/extension/privacy](/extension/privacy).-This is the one path you don't embed — you point your visitors at the install. It's the most ambitious surface of the [/walk](/walk) product, and the strongest reason to give your users a three.ws avatar in the first place.+This is the one path you don't embed: you point your visitors at the install. It's the most ambitious surface of the [/walk](/walk) product, and the strongest reason to give your users a three.ws avatar in the first place.---## Step 7: The distance leaderboard-Every stroll logs distance, and the longest ones climb the global board at [/walk-leaderboard](/walk-leaderboard) — ranked daily, weekly, and all-time. The data is real, served from `/api/walk/leaderboard`, so you can surface a "top walkers" teaser on your own page:+Every stroll logs distance, and the longest ones climb the global board at [/walk-leaderboard](/walk-leaderboard), ranked daily, weekly, and all-time. The data is real, served from `/api/walk/leaderboard`, so you can surface a "top walkers" teaser on your own page:```jsasync function loadTopWalkers() {const res = await fetch(- 'https://three.ws/api/walk/leaderboard?period=all-time&metric=distance',+ 'https://three.ws/api/walk/leaderboard?period=all-time&metric=distance&limit=3',{ headers: { accept: 'application/json' } },);if (!res.ok) throw new Error(`HTTP ${res.status}`);- const data = await res.json();- // The endpoint may return { leaders } | { walkers } | { entries } | [...]- const rows = Array.isArray(data)- ? data- : data.leaders || data.walkers || data.entries || data.results || data.data || [];- return rows.slice(0, 3); // each: { name, distance, image_url?, url? }+ const { rows = [] } = await res.json();+ // Each row: { rank, key, username, handle, avatarId, avatar, value, deltaFromYesterday }+ // `value` is the metric you asked for: meters for metric=distance.+ return rows;}```-Format distances for display the way the live page does — meters under 1km, kilometres above:+`period` is `daily` / `weekly` (the default) / `all-time`, `metric` is `distance` (the default) / `sites` / `time`, and `limit` is 1 to 100 (default 50). The response also carries `total`, `offset`, and `hasMore` for paging.++Format distances for display the way the live board does, meters under 1 km, kilometres above:```jsfunction formatDistance(meters) {const m = Number(meters);- if (!Number.isFinite(m) || m <= 0) return '—';- if (m >= 1000) return (m / 1000).toFixed(m >= 10000 ? 0 : 1) + ' km';+ if (!Number.isFinite(m) || m <= 0) return '0 m';+ if (m >= 1000) return (m / 1000).toFixed(2) + ' km';return Math.round(m) + ' m';}```@@ -106645,14 +107332,14 @@ Always design the empty and error states: a fresh deployment has no walks logged## Troubleshooting-- **Iframe is blank / "loading avatar…" never clears** — the host needs WebGL. Confirm the browser is WebGL-capable and the page isn't blocking the iframe with a restrictive `Content-Security-Policy` `frame-src`. The embed ships `frame-ancestors *`, so it's the host CSP that usually blocks it.-- **postMessage commands do nothing** — you're probably sending before `walk:ready`. Wait for the `walk:ready` event, or send `walk:ping` to re-trigger it. Also confirm your envelope is `{ channel: 'three-walk', v: 1, type, ...payload }` — messages without the channel are ignored unless they use a known legacy `walk:*` type.-- **`walk:goto` lands somewhere unexpected** — coordinates are clamped to the world radius (~±11.5m). A target outside the ground disc is pulled back in.-- **`walk:env` rejected with a `walk:error`** — `env` must be exactly one of `studio` `void` `beach` `sunset` `night` `grid`. Anything else is refused.-- **Avatar shows a frozen T-pose** — that means the rig strategy is wrong for the GLB. A humanoid that ships only a T-pose must use `rig: 'shared'` so the shared clip library is retargeted onto it; `embedded` is only for GLBs that carry their own clips.-- **SDK throws on import about `three`** — `three` is a peer dependency. Install it (`npm install three`) and make sure your bundle resolves a single copy >= 0.150.-- **Companion never appears after `bootstrap()`** — check it's not an excluded route. By default the corner mascot skips full-screen 3D paths (`/walk`, `/walk-embed`, `/play`, `/ar`, and similar). Override `excludedRoutes` if your paths overlap.-- **The companion loaded Three.js on a page that doesn't use it** — it shouldn't: `createWalkCompanion` is side-effect-free on import and fetches nothing until `enable()`/`bootstrap()`. If you see a fetch, something is calling `enable()` unconditionally.+- **Iframe is blank / "loading avatar…" never clears**, the host needs WebGL. Confirm the browser is WebGL-capable and the page isn't blocking the iframe with a restrictive `Content-Security-Policy` `frame-src`. The embed ships `frame-ancestors *`, so it's the host CSP that usually blocks it.+- **postMessage commands do nothing**: you're probably sending before `walk:ready`. Wait for the `walk:ready` event, or send `walk:ping` to re-trigger it. Also confirm your envelope is `{ channel: 'three-walk', v: 1, type, ...payload }`, messages without the channel are ignored unless they use a known legacy `walk:*` type.+- **`walk:goto` lands somewhere unexpected**: coordinates are clamped to the world radius (~±11.5m). A target outside the ground disc is pulled back in.+- **`walk:env` rejected with a `walk:error`**: `env` must be exactly one of `studio` `void` `beach` `sunset` `night` `grid`. Anything else is refused.+- **Avatar shows a frozen T-pose**: that means the rig strategy is wrong for the GLB. A humanoid that ships only a T-pose must use `rig: 'shared'` so the shared clip library is retargeted onto it; `embedded` is only for GLBs that carry their own clips.+- **SDK throws on import about `three`**: `three` is a peer dependency. Install it (`npm install three`) and make sure your bundle resolves a single copy >= 0.150.+- **Companion never appears after `bootstrap()`**: check it's not an excluded route. By default the corner mascot skips full-screen 3D paths (`/walk`, `/walk-embed`, `/play`, `/ar`, and similar). Override `excludedRoutes` if your paths overlap.+- **The companion loaded Three.js on a page that doesn't use it**, it shouldn't: `createWalkCompanion` is side-effect-free on import and fetches nothing until `enable()`/`bootstrap()`. If you see a fetch, something is calling `enable()` unconditionally.---@@ -106660,20 +107347,20 @@ Always design the empty and error states: a fresh deployment has no walks loggedYou added a walking 3D avatar to your site three ways and learned what the [/walk](/walk) product ships:-- **One-tag embed** — paste the [/walk-embed](/walk-embed) iframe, pick the world and controls with query params (`env`, `controls`, `orbit`, `avatar`). No build step.-- **postMessage contract** — drive the embed from the host page with `walk:goto` / `walk:say` / `walk:env` and listen for `walk:ready` / `walk:position`, on the versioned `three-walk` channel. Full reference at [/docs/walk-embed-api](/docs/walk-embed-api).-- **`@three-ws/walk` SDK** — `createWalkCompanion().bootstrap()` mounts the real corner companion plus the full-page playground, side-effect-free until enabled, with a built-in avatar picker and a two-strategy roster that never T-poses.-- **The product surfaces** — the Chrome extension presented on [/walk](/walk) that walks the whole web, and the distance [/walk-leaderboard](/walk-leaderboard) you can read from `/api/walk/leaderboard`.+- **One-tag embed**: paste the [/walk-embed](/walk-embed) iframe, pick the world and controls with query params (`env`, `controls`, `orbit`, `avatar`). No build step.+- **postMessage contract**: drive the embed from the host page with `walk:goto` / `walk:say` / `walk:env` and listen for `walk:ready` / `walk:position`, on the versioned `three-walk` channel. Full reference at [/docs/walk-embed-api](/docs/walk-embed-api).+- **`@three-ws/walk` SDK**: `createWalkCompanion().bootstrap()` mounts the real corner companion plus the full-page playground, side-effect-free until enabled, with a built-in avatar picker and a two-strategy roster that never T-poses.+- **The product surfaces**: the Chrome extension presented on [/walk](/walk) that walks the whole web, and the distance [/walk-leaderboard](/walk-leaderboard) you can read from `/api/walk/leaderboard`.-The leverage is composability: the same engine renders the corner mascot, the full-page playground, the standalone embed, and the extension — so an avatar you build once walks everywhere.+The leverage is composability: the same engine renders the corner mascot, the full-page playground, the standalone embed, and the extension, so an avatar you build once walks everywhere.## See also-- [3D store guide for Shopify](/tutorials/shopify-store-guide) — the same engine as a guided tour: the avatar walks a storefront, spotlights sections, and narrates each one-- [Walk docs](/docs/walk) — the full developer + user reference for the walking-avatar system-- [Walk embed API](/docs/walk-embed-api) — interactive playground for the postMessage contract-- [Swap your avatar in Studio](/docs/tutorials/swap-avatar-in-studio) — build the avatar that walks-- [Embed your agent on a website](/docs/tutorials/embed-on-website) — the other side of putting three.ws on your page+- [3D store guide for Shopify](/tutorials/shopify-store-guide), the same engine as a guided tour: the avatar walks a storefront, spotlights sections, and narrates each one+- [Walk docs](/docs/walk): the full developer + user reference for the walking-avatar system+- [Walk embed API](/docs/walk-embed-api): interactive playground for the postMessage contract+- [Swap your avatar in Studio](/docs/tutorials/swap-avatar-in-studio), build the avatar that walks+- [Embed your agent on a website](/docs/tutorials/embed-on-website), the other side of putting three.ws on your page---@@ -106967,9 +107654,9 @@ A wallet sign-in that works from any origin that can reach the API, survives the# Use the <agent-3d> web component end-to-end-The iframe snippet is convenient. Paste it, agent on the page. But once your site has a component system — React, Vue, Svelte, a design system — that opaque iframe starts to feel like a stranger in the codebase. You want the agent to be a real component, with props, refs, lifecycle, and a place in your component library.+The iframe snippet is convenient. Paste it, agent on the page. But once your site has a component system, React, Vue, Svelte, a design system, that opaque iframe starts to feel like a stranger in the codebase. You want the agent to be a real component, with props, refs, lifecycle, and a place in your component library.-That's what `<agent-3d>` is for. It's a standards-based custom element that drops cleanly into any framework, exposes the full JavaScript API (methods, events, live attributes), and supports reactive attribute changes — you can swap the loaded agent at runtime by changing one prop.+That's what `<agent-3d>` is for. It's a standards-based custom element that drops cleanly into any framework, exposes the full JavaScript API (methods, events, live attributes), and supports reactive attribute changes, you can swap the loaded agent at runtime by changing one prop.By the end of this tutorial you'll know the spec well enough to pick the right embed style for any project, wire the element into React and Vue with refs and reactivity, slot your own UI alongside the avatar, and react to attribute changes after mount.@@ -106981,15 +107668,15 @@ By the end of this tutorial you'll know the spec well enough to pick the right e- A slotted layout where your chat input lives next to the avatar- A short web-components primer if you've never built a custom element-**Prerequisites:** Familiarity with React (hooks, refs) or Vue 3 (Composition API). You don't need prior experience with the Custom Elements spec — Step 1 covers the basics.+**Prerequisites:** Familiarity with React (hooks, refs) or Vue 3 (Composition API). You don't need prior experience with the Custom Elements spec, Step 1 covers the basics.----## Step 1 — A 60-second web components primer+## Step 1: A 60-second web components primerIf you already know custom elements, skip to Step 2. Otherwise, here's the part of the spec that matters for using `<agent-3d>`.-A custom element is a tag your browser doesn't ship by default. Someone (us, in this case) registers a JavaScript class against a name, and from that point on the tag works exactly like any built-in element. You can put `<agent-3d>` in HTML, in JSX, in a Vue template — anywhere a `<div>` would go.+A custom element is a tag your browser doesn't ship by default. Someone (us, in this case) registers a JavaScript class against a name, and from that point on the tag works exactly like any built-in element. You can put `<agent-3d>` in HTML, in JSX, in a Vue template, anywhere a `<div>` would go.Three things make custom elements powerful:@@ -107007,11 +107694,11 @@ From that point on, `<agent-3d>` is a real tag in the document. No further setup----## Step 2 — iframe embed vs the custom element+## Step 2: iframe embed vs the custom elementThe platform offers two embed styles for the same agent. The differences are ergonomic.-**iframe form** — sandboxed, self-contained, no script tag on your page:+**iframe form**: sandboxed, self-contained, no script tag on your page:```html<iframe@@ -107024,7 +107711,7 @@ The platform offers two embed styles for the same agent. The differences are erg></iframe>```-The agent runs entirely inside the iframe. You can't call methods on it or listen to its events from your page — the trade for that isolation is zero integration surface.+The agent runs entirely inside the iframe. You can't call methods on it or listen to its events from your page, the trade for that isolation is zero integration surface.This is the right embed when:@@ -107032,7 +107719,7 @@ This is the right embed when:- You want strict sandboxing between the agent and your page- You don't need to drive the agent from your own JavaScript-**Custom element form** — explicit, structured, framework-friendly:+**Custom element form**: explicit, structured, framework-friendly:```html<script type="module" src="https://three.ws/agent-3d/1.5.2/agent-3d.js"></script>@@ -107046,7 +107733,7 @@ This is the right embed when:></agent-3d>```-You separate "load the runtime" from "place the agent". The agent can appear anywhere in your tree, with explicit attributes you can read from a build system, type-check, or template — and you get the full JS API: `say()`, `ask()`, `wave()`, `play()`, and the event stream.+You separate "load the runtime" from "place the agent". The agent can appear anywhere in your tree, with explicit attributes you can read from a build system, type-check, or template, and you get the full JS API: `say()`, `ask()`, `wave()`, `play()`, and the event stream.This is the right embed when:@@ -107058,9 +107745,9 @@ The rest of this tutorial uses the custom-element form, because that's the one t----## Step 3 — The full attribute surface+## Step 3: The attribute surface-Here's the full list of attributes the element observes, in the categories you'll actually reach for.+Here are the attributes you'll actually reach for, by category. (`observedAttributes` in [src/element.js](https://github.com/nirholas/three.ws/blob/main/src/element.js) is the exhaustive list; it also carries niche ones like `avatar-id`, `api-base`, `name-plate`, `tracked-mint`, `clip`, `wallet`, and `sign-language`.)**Identity (one of these is required):**@@ -107068,7 +107755,7 @@ Here's the full list of attributes the element observes, in the categories you'l|---|---|| `agent-id` | The platform-hosted agent ID. Resolves the manifest from three.ws. || `manifest` | URL to a JSON manifest file. Use this for self-hosted agents. |-| `body` | Direct URL to a GLB model. Bypasses the manifest path entirely — useful for quick tests. |+| `body` | Direct URL to a GLB model. Bypasses the manifest path entirely, useful for quick tests. || `src` | Legacy alias for `manifest`. Prefer `manifest` for new code. |**Layout:**@@ -107088,20 +107775,21 @@ Here's the full list of attributes the element observes, in the categories you'l|---|---|| `name` | The agent's display name in the nameplate || `voice` | Set to `livekit` to opt into LiveKit-backed real-time voice |-| `avatar-chat` | Set to `off` to hide the built-in chat input |+| `chat` | Set to `off` for a bare avatar with no built-in chat shell (`kiosk` does the same) |+| `avatar-chat` | Set to `off` to drop the avatar out of the chat column and lay the chat out as a plain bottom bar || `avatar-walk` | Set to `off` to disable the walk-when-talking behaviour || `framing` | Set to `portrait` for a head-and-shoulders camera framing; the default frames the full body |-| `eager` | Skip the lazy-load wait — boot immediately even when off-screen |+| `eager` | Skip the lazy-load wait: boot immediately even when off-screen || `api-key` | Override the brain API key (use sparingly; backends are safer) || `key-proxy` | URL of your own proxy that vends scoped keys |-Every observed attribute can be changed after mount. Step 6 shows what that looks like in practice.+Every observed attribute can be changed after mount, and Step 6 shows what that looks like in practice. Two of the attributes above are read once at boot rather than observed: `name` and `eager`. Setting either after the element has booted has no effect.----## Step 4 — A reusable React wrapper+## Step 4: A reusable React wrapper-React doesn't know about custom elements out of the box. The DOM does — React just passes attributes and children through. That means most things "just work", with two exceptions:+React doesn't know about custom elements out of the box. The DOM does, React just passes attributes and children through. That means most things "just work", with two exceptions:1. **Booleans:** React converts `eager={true}` into the string `"true"`, which is *not* the same as the bare `eager` attribute. Use `eager=""` or omit the attribute entirely.2. **Events:** React's `onSomething` props only work for events the framework knows about. Custom events need an `addEventListener` in a `useEffect`.@@ -107217,7 +107905,7 @@ A few notes on what the wrapper does:- **Runtime loaded once.** `ensureRuntime()` guards against re-injecting the script on every mount. It checks for an existing tag with `data-agent-3d-runtime` and resolves immediately if found.- **Events bound in `useEffect`.** Custom event names map to props (`onReady`, `onMessage`). The cleanup function unbinds them, so the wrapper plays nicely with strict mode and unmount.-- **No camelCase attribute names.** Custom elements use dash-case (`agent-id`, not `agentId`). React passes attributes through as-is — `agent-id` is fine in JSX.+- **No camelCase attribute names.** Custom elements use dash-case (`agent-id`, not `agentId`). React passes attributes through as-is, `agent-id` is fine in JSX.- **`useRef` is the API handle.** If you need to call `ref.current.say('hi')` from a parent, expose the ref via `forwardRef` or pass an `apiRef` prop in.For TypeScript, drop this in a `.d.ts`:@@ -107245,7 +107933,7 @@ declare namespace JSX {----## Step 5 — A Vue 3 wrapper+## Step 5: A Vue 3 wrapperVue handles custom elements gracefully provided you flag them as such. Add `agent-3d` to the compiler's custom-element list in your build config:@@ -107371,7 +108059,7 @@ The `defineExpose` block matters: without it, the parent's `agent.value.say(...)----## Step 6 — Reactive attribute changes+## Step 6: Reactive attribute changesThis is the moment when the custom-element approach really pays off. The element observes its key attributes, so changing one re-runs the relevant boot logic.@@ -107398,11 +108086,11 @@ The same trick works for `body`, `manifest`, `src`, and the layout attributes (`There are a few attributes worth treating carefully:-- `eager` — only matters at first mount; toggling it after boot has no effect since boot already happened.-- `api-key` — changing this mid-session won't re-issue in-flight LLM calls. Treat it as set-once for any given agent instance.-- `tracked-mint` — changing this swaps the on-chain trade feed the agent is reacting to. Useful for token-aware widgets.+- `eager`: only matters at first mount; toggling it after boot has no effect since boot already happened.+- `api-key`: changing this mid-session won't re-issue in-flight LLM calls. Treat it as set-once for any given agent instance.+- `tracked-mint`: changing this swaps the on-chain trade feed the agent is reacting to. Useful for token-aware widgets.-If you need a *full* fresh re-mount (rare — usually the in-place swap is what you want), key the element on the agent ID:+If you need a *full* fresh re-mount (rare: usually the in-place swap is what you want), key the element on the agent ID:```jsx<Agent3D key={activeAgent} agentId={activeAgent} />@@ -107412,30 +108100,32 @@ The `key` prop forces React to unmount and remount the wrapper, which fully tear----## Step 7 — Slotting your own UI+## Step 7: Slotting your own UI-The element has a built-in chat input at the bottom. That's fine for a drop-in widget. For an integrated product page, you usually want your own input — styled to match your design system, sharing the page layout, with custom send buttons.+The element has a built-in chat input at the bottom. That's fine for a drop-in widget. For an integrated product page, you usually want your own input, styled to match your design system, sharing the page layout, with custom send buttons.Two parts to this.-**Hide the built-in UI** with `avatar-chat="off"`:+**Hide the built-in UI** with `chat="off"` (the same bare-avatar switch `kiosk` flips, but as a value you can bind from a template):```html<agent-3did="agent"agent-id="YOUR_AGENT_ID"- avatar-chat="off"+ chat="off"width="100%"height="100%"></agent-3d>```+The brain still boots, so `say()`, `ask()`, and the whole event stream keep working, only the chrome is gone.+**Wire your own UI** that calls the element's API:```html<div class="agent-shell"><div class="canvas">- <agent-3d id="agent" agent-id="YOUR_AGENT_ID" avatar-chat="off"></agent-3d>+ <agent-3d id="agent" agent-id="YOUR_AGENT_ID" chat="off"></agent-3d></div><div class="composer"><input id="message" placeholder="Ask me anything" />@@ -107482,14 +108172,14 @@ That's the bare minimum. In a real product page you would also add a chat-log elTwo cautions when going custom-UI:-- **Don't try to inject DOM into the agent's shadow root.** The element uses Shadow DOM (`mode: 'open'`) — you *can* technically reach into it, but anything in there is internal and will change between versions. Build your UI *around* the agent, not *inside* it.+- **Don't try to inject DOM into the agent's shadow root.** The element uses Shadow DOM (`mode: 'open'`), you *can* technically reach into it, but anything in there is internal and will change between versions. Build your UI *around* the agent, not *inside* it.- **Style the wrapper, not the internals.** CSS rules on `<agent-3d>` itself (width, height, position) work fine. CSS rules targeting its shadow children won't survive a minor version bump.----## Step 8 — A complete example, top to bottom+## Step 8: A complete example, top to bottom-Here's a single-file working example you can drop into any Vite or Next.js app. It's the full pattern from Steps 4 and 6 combined — a wrapper, a reactive agent swap, and event handling.+Here's a single-file working example you can drop into any Vite or Next.js app. It's the full pattern from Steps 4 and 6 combined, a wrapper, a reactive agent swap, and event handling.```jsx// pages/agents.jsx (Next.js) or src/Agents.jsx (Vite)@@ -107545,20 +108235,20 @@ Pick an agent from the dropdown, the active one swaps in place, and the event loYou can now treat `<agent-3d>` as a real component in any framework. The big takeaways:-- The iframe and custom-element embeds serve different jobs — sandboxed drop-in vs a full-API component; reach for the element whenever your own code needs to drive the agent+- The iframe and custom-element embeds serve different jobs, sandboxed drop-in vs a full-API component; reach for the element whenever your own code needs to drive the agent- Attribute changes are reactive; you can swap agents, modes, and layouts at runtime- React works fine once you bind events in `useEffect`; remember dash-case attribute names- Vue works fine once you flag the tag as a custom element in the compiler config-- Use `avatar-chat="off"` to bring your own composer when you want full control+- Use `chat="off"` to bring your own composer when you want full control- Don't reach into the shadow DOM; style the wrapper, not the internalsThe web component is the most robust integration point the platform offers. Build your design system around it once and the agent fits anywhere you ship.## Next steps-- [Drive the agent with the JavaScript API](/tutorials/js-api-events) — methods and events covered in depth-- [Embed a three.ws agent on your website](#sec-431) — the no-framework paths (Webflow, WordPress, Squarespace) for completeness-- [Trigger the agent from page events](/tutorials/trigger-from-page-events) — once it's mounted, make it react to the user journey+- [Drive the agent with the JavaScript API](/tutorials/js-api-events), methods and events covered in depth+- [Embed a three.ws agent on your website](#sec-431), the no-framework paths (Webflow, WordPress, Squarespace) for completeness+- [Trigger the agent from page events](/tutorials/trigger-from-page-events), once it's mounted, make it react to the user journey---@@ -107570,7 +108260,7 @@ The web component is the most robust integration point the platform offers. Buil**Level:** intermediate. You should be comfortable with Node and `git`.**Time:** about 20 minutes.-**You will build:** a real guard that fails the build when an API handler forgets its error boundary, wired into the gate, covered by tests, and registered so it shows up on [/guards](/guards).+**You will build:** a real guard that fails the build when a server-side `fetch()` has no timeout, wired into the gate, proven against the violation it claims to catch, covered by tests, and registered so it shows up on [/guards](/guards).This repository has no CI, so a guard is not a nice-to-have that runs somewhere in the cloud. It is the only thing standing between a mistake and production. [Repository guards](/docs/guards) explains the system; this page walks you through adding one.@@ -107676,12 +108366,32 @@ Add an entry to `data/guards.json`. This is what [/guards](/guards) renders and"protects": "No server-side fetch can hang without a timeout.","why": "A fetch with no timeout turns one slow upstream into stacked requests and 502s on unrelated endpoints. It reads as ordinary code in review.","stages": ["gate"],- "needs": "none"+ "needs": "none",+ "proof": {+ "summary": "An API handler calling fetch() with no timeout.",+ "violation": {+ "write": {+ "api/guard-proof-fetch-timeout.js": "export default async function handler(req, res) {\n\tconst r = await fetch('https://example.com/slow');\n\tres.json(await r.json());\n}\n"+ }+ },+ "expect": "api/guard-proof-fetch-timeout.js"+ }}```Every field is required, and `audit-guards` enforces that, because a guard with no `why` is one nobody dares delete and nobody understands.+`proof` is the field people forget, and it is the one the auditor refuses to let you skip. Leave it out and `npm run audit:guards` fails with:++```+[audit-guards] guard `check-fetch-timeouts`: guard "check-fetch-timeouts" has no+proof block. Every guard must declare the violation it rejects (see docs/guards.md).+```++It declares the violation your guard must reject, in fixture form rather than code: `summary` says what the violation is in one line, `violation` is the mutation applied to a throwaway copy of the repo, and `expect` is the fragment the guard's own failure output must contain. Step 5 runs it. `violation` also takes `append`, `delete`, `link`, and `json` instead of `write`; a guard that genuinely cannot be proven offline declares `{"kind": "live", "reason": "..."}` and says why, rather than faking a green.++Nothing else needs regenerating by hand: `npm run build:guards` refreshes `public/guards.json` (the file [/guards](/guards) fetches), and it already runs inside `prebuild` on every build.+---## Step 4: wire it into a stage@@ -107721,9 +108431,30 @@ Anything needing the network or credentials goes in `manual`. A flaky guard on a----## Step 5: test it+## Step 5: prove it still catches something++`audit:guards` proved the guard is *wired*. It cannot prove the guard still *catches* anything. A checker that has rotted into a no-op (a directory it stopped scanning, a regex that stopped matching, an exclusion list that grew until it excluded everything) exits 0 forever, and exit 0 is indistinguishable from a clean tree. That is the worst failure mode a safety net has: loudest when it works, silent when it dies.++The `proof` block you wrote in Step 3 is what closes that hole. Run it:++```bash+npm run prove:guards -- --only check-fetch-timeouts+```++The runner builds a throwaway git worktree overlaid with your working tree and runs your guard twice there. Both halves are required:++1. **Control.** The unmutated sandbox must make the guard exit 0. A clean baseline is what makes the next step attributable. Without it, a non-zero exit could just mean the sandbox is broken.+2. **Violation.** The `write` fixture lands `api/guard-proof-fetch-timeout.js`, and the guard must now exit non-zero *and* print the `expect` fragment, because a guard that fails for the wrong reason is not a working guard.++The verdicts you can get back are `proven`, `control-failed` (your guard already fails on a clean tree), `not-caught` (the fixture slipped past it, so the guard is a no-op), and `wrong-reason` (it failed, but not on your violation). Only the first one means what you built works. Results land in `public/guard-proofs.json` with a verdict per guard.++It is safe to run while other agents are working in this tree: each run gets its own sandbox keyed to its process id and never writes to the repository except that one results file.++---++## Step 6: test it-A guard with no test rots into a no-op, and you find out when the thing it was supposed to catch ships anyway. Create `tests/check-fetch-timeouts.test.js`:+A guard with no test rots into a no-op, and you find out when the thing it was supposed to catch ships anyway. A proof covers the violation you thought of; a test file is where you pin the false positives. Create `tests/check-fetch-timeouts.test.js`:```jsimport { describe, it, expect, beforeAll, afterAll } from 'vitest';@@ -107796,7 +108527,7 @@ Build the sandbox rather than pointing the test at the real repository. A test t----## Step 6: document it+## Step 7: document itAdd a row to the relevant table in [`docs/guards.md`](/docs/guards), and add a `data/changelog.json` entry if the guard changes what contributors have to do.@@ -107808,9 +108539,10 @@ Your guard is done when all of these are true:- [ ] `scripts/check-<thing>.mjs` exists, exits non-zero with an actionable message, and opens with the incident that motivated it.- [ ] An npm script runs it.-- [ ] `data/guards.json` has an entry with `title`, `protects`, `why`, and `stages`.+- [ ] `data/guards.json` has an entry with `title`, `protects`, `why`, `stages`, and a `proof`.- [ ] It is wired into the chain for every stage it claims.- [ ] `npm run audit:guards` passes.+- [ ] `npm run prove:guards -- --only <id>` returns `proven`, not `not-caught` or `control-failed`.- [ ] A test covers the pass case, the fail case, and at least one false positive it must not report.- [ ] `npm run gate` still passes.@@ -107818,7 +108550,7 @@ Your guard is done when all of these are true:## Related-- [Repository guards](/docs/guards): every existing guard, its stage, and the design principles.+- [Repository guards](/docs/guards): every existing guard, its stage, the design principles, and the full `proof` vocabulary.- [/guards](/guards): the registry as a browsable page.- [Start here](/docs/start-here): what three.ws is, if you landed here first.@@ -112031,7 +112763,7 @@ curl "https://three.ws/api/x402/vanity?prefix=So"Longer than 3 chars? A 4–5 char pattern is served if (and only if) it's instock — same endpoint, premium price, `source: "inventory"`. Out of stock getsa `404 not_in_stock`; grind it yourself in the browser at-[`/vanity`](https://three.ws/vanity), or browse what IS available at+[`/vanity-wallet`](https://three.ws/vanity-wallet), or browse what IS available at[premium inventory](#tier-3--premium-inventory).### Security model@@ -112121,7 +112853,7 @@ challenges and the discovery doc stay in parity.- [x402 endpoints overview](#sec-514)- [three-vanity/v1 protocol spec](#sec-005)- [Pump Launcher](#sec-333) — accepts an optional vanity mint prefix/suffix-- Web grinder + verifier: [`/vanity`](https://three.ws/vanity), [`/vanity/verify`](https://three.ws/vanity/verify)+- Web grinder + verifier: [`/vanity-wallet`](https://three.ws/vanity-wallet), [`/vanity/verify`](https://three.ws/vanity/verify)---@@ -117067,8 +117799,13 @@ search results after 30 days without a settle**.`x-payment-info` + `responses.402` + request/response schemas — all emitted by[`api/openapi-json.js`](../api/openapi-json.js)), and (3) probing each paidroute's live 402 challenge. Validate any time with- `npx -y @agentcash/discovery@latest discover https://three.ws` and- `… check https://three.ws/<paid-route>`.+ `npx -y @agentcash/discovery@latest discover https://three.ws`, and a single+ route with+ `npx -y @agentcash/discovery@latest check https://three.ws/api/x402/crypto-intel`.+ `check` reads the OpenAPI spec, so pass a route the spec actually carries (the+ `/api/v1/x/*` proxy lane, `/api/mcp`, and the paid routes enumerated in+ `openapi-json.js`); a route outside it answers `L3_NOT_FOUND` even though its+ live 402 challenge is perfectly valid.- **Critical invariant — the `PAYMENT-REQUIRED` header carries the bazaarblock.** AgentCash's probe reads the 402 challenge from the `PAYMENT-REQUIRED`**response header** in preference to the JSON body, and checks@@ -118462,8 +119199,15 @@ to one alert per class per day.# 1. Generate the wallets (no chain, no funding — just keys).node scripts/x402-ring-setup.mjs-# 2. Apply the schema.-psql "$DATABASE_URL" -f api/_lib/migrations/2026-07-01-x402-ring-economy.sql+# 2. Apply the schema through the migration runner, never raw psql: it stamps+# api/_lib/migrations/*.sql into `schema_migrations` by sha256, and the+# deploy gate (npm run db:check) reads that ledger. A file applied by hand+# stays "pending" forever and blocks the next deploy. Preview first, because+# db:migrate applies EVERY pending migration with no dry run of its own.+npm run db:status # lists what is pending; writes nothing+npm run db:migrate # applies them (the ring lane needs 2026-07-01-x402-ring-economy.sql,+ # 2026-07-03-x402-ring-agents.sql, 2026-07-03-x402-ring-leak-scan.sql+ # and, for the payer pool below, 2026-07-17-x402-ring-pool.sql)# 3. Set env on the Cloud Run service, from the printed block# (gcloud run services update three-ws-api --region us-central1 --update-env-vars …):diff --git a/prompts/swarm-100/docs-batch-34.md b/prompts/swarm-100/docs-batch-34.mddeleted file mode 100644index d4d810a81..000000000--- a/prompts/swarm-100/docs-batch-34.md+++ /dev/null@@ -1,100 +0,0 @@-# Docs audit batch 34: /docs/hold-to-access through /docs/ibm--How to run: paste this file's repo path into a fresh Claude Code chat in this-repository and say "run this work order". This file is fully self-contained:-it depends on no other prompt file anywhere. If neighboring files in-prompts/swarm-100/ are gone, that work is done; if present, ignore them.-Every claim below rots; step 0 re-measures, and what you measure wins.--## Operating clause (binding)--- Read CLAUDE.md first. Its rules override everything, including this file.-- Finish 100% in this session. Never end the turn with a question, an option- list, or an unexecuted plan. A judgment call goes in one line of the final- report; it never becomes a question that halts work.-- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real- funds or any irreversible on-chain write, git push or a production deploy,- committing content that references a crypto project other than $THREE, and- destroying unrecoverable data.-- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no- commented-out code. Real APIs and real integrations only.-- The em-dash and en-dash characters are banned in everything you write.-- Concurrent agents share this worktree: stage explicit paths only (never a- bare add-everything), and commit finished work promptly.-- Before committing, run: npm run check:rules -- --paths <files you touched>.- It must exit 0.--## Step 0: re-derive the current state--1. Confirm each path below still exists in data/pages.json; a path that was- removed there is out of scope (note it in the report, skip it).-2. Start (or reuse) the local dev server: npm run dev (vite, port 3000).-3. Probe production for each path:-- for p in /docs/hold-to-access /docs/plan-checkout /docs/market-data-api /docs/oracle /docs/x402-distribution /docs/x402-ring-economy /docs/three-microbuy /docs/ibm; do printf '%s ' "$p"; curl -so /dev/null -w '%{http_code}\n' "https://three.ws$p"; done--## Task: audit this batch of docs pages, then fix everything found--Pages in this batch:--- /docs/hold-to-access ("Docs · Hold-to-access")-- /docs/plan-checkout ("Docs · Paid plans")-- /docs/market-data-api ("Docs · Market Data API")-- /docs/oracle ("Docs · Oracle, the conviction engine")-- /docs/x402-distribution ("Docs · x402 distribution")-- /docs/x402-ring-economy ("Docs · The closed-loop x402 ring economy")-- /docs/three-microbuy ("Docs · The $THREE micro-buy loop")-- /docs/ibm ("Docs · IBM watsonx and Granite")--For every page, in a real headless browser against localhost:--1. HTTP 200, zero console errors, zero unhandled failed requests.-2. Every link on the page resolves (internal paths exist in the route table;- anchors have targets). Fix or remove dead ones.-3. Content accuracy: the page documents current behavior. Spot-check its claims against the code it describes; where it names a command, run the command; where it shows a code sample, the sample must actually run. Fix stale claims in the same change.-4. Title tag and meta description present and specific.-5. Fix defects at their root and re-run until clean.--## Definition of done--- [ ] Every page in the batch loads locally with HTTP 200 and zero console- errors.-- [ ] Zero dead links across the batch.-- [ ] Every named command and code sample on these pages verified runnable, or corrected.-- [ ] Title and meta description verified on every page.-- [ ] npm run check:rules -- --paths <touched files> exits 0; npm test passes- if you touched code.-- [ ] Production status per page recorded in the report.--## Never blocked--| Blocker | Resolution (act, do not ask) |-|---|---|-| Missing env var or credential | Check .env and .env.local, then the Cloud Run service env, then Secret Manager (the CLAUDE.md self-unblock playbook has the exact commands). If it truly exists nowhere, wire the code fully behind the env var, prove the wiring with a dry run, and name the single missing var in the report. |-| gcloud not on PATH | Run: export PATH="$HOME/google-cloud-sdk/bin:$PATH" |-| Dev server port 3000 busy | Another agent may be serving this repo; probe it and reuse if so. Otherwise start your own on a free port: npx vite --port 3101 |-| Playwright browser missing | npx playwright install chromium |-| A surface needs a signed-in user | Register a fresh account through the real /register flow against the real API and use it. Never mock the session. |-| A defect sits in code you did not touch | Fix it if it blocks a Definition of done line (root cause it, never mask it). Otherwise note it in the report and continue. |-| An unrelated test is red | Same rule. Never pipe npm test through tail; it masks exit codes. |--## Close out (required)--1. Verify every Definition of done line with the actual command output in- front of you. Never claim a line you did not verify.-2. Commit with explicit paths and a subject that describes the diff (house- style: type(scope): what changed and why a reader cares).-3. Delete this prompt file in that same commit:-- git rm prompts/swarm-100/docs-batch-34.md-- The shrinking directory is this campaign's only progress ledger; there is- no progress log to update.-4. Final report: what step 0 measured, what changed (file list), evidence per- Definition of done line, and any one-line judgment calls. No trailing- questions, no unexecuted plans.--If a line genuinely cannot pass inside this session (an external party must-respond, or an owner-gated action is the final step), finish everything else,-leave this file in place, and state exactly which line remains and who owns-it. Never delete this file on a partial.