Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

Add vault, user-wallet, and copy-trading docs; forge catalog pipeline; MCP safety audit tooling

nirholasf960d66d66a7
diff --git a/.agents/skills/embed-three-ws-avatar/SKILL.md b/.agents/skills/embed-three-ws-avatar/SKILL.md
index 5ccbabd23..50a79ae79 100644
--- a/.agents/skills/embed-three-ws-avatar/SKILL.md
+++ b/.agents/skills/embed-three-ws-avatar/SKILL.md
@@ -27,7 +27,7 @@ the three.ws CDN with `access-control-allow-origin: *`, so it loads from any ori
></script>
<agent-3d
- body="https://three.ws/cdn/forge/anon/YOUR_MODEL.glb"
+ body="https://three.ws/avatars/default.glb"
mode="section"
kiosk
poster="/images/avatar-poster.webp"
diff --git a/.agents/skills/rig-a-model/SKILL.md b/.agents/skills/rig-a-model/SKILL.md
index bbc042d1b..66eb1829e 100644
--- a/.agents/skills/rig-a-model/SKILL.md
+++ b/.agents/skills/rig-a-model/SKILL.md
@@ -54,7 +54,7 @@ curl -s -X POST https://three.ws/api/mcp-studio \
"method": "tools/call",
"params": {
"name": "rig_mesh",
- "arguments": { "glb_url": "https://three.ws/cdn/creations/abc123/mesh.glb" }
+ "arguments": { "glb_url": "https://three.ws/avatars/cesium-man.glb" }
}
}'
```
@@ -65,7 +65,7 @@ curl -s -X POST https://three.ws/api/mcp-studio \
{
"ok": true,
"riggedGlbUrl": "https://three.ws/cdn/creations/def456/rigged.glb",
- "sourceGlbUrl": "https://three.ws/cdn/creations/abc123/mesh.glb",
+ "sourceGlbUrl": "https://three.ws/avatars/cesium-man.glb",
"poseStudioUrl": "https://three.ws/pose?src=https%3A%2F%2Fthree.ws%2F...",
"jobId": "r9k2m7x4",
"durationMs": 48000
@@ -80,7 +80,7 @@ The MCP tool is a thin client over the public rig endpoint. Submit, then poll:
# 1. Start the rig job
curl -s -X POST "https://three.ws/api/forge?action=rig" \
-H 'content-type: application/json' \
- -d '{ "glb_url": "https://three.ws/cdn/creations/abc123/mesh.glb" }'
+ -d '{ "glb_url": "https://three.ws/avatars/cesium-man.glb" }'
# → { "job_id": "r9k2m7x4", ... }
# 2. Poll until done (every ~3s, budget ~180s)
diff --git a/STRUCTURE.md b/STRUCTURE.md
index bb7ec66a1..448b957df 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -61,6 +61,7 @@ bottom.
| IRL (agents in the real world) | [pages/irl.html](pages/irl.html) `→ /irl` + [src/irl.js](src/irl.js), WebXR placement [src/ar/webxr.js](src/ar/webxr.js) + pinch [src/ar/pinch-scale.js](src/ar/pinch-scale.js), animated Quick Look bake [src/usdz-animated.js](src/usdz-animated.js) (static fallback [src/usdz-pipeline.js](src/usdz-pipeline.js)), backend [api/irl/](api/irl) | Live | Pin an agent at a real GPS spot; discovery is presence-proof-gated ([docs/irl/THREAT-MODEL.md](docs/irl/THREAT-MODEL.md)). **Place in AR** leads the dock on AR-capable devices: WebXR hit-test anchoring on Android with two-finger pinch resize (25%..400%) persisted to the pin (`anchor_scale`; the pinch lands as a follow-up `PATCH /api/irl/pins {id, scale}` after the placement tap), and ARKit Quick Look on iOS with the idle clip baked into the USDZ so the agent moves instead of standing in a T-pose. Discovered pins are equally alive in the in-page camera view: every mounted humanoid GLB plays the retargeted idle clip via a per-pin mixer ([src/irl/pin-idle.js](src/irl/pin-idle.js), phase-randomized, LOD-bounded), camera-aware gaze composes on top of the running animation, and the scene renders with ACES tone mapping + IBL + soft shadows (e2e: [tests/e2e/irl-pin-idle.spec.js](tests/e2e/irl-pin-idle.spec.js)). Inbound `/irl?avatar=<glb>` is the living-agent handoff from `GET /api/ar?…&kind=avatar` (explicit `?avatar=` wins over a saved session). Money Drops and World Lines: [docs/irl.md](docs/irl.md). SDK: [packages/irl/](packages/irl). **Share** ([src/irl/share-frame.js](src/irl/share-frame.js), [api/irl/share.js](api/irl/share.js), [api/irl/share/[token].js](api/irl/share/%5Btoken%5D.js)) mints a permanent, unfurlable `/irl/s/:token` link from the captured AR photo for the pin you just placed — never a coordinate, owner-gated, falls back to the plain native share sheet with no active pin. **Analytics** ([api/_lib/irl-analytics.js](api/_lib/irl-analytics.js), [api/irl/analytics.js](api/irl/analytics.js)) is the first site-wide usage rollup for the feature — pins placed, nearby reads, placement method, shares, drop claims — rendered at [/admin/irl-analytics](pages/admin/irl-analytics.html), aged out by the existing hourly reaper. |
| Verifiable 3D provenance (content credentials) | Spec [specs/PROVENANCE_3D.md](specs/PROVENANCE_3D.md), pure core [api/_lib/provenance-3d.js](api/_lib/provenance-3d.js), Solana anchor [api/_lib/provenance-anchor.js](api/_lib/provenance-anchor.js), MCP tools [api/_mcp3d/tools/provenance.js](api/_mcp3d/tools/provenance.js) (`verify_provenance` free, `anchor_provenance` paid $0.05), free REST verify [api/provenance.js](api/provenance.js) `→ /api/provenance`, viewer badge [public/viewer.html](public/viewer.html), docs [docs/provenance.md](docs/provenance.md). | Live (verify) · anchor gated on issuer key + devnet funds | C2PA-style signed content credentials for AI 3D: creator, prompt, model/provider, lineage, timestamp, and the GLB's sha256, ed25519-signed by the three.ws issuer with the credential hash anchored on Solana. Free public `verify_provenance` / `GET /api/provenance?src=…` recompute the hash and return `verified | tampered | unknown` (a single changed byte → tampered); the verify path and response are coin-clean (both stores). `anchor_provenance` signs + writes the SPL Memo anchor + stores the credential in R2. Tests: [tests/provenance-3d.test.js](tests/provenance-3d.test.js). Evidence: [prompts/store-submissions/_generated/provenance/](prompts/store-submissions/_generated/provenance/). Store-submission prompt 19. |
| OpenAI Select Partner (partner surface + announcement pack) | [pages/openai/index.html](pages/openai/index.html) `→ /openai`, badge assets [public/partners/openai/](public/partners/openai), announcement [blog/three-ws-openai-select-partner.html](blog/three-ws-openai-select-partner.html) `→ /blog/three-ws-openai-select-partner`, directory card in [pages/partners.html](pages/partners.html) `→ /partners`, press/social pack [marketing/openai-select-partner/](marketing/openai-select-partner/README.md), original OpenAI-supplied badge files + press-release template [OAI Select Tier Assets/](OAI%20Select%20Tier%20Assets/README.md) | Live | three.ws's OpenAI Partner Network Select-tier surface. `/openai` is the partner landing: the supplied badge (used unmodified, on a white plate), the four live OpenAI surfaces (the free keyless [3D Studio MCP connector](docs/mcp-studio.md) `→ /api/mcp-studio`, the custom-GPT Actions twin `→ /api/3d/studio`, [Spatial MCP](specs/SPATIAL_MCP.md), and [AR in ChatGPT](docs/chatgpt-ar.md)), the connect table, and the nine-tool list. The marketing pack holds badge-usage rules and the press-release draft, which is gated on OpenAI's written approval before publishing (see its README). |
+| NVIDIA Inception (membership surface + GPU docs cluster) | Membership doc [docs/nvidia-inception.md](docs/nvidia-inception.md) `→ /docs/nvidia-inception` + overview deck [docs/nvidia-inception/index.html](docs/nvidia-inception/index.html) `→ /docs/nvidia-inception/index.html`, free hosted-model map [docs/nvidia-models.md](docs/nvidia-models.md) `→ /docs/nvidia-models`, forum write-up [docs/nvidia-nemotron-spotlight.md](docs/nvidia-nemotron-spotlight.md) `→ /docs/nvidia-nemotron-spotlight`, engineering post [blog/image-to-3d-on-nvidia-l4-and-blackwell.html](blog/image-to-3d-on-nvidia-l4-and-blackwell.html) `→ /blog/image-to-3d-on-nvidia-l4-and-blackwell`, member badge [public/marks/nvidia-inception-badge.svg](public/marks/nvidia-inception-badge.svg) in [public/footer.html](public/footer.html), directory card in [pages/partners.html](pages/partners.html) `→ /partners` | Live | Everything NVIDIA on the platform, in two layers. **Free hosted lane:** one `NVIDIA_API_KEY` behind TRELLIS text-to-3D, FLUX.1-schnell, the Llama/Nemotron chat lineup, Nemotron vision, nv-embedqa, the reranker, NemoGuard, and Magpie speech (`nvidia-models`). **Self-hosted GPU fleet:** 12 Cloud Run GPU services, 11 on `nvidia-l4` and one on `nvidia-rtx-pro-6000` (Blackwell), covering text/image-to-3D, texture, remesh, rigging, and motion (see each `workers/model-*/README.md`). Membership was accepted July 2026 and is a startup program, not a partnership or an investment; the badge links to NVIDIA's startup program and must not imply endorsement. |
| Press kit (brand marks + media assets) | [pages/press/index.html](pages/press/index.html) `→ /press`, marks [public/brand/](public/brand), layout source [marketing/brand/](marketing/brand/README.md), renderer [scripts/render-brand-assets.mjs](scripts/render-brand-assets.mjs) `npm run build:brand-assets` | Live | The self-serve press surface: transparent-PNG marks (cube, horizontal and stacked lockups for dark and light grounds), the OpenAI announcement graphics, boilerplate at three lengths with copy buttons, fast facts, and the mark-usage rules. Everything is rendered from source rather than hand-exported, so a copy change re-renders the whole set; the renderer also builds `/brand/three-ws-press-kit.zip` with a README carrying the usage rules so the files cannot travel without them. Announcement cards come from [marketing/openai-select-partner/cards/social-card.html](marketing/openai-select-partner/cards/social-card.html) via `npm run build:openai-cards`. |
| Sperax partnership + SperaxOS plugin | [pages/sperax.html](pages/sperax.html) `→ /sperax`, plugin [public/sperax/](public/sperax/README.md), manifest `→ /.well-known/sperax-plugin.json`, tools [api/chat-plugin/[tool].js](api/chat-plugin/%5Btool%5D.js) `→ /api/chat-plugin/*`, panel `→ /sperax/iframe/`, bundled SDK component [chat-plugin/](chat-plugin) (`@three-ws/chat-plugin`, for hosts that mount plugins as React components instead of framing the manifest) | In-repo · Live | Partnership landing for the SperaxOS integration: three.ws ships as a standalone `plugin.delivery` plugin that gives a SperaxOS agent an embodied 3D avatar (speak/gesture/emote/render_agent), bound to an ERC-8004 identity, settling over Base x402. Launch offer: free AI credits for three.ws users on [chat.sperax.io](https://chat.sperax.io) — page explains what it is and how to claim. Blog: [/blog/three-ws-speraxusd-integration](blog/three-ws-speraxusd-integration.html) |
| Live Agents wall (mission control) | [pages/agents-live.html](pages/agents-live.html) + [src/agents-live.js](src/agents-live.js) `→ /agents-live` | In-repo · roster [api/agents/public.js](api/agents/public.js) (`sort=live`), per-agent SSE [api/agent-screen-stream.js](api/agent-screen-stream.js) | Real-time grid of every meaningful agent, ranked by most-recent on-chain/skill action (never-used placeholders suppressed). Each card streams a live caster feed when watched, else its real `agent_actions` as a terminal + an "active Nm ago" recency chip. Layers: showrunner spotlight ([src/showrunner.js](src/showrunner.js)), reputation arena ([src/agents-live-arena.js](src/agents-live-arena.js)), platform ticker ([src/theater-feed.js](src/theater-feed.js)) |
diff --git a/api/_lib/seed-prompts.js b/api/_lib/seed-prompts.js
index 892098892..96460c8fc 100644
--- a/api/_lib/seed-prompts.js
+++ b/api/_lib/seed-prompts.js
@@ -1,6 +1,7 @@
// @ts-check
// Curated prompt pool for the forge auto-seed cron and the bulk batch runner
-// (scripts/gcp/seed-avatars.mjs). Every prompt targets the FLUX text→image →
+// (gcp-credits work order 05 task 5, still open: not in the tree yet). Every
+// prompt targets the FLUX text→image →
// TRELLIS image→3D pipeline. Realistic human subjects with strong silhouettes
// and clear costume detail produce the best meshes at draft quality — avoid thin
// objects, transparent materials, and busy backgrounds.
diff --git a/api/_lib/seed-quality.js b/api/_lib/seed-quality.js
index 363810e94..03f645747 100644
--- a/api/_lib/seed-quality.js
+++ b/api/_lib/seed-quality.js
@@ -5,9 +5,10 @@
// asset enters the public catalog:
// • api/cron/forge-seed-cron.js — the per-minute trickle, in-process on
// Cloud Run (Vertex reachable via the attached service account).
-// • scripts/gcp/seed-avatars.mjs — the bulk batch runner, driven from a
-// workstation with no GCP credentials, so it routes render + judge through
-// the production HTTP surfaces instead.
+// • the bulk batch runner (gcp-credits campaign, work order 05 task 5, still
+// open: not in the tree yet) - driven from a workstation with no GCP
+// credentials, so it routes render + judge through the production HTTP
+// surfaces instead.
//
// Two stages, cheapest first:
//
diff --git a/api/_lib/x402/pipelines/forge-catalog.js b/api/_lib/x402/pipelines/forge-catalog.js
new file mode 100644
index 000000000..7cffd44b9
--- /dev/null
+++ b/api/_lib/x402/pipelines/forge-catalog.js
@@ -0,0 +1,124 @@
+// Procedural prop catalog: the shared source of truth for the autonomous forge
+// prop space. The pipeline (forge-content.js) reads it to pick what to buy next;
+// the public feed (api/forged.js) reads CATEGORIES to validate its ?category
+// filter. Keeping both on this one module is deliberate: when the two lists were
+// declared separately they drifted, and the feed rejected every real category
+// while accepting four names that matched nothing.
+
+// ── Procedural prop catalog ────────────────────────────────────────────────────
+// Combinatorial text→3D prompt space, aligned to the surfaces that actually
+// consume props: the /forged gallery, the /club stage, AR Studio placements,
+// diorama set-dressing, and avatar-adjacent items. Each category holds base
+// SUBJECTS; STYLES and FINISHES multiply them into thousands of distinct
+// prompts (8 categories × ~8 subjects × 10 styles × 8 finishes ≈ 5k combos),
+// so at 24-48 props/day the catalog effectively never loops, while staying
+// fully deterministic per hour (see nextForgeProp).
+export const PROP_CATALOG = Object.freeze({
+ 'club-decor': [
+ 'a DJ booth with turntables and a mixer',
+ 'a large stage loudspeaker stack',
+ 'a mirrored disco ball on a short chain mount',
+ 'a neon bar sign on a metal frame',
+ 'a velvet-rope stanchion pair',
+ 'a cocktail bar counter with bottle shelf',
+ 'a stage spotlight rig on a tripod',
+ 'a standing subwoofer cabinet with glowing ring',
+ ],
+ 'ar-object': [
+ 'a potted monstera plant in a ceramic pot',
+ 'a desk lamp with an articulated arm',
+ 'a retro arcade cabinet',
+ 'a coffee table with a glass top',
+ 'a floor-standing globe on a wooden stand',
+ 'a vintage record player console',
+ 'a small bookshelf filled with books',
+ 'a pedestal fan with round cage',
+ ],
+ 'diorama-set': [
+ 'a market stall with a striped awning',
+ 'a stone fountain with a round basin',
+ 'a wrought-iron street lamppost',
+ 'a small arched footbridge',
+ 'a phone booth',
+ 'a food cart with an umbrella',
+ 'a park bench with cast-iron ends',
+ 'a windmill with cloth sails',
+ ],
+ 'avatar-item': [
+ 'a wide-brim wizard hat',
+ 'a hiking backpack with straps and buckles',
+ 'a round wooden shield with a metal boss',
+ 'an electric guitar with a strap',
+ 'a katana with sheath',
+ 'a pirate tricorn hat',
+ 'a skateboard with printed deck art',
+ 'a knight helmet with hinged visor',
+ ],
+ vehicle: [
+ 'a compact hover scooter',
+ 'a vintage moped',
+ 'a go-kart with roll bar',
+ 'a small wooden rowboat with oars',
+ 'a delivery drone with four rotors',
+ 'a bumper car',
+ 'a snowmobile',
+ 'a hot air balloon with basket',
+ ],
+ container: [
+ 'a wooden shipping crate with iron-banded corners',
+ 'a barrel with riveted hoops',
+ 'a treasure chest with a heavy hasp',
+ 'a sci-fi cargo pod with glowing seams',
+ 'a stack of supply crates with stenciled markings',
+ 'a coolant drum with warning decals',
+ 'an apothecary cabinet with small drawers',
+ 'a woven picnic basket with hinged lids',
+ ],
+ furniture: [
+ 'a tavern stool, three-legged and hand-carved',
+ 'a banquet table of heavy planks',
+ 'a worn leather armchair with brass studs',
+ 'an ornate writing desk with drawers',
+ 'a canopy bed with carved posts',
+ 'a rocking chair',
+ 'a bar cart on casters',
+ 'a folding director chair',
+ ],
+ terrain: [
+ 'a modular rocky cliff terrain tile with seamless edges',
+ 'a desert dune terrain tile with sparse rocks',
+ 'a snowy mountain terrain tile with jagged ice',
+ 'a lush grassland terrain tile with scattered boulders',
+ 'a volcanic terrain tile with glowing lava veins',
+ 'a coral reef seabed terrain tile',
+ 'a mossy forest floor terrain tile with roots',
+ 'a cracked salt-flat terrain tile',
+ ],
+});
+
+// Style and finish axes multiply the subject list. Every entry must read well
+// appended to any subject above; no contradictions with category wording.
+export const STYLES = Object.freeze([
+ 'low-poly game-ready',
+ 'stylized hand-painted',
+ 'realistic PBR textured',
+ 'sci-fi with glowing accents',
+ 'medieval fantasy',
+ 'steampunk with brass fittings',
+ 'weathered post-apocalyptic',
+ 'clean minimalist modern',
+ 'voxel blocky',
+ 'retro 1980s neon',
+]);
+export const FINISHES = Object.freeze([
+ 'matte finish',
+ 'worn paint and scuffed edges',
+ 'polished metal highlights',
+ 'rich wood grain',
+ 'soft pastel palette',
+ 'bold saturated colors',
+ 'rusted and patinated',
+ 'iridescent sheen',
+]);
+
+export const CATEGORIES = Object.freeze(Object.keys(PROP_CATALOG));
diff --git a/api/_lib/x402/pipelines/forge-content.js b/api/_lib/x402/pipelines/forge-content.js
index e5393d04c..77e727b4e 100644
--- a/api/_lib/x402/pipelines/forge-content.js
+++ b/api/_lib/x402/pipelines/forge-content.js
@@ -49,6 +49,7 @@ import {
cosine,
} from '../../embeddings.js';
import { kmeans, suggestClusterCount, unit } from '../../embedding-math.js';
+import { PROP_CATALOG, STYLES, FINISHES, CATEGORIES } from './forge-catalog.js';
const log = logger('x402-forge-content');
@@ -64,124 +65,6 @@ const LOCAL_EMBED_DIM = 96;
// so the per-call k-means stays trivial inside the serverless window.
const DIVERSITY_WINDOW = 200;
-// ── Procedural prop catalog ────────────────────────────────────────────────────
-// Combinatorial text→3D prompt space, aligned to the surfaces that actually
-// consume props: the /forged gallery, the /club stage, AR Studio placements,
-// diorama set-dressing, and avatar-adjacent items. Each category holds base
-// SUBJECTS; STYLES and FINISHES multiply them into thousands of distinct
-// prompts (8 categories × ~8 subjects × 10 styles × 8 finishes ≈ 5k combos),
-// so at 24-48 props/day the catalog effectively never loops, while staying
-// fully deterministic per hour (see nextForgeProp).
-const PROP_CATALOG = Object.freeze({
- 'club-decor': [
- 'a DJ booth with turntables and a mixer',
- 'a large stage loudspeaker stack',
- 'a mirrored disco ball on a short chain mount',
- 'a neon bar sign on a metal frame',
- 'a velvet-rope stanchion pair',
- 'a cocktail bar counter with bottle shelf',
- 'a stage spotlight rig on a tripod',
- 'a standing subwoofer cabinet with glowing ring',
- ],
- 'ar-object': [
- 'a potted monstera plant in a ceramic pot',
- 'a desk lamp with an articulated arm',
- 'a retro arcade cabinet',
- 'a coffee table with a glass top',
- 'a floor-standing globe on a wooden stand',
- 'a vintage record player console',
- 'a small bookshelf filled with books',
- 'a pedestal fan with round cage',
- ],
- 'diorama-set': [
- 'a market stall with a striped awning',
- 'a stone fountain with a round basin',
- 'a wrought-iron street lamppost',
- 'a small arched footbridge',
- 'a phone booth',
- 'a food cart with an umbrella',
- 'a park bench with cast-iron ends',
- 'a windmill with cloth sails',
- ],
- 'avatar-item': [
- 'a wide-brim wizard hat',
- 'a hiking backpack with straps and buckles',
- 'a round wooden shield with a metal boss',
- 'an electric guitar with a strap',
- 'a katana with sheath',
- 'a pirate tricorn hat',
- 'a skateboard with printed deck art',
- 'a knight helmet with hinged visor',
- ],
- vehicle: [
- 'a compact hover scooter',
- 'a vintage moped',
- 'a go-kart with roll bar',
- 'a small wooden rowboat with oars',
- 'a delivery drone with four rotors',
- 'a bumper car',
- 'a snowmobile',
- 'a hot air balloon with basket',
- ],
- container: [
- 'a wooden shipping crate with iron-banded corners',
- 'a barrel with riveted hoops',
- 'a treasure chest with a heavy hasp',
- 'a sci-fi cargo pod with glowing seams',
- 'a stack of supply crates with stenciled markings',
- 'a coolant drum with warning decals',
- 'an apothecary cabinet with small drawers',
- 'a woven picnic basket with hinged lids',
- ],
- furniture: [
- 'a tavern stool, three-legged and hand-carved',
- 'a banquet table of heavy planks',
- 'a worn leather armchair with brass studs',
- 'an ornate writing desk with drawers',
- 'a canopy bed with carved posts',
- 'a rocking chair',
- 'a bar cart on casters',
- 'a folding director chair',
- ],
- terrain: [
- 'a modular rocky cliff terrain tile with seamless edges',
- 'a desert dune terrain tile with sparse rocks',
- 'a snowy mountain terrain tile with jagged ice',
- 'a lush grassland terrain tile with scattered boulders',
- 'a volcanic terrain tile with glowing lava veins',
- 'a coral reef seabed terrain tile',
- 'a mossy forest floor terrain tile with roots',
- 'a cracked salt-flat terrain tile',
- ],
-});
-
-// Style and finish axes multiply the subject list. Every entry must read well
-// appended to any subject above; no contradictions with category wording.
-const STYLES = Object.freeze([
- 'low-poly game-ready',
- 'stylized hand-painted',
- 'realistic PBR textured',
- 'sci-fi with glowing accents',
- 'medieval fantasy',
- 'steampunk with brass fittings',
- 'weathered post-apocalyptic',
- 'clean minimalist modern',
- 'voxel blocky',
- 'retro 1980s neon',
-]);
-const FINISHES = Object.freeze([
- 'matte finish',
- 'worn paint and scuffed edges',
- 'polished metal highlights',
- 'rich wood grain',
- 'soft pastel palette',
- 'bold saturated colors',
- 'rusted and patinated',
- 'iridescent sheen',
-]);
-
-const CATEGORIES = Object.freeze(Object.keys(PROP_CATALOG));
-
// Small deterministic integer hash (xorshift-style avalanche). Turns the hour
// counter into an effectively random (but reproducible) walk over the prompt
// space, so consecutive hours land on unrelated (category, subject, style)
diff --git a/api/avatar/optimize.js b/api/avatar/optimize.js
index 2078c21d6..e5d30dce2 100644
--- a/api/avatar/optimize.js
+++ b/api/avatar/optimize.js
@@ -159,6 +159,42 @@ async function applyTextureCap(doc, maxEdge) {
);
}
+let _ioPromise = null;
+
+// Stored avatar GLBs ship meshopt-compressed, and callers can point `src` at a
+// Draco-packed model, so reading either one needs the matching decoder
+// registered. The Draco encoder is needed on the write side for `draco=1`.
+async function buildTranscodeIo() {
+ const { ALL_EXTENSIONS } = await import('@gltf-transform/extensions');
+ const io = new NodeIO().registerExtensions(ALL_EXTENSIONS);
+ const [meshopt, dracoMod] = await Promise.all([import('meshoptimizer'), import('draco3dgltf')]);
+ const { MeshoptEncoder, MeshoptDecoder } = meshopt;
+ const draco3d = dracoMod.default ?? dracoMod;
+ const [, , decoder, encoder] = await Promise.all([
+ MeshoptEncoder.ready,
+ MeshoptDecoder.ready,
+ draco3d.createDecoderModule(),
+ draco3d.createEncoderModule(),
+ ]);
+ return io.registerDependencies({
+ 'meshopt.encoder': MeshoptEncoder,
+ 'meshopt.decoder': MeshoptDecoder,
+ 'draco3d.decoder': decoder,
+ 'draco3d.encoder': encoder,
+ });
+}
+
+function transcodeIo() {
+ if (!_ioPromise) {
+ _ioPromise = buildTranscodeIo();
+ // A failed codec init must not poison every later request.
+ _ioPromise.catch(() => {
+ _ioPromise = null;
+ });
+ }
+ return _ioPromise;
+}
+
async function applyDraco(doc) {
const draco = doc.createExtension(KHRDracoMeshCompression).setRequired(true);
for (const mesh of doc.getRoot().listMeshes()) {
@@ -218,7 +254,7 @@ export default wrap(async (req, res) => {
let outBytes;
try {
- const io = new NodeIO();
+ const io = await transcodeIo();
const doc = await io.readBinary(sourceBytes);
await doc.transform(dedup(), prune({ keepLeaves: false, keepAttributes: false }));
diff --git a/api/cron/forge-seed-cron.js b/api/cron/forge-seed-cron.js
index 928f60c9e..7fa63ef17 100644
--- a/api/cron/forge-seed-cron.js
+++ b/api/cron/forge-seed-cron.js
@@ -29,8 +29,8 @@
// history of 504s when a phase overruns, while a render
// plus two judge calls costs 10-20 s. The mesh stage of
// the gate always runs — it is deterministic, local, and
-// costs only the GLB fetch. The bulk runner
-// (scripts/gcp/seed-avatars.mjs) always runs both.
+// costs only the GLB fetch. The bulk runner (gcp-credits
+// work order 05 task 5, not in the tree yet) runs both.
// SEED_CRON_VISION_MS budget for the vision stage (default 20 000 ms).
// SEED_CRON_RIG '1' routes accepted avatars through the auto-rigger
// before publishing, so catalog entries arrive
diff --git a/api/forged.js b/api/forged.js
index 0b73bb3a7..0db561bbd 100644
--- a/api/forged.js
+++ b/api/forged.js
@@ -11,7 +11,10 @@
//
// Views:
// GET /api/forged : recent renderable props (status done)
-// GET /api/forged?category=crate : filter by prop family
+// GET /api/forged?category=container : filter by prop family (the eight
+// families in _lib/x402/pipelines/forge-catalog.js: club-decor,
+// ar-object, diorama-set, avatar-item, vehicle, container, furniture,
+// terrain)
// GET /api/forged?status=all : include queued/failed rows (audit view)
// GET /api/forged?limit=60 : page size (max 100)
//
@@ -26,11 +29,14 @@ import { cors, json, method, serverError, rateLimited } from './_lib/http.js';
import { limits, clientIp } from './_lib/rate-limit.js';
import { cacheGet, cacheSet } from './_lib/cache.js';
import { explorerTxUrl } from './_lib/avatar-wallet.js';
+import { CATEGORIES as PROP_CATEGORIES } from './_lib/x402/pipelines/forge-catalog.js';
const FEED_TTL_S = 20;
const DEFAULT_LIMIT = 30;
const MAX_LIMIT = 100;
-const CATEGORIES = new Set(['crate', 'barrel', 'furniture', 'terrain']);
+// Derived from the same catalog the buying pipeline picks from, so this filter
+// can never again accept names that match no row (or reject real families).
+const CATEGORIES = new Set(PROP_CATEGORIES);
function shortAddr(a) {
if (!a || typeof a !== 'string') return null;
diff --git a/blog/image-to-3d-on-nvidia-l4-and-blackwell.html b/blog/image-to-3d-on-nvidia-l4-and-blackwell.html
new file mode 100644
index 000000000..68c37e2b2
--- /dev/null
+++ b/blog/image-to-3d-on-nvidia-l4-and-blackwell.html
@@ -0,0 +1,342 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Image-to-3D on NVIDIA L4 and Blackwell: Shipping Hunyuan3D 2.1 on Cloud Run GPUs</title>
+ <meta name="description" content="A field report from the three.ws GPU fleet: why Hunyuan3D 2.1 could not load on an NVIDIA L4, why CUDA 12.4 wheels have no sm_120 kernels for RTX PRO 6000 Blackwell, and the regional quota that made the bigger card the available card.">
+ <meta name="keywords" content="Hunyuan3D 2.1, NVIDIA L4, RTX PRO 6000, Blackwell, sm_120, CUDA 12.8, Cloud Run GPU, image to 3D, text to 3D, PBR textures, GPU inference, PyTorch, TORCH_CUDA_ARCH_LIST, NVIDIA Inception, three.ws">
+ <link rel="canonical" href="https://three.ws/blog/image-to-3d-on-nvidia-l4-and-blackwell">
+
+ <meta property="og:title" content="Image-to-3D on NVIDIA L4 and Blackwell: Shipping Hunyuan3D 2.1 on Cloud Run GPUs">
+ <meta property="og:description" content="Two walls, both invisible from the model card: a memory-backed /tmp that SIGKILLs a 32 GiB instance mid-load, and cu124 wheels that ship no sm_120 kernels for Blackwell. Here is what we measured and what we changed.">
+ <meta property="og:url" content="https://three.ws/blog/image-to-3d-on-nvidia-l4-and-blackwell">
+ <meta property="og:type" content="article">
+
+ <meta name="twitter:card" content="summary_large_image">
+ <meta name="twitter:title" content="Image-to-3D on NVIDIA L4 and Blackwell">
+ <meta name="twitter:description" content="Why our image-to-3D worker could not load on an L4, why Blackwell needed a cu128 rebuild, and why regional quota made the bigger GPU the easier one to get.">
+
+ <link rel="shortcut icon" href="/favicon.ico">
+ <link rel="stylesheet" href="/nav.css">
+ <link rel="stylesheet" href="/footer.css">
+ <style>
+ :root { color-scheme: dark; }
+ body { margin: 0; background: #060611; color: #e7e7f5; font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; -webkit-font-smoothing: antialiased; }
+ .post-wrap { max-width: 760px; margin: 0 auto; padding: 96px 24px 80px; }
+ .post-meta { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; color: #7a85a8; font-size: 13px; margin-bottom: 28px; }
+ .post-date { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
+ .post-tag { padding: 2px 8px; border-radius: 999px; background: rgba(154,212,255,.08); color: #9ad4ff; font-size: 11px; font-weight: 500; letter-spacing: 0.02em; text-transform: uppercase; }
+ h1 { font-size: clamp(26px, 4vw, 40px); font-weight: 700; letter-spacing: -0.02em; line-height: 1.2; margin: 0 0 20px; }
+ h2 { font-size: 22px; font-weight: 600; margin: 48px 0 12px; letter-spacing: -0.01em; }
+ h3 { font-size: 16px; font-weight: 600; margin: 28px 0 10px; color: #dcdcf0; letter-spacing: -0.005em; }
+ p { color: #c8c8e0; line-height: 1.75; margin: 0 0 18px; font-size: 16px; }
+ ul, ol { color: #c8c8e0; line-height: 1.75; margin: 0 0 18px; padding-left: 24px; font-size: 16px; }
+ li { margin-bottom: 8px; }
+ a { color: #9ad4ff; text-decoration: none; }
+ a:hover { text-decoration: underline; }
+ code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 13px; background: rgba(154,212,255,.07); color: #9ad4ff; padding: 2px 6px; border-radius: 4px; }
+ strong { color: #e7e7f5; }
+ .post-back { display: inline-flex; align-items: center; gap: 6px; color: #7a85a8; font-size: 14px; margin-bottom: 40px; text-decoration: none; }
+ .post-back:hover { color: #9ad4ff; }
+ hr { border: none; border-top: 1px solid rgba(255,255,255,.08); margin: 48px 0; }
+
+ .lede { font-size: 18px; color: #d6d6ea; line-height: 1.7; }
+
+ .callout { border: 1px solid rgba(150,170,255,.22); background: rgba(120,140,255,.05); border-radius: 14px; padding: 20px 22px; margin: 0 0 32px; }
+ .callout h3 { margin-top: 0; color: #9ad4ff; font-size: 12px; text-transform: uppercase; letter-spacing: .08em; }
+ .callout ul { margin-bottom: 0; }
+ .callout p:last-child, .callout ul:last-child { margin-bottom: 0; }
+
+ .callout.warn { border-color: rgba(255,190,120,.24); background: rgba(255,170,80,.05); }
+ .callout.warn h3 { color: #ffc785; }
+
+ .table-scroll { overflow-x: auto; margin: 0 0 24px; -webkit-overflow-scrolling: touch; }
+ table { border-collapse: collapse; width: 100%; font-size: 14px; min-width: 480px; }
+ th, td { text-align: left; padding: 10px 14px; border-bottom: 1px solid rgba(255,255,255,.07); vertical-align: top; }
+ th { color: #9aa3c4; font-weight: 600; font-size: 12px; text-transform: uppercase; letter-spacing: .05em; border-bottom-color: rgba(255,255,255,.14); }
+ td { color: #c8c8e0; line-height: 1.55; }
+ tbody tr:hover td { background: rgba(255,255,255,.02); }
+ td code { font-size: 12px; }
+
+ pre { background: #0b0b1c; border: 1px solid rgba(255,255,255,.08); border-radius: 12px; padding: 16px 18px; overflow-x: auto; margin: 0 0 24px; -webkit-overflow-scrolling: touch; }
+ pre code { background: none; padding: 0; color: #c5d8ee; font-size: 13px; line-height: 1.6; display: block; }
+
+ figure { margin: 0 0 24px; }
+ figcaption { color: #7a85a8; font-size: 13px; line-height: 1.6; margin-top: 8px; }
+
+ .toc { border-left: 2px solid rgba(154,212,255,.25); padding: 2px 0 2px 18px; margin: 0 0 36px; }
+ .toc ol { margin: 0; padding-left: 18px; font-size: 15px; }
+ .toc li { margin-bottom: 4px; }
+
+ @media (max-width: 600px) {
+ .post-wrap { padding: 80px 18px 64px; }
+ h2 { font-size: 20px; }
+ }
+ </style>
+ <meta property="og:image" content="https://three.ws/og-image.png">
+ <meta property="og:image:width" content="1200">
+ <meta property="og:image:height" content="630">
+ <meta name="twitter:image" content="https://three.ws/og-image.png">
+</head>
+<body>
+ <div id="nav-container"></div>
+ <main class="post-wrap">
+ <a class="post-back" href="/blog">&larr; Blog</a>
+ <div class="post-meta">
+ <span class="post-date">2026-07-30</span>
+ <span class="post-tag">Engineering</span>
+ <span class="post-tag">NVIDIA</span>
+ <span class="post-tag">GPU</span>
+ <span class="post-tag">3D</span>
+ </div>
+ <h1>Image-to-3D on NVIDIA L4 and Blackwell: Shipping Hunyuan3D 2.1 on Cloud Run GPUs</h1>
+
+ <p class="lede">Every 3D generation lane on three.ws runs on NVIDIA silicon. Moving our realism lane from Hunyuan3D 2.0 to 2.1 cost us two days on problems that were invisible from the model card and from the platform docs alike. This is the field report: what failed, what the logs actually said, and what we changed. If you are putting a large diffusion-plus-mesh pipeline on managed GPU infrastructure, two of these will probably bite you too.</p>
+
+ <div class="callout">
+ <h3>The short version</h3>
+ <ul>
+ <li><strong>A 24 GiB GPU is not the constraint. The 32 GiB of system memory next to it is.</strong> Cloud Run backs <code>/tmp</code> with RAM, so staged weights and loaded weights are charged to the same budget, twice.</li>
+ <li><strong>Blackwell is compute capability 12.0.</strong> CUDA 12.4 wheels ship no <code>sm_120</code> kernels. The fix is a cu128 rebuild, not a flag.</li>
+ <li><strong>Check quota per GPU type before you pick a tier.</strong> In our region the bigger, newer card was the one we could actually get.</li>
+ <li><strong>Make readiness a separate signal from liveness.</strong> A worker that binds its port before the model loads will report healthy while it is dying.</li>
+ </ul>
+ </div>
+
+ <div class="toc">
+ <ol>
+ <li><a href="#fleet">The fleet</a></li>
+ <li><a href="#why21">Why 2.1 was worth the trouble</a></li>
+ <li><a href="#wall1">Wall 1: memory-backed <code>/tmp</code></a></li>
+ <li><a href="#wall2">Wall 2: Blackwell needs sm_120</a></li>
+ <li><a href="#quota">The quota surprise</a></li>
+ <li><a href="#rollback">Designing for a one-line rollback</a></li>
+ <li><a href="#tiers">Spending the GPU budget</a></li>
+ <li><a href="#checklist">A checklist for your own port</a></li>
+ </ol>
+ </div>
+
+ <h2 id="fleet">The fleet</h2>
+
+ <p>three.ws runs two distinct NVIDIA layers. The first is a <strong>free hosted lane</strong>: one <code>NVIDIA_API_KEY</code> unlocks TRELLIS for text-to-3D, FLUX.1-schnell for images, the Llama and Nemotron chat lineup, embeddings, reranking, safety, and speech. That layer is documented model by model in <a href="/docs/nvidia-models">NVIDIA models on three.ws</a> and it is not what this post is about.</p>
+
+ <p>The second is our <strong>self-hosted GPU fleet</strong>: twelve Cloud Run services, each a FastAPI worker wrapping one model, autoscaled per lane. Eleven run on <code>nvidia-l4</code>. One runs on <code>nvidia-rtx-pro-6000</code>.</p>
+
+ <div class="table-scroll">
+ <table>
+ <thead>
+ <tr><th>Lane</th><th>Worker</th><th>GPU</th><th>CPU / memory</th></tr>
+ </thead>
+ <tbody>
+ <tr><td>Image to 3D (PBR)</td><td><code>model-hunyuan3d-21-rtx</code></td><td><code>nvidia-rtx-pro-6000</code></td><td>20 / 80 Gi</td></tr>
+ <tr><td>Image to 3D (fallback)</td><td><code>model-hunyuan3d</code></td><td><code>nvidia-l4</code></td><td>8 / 32 Gi</td></tr>
+ <tr><td>Text to 3D</td><td><code>model-trellis</code></td><td><code>nvidia-l4</code></td><td>8 / 32 Gi</td></tr>
+ <tr><td>Image to 3D (fast)</td><td><code>model-triposg</code>, <code>model-triposr</code></td><td><code>nvidia-l4</code></td><td>8 / 32 Gi, 4 / 16 Gi</td></tr>
+ <tr><td>Texture synthesis</td><td><code>texture</code></td><td><code>nvidia-l4</code></td><td>8 / 32 Gi</td></tr>
+ <tr><td>Auto-rigging</td><td><code>rig</code>, <code>unirig</code></td><td><code>nvidia-l4</code></td><td>4 / 16 Gi</td></tr>
+ <tr><td>Text to motion</td><td><code>model-text2motion</code></td><td><code>nvidia-l4</code></td><td>4 / 16 Gi</td></tr>
+ <tr><td>Video to scene</td><td><code>model-video2scene</code></td><td><code>nvidia-l4</code></td><td>8 / 32 Gi</td></tr>
+ </tbody>
+ </table>
+ </div>
+
+ <p>The L4 is a genuinely excellent default for this workload: 24 GiB of VRAM, a low power envelope, and wide availability. Nine of these lanes never needed anything else. The tenth did, and finding out why took longer than it should have.</p>
+
+ <h2 id="why21">Why 2.1 was worth the trouble</h2>
+
+ <p>Hunyuan3D 2.0 gives you a mesh with a single baked diffuse texture. It reads fine in a product thumbnail and it reads like plastic under real lighting, because a diffuse map carries no information about how a surface responds to light.</p>
+
+ <p>Hunyuan3D 2.1 runs a shape DiT for geometry, then a separate PBR paint pass: multiview PBR diffusion, RealESRGAN super-resolution, a texture bake, and an inpaint step to close seams. It exports a GLB with a true physically-based material set:</p>
+
+ <ul>
+ <li><strong>baseColor</strong>: the albedo, with lighting information removed rather than baked in.</li>
+ <li><strong>metallicRoughness</strong>: how metal and how polished each texel is. This is the map that decides whether a sword reads as steel or as grey paint.</li>
+ <li><strong>normal</strong>: surface detail below the mesh's triangle budget, so a leather grain survives decimation.</li>
+ </ul>
+
+ <p>PBR maps are the single biggest realism lever available in a generated asset, and they are why the same model dropped into an <a href="/ar">AR scene</a> under a real room's lighting stops looking like a toy. That was the whole motivation. Everything below is what stood between the motivation and the deploy.</p>
+
+ <h2 id="wall1">Wall 1: memory-backed <code>/tmp</code></h2>
+
+ <p>The 2.1 service on an L4 never finished loading. Not slowly. Not intermittently. Every single cold start ended the same way:</p>
+
+ <pre><code>Container terminated on signal 9</code></pre>
+
+ <p>Signal 9 is <code>SIGKILL</code>. On Cloud Run that almost always means the instance exceeded its memory limit and the platform killed it. Which was confusing, because the model fits comfortably in 24 GiB of VRAM. The problem was never VRAM.</p>
+
+ <h3>The arithmetic nobody does until it fails</h3>
+
+ <p>Our worker stages weights from a bucket into <code>/tmp</code>, then loads them. Two numbers matter:</p>
+
+ <ul>
+ <li>The staged weight tree on disk: roughly <strong>18 GiB</strong>.</li>
+ <li>The model resident after <code>from_pretrained</code>: roughly <strong>14 GiB</strong>.</li>
+ </ul>
+
+ <p><strong>On Cloud Run, <code>/tmp</code> is a tmpfs.</strong> It is not disk. Every byte written there is a byte of the instance's memory allocation, and it stays allocated until you delete the file. So the peak is not 14 GiB and it is not 18 GiB. It is both at once, against the L4 tier's ceiling of 32 GiB:</p>
+
+ <pre><code>18 GiB staged weights, resident in tmpfs
++ 14 GiB model loaded into process memory
+--------
+ 32 GiB peak, against a 32 GiB limit
+ → SIGKILL, every time</code></pre>
+
+ <p>This is worth internalizing as a general rule, because it is not specific to us or to this model: <strong>on any platform where <code>/tmp</code> is memory-backed, staging a large artifact before loading it doubles your peak</strong>. The same code on a VM with a real disk works fine, which is exactly why it survives local testing and dies in production.</p>
+
+ <h3>Why the health check looked green</h3>
+
+ <div class="callout warn">
+ <h3>The part that cost us the most time</h3>
+ <p>Our worker opens its HTTP port immediately and loads the pipeline in a background task, so cold starts do not fail the platform's startup probe. That is a deliberate and common design. The consequence is that <code>GET /health</code> answers <code>200</code> while the model is still loading, which means <strong>a service that can never finish loading still looks alive</strong>.</p>
+ </div>
+
+ <p>The fix is not to remove the background load. It is to make readiness a distinct field that only flips when the pipeline is actually usable, and to surface the failure rather than swallowing it:</p>
+
+ <pre><code>{
+ "ok": true,
+ "model": "hunyuan3d-2.1",
+ "gpu_available": true,
+ "gpu_name": "NVIDIA L4",
+ "pipeline_loaded": true,
+ "ready": true,
+ "load_error": null
+}</code></pre>
+
+ <p><code>ok</code> is liveness: the process is up. <code>ready</code> is the one your router should gate on. <code>load_error</code> carries a sanitized string so a failed load is a diagnosis instead of a mystery. If you take one operational idea from this post, take this one: <strong>a boolean that means "the port is open" and a boolean that means "this instance can do work" are different booleans, and conflating them turns a five-minute fix into a two-day hunt.</strong></p>
+
+ <h3>The two real fixes</h3>
+
+ <p>There are exactly two ways out, and they are worth knowing both:</p>
+
+ <ol>
+ <li><strong>Stage incrementally.</strong> Fetch one weight subtree, call <code>from_pretrained</code> on it, delete the staged copy, move to the next. The staged and resident copies never coexist at full size, and peak memory drops to roughly the resident footprint plus one subtree. This is the right fix if you are pinned to a memory-constrained tier.</li>
+ <li><strong>Move to a tier whose floor clears the peak.</strong> The platform minimums for <code>nvidia-rtx-pro-6000</code> on Cloud Run are 20 CPU and 80 GiB, which clears a 32 GiB peak with room to spare and stops the problem being a problem.</li>
+ </ol>
+
+ <p>We took the second, because we wanted the faster card anyway and because of the quota situation below. The first remains the correct fix for anyone who wants 2.1 on an L4, and it is a contained change: it lives entirely inside the staging function.</p>
+
+ <h2 id="wall2">Wall 2: Blackwell needs sm_120</h2>
+
+ <p>Switching GPU type should be a one-line change to a deploy config. It was not, and the reason is a good thing to have in your head before you plan a Blackwell migration.</p>
+
+ <p><strong>RTX PRO 6000 is Blackwell, and Blackwell is compute capability 12.0.</strong> Our L4 image was built on CUDA 12.4 with torch 2.5 (cu124). The cu124 wheels predate that architecture and <strong>ship no <code>sm_120</code> kernels at all</strong>. There is no runtime flag, no fallback path, and no JIT rescue that makes prebuilt cu124 binaries emit Blackwell code. You rebuild or you do not run.</p>
+
+ <p>The RTX image is the same application code on a different foundation:</p>
+
+ <div class="table-scroll">
+ <table>
+ <thead>
+ <tr><th></th><th>L4 image</th><th>RTX PRO 6000 image</th></tr>
+ </thead>
+ <tbody>
+ <tr><td>Architecture</td><td>Ada Lovelace, <code>sm_89</code></td><td>Blackwell, <code>sm_120</code></td></tr>
+ <tr><td>CUDA</td><td>12.4</td><td>12.8</td></tr>
+ <tr><td>PyTorch</td><td>2.5 (cu124)</td><td>2.7.1 (cu128)</td></tr>
+ <tr><td>Extensions built for</td><td><code>8.9</code></td><td><code>8.9;12.0</code></td></tr>
+ </tbody>
+ </table>
+ </div>
+
+ <p>Note the last row. We compile the custom CUDA extensions for <strong>both</strong> architectures, not just the one we deploy to:</p>
+
+ <pre><code>ENV TORCH_CUDA_ARCH_LIST="8.9;12.0"</code></pre>
+
+ <p>It costs build minutes and a little image size. It buys something worth much more: one image that boots on either GPU type. That turns "which card is available in this region today" from a rebuild into a deploy flag, and it turns a rollback into a redeploy rather than a re-architecture. If you are building images for a fleet that spans GPU generations, build fat and pick at deploy time.</p>
+
+ <p>The same discipline applies one level up. Hunyuan3D 2.0 and 2.1 have <em>mutually incompatible</em> Python stacks (torch 2.3 / cu121 with <code>hy3dgen</code> against torch 2.5 / cu124 with <code>hy3dshape</code> and <code>hy3dpaint</code>). Rather than fight that, we run them as two separate services. Trying to unify them in one image would have cost days and produced something more fragile than two clean containers.</p>
+
+ <h2 id="quota">The quota surprise</h2>
+
+ <p>This one is not code, and it is the finding most likely to save someone a planning cycle.</p>
+
+ <p>The intuitive assumption is that the small, cheap, mature GPU is the easy one to get, and the big new one is the scarce one you have to beg for. In <code>us-central1</code>, for us, it was the reverse. Our L4 quota was <strong>3 GPUs</strong>, shared across the entire fleet and permanently pinned at that ceiling. Every new L4 lane was a fight with the lanes we already had. The RTX PRO 6000 quota in the same region was granted at a far higher number.</p>
+
+ <div class="callout">
+ <h3>Practical takeaway</h3>
+ <p>Check your granted quota <em>per GPU type, per region</em> before you choose a tier on price or spec. The larger card can be the more available card, and "available" beats "theoretically cheaper" every time you are trying to ship. Note also that a granted quota number and what deploy-time enforcement lets you run can differ, so confirm with an actual deploy rather than a dashboard reading.</p>
+ </div>
+
+ <p>Our RTX service runs with min instances and max instances both set to 1, held warm. Nothing about that is elegant, but for a lane where a cold start means loading 14 GiB before the first token of work, a warm instance is the difference between a 20-second response and a 4-minute one. Warm capacity is the cheapest latency optimization available to anyone running large models behind a request path.</p>
+
+ <h2 id="rollback">Designing for a one-line rollback</h2>
+
+ <p>The best decision in this whole migration was made before any of it started: <strong>every image-to-3D worker speaks the same wire contract.</strong> Same request shape, same response shape, same task-polling semantics, regardless of which model or GPU is behind it.</p>
+
+ <pre><code>POST /infer → 202 { "task_id": "...", "status": "queued" }
+GET /tasks/:id → { "status": "done", "result_gcs_url": "...", "elapsed_ms": 224140 }
+GET /health → { "ok": true, "ready": true, "load_error": null }</code></pre>
+
+ <p>Because of that, rolling the realism lane back from 2.1 to 2.0 is repointing one environment variable at a different service URL. No rebuild, no code change, no redeploy of the caller. When you are moving a production lane onto new hardware, the ability to undo it in thirty seconds is what makes it reasonable to try at all.</p>
+
+ <p>Two smaller decisions carried more weight than they looked like they would:</p>
+
+ <ul>
+ <li><strong>Task state lives in object storage, not in the instance.</strong> Every transition writes a durable <code>tasks/{id}.json</code> blob, so a <code>POST /infer</code> and a later <code>GET /tasks/:id</code> that land on different autoscaled instances still resolve the same record. Without this, autoscaling silently loses jobs, and you will diagnose it as a model problem.</li>
+ <li><strong>Every remote image URL goes through an SSRF guard.</strong> Image-to-3D means accepting a URL from a caller and fetching it server-side, which is a textbook server-side request forgery surface. Ours is https-only and rejects private, loopback, link-local, and cloud-metadata addresses <em>on every redirect hop</em>, not just the first. Checking only the initial URL is the classic mistake: a redirect to <code>169.254.169.254</code> is one hop away from your instance metadata.</li>
+ </ul>
+
+ <h2 id="tiers">Spending the GPU budget</h2>
+
+ <p>With the memory ceiling gone, the interesting question becomes how to spend the compute. The 2.1 budget splits between the shape DiT (inference steps and marching-cubes octree resolution) and the paint pass (how many views, and at what resolution each view diffuses). We expose three tiers:</p>
+
+ <div class="table-scroll">
+ <table>
+ <thead>
+ <tr><th>Tier</th><th>Shape steps</th><th>Octree</th><th>Paint views</th><th>Paint resolution</th></tr>
+ </thead>
+ <tbody>
+ <tr><td><code>draft</code></td><td>30</td><td>256</td><td>6</td><td>512</td></tr>
+ <tr><td><code>standard</code></td><td>50</td><td>384</td><td>6</td><td>512</td></tr>
+ <tr><td><code>high</code> (default)</td><td>50</td><td>512</td><td>6</td><td>768</td></tr>
+ </tbody>
+ </table>
+ </div>
+
+ <p>The non-obvious choice is that <strong>the multiview count stays at 6 across all three tiers.</strong> Views are the expensive axis: each additional view is another full diffusion pass held in VRAM alongside the shape DiT, the DINOv2 reference encoder, and RealESRGAN. Holding views constant and spending the extra budget on octree resolution and per-view resolution buys sharper geometry and crisper PBR maps without pushing VRAM into swap-or-die territory. The texture atlas is pinned high at load time regardless of tier (2048 render, 4096 texture), because atlas resolution is cheap relative to what it contributes.</p>
+
+ <p>The <code>elapsed_ms</code> in the response above is real: a <code>high</code>-tier generation is a multi-minute job. That is the correct trade for us. GPU time is the cheapest input in this pipeline and a user's opinion of the result is the most expensive output, so quality wins by default and the fast lanes exist for people who explicitly ask for one.</p>
+
+ <h2 id="checklist">A checklist for your own port</h2>
+
+ <p>If you are about to put a large image-to-3D or diffusion pipeline on managed GPU infrastructure, this is the list we wish we had started with:</p>
+
+ <ol>
+ <li><strong>Find out whether <code>/tmp</code> is memory-backed.</strong> If it is, add your staged size to your resident size and compare that sum, not either number alone, to the tier's memory limit.</li>
+ <li><strong>Separate liveness from readiness.</strong> Return both, gate routing on readiness, and surface the load error in the payload.</li>
+ <li><strong>Read your granted GPU quota per type and per region</strong> before you pick a tier. Then verify it with a real deploy.</li>
+ <li><strong>Match the CUDA toolkit to the target architecture.</strong> Blackwell is <code>sm_120</code> and needs cu128 wheels; no flag substitutes for the rebuild.</li>
+ <li><strong>Set <code>TORCH_CUDA_ARCH_LIST</code> to every architecture you might deploy to</strong>, not just today's. Fat images make GPU choice a deploy-time decision.</li>
+ <li><strong>Persist task state outside the instance</strong> the moment you enable autoscaling.</li>
+ <li><strong>Validate remote fetches on every redirect hop</strong>, not only the submitted URL.</li>
+ <li><strong>Keep one wire contract across model versions</strong> so rollback is an environment variable.</li>
+ <li><strong>Keep the old lane deployed</strong> while the new one earns its place. A warm fallback costs less than an outage.</li>
+ </ol>
+
+ <p>One licensing note, because it is easy to skip and expensive to skip: generative 3D checkpoints ship under a wide spread of terms, and several popular ones carry non-commercial or otherwise restricted licenses that differ from the permissive license on the surrounding code. Read the license on the exact checkpoint you intend to deploy, including any super-resolution or encoder models pulled in as dependencies, before it reaches production.</p>
+
+ <hr>
+
+ <h2>Where this runs</h2>
+
+ <p>Everything above is in production behind <a href="/forge">the forge</a>, the text and image to 3D surface on three.ws. The free lane needs no key and no account; the paid lanes route to the self-hosted fleet described here. Generated models drop straight into <a href="/ar">AR</a>, the <a href="/create">avatar studio</a>, and the <code>&lt;agent-3d&gt;</code> <a href="/docs/web-component">web component</a> for embedding on any site.</p>
+
+ <p>three.ws joined the <a href="/docs/nvidia-inception">NVIDIA Inception program</a> in July 2026. It is a startup program rather than a partnership or an investment, and in practice it means GPU capacity and engineering access on the exact constraint this post is about. The work of relaxing that constraint is ongoing, and we will keep publishing the numbers as we get them.</p>
+
+ <h2>Related reading</h2>
+ <ul>
+ <li><a href="/docs/nvidia-models">Every NVIDIA model three.ws runs for free</a>: the hosted inference layer, model by model, with the endpoint each one serves.</li>
+ <li><a href="/docs/nvidia-nemotron-spotlight">The generator was never the hard part</a>: our Nemotron Nano write-up, published on the NVIDIA Developer Forums, on why the vision model in front of the 3D generator mattered more than the generator.</li>
+ <li><a href="/docs/nvidia-inception">NVIDIA Inception membership</a>: what already runs on NVIDIA here and what the program adds.</li>
+ <li><a href="/docs/3d-asset-pipeline">The 3D asset pipeline</a>: what happens to a mesh between generation and a browser.</li>
+ <li><a href="https://github.com/nirholas/three.ws" rel="noopener">github.com/nirholas/three.ws</a>: the platform is open source, including the worker configurations quoted throughout this post.</li>
+ </ul>
+
+ <hr>
+ <p><a href="/blog">&larr; All posts</a></p>
+ </main>
+ <div id="footer-container"></div>
+ <script src="/nav.js"></script>
+ <script src="/footer.js"></script>
+</body>
+</html>
diff --git a/data/pages.json b/data/pages.json
index 8ba4451f2..20ec345f6 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -3016,6 +3016,20 @@
"changefreq": "monthly",
"added": "2026-07-21"
},
+ {
+ "path": "/docs/nvidia-models",
+ "title": "Docs · Every NVIDIA model three.ws runs for free",
+ "description": "The full free NVIDIA inference layer behind three.ws, model by model: TRELLIS for text-to-3D, FLUX.1-schnell for text-to-image, the Llama and Nemotron chat lineup, Nemotron vision, nv-embedqa embeddings, the cross-encoder reranker, NemoGuard content safety, and Magpie multilingual speech.",
+ "priority": 0.6,
+ "changefreq": "monthly"
+ },
+ {
+ "path": "/docs/nvidia-nemotron-spotlight",
+ "title": "Docs · How Nemotron Nano made free text-to-3D production-ready",
+ "description": "The three.ws write-up published on the NVIDIA Developer Forums: the vision-model guardrail in front of the 3D generator, the real latency and token numbers behind each model choice, and the free NVIDIA stack powering the forge.",
+ "priority": 0.6,
+ "changefreq": "monthly"
+ },
{
"path": "/cookbook",
"title": "Cookbook: self-correcting 3D with function calling",
diff --git a/data/skills/protocol/erc8004-agent-identity/SKILL.md b/data/skills/protocol/erc8004-agent-identity/SKILL.md
index 09a0f7862..62a6c0ae7 100644
--- a/data/skills/protocol/erc8004-agent-identity/SKILL.md
+++ b/data/skills/protocol/erc8004-agent-identity/SKILL.md
@@ -1,6 +1,6 @@
---
name: erc8004-agent-identity
-description: Complete guide to ERC-8004 — the open standard for on-chain AI agent identity, reputation, and validation. Covers agent registration as NFTs, reputation signals, validator attestations, and multi-chain deployment across 12 chains. Essential for building trustless AI agent ecosystems.
+description: Complete guide to ERC-8004: the open standard for on-chain AI agent identity, reputation, and validation. Covers agent registration as NFTs, reputation signals, validator attestations, and multi-chain deployment across 12 chains. Essential for building trustless AI agent ecosystems.
license: MIT
metadata:
category: protocol
@@ -9,7 +9,7 @@ metadata:
tags: [protocol, erc8004-agent-identity]
---
-# ERC-8004 — On-Chain AI Agent Identity
+# ERC-8004: On-Chain AI Agent Identity
ERC-8004 is an open Ethereum standard for **discovering, choosing, and interacting with AI agents** across organizational boundaries without pre-existing trust. It was created by the Sperax team and is deployed across 12 chains.
@@ -29,7 +29,7 @@ ERC-8004 solves this with three on-chain registries.
### 1. Identity Registry (ERC-721 NFT)
-Every agent gets an **NFT identity** — a unique, transferrable on-chain identity.
+Every agent gets an **NFT identity**: a unique, transferrable on-chain identity.
- Based on ERC-721 with URIStorage
- TokenURI points to a JSON registration file
@@ -42,7 +42,7 @@ A standard interface for posting and querying **feedback signals** about agents.
| Signal | Measures | Scale |
|--------|----------|-------|
-| `starred` | Quality rating | 0–100 |
+| `starred` | Quality rating | 0-100 |
| `reachable` | Endpoint reachable | binary |
| `uptime` | Availability | percentage |
| `successRate` | Task completion rate | percentage |
@@ -50,7 +50,7 @@ A standard interface for posting and querying **feedback signals** about agents.
| `tradingYield` | Trading return | signed percentage |
| `revenues` | Cumulative revenue | USD |
-**Star ratings** map to the 0–100 scale:
+**Star ratings** map to the 0-100 scale:
- 1★ = 20, 2★ = 40, 3★ = 60, 4★ = 80, 5★ = 100
### 3. Validation Registry
@@ -70,7 +70,7 @@ A standard interface for posting and querying **feedback signals** about agents.
"type": "https://eips.ethereum.org/EIPS/eip-8004#registration-v1",
"name": "My Trading Agent",
"description": "Automated yield optimizer on Arbitrum",
- "image": "https://cdn.example.com/agent-avatar.png",
+ "image": "https://three.ws/avatars/thumbs/default.png",
"services": [
{
"name": "MCP",
@@ -137,22 +137,22 @@ All contracts use vanity addresses starting with `0x8004...`
### Registration
1. **Always include a rich registration file** with name, description, image, and services
-2. **Declare services explicitly** — other agents need to know how to communicate
-3. **Keep metadata current** — update when endpoints change
-4. **Use active flag** — set `"active": false` when taking agent offline
+2. **Declare services explicitly**: other agents need to know how to communicate
+3. **Keep metadata current**: update when endpoints change
+4. **Use active flag**: set `"active": false` when taking agent offline
### Reputation
-1. **Encourage feedback** — more signals = more trust
-2. **Monitor your scores** — respond to quality issues
-3. **Use standard signal types** — stick to the defined tags for interoperability
+1. **Encourage feedback**: more signals = more trust
+2. **Monitor your scores**: respond to quality issues
+3. **Use standard signal types**: stick to the defined tags for interoperability
4. **Trusted probers** (infra watchtowers) should regularly publish uptime/reachability
### Security
-1. **Validate callers** — check msg.sender for sensitive operations
-2. **Rate-limit feedback** — prevent spam signals
-3. **Verify validators** — ensure validator contracts are trustworthy
+1. **Validate callers**: check msg.sender for sensitive operations
+2. **Rate-limit feedback**: prevent spam signals
+3. **Verify validators**: ensure validator contracts are trustworthy
## Use Cases for OpenClaw Agents
diff --git a/data/skills/seed.json b/data/skills/seed.json
index 4cc94e23f..5ee019393 100644
--- a/data/skills/seed.json
+++ b/data/skills/seed.json
@@ -208,7 +208,7 @@
},
{
"category": "protocol",
- "content": "# ERC-8004 — On-Chain AI Agent Identity\n\nERC-8004 is an open Ethereum standard for **discovering, choosing, and interacting with AI agents** across organizational boundaries without pre-existing trust. It was created by the Sperax team and is deployed across 12 chains.\n\n**Spec**: https://eips.ethereum.org/EIPS/eip-8004\n\n## Why ERC-8004?\n\nAs AI agents proliferate, we need a way to:\n- **Discover** agents across platforms (not locked in one vendor)\n- **Verify** agent capabilities and track record\n- **Trust** agents without knowing who built them\n- **Pay** agents via standard protocols (x402, on-chain)\n\nERC-8004 solves this with three on-chain registries.\n\n## The Three Registries\n\n### 1. Identity Registry (ERC-721 NFT)\n\nEvery agent gets an **NFT identity** — a unique, transferrable on-chain identity.\n\n- Based on ERC-721 with URIStorage\n- TokenURI points to a JSON registration file\n- Owners can update metadata, transfer, or burn\n- One NFT = one agent identity\n\n### 2. Reputation Registry\n\nA standard interface for posting and querying **feedback signals** about agents.\n\n| Signal | Measures | Scale |\n|--------|----------|-------|\n| `starred` | Quality rating | 0–100 |\n| `reachable` | Endpoint reachable | binary |\n| `uptime` | Availability | percentage |\n| `successRate` | Task completion rate | percentage |\n| `responseTime` | Response latency | milliseconds |\n| `tradingYield` | Trading return | signed percentage |\n| `revenues` | Cumulative revenue | USD |\n\n**Star ratings** map to the 0–100 scale:\n- 1★ = 20, 2★ = 40, 3★ = 60, 4★ = 80, 5★ = 100\n\n### 3. Validation Registry\n\n**Independent validator attestations** for agent capabilities:\n- zkML proofs (zero-knowledge machine learning)\n- TEE attestations (trusted execution environment)\n- Staker validations (economic security)\n- Custom validator contracts\n\n## Agent Registration\n\n### Registration File Format\n\n```json\n{\n \"type\": \"https://eips.ethereum.org/EIPS/eip-8004#registration-v1\",\n \"name\": \"My Trading Agent\",\n \"description\": \"Automated yield optimizer on Arbitrum\",\n \"image\": \"https://cdn.example.com/agent-avatar.png\",\n \"services\": [\n {\n \"name\": \"MCP\",\n \"endpoint\": \"https://api.myagent.com/mcp\",\n \"version\": \"2025-06-18\",\n \"mcpTools\": [\"getQuote\", \"executeTrade\"]\n },\n {\n \"name\": \"A2A\",\n \"endpoint\": \"https://api.myagent.com/.well-known/agent-card.json\",\n \"version\": \"0.3.0\",\n \"a2aSkills\": [\"defi/yield_optimization\"]\n },\n {\n \"name\": \"ENS\",\n \"endpoint\": \"myagent.eth\",\n \"version\": \"v1\"\n }\n ],\n \"x402Support\": true,\n \"active\": true\n}\n```\n\n### Service Types\n\n| Service | Purpose | Use When |\n|---------|---------|----------|\n| MCP | Model Context Protocol | Agent exposes tools for other AI to call |\n| A2A | Agent-to-Agent | Agent participates in multi-agent workflows |\n| ENS | Ethereum Name Service | Human-readable agent address |\n| DID | Decentralized Identifier | Cross-chain identity |\n\n### Key Operations\n\n| Operation | Description |\n|-----------|-------------|\n| `registerAgent` | Mint an agent NFT with metadata |\n| `lookupAgent` | Query agent details by token ID |\n| `searchAgents` | Find agents by criteria |\n| `updateMetadata` | Update agent's registration file |\n| `transferAgent` | Transfer ownership to new address |\n| `getAgentReputation` | Fetch reputation signals |\n| `submitFeedback` | Post a reputation signal |\n| `addValidation` | Add validator attestation |\n| `getValidations` | Query validations for an agent |\n| `listAgents` | List agents by owner |\n\n## Supported Chains (12)\n\n| Chain | Networks |\n|-------|----------|\n| Ethereum | Mainnet, Sepolia |\n| BNB Chain | Mainnet, Testnet |\n| Arbitrum | Mainnet, Sepolia |\n| Base | Mainnet, Sepolia |\n| Optimism | Mainnet, Sepolia |\n| Polygon | Mainnet, Amoy |\n\nAll contracts use vanity addresses starting with `0x8004...`\n\n## Best Practices\n\n### Registration\n\n1. **Always include a rich registration file** with name, description, image, and services\n2. **Declare services explicitly** — other agents need to know how to communicate\n3. **Keep metadata current** — update when endpoints change\n4. **Use active flag** — set `\"active\": false` when taking agent offline\n\n### Reputation\n\n1. **Encourage feedback** — more signals = more trust\n2. **Monitor your scores** — respond to quality issues\n3. **Use standard signal types** — stick to the defined tags for interoperability\n4. **Trusted probers** (infra watchtowers) should regularly publish uptime/reachability\n\n### Security\n\n1. **Validate callers** — check msg.sender for sensitive operations\n2. **Rate-limit feedback** — prevent spam signals\n3. **Verify validators** — ensure validator contracts are trustworthy\n\n## Use Cases for OpenClaw Agents\n\n### Register Your OpenClaw Agent On-Chain\n\nGive your agent a verifiable identity that works across platforms:\n1. Deploy agent registration via ERC-8004\n2. Advertise MCP endpoints so other agents can discover your tools\n3. Build reputation over time as users interact\n\n### Discover & Interact With Other Agents\n\nUse the ERC-8004 registries to:\n1. Find specialized agents (e.g., \"DeFi yield optimizer on Arbitrum\")\n2. Check reputation before trusting\n3. Call via MCP or A2A protocols\n\n### Build Agent Marketplaces\n\nERC-8004 provides the infra layer for on-chain agent marketplaces:\n- Identity (who is this agent?)\n- Reputation (is it any good?)\n- Validation (has it been audited?)\n- Discovery (how do I find it?)\n\n## Related Resources\n\n| Resource | URL |\n|----------|-----|\n| ERC-8004 Spec | https://eips.ethereum.org/EIPS/eip-8004 |\n| Best Practices | https://github.com/sperax |\n| Agent Creator UI | https://github.com/sperax |\n| Demo Agent | https://github.com/sperax |\n| Solidity Contracts | https://github.com/sperax |\n| Subgraph | https://github.com/sperax |\n| SperaxOS | https://chat.sperax.io |",
+ "content": "# ERC-8004: On-Chain AI Agent Identity\n\nERC-8004 is an open Ethereum standard for **discovering, choosing, and interacting with AI agents** across organizational boundaries without pre-existing trust. It was created by the Sperax team and is deployed across 12 chains.\n\n**Spec**: https://eips.ethereum.org/EIPS/eip-8004\n\n## Why ERC-8004?\n\nAs AI agents proliferate, we need a way to:\n- **Discover** agents across platforms (not locked in one vendor)\n- **Verify** agent capabilities and track record\n- **Trust** agents without knowing who built them\n- **Pay** agents via standard protocols (x402, on-chain)\n\nERC-8004 solves this with three on-chain registries.\n\n## The Three Registries\n\n### 1. Identity Registry (ERC-721 NFT)\n\nEvery agent gets an **NFT identity**: a unique, transferrable on-chain identity.\n\n- Based on ERC-721 with URIStorage\n- TokenURI points to a JSON registration file\n- Owners can update metadata, transfer, or burn\n- One NFT = one agent identity\n\n### 2. Reputation Registry\n\nA standard interface for posting and querying **feedback signals** about agents.\n\n| Signal | Measures | Scale |\n|--------|----------|-------|\n| `starred` | Quality rating | 0-100 |\n| `reachable` | Endpoint reachable | binary |\n| `uptime` | Availability | percentage |\n| `successRate` | Task completion rate | percentage |\n| `responseTime` | Response latency | milliseconds |\n| `tradingYield` | Trading return | signed percentage |\n| `revenues` | Cumulative revenue | USD |\n\n**Star ratings** map to the 0-100 scale:\n- 1★ = 20, 2★ = 40, 3★ = 60, 4★ = 80, 5★ = 100\n\n### 3. Validation Registry\n\n**Independent validator attestations** for agent capabilities:\n- zkML proofs (zero-knowledge machine learning)\n- TEE attestations (trusted execution environment)\n- Staker validations (economic security)\n- Custom validator contracts\n\n## Agent Registration\n\n### Registration File Format\n\n```json\n{\n \"type\": \"https://eips.ethereum.org/EIPS/eip-8004#registration-v1\",\n \"name\": \"My Trading Agent\",\n \"description\": \"Automated yield optimizer on Arbitrum\",\n \"image\": \"https://three.ws/avatars/thumbs/default.png\",\n \"services\": [\n {\n \"name\": \"MCP\",\n \"endpoint\": \"https://api.myagent.com/mcp\",\n \"version\": \"2025-06-18\",\n \"mcpTools\": [\"getQuote\", \"executeTrade\"]\n },\n {\n \"name\": \"A2A\",\n \"endpoint\": \"https://api.myagent.com/.well-known/agent-card.json\",\n \"version\": \"0.3.0\",\n \"a2aSkills\": [\"defi/yield_optimization\"]\n },\n {\n \"name\": \"ENS\",\n \"endpoint\": \"myagent.eth\",\n \"version\": \"v1\"\n }\n ],\n \"x402Support\": true,\n \"active\": true\n}\n```\n\n### Service Types\n\n| Service | Purpose | Use When |\n|---------|---------|----------|\n| MCP | Model Context Protocol | Agent exposes tools for other AI to call |\n| A2A | Agent-to-Agent | Agent participates in multi-agent workflows |\n| ENS | Ethereum Name Service | Human-readable agent address |\n| DID | Decentralized Identifier | Cross-chain identity |\n\n### Key Operations\n\n| Operation | Description |\n|-----------|-------------|\n| `registerAgent` | Mint an agent NFT with metadata |\n| `lookupAgent` | Query agent details by token ID |\n| `searchAgents` | Find agents by criteria |\n| `updateMetadata` | Update agent's registration file |\n| `transferAgent` | Transfer ownership to new address |\n| `getAgentReputation` | Fetch reputation signals |\n| `submitFeedback` | Post a reputation signal |\n| `addValidation` | Add validator attestation |\n| `getValidations` | Query validations for an agent |\n| `listAgents` | List agents by owner |\n\n## Supported Chains (12)\n\n| Chain | Networks |\n|-------|----------|\n| Ethereum | Mainnet, Sepolia |\n| BNB Chain | Mainnet, Testnet |\n| Arbitrum | Mainnet, Sepolia |\n| Base | Mainnet, Sepolia |\n| Optimism | Mainnet, Sepolia |\n| Polygon | Mainnet, Amoy |\n\nAll contracts use vanity addresses starting with `0x8004...`\n\n## Best Practices\n\n### Registration\n\n1. **Always include a rich registration file** with name, description, image, and services\n2. **Declare services explicitly**: other agents need to know how to communicate\n3. **Keep metadata current**: update when endpoints change\n4. **Use active flag**: set `\"active\": false` when taking agent offline\n\n### Reputation\n\n1. **Encourage feedback**: more signals = more trust\n2. **Monitor your scores**: respond to quality issues\n3. **Use standard signal types**: stick to the defined tags for interoperability\n4. **Trusted probers** (infra watchtowers) should regularly publish uptime/reachability\n\n### Security\n\n1. **Validate callers**: check msg.sender for sensitive operations\n2. **Rate-limit feedback**: prevent spam signals\n3. **Verify validators**: ensure validator contracts are trustworthy\n\n## Use Cases for OpenClaw Agents\n\n### Register Your OpenClaw Agent On-Chain\n\nGive your agent a verifiable identity that works across platforms:\n1. Deploy agent registration via ERC-8004\n2. Advertise MCP endpoints so other agents can discover your tools\n3. Build reputation over time as users interact\n\n### Discover & Interact With Other Agents\n\nUse the ERC-8004 registries to:\n1. Find specialized agents (e.g., \"DeFi yield optimizer on Arbitrum\")\n2. Check reputation before trusting\n3. Call via MCP or A2A protocols\n\n### Build Agent Marketplaces\n\nERC-8004 provides the infra layer for on-chain agent marketplaces:\n- Identity (who is this agent?)\n- Reputation (is it any good?)\n- Validation (has it been audited?)\n- Discovery (how do I find it?)\n\n## Related Resources\n\n| Resource | URL |\n|----------|-----|\n| ERC-8004 Spec | https://eips.ethereum.org/EIPS/eip-8004 |\n| Best Practices | https://github.com/sperax |\n| Agent Creator UI | https://github.com/sperax |\n| Demo Agent | https://github.com/sperax |\n| Solidity Contracts | https://github.com/sperax |\n| Subgraph | https://github.com/sperax |\n| SperaxOS | https://chat.sperax.io |",
"description": "Complete guide to ERC-8004 — the open standard for on-chain AI agent identity, reputation, and validation. Covers agent registration as NFTs, reputation signals, validator attestations, and multi-chain deployment across 12 chains. Essential for building trustless AI agent ecosystems.",
"identifier": "erc8004-agent-identity",
"manifest": {
diff --git a/docs/ALL.md b/docs/ALL.md
index f27c76131..99608efbf 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-07-30 from **391 files** (~5587 KB).
+> Single-file snapshot of every document under [`docs/`](.). Generated 2026-07-30 from **391 files** (~5588 KB).
> The individual source files remain the canonical, editable copies — this file is a read-only aggregate.
## Table of contents
@@ -30132,7 +30132,7 @@ Four real capabilities cover embodiment, reach, and trust:
```html
<script type="module" src="https://three.ws/agent-3d/1.5.2/agent-3d.js"></script>
<agent-3d
- body="https://three.ws/cdn/models/brand-agent.glb"
+ body="https://three.ws/avatars/michelle.glb"
brain="claude-sonnet-4-6"
name="Lyra-bot"
instructions="Official brand assistant. Answer product questions, link to pricing, stay on-brand."
@@ -30287,7 +30287,7 @@ Together: your face (or your prompt) becomes a model, the model becomes a talkin
```html
<script type="module" src="https://three.ws/agent-3d/1.5.2/agent-3d.js"></script>
<agent-3d
- body="https://three.ws/cdn/models/procyon-fox.glb"
+ body="https://three.ws/avatars/fox.glb"
brain="claude-sonnet-4-6"
name="Procyon"
instructions="You are Procyon's studio fox. Greet visitors warmly, talk about the art prints, and wave when someone says hi."
@@ -34737,7 +34737,7 @@ The element accepts several ways to point at an agent — pick one:
| `agent-id` (CAIP-10) | `agent-id="eip155:8453:0xReg…:42"` | Fully qualified on-chain reference |
| `agent-id` (backend) | `agent-id="a_abc123"` | Legacy backend account ID |
| `manifest` | `ipfs://bafy.../manifest.json` | IPFS or HTTPS manifest URL |
-| `body` | `./avatar.glb` | Bare GLB for an ad-hoc agent (viewer-only unless you also set `brain`) |
+| `body` | `https://three.ws/avatars/default.glb` | Bare GLB for an ad-hoc agent (viewer-only unless you also set `brain`) |
When multiple are set, priority is `src` > `agent-id` > `manifest` > `body`.
@@ -34748,7 +34748,7 @@ free-tier proxy. Pair it with `instructions` for a system prompt:
```html
<agent-3d
- body="./avatar.glb"
+ body="https://three.ws/avatars/realistic-female.glb"
brain="free"
instructions="You are Maya, a friendly guide to this site."
></agent-3d>
@@ -36130,7 +36130,7 @@ import { agentRegistryId, REGISTRY_DEPLOYMENTS } from './src/erc8004/abi.js';
const card = buildRegistrationJSON({
name: 'My Agent',
description: 'Description here.',
- imageUrl: 'https://cdn.example.com/thumb.png', // 2D thumbnail
+ imageUrl: 'https://three.ws/avatars/thumbs/default.png', // 2D thumbnail
glbUrl: 'ipfs://bafy.../body.glb', // 3D model
agentId: 42,
chainId: 8453,
@@ -44424,13 +44424,16 @@ automatically. Subsequent requests answer `302` to the CDN copy
# Discover the parameters, scenes, and pose catalog
curl -s https://three.ws/api/avatar/render
+# The avatar id below is Michelle, a public featured avatar, so these run as-is.
+# Swap in your own id from GET https://three.ws/api/avatars/featured or /avatars/<id>.
+
# Render a 256px transparent portrait
curl -sL -o portrait.png \
- 'https://three.ws/api/avatar/render?avatar=YOUR_AVATAR_ID&scene=portrait&size=256&bg=transparent'
+ 'https://three.ws/api/avatar/render?avatar=13f259c7-7024-4d68-b1f0-dbbf52c06209&scene=portrait&size=256&bg=transparent'
# Waving, smiling, as WebP
curl -sL -o card.webp \
- 'https://three.ws/api/avatar/render?avatar=YOUR_AVATAR_ID&pose=wave&expression=%7B%22mouthSmile%22%3A0.6%7D&format=webp'
+ 'https://three.ws/api/avatar/render?avatar=13f259c7-7024-4d68-b1f0-dbbf52c06209&pose=wave&expression=%7B%22mouthSmile%22%3A0.6%7D&format=webp'
```
---
@@ -44539,7 +44542,7 @@ Requests are rate-limited per IP; a `429` carries `Retry-After`.
```bash
# Mobile budget: 512px textures, ARKit-52 morphs only, Draco-compressed
curl -sL -o mobile.glb \
- 'https://three.ws/api/avatar/optimize?id=YOUR_AVATAR_ID&textureSize=512&morphs=arkit52&draco=1'
+ 'https://three.ws/api/avatar/optimize?id=13f259c7-7024-4d68-b1f0-dbbf52c06209&textureSize=512&morphs=arkit52&draco=1'
# By source URL, LOD 1
curl -sL -o lite.glb \
@@ -44938,7 +44941,7 @@ the submission proceeds; forge still validates the image.
```bash
curl -s -X POST https://three.ws/api/input-photo \
-H 'content-type: application/json' \
- -d '{"image_url":"https://example.com/selfie.jpg","tier":"standard"}'
+ -d '{"image_url":"https://three.ws/avatars/thumbs/default.png","tier":"standard"}'
```
---
@@ -45112,7 +45115,7 @@ auth; rate-limited per IP.
# Submit
curl -s -X POST https://three.ws/api/forge-rembg \
-H 'content-type: application/json' \
- -d '{"image_url":"https://example.com/product-shot.jpg","model":"rmbg2"}'
+ -d '{"image_url":"https://three.ws/avatars/thumbs/default.png","model":"rmbg2"}'
# Poll
curl -s 'https://three.ws/api/forge-rembg?job=JOB_ID'
@@ -52248,7 +52251,7 @@ curl -X POST https://three.ws/api/x402/pump-launch \
-d '{
"name": "Helios",
"symbol": "HELIO",
- "imageUrl": "https://example.com/helios.png",
+ "imageUrl": "https://three.ws/logo.png",
"description": "A sun-themed community coin.",
"creator": "wwwPqsM4N7T9J69tB82nLyzxqsH159j4orftLTQfUGV",
"twitter": "https://x.com/heliocoin",
@@ -56718,7 +56721,7 @@ Both are Apache-2.0 licensed. Neither requires the other.
```html
<script type="module" src="https://three.ws/agent-3d/latest/agent-3d.js"></script>
-<agent-3d model="./avatar.glb"></agent-3d>
+<agent-3d model="https://three.ws/avatars/default.glb"></agent-3d>
```
**UMD (legacy bundlers or `<script>` without `type="module"`):**
@@ -56781,7 +56784,7 @@ Direct three.js viewer — loads GLB/glTF, manages camera, lighting, and animati
import { Viewer } from './src/lib.js';
const viewer = new Viewer(document.getElementById('canvas-container'));
-viewer.load('./avatar.glb');
+viewer.load('https://three.ws/avatars/default.glb');
```
Full attribute and event API is documented in [Web Component reference](#sec-375).
@@ -74461,9 +74464,11 @@ You'll see your agent rendered against the ambient dark background, an **IRL** b
To start with a specific agent's avatar, append `?avatar=` to the URL:
```
-https://three.ws/irl?avatar=YOUR_AVATAR_ID
+https://three.ws/irl?avatar=13f259c7-7024-4d68-b1f0-dbbf52c06209
```
+That id is Michelle, a public featured avatar, so you can open the link as-is to try it. Use your own avatar id (from `/avatars/<id>`, or `GET https://three.ws/api/avatars/featured`) to place your own agent.
+
An explicit `?avatar=` link always wins over the avatar you used last visit. (Links from an agent profile's "View in IRL" button also pass `?agent=` to deep-focus that agent's pin once it's nearby.)
---
@@ -79259,16 +79264,18 @@ With `ar` present, a **View in AR** button appears on the viewer. Clicking it op
**Full agent embed (`<agent-3d>`).** The talking-agent web component does not take an `ar` attribute. To offer AR next to it, link to the avatar's dedicated full-screen AR page, which picks the right method per device automatically:
```html
-<a href="https://three.ws/avatars/YOUR_AVATAR_ID/ar">See it in your room</a>
+<a href="https://three.ws/avatars/13f259c7-7024-4d68-b1f0-dbbf52c06209/ar">See it in your room</a>
```
+That id is Michelle, a public featured avatar, so the link works as written. Swap in your own avatar id from `/avatars/<id>` or `GET https://three.ws/api/avatars/featured`.
+
### Iframe embed + AR
If you're using the iframe embed, add `xr-spatial-tracking` to the `allow` attribute:
```html
<iframe
- src="https://three.ws/embed/avatar/YOUR_AVATAR_ID"
+ src="https://three.ws/embed/avatar/13f259c7-7024-4d68-b1f0-dbbf52c06209"
allow="microphone; camera; xr-spatial-tracking; fullscreen"
width="400"
height="500"
@@ -84861,7 +84868,7 @@ The agent-voice handler ([`api/agents/_id/voice.js`](../api/agents/_id/voice.js)
<agent-3d src="agent://base/42" style="width:400px;height:500px"></agent-3d>
```
-All four layout modes, voice I/O, the LLM brain, persistent memory, and an extensible skill system are built in. Every feature is opt-in — a bare `<agent-3d body="https://three.ws/avatars/default.glb">` renders a silent 3D viewer with no API key and no external calls beyond the GLB itself.
+All four layout modes, voice I/O, the LLM brain, persistent memory, and an extensible skill system are built in. Every feature is opt-in: a bare `<agent-3d body="https://three.ws/avatars/default.glb">` renders a silent 3D viewer with no API key and no external calls beyond the GLB itself.
---
diff --git a/docs/copy-trading.md b/docs/copy-trading.md
new file mode 100644
index 000000000..e61c86db6
--- /dev/null
+++ b/docs/copy-trading.md
@@ -0,0 +1,430 @@
+# Copy Trading
+
+Copy trading on three.ws lets one wallet follow another wallet's real trades. There are two separate engines behind that sentence, they have different risk profiles, and it matters which one you are using:
+
+| Engine | Where | Who signs the trade | What happens when the leader trades |
+| --- | --- | --- | --- |
+| **Agent mirror** (custodial) | [/mirror](https://three.ws/mirror) | The platform signs from **your agent's own custodial Solana wallet** | A real buy or sell is built, broadcast, and confirmed on-chain, inside your agent's spend policy |
+| **Copier subscriptions** (non-custodial) | [/dashboard/copy](https://three.ws/dashboard/copy) | **You do**, from your own wallet | A sized, safety-checked *intent* is recorded for you to act on. Nothing is signed for you |
+
+Both are Solana-native. Both run on `mainnet` and `devnet`. Neither is a paper-trading mode: there is no simulation layer anywhere in this stack, and no synthetic fills. Read [Simulated versus executed](#simulated-versus-executed) before you enable anything.
+
+Related reading: [Smart Money Radar](./smart-money.md) for the first-party wallet reputation graph, [the trading surfaces](./trading-surfaces.md) for the screeners and the trading cockpit these leaders trade from, [agent wallets](./agent-wallets.md) for the custody and spend-policy model, and [signal marketplace](./signals.md) for the paid-feed variant that reuses the same guarded executor.
+
+---
+
+## Simulated versus executed
+
+State this to yourself before you touch a control:
+
+- **The agent mirror executes with real funds.** When a leader agent's trade confirms on-chain, `api/_lib/agent-mirror.js` quotes the pump curve or AMM, recovers your agent's key, builds real instructions, and broadcasts them through the MEV-aware execution engine. The resulting signature is a real Solana transaction. There is no dry-run flag, no shadow mode, and no "test" sizing.
+- **Copier subscriptions never execute.** `api/cron/copy-fanout.js` writes a row into `copy_executions` with a planned size and a reason. That is the whole action. You open the intent, trade from your own wallet, and then tell the platform what you did by POSTing `{ action: 'acted', tx_signature }`. Marking an intent `acted` records history. It moves no funds, and the platform never holds your keys on this path.
+- **The leaderboard and track records are computed from real fills only.** `api/_lib/mirror-stats.js` and `api/mirror/leaderboard.js` read closed sniper round-trips (`agent_sniper_positions`) and the confirmed custody trade ledger (`agent_custody_events`). An agent with no history returns zeros and nulls, not a placeholder number. Losing agents appear with their losses.
+- **The only thing that is estimated anywhere** is copy profit attribution for performance fees: a copier's realized profit on one copy is `planned_sol * (leader_realized_pnl_pct / 100)`, that is, your committed size at the leader's realized return. That is a stated basis, not a measured fill of your own transaction, and it is documented in `api/_lib/copy-earnings.js`.
+
+Money-moving actions are yours to confirm. Nothing on these pages spends without either (a) an explicit agent-level opt-in with a spend policy, in the mirror case, or (b) you personally signing, in the copier case.
+
+---
+
+## The leaderboard: finding a leader
+
+`/mirror` opens on **Discover leaders**, a performance-weighted ranking served by `GET /api/mirror/leaderboard`. Public, no key, cached at the edge for 60 seconds (`max-age=30, s-maxage=60`), IP rate-limited.
+
+### Parameters
+
+| Param | Values | Default |
+| --- | --- | --- |
+| `network` | `mainnet`, `devnet` | `mainnet` |
+| `sort` | `score`, `pnl`, `followers`, `volume`, `winrate` | `score` |
+| `limit` | 1 to 50 | 25 |
+
+### Who is eligible
+
+An agent appears if it is public (`is_public <> false`), not deleted, and has **either** at least one closed sniper position **or** at least one confirmed discretionary trade on that network. An agent that only trades discretionarily still ranks, with volume and no realized P&L. The candidate scan is capped at 500 rows before scoring.
+
+### The weighting, exactly as coded
+
+```
+sample = min(1, settled / 8) # sample-size damping
+score = round(
+ (roi_pct != null ? roi_pct * sample : 0) # realized ROI, damped
+ + (win_rate != null ? (win_rate - 50) * 0.5 * sample : 0) # edge over a coin flip, damped
+ + min(20, followers * 2) # follower trust, capped at +20
+ + min(10, volume_sol) # activity, capped at +10
+ )
+```
+
+Where the inputs come from:
+
+- `settled` = count of closed sniper positions. `wins` = those with `realized_pnl_lamports > 0`.
+- `win_rate` = `wins / settled * 100`, null when `settled` is 0.
+- `pnl_sol` = summed realized P&L in SOL. `roi_pct` = `pnl_sol / summed entry SOL * 100`, null when nothing was entered.
+- `volume_sol` = summed `amount_lamports` of confirmed `category = 'trade'` custody events where `asset = 'SOL'` (buy-side volume).
+- `followers` / `active_followers` = rows in `agent_mirror_follows` for that leader, and those with `enabled = true`.
+
+The consequences are deliberate. A one-trade fluke is damped to one eighth of its ROI contribution, so it cannot outrank a consistent trader. A 50 percent win rate contributes nothing. Followers can add at most 20 points, so popularity cannot manufacture a track record. Sorting by any field other than `score` ignores the composite entirely and orders on that raw field.
+
+```bash
+# Top leaders by composite score
+curl -s 'https://three.ws/api/mirror/leaderboard?limit=5'
+
+# Honest P&L order, including the losers at the bottom
+curl -s 'https://three.ws/api/mirror/leaderboard?sort=pnl&limit=25'
+
+# Devnet board
+curl -s 'https://three.ws/api/mirror/leaderboard?network=devnet&sort=winrate'
+```
+
+Response shape:
+
+```json
+{
+ "data": {
+ "network": "mainnet",
+ "sort": "score",
+ "leaders": [
+ {
+ "rank": 1,
+ "agent_id": "00000000-0000-0000-0000-000000000000",
+ "name": "Example Trader",
+ "avatar": null,
+ "settled": 8,
+ "wins": 4,
+ "win_rate": 50,
+ "pnl_sol": 0.1725,
+ "roi_pct": 10.2,
+ "trades": 0,
+ "volume_sol": 0,
+ "followers": 0,
+ "active_followers": 0,
+ "last_trade_at": null,
+ "score": 10
+ }
+ ]
+ }
+}
+```
+
+For one leader's full record (drawdown, best and worst trade, USD volume) call the per-agent route instead, which is also public:
+
+```bash
+curl -s 'https://three.ws/api/agents/<AGENT_ID>/mirror/track-record'
+curl -s 'https://three.ws/api/agents/<AGENT_ID>/mirror/followers'
+```
+
+`track-record` adds `realized.max_drawdown_sol` (peak to trough over the cumulative realized-P&L curve), `realized.best_pct` / `worst_pct`, `volume.usd`, and a `total` that spans both sources so "no track record yet" is expressed as `total: 0` rather than invented numbers.
+
+---
+
+## How following works (the agent mirror)
+
+The mirror is a graph of **follow edges**: one of your agents (the follower) mirrors one public agent (the leader). Edges live in `agent_mirror_follows` and are managed under `/api/agents/:id/mirror`, where `:id` is **your follower agent**. All write routes are owner-only and CSRF-protected for cookie sessions; bearer tokens are accepted for agent clients.
+
+| Route | Method | Access |
+| --- | --- | --- |
+| `/api/agents/:id/mirror` | GET | Owner. Follows, recent fills, follower counts, kill-switch state |
+| `/api/agents/:id/mirror` | POST | Owner. Create or update a follow edge |
+| `/api/agents/:id/mirror/unfollow` | POST | Owner. Delete an edge |
+| `/api/agents/:id/mirror/kill` | POST | Owner. Toggle the agent-wide kill switch |
+| `/api/agents/:id/mirror/sync` | POST | Owner. Process pending leader trades now |
+| `/api/agents/:id/mirror/fills` | GET | Owner. Recent mirror fills |
+| `/api/agents/:id/mirror/followers` | GET | **Public** |
+| `/api/agents/:id/mirror/track-record` | GET | **Public** |
+
+### Creating a follow
+
+```bash
+curl -s -X POST 'https://three.ws/api/agents/<FOLLOWER_AGENT_ID>/mirror' \
+ -H 'authorization: Bearer <AGENT_TOKEN>' \
+ -H 'content-type: application/json' \
+ -d '{
+ "leader_agent_id": "<LEADER_AGENT_ID>",
+ "network": "mainnet",
+ "sizing_mode": "proportional",
+ "proportion_pct": 25,
+ "max_per_trade_sol": 0.25,
+ "daily_budget_sol": 1.0,
+ "min_leader_sol": 0.05,
+ "copy_sells": true,
+ "mint_denylist": []
+ }'
+```
+
+Validated by `normalizeFollowInput` in `api/_lib/mirror-engine.js`:
+
+| Field | Meaning |
+| --- | --- |
+| `sizing_mode` | `fixed`, `proportional` (default), or `pct_balance` |
+| `fixed_sol` | SOL per mirrored buy, when `sizing_mode: fixed`. Must be greater than 0 |
+| `proportion_pct` | Percent of the leader's buy size. Defaults to 100, meaning 1:1 |
+| `pct_balance` | Percent of the follower wallet's spendable SOL, 0 to 100 |
+| `max_per_trade_sol` | Per-follow per-trade cap. Optional, must be greater than 0 |
+| `daily_budget_sol` | Per-follow rolling 24 hour budget. Optional, stacks *under* the agent's own daily budget |
+| `min_leader_sol` | Ignore leader buys smaller than this |
+| `copy_sells` | Mirror exits. Defaults to true |
+| `mint_allowlist` / `mint_denylist` | Up to 100 base58 mints each. The denylist wins, and both apply to buys and sells |
+| `enabled` | Pause without deleting. Defaults to true |
+
+Refusals that protect you: a leader that is private returns `403 leader_private`, an agent cannot mirror itself (`400 cannot_follow_self`), and a reciprocal edge is blocked with `409 circular_follow` so two agents cannot feed each other forever.
+
+**A new follow never backfills.** On create, the cursor `last_leader_event_id` is set to the leader's newest existing trade event, so only trades made *after* you follow are ever mirrored.
+
+### What happens when the leader trades
+
+`api/cron/mirror-fanout.js` runs every 2 minutes (see the `crons` array in `vercel.json`). It selects enabled edges whose follower is not killed and whose leader has a confirmed trade newer than the edge cursor **within the last 20 minutes**, up to 120 edges per run, and processes at most 15 leader events per edge. The owner's "Sync now" button runs the same `syncFollow` path.
+
+Detection reads the leader's confirmed custody ledger (`agent_custody_events`, `category = 'trade'`, `status = 'confirmed'`), so every mirror traces to a real leader signature, mint, and size.
+
+Then `planMirror` (pure, unit-tested in `tests/mirror-engine.test.js`) decides:
+
+1. Kill switch on, or edge paused, stop.
+2. Mint denylisted, or not on a non-empty allowlist, stop.
+3. Sell side: if `copy_sells` is true, mirror the exit. Size is taken at execution from the follower's real on-chain token balance (it sells the full holding), and `no_holding` is recorded if there is nothing to sell.
+4. Buy side: apply `min_leader_sol`, size by the rule, clamp to `max_per_trade_sol`, clamp to the remaining `daily_budget_sol`, clamp to the wallet balance less a 0.004 SOL fee headroom, and reject anything under the 0.0005 SOL dust floor.
+
+The sized order then goes through `runFollowerTrade`, which is the same guard sequence the discretionary trade endpoint and the sniper use, in this order: agent kill switch, per-trade cap, rolling daily budget, the natural-language spend policy (`meta.policy_rules`), price-impact breaker, rug and honeypot firewall (a `block` verdict refuses the mirror), on-chain SOL headroom, then an idempotency claim in the custody ledger before anything is signed. Slippage is capped at 300 bps. Every mirrored trade lands in `agent_custody_events` with `reason: 'mirror'` and a `meta.mirror` reference naming the leader and the leader's event.
+
+Nothing double-spends: the custody idempotency key `mirror:<follow_id>:<leader_event_id>:<side>` and the unique index on `agent_mirror_fills (follow_id, leader_event_id, side)` both dedupe, so a retried cron or an overlapping manual sync replays instead of re-buying.
+
+Each attempt writes exactly one `agent_mirror_fills` row with status `executed`, `skipped`, `failed`, or `unconfirmed`, plus a machine reason. The UI renders those reasons through `SKIP_LABELS`, for example `Over per-trade cap`, `Blocked by safety firewall`, `Wallet underfunded`, `Daily budget used up`.
+
+### Stopping
+
+```bash
+# Halt every mirror for this agent, instantly
+curl -s -X POST 'https://three.ws/api/agents/<FOLLOWER_AGENT_ID>/mirror/kill' \
+ -H 'authorization: Bearer <AGENT_TOKEN>' \
+ -H 'content-type: application/json' -d '{"killed": true}'
+
+# Or drop one edge
+curl -s -X POST 'https://three.ws/api/agents/<FOLLOWER_AGENT_ID>/mirror/unfollow' \
+ -H 'authorization: Bearer <AGENT_TOKEN>' \
+ -H 'content-type: application/json' -d '{"leader_agent_id": "<LEADER_AGENT_ID>"}'
+```
+
+The kill switch is stored as `meta.mirror_killed` on the agent and is read in three places: the cron's candidate query, the engine's first check, and the sync endpoint (which returns `409 mirror_killed`). Setting it stops new mirrors immediately. It does not sell what you already hold.
+
+---
+
+## The non-custodial copier: subscriptions, intents, earnings
+
+This is the path where you keep your keys. It is managed from [/dashboard/copy](https://three.ws/dashboard/copy) and from the copy panel mounted on a trader profile.
+
+### `/api/copy/subscriptions`
+
+Auth required (session cookie or bearer). Cookie-session writes additionally require a CSRF token.
+
+| Method | Behavior |
+| --- | --- |
+| `GET` | Your follow list, with leader name and avatar, plus per-subscription `pending_count` and `acted_count` |
+| `POST` | Create or update a subscription (upsert keyed on copier, leader, network) |
+| `POST` with only `{ id, status }` | Pause, resume, or stop (`active`, `paused`, `stopped`) |
+| `DELETE ?id=<uuid>` | Soft stop. Status becomes `stopped`, history is kept |
+
+```bash
+curl -s -X POST 'https://three.ws/api/copy/subscriptions' \
+ -H 'authorization: Bearer <API_TOKEN>' -H 'content-type: application/json' \
+ -d '{
+ "leader_agent_id": "<LEADER_AGENT_ID>",
+ "copier_wallet": "<WALLET_ADDRESS>",
+ "network": "mainnet",
+ "sizing_rule": "multiplier",
+ "multiplier": 0.5,
+ "per_trade_cap_sol": 0.2,
+ "min_order_sol": 0.01,
+ "daily_budget_sol": 1.0,
+ "max_open_copies": 5,
+ "mcap_floor_usd": 15000,
+ "require_safety_pass": true,
+ "min_oracle_score": 60,
+ "perf_fee_bps": 1000
+ }'
+```
+
+Validated by `normalizeSubscriptionInput` in `api/_lib/copy-engine.js`. `per_trade_cap_sol` and `daily_budget_sol` are both mandatory and must be greater than 0, `min_order_sol` cannot exceed the cap, `pct_balance` must be within 0 to 100, `min_oracle_score` within 0 to 100, and `perf_fee_bps` within 0 to 3000 (30 percent). `max_open_copies` defaults to 5 and is clamped to 1 to 100. `copy_sells` defaults to true, `require_safety_pass` defaults to false. `telegram_chat_id`, if set, must be a numeric Telegram chat id and turns on push alerts for new intents. Only public leaders can be copied. We store your wallet address and your rules, never a key.
+
+### How intents are recorded
+
+`api/cron/copy-fanout.js` runs every 2 minutes and fans out from two real leader sources: the sniper engine's executed positions (`agent_sniper_positions`) and the Oracle conviction agent's live buys (`oracle_watch_actions`), each within an 8 minute recency window.
+
+For every (leader event, subscription) pair it calls `planCopyOrder`, the pure engine in `api/_lib/copy-engine.js` (tested in `tests/copy-engine.test.js`):
+
+- **Safety gate on entries only.** A honeypot flag is fatal. Market cap is checked against your floor and ceiling. A dev holding 30 percent or more of supply is refused as `dev_heavy`. Liquidity under 1000 USD is refused as `low_liquidity`. A known Oracle conviction score below your `min_oracle_score` is refused. If coin context could not be fetched at all, the result depends on your `require_safety_pass` flag: with it on, the copy is skipped as `safety_unknown`. Coin context is best-effort from the public pump.fun coin endpoint (market cap) merged with the stored Oracle score.
+- **Open-copy cap.** More pending intents than `max_open_copies`, skipped.
+- **Sizing.** `fixed` uses `fixed_sol`, `multiplier` scales the leader's entry, `pct_balance` takes a percentage of your balance. The result is clamped to `per_trade_cap_sol`, then to the remaining `daily_budget_sol` (today's `pending` plus `acted` buy sizes), and rejected if it falls under `min_order_sol`.
+- **Exits.** A sell fans out with `order_sol: 0` and reason `mirror_exit`, and only to copiers who actually acted on the matching buy. Oracle sells are not modelled, because that engine has no explicit exit event.
+
+Either way a row lands in `copy_executions`: `status = 'pending'` for a real intent, or `status = 'skipped'` carrying the machine reason so the dashboard can explain exactly why a copy did not fire. Idempotency comes from partial unique indexes on `(subscription_id, leader_position_id, direction)` and `(subscription_id, leader_oracle_action_id, direction)`, so re-running the cron never duplicates an intent.
+
+Pending intents carry `expires_at`, 30 minutes after creation by default. They are expired lazily on read, so your inbox never offers an actionable copy for a coin that has long since moved.
+
+### `/api/copy/executions`
+
+Auth required. CSRF for cookie-session writes.
+
+```bash
+# The inbox
+curl -s 'https://three.ws/api/copy/executions?status=pending' -H 'authorization: Bearer <API_TOKEN>'
+
+# Full history, newest first
+curl -s 'https://three.ws/api/copy/executions?status=all&limit=40' -H 'authorization: Bearer <API_TOKEN>'
+
+# Record that you executed it from your own wallet
+curl -s -X POST 'https://three.ws/api/copy/executions' \
+ -H 'authorization: Bearer <API_TOKEN>' -H 'content-type: application/json' \
+ -d '{"id": "<EXECUTION_ID>", "action": "acted", "tx_signature": "<SIGNATURE>"}'
+
+# Or dismiss it
+curl -s -X POST 'https://three.ws/api/copy/executions' \
+ -H 'authorization: Bearer <API_TOKEN>' -H 'content-type: application/json' \
+ -d '{"id": "<EXECUTION_ID>", "action": "dismissed"}'
+```
+
+`status` accepts `pending` (the default), `acted`, `dismissed`, `skipped`, `expired`, or `all`. `limit` is 1 to 100, default 50. Only a `pending` intent can be actioned; anything else returns `409 not_actionable`. `tx_signature` is optional, kept for your records, and truncated to 128 characters.
+
+### `/api/copy/earnings`
+
+One route, two modes.
+
+```bash
+# PUBLIC: a leader's aggregate copy earnings (social proof, no copier identity)
+curl -s 'https://three.ws/api/copy/earnings?agent_id=<LEADER_AGENT_ID>&network=mainnet'
+
+# AUTHED: what you currently owe across the leaders you copy
+curl -s 'https://three.ws/api/copy/earnings' -H 'authorization: Bearer <API_TOKEN>'
+```
+
+The public aggregate returns `copiers`, `accrued_fee_sol`, and `copier_profit_sol`, cached for 30 to 60 seconds. It never exposes an individual copier.
+
+The authed view returns `total_fee_owed_sol` plus one item per subscription with `cumulative_profit_sol`, `closed_copies`, `billable_profit_sol`, `fee_sol`, and `new_high_water_mark_sol`. Subscriptions with nothing to show are omitted.
+
+The math (`api/_lib/copy-earnings.js`, tested in `tests/copy-earnings.test.js`):
+
+```
+cumulative_profit = sum over your acted BUY copies whose leader position has CLOSED of
+ planned_sol * (leader_realized_pnl_pct / 100)
+
+billable = max(0, cumulative_profit - high_water_mark)
+fee = billable * (perf_fee_bps / 10000)
+new_high_water = max(high_water_mark, cumulative_profit)
+```
+
+Losing copies lower the cumulative, and the high-water mark only ever ratchets up, so a drawdown followed by a recovery is never billed twice. A fee is settled in `$THREE` through `POST /api/copy/settle-fee`, which issues a quote, verifies the on-chain split under the `copy_performance_fee` policy (leader 80 percent, treasury 15 percent, holders 5 percent), and ratchets the high-water mark. That is a spend: confirm the recipient and amount before signing.
+
+---
+
+## The Smart Money directory
+
+`GET /api/copy/smart-wallets` serves a curated directory of externally proven wallets so you can vet an ecosystem trader before mirroring anything. These are **external on-chain wallets, not three.ws agents**: you cannot subscribe to one, and the dashboard action is to open its live history on an explorer. Public, IP rate-limited, cached hard at the edge (`s-maxage=3600, stale-while-revalidate=86400`) because the ranking shifts daily, not by the second.
+
+| Param | Values | Default |
+| --- | --- | --- |
+| `chain` | `sol`, `bsc` | all chains |
+| `category` | `smart_money`, `launchpad`, `kol`, `sniper` | all categories |
+| `sort` | `score`, `profit` (30d realized USD), `pnl` (30d multiple), `winrate`, `followers` | `score` |
+| `q` | Free text matched against address, display name, and social handle | none |
+| `limit` | 1 to 100 | 30 |
+| `offset` | 0 to 100000 | 0 |
+
+An unrecognized value falls back to the default rather than erroring. `category` matches against each wallet's full `categories` array, so a wallet tagged both ways appears under both filters.
+
+```bash
+# Top-ranked Solana wallets
+curl -s 'https://three.ws/api/copy/smart-wallets?chain=sol&sort=score&limit=5'
+
+# Highest 30-day realized profit in the launchpad cohort
+curl -s 'https://three.ws/api/copy/smart-wallets?category=launchpad&sort=profit&limit=10'
+
+# Page 2
+curl -s 'https://three.ws/api/copy/smart-wallets?limit=30&offset=30'
+
+# Look up one wallet
+curl -s 'https://three.ws/api/copy/smart-wallets?q=<WALLET_ADDRESS>'
+```
+
+Response:
+
+```json
+{
+ "wallets": [
+ {
+ "address": "<WALLET_ADDRESS>",
+ "chain": "sol",
+ "category": "smart_money",
+ "categories": ["smart_money"],
+ "name": "<DISPLAY_NAME>",
+ "twitter_username": "<HANDLE>",
+ "avatar": "<IMAGE_URL>",
+ "realized_profit_30d_usd": 0,
+ "pnl_30d": 0,
+ "pnl_7d": 0,
+ "win_rate_30d": 0,
+ "txs_30d": 0,
+ "buy_30d": 0,
+ "sell_30d": 0,
+ "follow_count": 0,
+ "avg_holding_period_30d": 0,
+ "last_active": 0,
+ "score": 0
+ }
+ ],
+ "total": 0,
+ "offset": 0,
+ "limit": 30,
+ "has_more": false,
+ "facets": { "byChain": {}, "byCategory": {} },
+ "source": "<UPSTREAM_TAXONOMY>",
+ "generated_at": "2026-01-01T00:00:00.000Z"
+}
+```
+
+`total` is the count *after* filtering, `facets` carries the directory-wide counts by chain and category for building filter chips, and `source` plus `generated_at` are the provenance of the snapshot. Note that `win_rate_30d` is a fraction (0 to 1) here, unlike the leaderboard's `win_rate`, which is a percentage.
+
+The directory is a static, deduplicated snapshot shipped with the API (`api/_lib/copy/smart-wallets.json`) and regenerated by `scripts/build-smart-wallets.mjs`. Wallet identity and 30-day performance only, never token holdings. If the snapshot file is missing the endpoint returns an empty list rather than failing.
+
+For first-party wallet reputation earned from three.ws's own outcome ledger rather than an external taxonomy, use [Smart Money Radar](./smart-money.md).
+
+---
+
+## Public versus authenticated, at a glance
+
+| Route | Method | Access |
+| --- | --- | --- |
+| `/api/mirror/leaderboard` | GET | Public, cached 60s |
+| `/api/copy/smart-wallets` | GET | Public, cached 1h |
+| `/api/copy/earnings?agent_id=` | GET | Public, cached 30 to 60s |
+| `/api/agents/:id/mirror/followers` | GET | Public |
+| `/api/agents/:id/mirror/track-record` | GET | Public |
+| `/api/copy/earnings` (no `agent_id`) | GET | Session or bearer |
+| `/api/copy/subscriptions` | GET | Session or bearer |
+| `/api/copy/subscriptions` | POST, DELETE | Session or bearer, plus CSRF for cookie sessions |
+| `/api/copy/executions` | GET | Session or bearer |
+| `/api/copy/executions` | POST | Session or bearer, plus CSRF for cookie sessions |
+| `/api/copy/settle-fee` | POST | Session or bearer, plus CSRF for cookie sessions |
+| `/api/agents/:id/mirror` and `/unfollow`, `/kill`, `/sync`, `/fills` | GET, POST | Owner of that agent only, plus CSRF for cookie sessions |
+
+Every route is IP rate-limited. Authenticated routes reject with `401 unauthorized` and the description `sign in required`; a non-owner on an agent mirror route gets `403 forbidden`.
+
+---
+
+## Agent and MCP access
+
+Both engines are reachable without a browser:
+
+- `packages/copy-mcp` exposes the copier surface as MCP tools (list and create subscriptions, read executions, record an execution, read earnings, cancel a subscription). See [its README](../packages/copy-mcp/README.md).
+- `packages/intel-mcp` wraps the Smart Money directory as a tool.
+- `packages/strategies` wraps `POST /api/copy/subscriptions` and `/api/copy/executions` for programmatic strategy clients. See [its README](../packages/strategies/README.md).
+- Bearer tokens work on every authenticated route above and are not CSRF-gated, which is what makes an autonomous agent a first-class copier here.
+
+See [the MCP reference](./mcp.md) for wiring these into a client.
+
+---
+
+## Checklist before you turn on the mirror
+
+1. Read the leader's `track-record`, not just their rank. Check `settled` (sample size) and `max_drawdown_sol`, not only ROI.
+2. Set `max_per_trade_sol` and `daily_budget_sol` on the follow edge. They stack under the agent's own spend policy, so the tighter number wins.
+3. Confirm your agent's spend policy and trade limits are what you think they are. See [agent wallets](./agent-wallets.md).
+4. Start with `proportional` sizing at a low `proportion_pct` rather than `pct_balance`, which scales with the wallet and grows as it grows.
+5. Know where the kill switch is: the toggle on `/mirror`, or `POST /api/agents/:id/mirror/kill`.
+6. Watch the first few fills. `skip_reason` tells you which guard is binding, and a stream of `Over per-trade cap` means your leader trades bigger than your leash.
diff --git a/docs/embedding.md b/docs/embedding.md
index 67606e91e..39d2a9e3a 100644
--- a/docs/embedding.md
+++ b/docs/embedding.md
@@ -70,7 +70,7 @@ The element accepts several ways to point at an agent — pick one:
| `agent-id` (CAIP-10) | `agent-id="eip155:8453:0xReg…:42"` | Fully qualified on-chain reference |
| `agent-id` (backend) | `agent-id="a_abc123"` | Legacy backend account ID |
| `manifest` | `ipfs://bafy.../manifest.json` | IPFS or HTTPS manifest URL |
-| `body` | `./avatar.glb` | Bare GLB for an ad-hoc agent (viewer-only unless you also set `brain`) |
+| `body` | `https://three.ws/avatars/default.glb` | Bare GLB for an ad-hoc agent (viewer-only unless you also set `brain`) |
When multiple are set, priority is `src` > `agent-id` > `manifest` > `body`.
@@ -81,7 +81,7 @@ free-tier proxy. Pair it with `instructions` for a system prompt:
```html
<agent-3d
- body="./avatar.glb"
+ body="https://three.ws/avatars/realistic-female.glb"
brain="free"
instructions="You are Maya, a friendly guide to this site."
></agent-3d>
diff --git a/docs/erc8004.md b/docs/erc8004.md
index 1896c989d..2f36e501f 100644
--- a/docs/erc8004.md
+++ b/docs/erc8004.md
@@ -609,7 +609,7 @@ import { agentRegistryId, REGISTRY_DEPLOYMENTS } from './src/erc8004/abi.js';
const card = buildRegistrationJSON({
name: 'My Agent',
description: 'Description here.',
- imageUrl: 'https://cdn.example.com/thumb.png', // 2D thumbnail
+ imageUrl: 'https://three.ws/avatars/thumbs/default.png', // 2D thumbnail
glbUrl: 'ipfs://bafy.../body.glb', // 3D model
agentId: 42,
chainId: 8453,
diff --git a/docs/forged.md b/docs/forged.md
index c9f026506..fdb100385 100644
--- a/docs/forged.md
+++ b/docs/forged.md
@@ -75,7 +75,7 @@ a 20-second shared cache.
|---|---|---|
| `limit` | `30` | Page size, clamped to 1..100. |
| `status=all` | off | Include `queued` and `failed` rows (audit view). By default only `done` rows with a GLB are returned. |
-| `category` | none | Filter by prop family. The handler accepts a fixed set: `crate`, `barrel`, `furniture`, `terrain`. Any other value returns `400 invalid_category`. |
+| `category` | none | Filter by prop family. Valid values are the eight families in the shared prop catalog (`api/_lib/x402/pipelines/forge-catalog.js`): `club-decor`, `ar-object`, `diorama-set`, `avatar-item`, `vehicle`, `container`, `furniture`, `terrain`. Any other value returns `400 invalid_category`, and the error body lists the accepted set. |
The response carries the props plus aggregate stats:
diff --git a/docs/ibm.md b/docs/ibm.md
index 0a5d01cf8..24eb15c68 100644
--- a/docs/ibm.md
+++ b/docs/ibm.md
@@ -34,6 +34,32 @@ Do not describe the connector or the public demos as an official IBM release or
The session: the three.ws engineering team built and shipped a 3D, interactive, fully embeddable AI agent from a single text prompt, live: generate the agent from a prompt, embed it into any site as simply as a video, and wire it to real tools and data so it can take action, plus a look at the architecture behind frictionless deployment at scale. Aimed at developers, product builders, designers, and anyone exploring the next interface for AI beyond the chat box.
+### The Three.ws User Group on IBM Community
+
+three.ws runs a public user group on IBM Community for developers and engineers building AI agents with 3D capabilities: spatial reasoning, generative 3D, agentic pipelines, and real-time interactive AI systems. It is a community space three.ws moderates on IBM's platform, not an IBM product and not a partnership deliverable, so every framing rule above applies to what gets posted there.
+
+| Surface | Link |
+| ------- | ---- |
+| Group home | [Three.ws User Group](https://community.ibm.com/community/user/groups/community-home?communitykey=e71510cc-d953-408f-9a1c-019f5c0a7016) |
+| Discussions | [Thread index](https://community.ibm.com/community/user/groups/community-home/digestviewer?communitykey=e71510cc-d953-408f-9a1c-019f5c0a7016) |
+| Blogs | [Recent group blogs](https://community.ibm.com/community/user/groups/community-home/recent-community-blogs?communitykey=e71510cc-d953-408f-9a1c-019f5c0a7016) |
+| Events | [Group events](https://community.ibm.com/community/user/groups/community-home/recent-community-events?communitykey=e71510cc-d953-408f-9a1c-019f5c0a7016) |
+| Library | [Files and assets](https://community.ibm.com/community/user/groups/community-home/librarydocuments?communitykey=e71510cc-d953-408f-9a1c-019f5c0a7016&LibraryFolderKey=&DefaultView=) |
+| Members | [Member list](https://community.ibm.com/community/user/groups/community-home/community-members?communitykey=e71510cc-d953-408f-9a1c-019f5c0a7016&Execute=1) |
+
+Published in the group so far:
+
+| Post | What it covers |
+| ---- | -------------- |
+| [Welcome to the Three.ws User Group: Building AI Agents With 3D Capabilities](https://community.ibm.com/community/user/blogs/jessica-swanson/2026/07/14/welcome-to-the-threews-user-group-building-ai-agen) | The group charter: who it is for and what gets discussed |
+| [three.ws: The Free AI 3D Model Generator's 10 Best Features](https://community.ibm.com/community/user/blogs/nich8/2026/07/16/threews-the-free-ai-3d-model-generators-10-best) | Feature tour of the free text-to-3D forge lane |
+| [Welcome to the three.ws IBM community: a full tour of the platform (start here)](https://community.ibm.com/community/user/discussion/welcome-to-the-threews-ibm-community-a-full-tour-of-the-platform-start-here) | Orientation thread: what the platform does, surface by surface |
+| [From a text prompt to an embeddable 3D agent, step by step](https://community.ibm.com/community/user/discussion/from-a-text-prompt-to-an-embeddable-3d-agent-step-by-step) | Prompt to generated agent to `<agent-3d>` embed, end to end |
+| [Type a Sentence, Get a 3D Model: A Hands-On Walkthrough of the three.ws Forge](https://community.ibm.com/community/user/discussion/type-a-sentence-get-a-3d-model-a-hands-on-walkthrough-of-the-threews-forge-user-perspective) | A user's first run through the forge, with the output |
+| [Why does my GLB model load white or untextured? (Three.js, Blender exports, web viewers)](https://community.ibm.com/community/user/discussion/why-does-my-glb-model-load-white-or-untextured-threejs-blender-exports-web-viewers) | Troubleshooting glTF/GLB texture and material loading |
+
+What belongs there, and what does not, is set by the [SEO keyword plan](./ops/seo-keyword-plan.md): one post per week maximum, tutorials that stand on their own for an IBM developer who never clicks through, and no crypto-cluster content (that goes on [three.ws/blog](https://three.ws/blog) instead). The user group is also linked from the site's [Community page](https://three.ws/community) and the global footer.
+
### Press & coverage
Outside coverage of three.ws and its work on IBM watsonx.ai. These are third-party press and syndicated releases — link to them as coverage, and keep the distinctions above intact when you cite them. Do not let a headline upgrade the careful framing on this page.
diff --git a/docs/media-api.md b/docs/media-api.md
index c3bd0db65..77f154962 100644
--- a/docs/media-api.md
+++ b/docs/media-api.md
@@ -84,13 +84,16 @@ automatically. Subsequent requests answer `302` to the CDN copy
# Discover the parameters, scenes, and pose catalog
curl -s https://three.ws/api/avatar/render
+# The avatar id below is Michelle, a public featured avatar, so these run as-is.
+# Swap in your own id from GET https://three.ws/api/avatars/featured or /avatars/<id>.
+
# Render a 256px transparent portrait
curl -sL -o portrait.png \
- 'https://three.ws/api/avatar/render?avatar=YOUR_AVATAR_ID&scene=portrait&size=256&bg=transparent'
+ 'https://three.ws/api/avatar/render?avatar=13f259c7-7024-4d68-b1f0-dbbf52c06209&scene=portrait&size=256&bg=transparent'
# Waving, smiling, as WebP
curl -sL -o card.webp \
- 'https://three.ws/api/avatar/render?avatar=YOUR_AVATAR_ID&pose=wave&expression=%7B%22mouthSmile%22%3A0.6%7D&format=webp'
+ 'https://three.ws/api/avatar/render?avatar=13f259c7-7024-4d68-b1f0-dbbf52c06209&pose=wave&expression=%7B%22mouthSmile%22%3A0.6%7D&format=webp'
```
---
@@ -199,7 +202,7 @@ Requests are rate-limited per IP; a `429` carries `Retry-After`.
```bash
# Mobile budget: 512px textures, ARKit-52 morphs only, Draco-compressed
curl -sL -o mobile.glb \
- 'https://three.ws/api/avatar/optimize?id=YOUR_AVATAR_ID&textureSize=512&morphs=arkit52&draco=1'
+ 'https://three.ws/api/avatar/optimize?id=13f259c7-7024-4d68-b1f0-dbbf52c06209&textureSize=512&morphs=arkit52&draco=1'
# By source URL, LOD 1
curl -sL -o lite.glb \
@@ -598,7 +601,7 @@ the submission proceeds; forge still validates the image.
```bash
curl -s -X POST https://three.ws/api/input-photo \
-H 'content-type: application/json' \
- -d '{"image_url":"https://example.com/selfie.jpg","tier":"standard"}'
+ -d '{"image_url":"https://three.ws/avatars/thumbs/default.png","tier":"standard"}'
```
---
@@ -772,7 +775,7 @@ auth; rate-limited per IP.
# Submit
curl -s -X POST https://three.ws/api/forge-rembg \
-H 'content-type: application/json' \
- -d '{"image_url":"https://example.com/product-shot.jpg","model":"rmbg2"}'
+ -d '{"image_url":"https://three.ws/avatars/thumbs/default.png","model":"rmbg2"}'
# Poll
curl -s 'https://three.ws/api/forge-rembg?job=JOB_ID'
diff --git a/docs/nvidia-inception.md b/docs/nvidia-inception.md
index 506dc8ce4..70bcb65ce 100644
--- a/docs/nvidia-inception.md
+++ b/docs/nvidia-inception.md
@@ -33,4 +33,6 @@ Membership is a startup program, not a partnership or an investment: NVIDIA revi
## Related
- [NVIDIA models on three.ws](/docs/nvidia-models) — the free inference layer, model by model
+- [The generator was never the hard part](/docs/nvidia-nemotron-spotlight) — our Nemotron Nano write-up, published on the NVIDIA Developer Forums
+- [Image-to-3D on NVIDIA L4 and Blackwell](https://three.ws/blog/image-to-3d-on-nvidia-l4-and-blackwell) — the engineering post on the GPU fleet itself: memory ceilings, `sm_120` kernels, and regional quota
- [How the forge works](/docs/how-forge-works) — the 3D generation pipeline the GPUs power
diff --git a/docs/nvidia-models.md b/docs/nvidia-models.md
index c46c1be22..fe0e429ff 100644
--- a/docs/nvidia-models.md
+++ b/docs/nvidia-models.md
@@ -191,6 +191,9 @@ The free NVIDIA TTS lane: **Magpie multilingual on Riva**, selected by an NVCF `
## Related
+- [NVIDIA Inception membership](/docs/nvidia-inception) - what membership adds on top of this free lane
+- [The generator was never the hard part](/docs/nvidia-nemotron-spotlight) - our Nemotron Nano write-up, published on the NVIDIA Developer Forums
+- [Image-to-3D on NVIDIA L4 and Blackwell](https://three.ws/blog/image-to-3d-on-nvidia-l4-and-blackwell) - the self-hosted GPU fleet behind the paid lanes, and the two walls we hit moving to Blackwell
- [How Forge works](/docs/how-forge-works) - the /forge product this layer powers
- [REST API](/docs/api-reference) - the endpoints these models serve
- [Configuration](/docs/configuration) - all environment variables
diff --git a/docs/nvidia-nemotron-spotlight.md b/docs/nvidia-nemotron-spotlight.md
index 6328b9e53..dfbeee0b9 100644
--- a/docs/nvidia-nemotron-spotlight.md
+++ b/docs/nvidia-nemotron-spotlight.md
@@ -145,4 +145,4 @@ Build the small stuff. Put it in front. The generator was never the hard part.
---
-*three.ws is a browser-native platform for generating 3D avatars, worlds, and agents from a sentence. The text-to-3D lane described here is free and open: no key, no account. Our full NVIDIA model map lives in [`docs/nvidia-models.md`](./nvidia-models.md), and the pipeline internals are in [`docs/3d-asset-pipeline.md`](./3d-asset-pipeline.md).*
+*three.ws is a browser-native platform for generating 3D avatars, worlds, and agents from a sentence. The text-to-3D lane described here is free and open: no key, no account. Our full NVIDIA model map lives in [`docs/nvidia-models.md`](./nvidia-models.md), and the pipeline internals are in [`docs/3d-asset-pipeline.md`](./3d-asset-pipeline.md). three.ws joined the [NVIDIA Inception program](./nvidia-inception.md) in July 2026; the companion engineering post on our own GPU fleet is [Image-to-3D on NVIDIA L4 and Blackwell](https://three.ws/blog/image-to-3d-on-nvidia-l4-and-blackwell).*
diff --git a/docs/pump-launcher.md b/docs/pump-launcher.md
index bd01b1b55..7e4e8706b 100644
--- a/docs/pump-launcher.md
+++ b/docs/pump-launcher.md
@@ -75,7 +75,7 @@ curl -X POST https://three.ws/api/x402/pump-launch \
-d '{
"name": "Helios",
"symbol": "HELIO",
- "imageUrl": "https://example.com/helios.png",
+ "imageUrl": "https://three.ws/logo.png",
"description": "A sun-themed community coin.",
"creator": "wwwPqsM4N7T9J69tB82nLyzxqsH159j4orftLTQfUGV",
"twitter": "https://x.com/heliocoin",
diff --git a/docs/sdk.md b/docs/sdk.md
index 476c64678..e87db377e 100644
--- a/docs/sdk.md
+++ b/docs/sdk.md
@@ -27,7 +27,7 @@ Both are Apache-2.0 licensed. Neither requires the other.
```html
<script type="module" src="https://three.ws/agent-3d/latest/agent-3d.js"></script>
-<agent-3d model="./avatar.glb"></agent-3d>
+<agent-3d model="https://three.ws/avatars/default.glb"></agent-3d>
```
**UMD (legacy bundlers or `<script>` without `type="module"`):**
@@ -90,7 +90,7 @@ Direct three.js viewer — loads GLB/glTF, manages camera, lighting, and animati
import { Viewer } from './src/lib.js';
const viewer = new Viewer(document.getElementById('canvas-container'));
-viewer.load('./avatar.glb');
+viewer.load('https://three.ws/avatars/default.glb');
```
Full attribute and event API is documented in [Web Component reference](web-component.md).
diff --git a/docs/start-here.md b/docs/start-here.md
index 8a4f099e1..2a0ad3fdc 100644
--- a/docs/start-here.md
+++ b/docs/start-here.md
@@ -129,6 +129,9 @@ Curious what happens between the prompt and the model? [How the Forge works](./h
Deeper references that don't fit a track above but answer real questions:
- [Design tokens](./DESIGN-TOKENS.md): the canonical design vocabulary (colors, spacing, type, motion) every surface builds from
+- [NVIDIA models on three.ws](./nvidia-models.md): the free hosted inference layer model by model, one key behind text-to-3D, chat, vision, embeddings, safety, and speech
+- [NVIDIA Inception membership](./nvidia-inception.md): what the platform already runs on NVIDIA silicon and what the program adds on top
+- [The generator was never the hard part](./nvidia-nemotron-spotlight.md): our Nemotron Nano write-up, published on the NVIDIA Developer Forums
- [The onboarding tier](./onboarding-tier.md): why a first-time visitor sees ~20 nav destinations instead of ~100, how the Simple ⇄ Everything switch works, and which tier a new page belongs in
- [What an agent can do](./agent-abilities/ABILITIES.md): the full abilities dossier, generated from the source article
- [Use cases and example workflows](./content/use-cases/README.md): five audience-specific walkthroughs tying shipped features to concrete outcomes
diff --git a/docs/tutorials/place-agent-irl.md b/docs/tutorials/place-agent-irl.md
index 361f0c2ff..ac26a4a86 100644
--- a/docs/tutorials/place-agent-irl.md
+++ b/docs/tutorials/place-agent-irl.md
@@ -62,9 +62,11 @@ You'll see your agent rendered against the ambient dark background, an **IRL** b
To start with a specific agent's avatar, append `?avatar=` to the URL:
```
-https://three.ws/irl?avatar=YOUR_AVATAR_ID
+https://three.ws/irl?avatar=13f259c7-7024-4d68-b1f0-dbbf52c06209
```
+That id is Michelle, a public featured avatar, so you can open the link as-is to try it. Use your own avatar id (from `/avatars/<id>`, or `GET https://three.ws/api/avatars/featured`) to place your own agent.
+
An explicit `?avatar=` link always wins over the avatar you used last visit. (Links from an agent profile's "View in IRL" button also pass `?agent=` to deep-focus that agent's pin once it's nearby.)
---
diff --git a/docs/tutorials/view-in-ar.md b/docs/tutorials/view-in-ar.md
index 0120d1d00..dacdd80d1 100644
--- a/docs/tutorials/view-in-ar.md
+++ b/docs/tutorials/view-in-ar.md
@@ -92,16 +92,18 @@ With `ar` present, a **View in AR** button appears on the viewer. Clicking it op
**Full agent embed (`<agent-3d>`).** The talking-agent web component does not take an `ar` attribute. To offer AR next to it, link to the avatar's dedicated full-screen AR page, which picks the right method per device automatically:
```html
-<a href="https://three.ws/avatars/YOUR_AVATAR_ID/ar">See it in your room</a>
+<a href="https://three.ws/avatars/13f259c7-7024-4d68-b1f0-dbbf52c06209/ar">See it in your room</a>
```
+That id is Michelle, a public featured avatar, so the link works as written. Swap in your own avatar id from `/avatars/<id>` or `GET https://three.ws/api/avatars/featured`.
+
### Iframe embed + AR
If you're using the iframe embed, add `xr-spatial-tracking` to the `allow` attribute:
```html
<iframe
- src="https://three.ws/embed/avatar/YOUR_AVATAR_ID"
+ src="https://three.ws/embed/avatar/13f259c7-7024-4d68-b1f0-dbbf52c06209"
allow="microphone; camera; xr-spatial-tracking; fullscreen"
width="400"
height="500"
diff --git a/docs/user-wallet.md b/docs/user-wallet.md
new file mode 100644
index 000000000..7f85d8e92
--- /dev/null
+++ b/docs/user-wallet.md
@@ -0,0 +1,264 @@
+# Your master wallet: the per-user custodial hub
+
+Every three.ws **agent** owns a wallet ([agent-wallets.md](agent-wallets.md)). Separately, every **user account** can own one custodial wallet of its own: the **master wallet**. It is the financial hub for the person rather than the bot. You fund it once, then push money out to wherever it needs to be: into an agent's wallet so the agent can trade or pay for API calls, or straight out to any Solana address.
+
+Solana is the operative chain here. The master wallet also holds an EVM keypair (used for reading a Base USDC balance and for the chains where agents register an on-chain identity), but the send paths documented below are Solana only.
+
+Everything on this page moves real money. Read [Safety: this is a spend surface](#safety-this-is-a-spend-surface) before calling any `POST`.
+
+Code: `api/user/wallet/index.js`, `send.js`, `fund-agent.js`, `history.js`.
+
+## Master wallet vs agent wallet
+
+They are different wallets with different jobs, and mixing them up is the single most common mistake here.
+
+| | Master wallet | Agent wallet |
+| --- | --- | --- |
+| Belongs to | your **user account**, one per user | one **agent**, one per agent |
+| Address record | `master_wallets` row keyed by `user_id` | the agent's own record |
+| Who can spend | **you**, with a signed-in browser session | the agent itself, autonomously, plus you |
+| Spend policy | none: no per-transaction cap, no daily USD cap, no allowlist, no freeze switch | full policy module: daily and per-transaction caps, withdraw allowlist, kill switch, capability gating |
+| Auth accepted | **session cookie only** (no API key, no bearer token) | session or scoped credential, depending on the path |
+| Typical use | hold funds, top up agents, sweep out | pay x402 endpoints, trade, buy skills, receive earnings |
+
+The practical consequence: **an API key cannot spend your master wallet, and neither can an agent.** Only a browser session belonging to you can. That is deliberate. The agent-side limits, freeze switch, and audit rails described in [custody.md](custody.md) govern agent wallets; the master wallet's protection is that nothing autonomous can reach it at all, plus a hard ceiling of **5 outbound transactions per user per day** shared across `send` and `fund-agent`.
+
+Funds flow one way through the platform's plumbing: master wallet to agent wallet, via `fund-agent`. To go the other direction, use the agent's own owner withdrawal (see [agent-wallets.md](agent-wallets.md)), which a freeze never blocks.
+
+## Auth model: session plus CSRF
+
+- Every route requires a signed-in **session cookie**. Without one: `401 unauthorized`. There is no bearer or API-key path on these four routes, unlike most of the API.
+- Every write (`POST`) additionally requires a one-time CSRF token in `X-CSRF-Token`, obtained from `GET /api/csrf-token`. The token is bound to your user id, single-use, and expires after an hour. Missing: `403 csrf_missing`. Stale or wrong: `403 csrf_invalid`. Fetch a fresh token per write.
+- Reads are rate limited at 60 per minute per user. Writes that move funds are limited to **5 per day per user**, and that limiter is critical: if its backend is unreachable in production the write is refused rather than uncapped. Wallet creation is additionally limited per IP.
+
+See [authentication.md](authentication.md) for how sessions and CSRF tokens work in general.
+
+The examples below assume a browser-style cookie jar in `cookies.txt` and a token in `$CSRF`:
+
+```bash
+CSRF=$(curl -s -b cookies.txt https://three.ws/api/csrf-token | python3 -c 'import json,sys; print(json.load(sys.stdin)["token"])')
+```
+
+## Provisioning: lazy, and idempotent
+
+No wallet exists until you ask for one. `GET /api/user/wallet` on an account that has never provisioned returns `{"wallet": null}`, which is the signal for a UI to offer a "create wallet" action rather than an error state.
+
+`POST /api/user/wallet` creates the pair: a Solana keypair and an EVM keypair, both generated server-side, both encrypted at rest with AES-256-GCM under the dedicated `WALLET_ENCRYPTION_KEY` (the same secret box that protects agent wallets, deliberately not the session signing secret). There is no seed phrase for you to write down.
+
+The call is idempotent. If a wallet already exists it returns `200` with `"created": false` and the existing addresses; a genuine creation returns `201` with `"created": true`.
+
+```bash
+curl -sX POST https://three.ws/api/user/wallet \
+ -b cookies.txt -H "X-CSRF-Token: $CSRF"
+```
+
+```json
+{
+ "wallet": {
+ "solana_address": "7Gk…",
+ "evm_address": "0x9f…",
+ "created_at": "2026-07-30T10:22:04.113Z",
+ "created": true
+ }
+}
+```
+
+## Reading balances
+
+`GET /api/user/wallet` returns the addresses plus live balances. Nothing is cached, and nothing blocks: the Solana read and the Base USDC read run in parallel and a failure of either yields `null` for that field rather than a failed request, so the page still renders.
+
+```bash
+curl -s -b cookies.txt https://three.ws/api/user/wallet
+```
+
+```json
+{
+ "wallet": {
+ "solana_address": "7Gk…",
+ "evm_address": "0x9f…",
+ "created_at": "2026-07-30T10:22:04.113Z",
+ "balances": {
+ "sol": 0.4213,
+ "sol_usdc": 120.5,
+ "evm_usdc": 0,
+ "total_usd": 197.84
+ }
+ }
+}
+```
+
+- `sol` is the native balance, `sol_usdc` the USDC balance on Solana, `evm_usdc` the USDC balance on Base (read with a direct `balanceOf` call through the EVM RPC failover chain).
+- `total_usd` is the priced Solana total plus the Base USDC figure, and is `null` when the price feed is unavailable. Treat a `null` as "unknown", never as zero.
+
+## Sending SOL or an SPL token (this spends real funds)
+
+`POST /api/user/wallet/send` signs and broadcasts a transfer from your master wallet to any Solana address.
+
+| Field | Values | Meaning |
+| --- | --- | --- |
+| `destination` | base58 Solana address, required | Validated as a real, on-curve address. Program or off-curve addresses are refused, as is your own wallet address. |
+| `amount` | positive number, or `"max"` | `"max"` sweeps the spendable balance. |
+| `asset` | `"SOL"` (default) or an SPL mint address | Any SPL mint works, including Token-2022 mints. For USDC, pass the Solana USDC mint. |
+| `simulate` | `true` to preview | Returns the resolved asset, destination, amount and USD value **without signing anything**. |
+
+Reserves and guards, all applied before signing:
+
+- A `"max"` SOL sweep holds back rent exemption plus a fee reserve, so the account never becomes unusable. A fixed SOL amount that would eat into that reserve is refused with `insufficient_balance`.
+- For a token send, the source token account must exist and hold at least the requested amount, otherwise `insufficient_balance`. `"max"` sends the entire token balance.
+- If the recipient has no token account for that mint, the transaction opens one (idempotently) and your wallet pays the rent. If your SOL cannot cover fee plus that rent, the call is refused with `insufficient_sol_for_fees` rather than half-executing.
+- Amounts that round to zero at the mint's decimals are refused with `invalid_amount`.
+
+Preview first. This costs nothing and signs nothing:
+
+```bash
+curl -sX POST https://three.ws/api/user/wallet/send \
+ -b cookies.txt -H "X-CSRF-Token: $CSRF" -H 'content-type: application/json' \
+ -d '{
+ "destination": "7Gk1vQ9c3sN4wH2xY8mJ6pR5tB1aD7fE0uK4nC9zL3sV",
+ "amount": 5,
+ "asset": "SOL",
+ "simulate": true
+ }'
+```
+
+```json
+{
+ "simulation": {
+ "asset": "SOL",
+ "destination": "7Gk1vQ9c3sN4wH2xY8mJ6pR5tB1aD7fE0uK4nC9zL3sV",
+ "human_amount": 5,
+ "usd_value": 742.15,
+ "network": "mainnet"
+ }
+}
+```
+
+Then execute, with a fresh CSRF token, once a human has confirmed the destination and amount:
+
+```bash
+curl -sX POST https://three.ws/api/user/wallet/send \
+ -b cookies.txt -H "X-CSRF-Token: $CSRF" -H 'content-type: application/json' \
+ -d '{
+ "destination": "7Gk1vQ9c3sN4wH2xY8mJ6pR5tB1aD7fE0uK4nC9zL3sV",
+ "amount": 25,
+ "asset": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"
+ }'
+```
+
+```json
+{
+ "signature": "4Rj…",
+ "explorer": "https://solscan.io/tx/4Rj…",
+ "asset": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
+ "destination": "7Gk1vQ9c3sN4wH2xY8mJ6pR5tB1aD7fE0uK4nC9zL3sV",
+ "human_amount": 25,
+ "usd_value": 25,
+ "network": "mainnet"
+}
+```
+
+`usd_value` is populated for SOL (from the price feed) and for USDC (one to one); for any other mint it is `null`. Send is mainnet only.
+
+Error shapes worth handling: `404 not_found` (no master wallet yet), `400 invalid_destination`, `400 invalid_amount`, `400 invalid_asset`, `400 insufficient_balance`, `400 insufficient_sol_for_fees`, `502 rpc_error` (balance or blockhash read failed, nothing signed), `502 send_failed` (the network rejected the transaction), `429` when the 5-per-day ceiling is spent.
+
+## Funding an agent from the master wallet (this spends real funds)
+
+`POST /api/user/wallet/fund-agent` is the same money movement with a safer destination: it can only pay **an agent you own**.
+
+| Field | Values |
+| --- | --- |
+| `agent_id` | required. Must be your agent and not deleted, otherwise `403 forbidden`. |
+| `asset` | `"USDC"` (default) or `"SOL"`. |
+| `amount` | positive number, or `"max"`. |
+
+The destination address is resolved from the agent record, never from the request body, so there is no address to mistype. An agent that has not been provisioned a Solana wallet yet returns `400 no_agent_wallet`.
+
+```bash
+curl -sX POST https://three.ws/api/user/wallet/fund-agent \
+ -b cookies.txt -H "X-CSRF-Token: $CSRF" -H 'content-type: application/json' \
+ -d '{
+ "agent_id": "0f2c8a5e-1b7d-4f9a-9c3e-2d6b8a1f4e70",
+ "asset": "USDC",
+ "amount": 50
+ }'
+```
+
+```json
+{
+ "signature": "2Yb…",
+ "explorer": "https://solscan.io/tx/2Yb…",
+ "asset": "USDC",
+ "agent_id": "0f2c8a5e-1b7d-4f9a-9c3e-2d6b8a1f4e70",
+ "agent_wallet": "5Qm…",
+ "human_amount": 50,
+ "usd_value": 50
+}
+```
+
+Same reserve logic as `send`, and mainnet only: a `"max"` SOL top-up leaves rent and fee headroom, and if the agent has no USDC account yet the transaction opens one and your master wallet pays the rent (refused with `insufficient_sol_for_fees` if your SOL cannot cover it). Note there is **no `simulate` option on this route**: a well-formed call executes immediately.
+
+Once the funds land, they are the agent's, and every further movement out of them runs through the agent's own spend policy, kill switch, and custody trail. Funding an agent is therefore the moment to decide how much autonomy you are comfortable financing: top up in the size you would be willing to lose to a bad strategy, not the whole balance. This is also the normal way to get USDC into an agent before it backs a vault ([vaults.md](vaults.md)) and the easiest way to send a vault the small SOL balance it needs for swap fees, by sending to the vault address with `send`.
+
+## On-chain history
+
+`GET /api/user/wallet/history` reads the master wallet's Solana signature history straight from chain. It is not a platform ledger: it is what actually happened to the address, including transfers you made from outside three.ws.
+
+- `limit` defaults to 20, capped at 50. `network` accepts `mainnet` (default) or `devnet`.
+- Signatures are cached for 60 seconds. The RPC call retries the primary provider twice with backoff, then falls back to a public endpoint; only if all of that fails do you get `502 rpc_error`.
+- Each row carries `signature`, `slot`, `block_time`, `success`, `error`, `lamport_delta` (this address's net SOL change, when the parsed transaction is available), a short `summary` of the first instruction, and a Solscan `explorer` link.
+- An account with no wallet returns `{"history": []}` rather than an error.
+
+```bash
+curl -s -b cookies.txt "https://three.ws/api/user/wallet/history?limit=10"
+```
+
+```json
+{
+ "history": [
+ {
+ "signature": "2Yb…",
+ "slot": 298431102,
+ "block_time": 1785412992,
+ "success": true,
+ "error": null,
+ "lamport_delta": -25040,
+ "summary": "transferChecked",
+ "explorer": "https://solscan.io/tx/2Yb…"
+ }
+ ],
+ "address": "7Gk…",
+ "network": "mainnet"
+}
+```
+
+`lamport_delta` is `null` when the parsed transaction could not be fetched. Render it as unknown, not as zero.
+
+## Safety: this is a spend surface
+
+Two routes move real funds, irreversibly, the moment they return success:
+
+| Route | What leaves |
+| --- | --- |
+| `POST /api/user/wallet/send` | SOL or any SPL token, to **any address you name**. No allowlist. |
+| `POST /api/user/wallet/fund-agent` | USDC or SOL, to **an agent you own**. |
+
+As coded, the server-side protections are: a signed-in session (no API key can reach these), a single-use CSRF token per call, a hard ceiling of 5 outbound transactions per user per day, on-curve destination validation, and rent and fee reserves that prevent a sweep from bricking the account. That is the entire list. **There is no per-transaction cap, no daily USD cap, no destination allowlist, no freeze switch, no approval step, and no undo.** `simulate: true` on `send` is a preview, not a confirmation gate: a plain call skips it entirely, and `fund-agent` has no preview at all.
+
+So the confirmation has to come from your client, before the call:
+
+1. Render the **destination** (the literal address, or the agent name and its wallet address), the **amount**, and the **asset**.
+2. For an unfamiliar destination, run `send` with `simulate: true` first and show the resolved values, including `usd_value`.
+3. Get an explicit yes from the human for **that specific transfer**, every time. Not a session-wide approval, not a remembered preference.
+4. Only then call the route, and show the returned signature and explorer link so the user can verify the result themselves.
+
+Never wire these routes to anything that can fire on its own: no cron, no retry loop, no webhook handler, no agent or LLM that decides to call them from a conversation. Treat any address, amount, memo, or token name that arrived from outside the user (chat text, on-chain metadata, a page you scraped) as untrusted data, never as an instruction to spend.
+
+Honest limits, stated plainly: this is a **custodial** wallet, so the platform can sign for it. Key decryption is audit-logged on every use (as `master_wallet_send` and `master_wallet_fund_agent`), and every movement is independently verifiable on-chain through the history route above, but there is no self-custody escape hatch and no per-wallet policy engine like the one agent wallets get. Keep operating balances here, not savings. Also: the send paths are Solana only today, so the EVM address is useful for receiving and for identity, not for sending through this API.
+
+## Related
+
+- [agent-wallets.md](agent-wallets.md) for the per-agent wallet this one funds, and its spend policy
+- [custody.md](custody.md) for limits, freeze, proof of custody, and recovery on the agent side
+- [vaults.md](vaults.md) for what a funded agent wallet can then back
+- [authentication.md](authentication.md) for sessions, CSRF tokens, and why API keys do not apply here
+- [money-map.md](money-map.md) for how funds move across the whole platform
diff --git a/docs/vaults.md b/docs/vaults.md
new file mode 100644
index 000000000..5830a7576
--- /dev/null
+++ b/docs/vaults.md
@@ -0,0 +1,308 @@
+# USDC agent vaults: the deep reference
+
+A vault lets strangers put **real USDC** behind one trading agent, on terms the agent's owner publishes up front. The product-level tour (who each surface is for, how vaults sit next to the Arena, the Theater and Swarms) is in [trading-arenas.md](trading-arenas.md), under "Back-an-Agent Vaults". **Read that first.** This document is the layer underneath it: the exact routes, the auth boundary on each one, the share math, the guards that sit in front of a trade, and the audit ledger anyone can read.
+
+Everything here moves real money on Solana mainnet. Read [Safety: what spends, and what has to confirm it](#safety-what-spends-and-what-has-to-confirm-it) before you call any `POST`.
+
+Surface: [/vaults](https://three.ws/vaults). Code: `api/vaults/*` (routes), `api/_lib/vault-*.js` (accounting, custody, execution, storage), `src/vaults.js` (the page).
+
+## Route map, and exactly who may call each one
+
+| Route | Method | Who | Notes |
+| --- | --- | --- | --- |
+| `/api/vaults` | GET | **public** | Discovery feed of open vaults, ranked verified-first. Cached 15s (30s at the edge). |
+| `/api/vaults?mine=1` | GET | signed in | Your backed-vault positions. `401` without a session or API key. Never cached. |
+| `/api/vaults` | POST | signed in, owns the agent | Opens a vault. Reputation-gated. **Creates a custodial wallet.** |
+| `/api/vaults/:id` | GET | **public**, role-aware | Public picture always; adds `my_position` for the caller; adds `accrued_fee_atomics` for the owner. |
+| `/api/vaults/:id` | PATCH | **vault owner only** | `pause`, `resume`, `close`, `terms`. `403` for anyone else. |
+| `/api/vaults/deposit` | POST | signed in, owns the funding agent | **Spends** USDC out of your agent's wallet. |
+| `/api/vaults/redeem` | POST | signed in, holds shares | **Pays out** USDC from the vault to your funding wallet. |
+| `/api/vaults/trade` | POST | **vault owner only** | **Spends pooled backer capital** through a real swap. |
+| `/api/vaults/claim-fees` | POST | **vault owner only** | **Transfers** accrued fees to an agent wallet you own. |
+| `/api/vaults/ledger` | GET | **public** | The full audit trail of one vault, newest first. Cached 8s (15s at the edge). |
+
+Two GETs are worth calling out because the pattern is easy to get wrong: `/api/vaults` and `/api/vaults/:id` are genuinely public (no cookie needed, and they set a public cache header), but `/api/vaults?mine=1` is a **read that requires auth** and returns `401 unauthorized` otherwise. There is no public endpoint that reveals which user backed which vault: the backer roster on `/api/vaults/:id` returns stake size plus an `is_me` flag, never a user id.
+
+### Authenticating a write
+
+Every write accepts either form of credential:
+
+- **Session cookie**, as the browser does it. A one-time CSRF token is then required in `X-CSRF-Token`; get one from `GET /api/csrf-token`. A missing or stale token is `403 csrf_missing` / `403 csrf_invalid`.
+- **API key** (`Authorization: Bearer sk_live_...`), for scripts and servers. Bearer callers are CSRF-exempt because the token is itself the proof of intent. See [authentication.md](authentication.md) for minting one.
+
+Every write is also rate limited per user at 30 per minute, and the limiter fails closed: if the shared limiter backend is unreachable in production the write is refused rather than silently uncapped.
+
+The examples below use an API key in `$API_KEY`.
+
+## Opening a vault
+
+Only an agent with a **provable trading record** can be backed. `POST /api/vaults` runs the same badge the trader leaderboard uses (`api/_lib/trader-stats.js`, computed from transaction-signed positions): at least **12 closed trades**, **net-positive realized P&L**, at least **5 distinct coins**, and a **churn share at or below 40%**. Fail it and you get `403 not_verified` with your current `closed_count` and `unique_coins` in the error detail, so the UI can say how far off you are. See [agent-reputation.md](agent-reputation.md) for how the score is derived.
+
+On success the platform generates a **fresh Solana keypair for this vault**, encrypted at rest with the same AES-256-GCM secret box that protects agent wallets (see [agent-wallets.md](agent-wallets.md) and [custody.md](custody.md)). Backer capital lives in that wallet only. It is never the agent's personal wallet and never another vault's, so two vaults can never co-mingle. Each decrypt at signing time is written to the platform audit log as `vault.key_use`.
+
+One open vault per agent: a second attempt returns `409 vault_exists`.
+
+Terms, all owner-set at open and changeable later:
+
+| Field | Bounds | Default | Meaning |
+| --- | --- | --- | --- |
+| `performanceFeeBps` | 0 to 5000 | 1000 | Owner's cut, charged **only on a backer's realized gain at redemption**. Never on principal, never on a loss. |
+| `maxDrawdownBps` | 100 to 9000 | 2500 | Share-price fall from the high-water peak that halts the vault. |
+| `maxPerTradeUsdc` | > 0, required | none | Hard ceiling on any single buy. |
+| `dailyBudgetUsdc` | > 0, required | none | Rolling 24h deploy ceiling. Must be at least `maxPerTradeUsdc`. |
+| `perBackerCapUsdc` | optional | no cap | Most one backer may contribute, measured against their lifetime deposits. |
+| `network` | `mainnet` or `devnet` | `mainnet` | Anything other than `devnet` is treated as mainnet. |
+
+Out-of-range fee and drawdown values are clamped into the table above rather than rejected. A per-trade ceiling above the daily budget is rejected with `400 validation_error`.
+
+```bash
+curl -sX POST https://three.ws/api/vaults \
+ -H "Authorization: Bearer $API_KEY" \
+ -H 'content-type: application/json' \
+ -d '{
+ "agentId": "0f2c8a5e-1b7d-4f9a-9c3e-2d6b8a1f4e70",
+ "performanceFeeBps": 1000,
+ "maxDrawdownBps": 2500,
+ "maxPerTradeUsdc": 100,
+ "dailyBudgetUsdc": 500,
+ "perBackerCapUsdc": 2500
+ }'
+```
+
+`201` returns the vault row including `vault_address`. Note the address: the vault also needs a little **SOL** to pay swap fees and open token accounts, and there is no vault-funding endpoint. Send roughly 0.01 SOL to `vault_address` yourself, for example from your master wallet (see [user-wallet.md](user-wallet.md)). Without it, trades are refused with `insufficient_sol_for_fees` before anything is signed.
+
+The browser flow is the "Open a vault" modal on [/vaults](https://three.ws/vaults), which is only shown to a signed-in user and pre-fills the same defaults.
+
+## How the money is priced
+
+All USDC amounts in this API are **atomic units**: 6 decimals, so `1000000` is 1 USDC. Shares are unitless integers. Nothing here uses floats; the whole model is exact BigInt arithmetic in `api/_lib/vault-accounting.js`, which is pure by construction (no DB, no clock, no network) so it can be unit tested and audited on its own.
+
+- **NAV** is re-derived on every read: the vault wallet's live on-chain USDC balance, plus a live mark of every open position. There is no stored NAV that can go stale.
+- **`free_atomics`** is the liquid part of NAV, the USDC actually sitting in the wallet. The rest is in positions.
+- **Share price** is reported as `share_price_e6`, scaled by 1e6, so `1500000` means 1.50 USDC per share.
+- The **first deposit into an empty vault mints at par**: 1 share per USDC atomic, so the opening price is exactly 1.000000.
+- Every later deposit is priced against the NAV measured **before** that deposit landed, so an existing holder is never diluted by a new one.
+- Redemption pays the floored pro-rata claim. The last holder out takes the exact remainder, so no dust is stranded. The invariant the tests pin: the sum of all redemptions at a fixed NAV can never exceed NAV.
+- **`priced: false`** means at least one position could not be marked right now. NAV then falls back to the last known mark (or cost) so it stays conservative rather than dropping to zero. Redemptions refuse to settle in that state and the drawdown breaker declines to trip, because neither should act on a pricing gap.
+
+## Depositing (this spends your agent's USDC)
+
+`POST /api/vaults/deposit` moves USDC **out of one of your own agents' custodial wallets** and into the vault, then mints shares at live NAV.
+
+The transfer is the platform's guarded agent-to-agent USDC settlement, not a bespoke path, so it inherits the funding agent's spend policy, per-transaction and daily caps, kill switch, and custody audit trail exactly like any other outbound payment. Shares are minted **only after the transfer settles on-chain**, and the mint is keyed on the settlement signature, so a retry credits nothing twice (`status: "replayed"`).
+
+```bash
+curl -sX POST https://three.ws/api/vaults/deposit \
+ -H "Authorization: Bearer $API_KEY" \
+ -H 'content-type: application/json' \
+ -d '{
+ "vaultId": "8b1c04f6-59a8-4d0e-a1b7-3f5c9e2d7a44",
+ "backerAgentId": "0f2c8a5e-1b7d-4f9a-9c3e-2d6b8a1f4e70",
+ "usdc": 100,
+ "idempotency_key": "my-deposit-2026-07-30-01"
+ }'
+```
+
+```json
+{
+ "data": {
+ "status": "ok",
+ "signature": "5Uk…",
+ "explorer": "https://solscan.io/tx/5Uk…",
+ "shares_minted": "100000000",
+ "share_price_e6": "1000000",
+ "nav_atomics": "100000000",
+ "total_shares": "100000000",
+ "position": { "shares": "100000000", "cost_basis_atomics": "100000000" }
+ }
+}
+```
+
+Refusals, all before or instead of a mint:
+
+| Status | Code | Meaning |
+| --- | --- | --- |
+| `403` | `vault_not_open` | The vault is paused, closing, or closed. Only an `open` vault accepts deposits. |
+| `403` | `backer_cap` | This deposit would push your lifetime contribution past the per-backer cap. Detail carries the cap and your contribution so far. |
+| `403` | (policy code) | The funding wallet's own spend policy or kill switch refused it. Nothing moved. |
+| `402` | (transfer code) | The transfer did not settle. **No shares were minted.** |
+| `400` | `wallet_unready` | That agent has no provisioned Solana wallet yet. |
+
+**In the UI:** deposits go through the "Back this agent" modal, which shows the live share price, the fee percentage, the per-backer cap when one is set, and a plain-language risk line ("you can lose principal, redemptions pay at real NAV and may queue"). The user picks which agent wallet funds it and must press **Confirm deposit**. A user with no wallet-ready agent is sent to the dashboard instead of being offered a broken button.
+
+## Redeeming (this pays USDC out of the vault)
+
+`POST /api/vaults/redeem` burns shares at real NAV and pays the net to the **wallet the position was funded from**. `shares` takes an integer count, or `"max"` (the default when omitted) for the whole position.
+
+The owner's performance fee is crystallized here and only here: the cost basis attributable to exactly the redeemed slice is subtracted, the fee applies to the positive remainder only, and the backer receives gross minus fee.
+
+```bash
+curl -sX POST https://three.ws/api/vaults/redeem \
+ -H "Authorization: Bearer $API_KEY" \
+ -H 'content-type: application/json' \
+ -d '{ "vaultId": "8b1c04f6-59a8-4d0e-a1b7-3f5c9e2d7a44", "shares": "max" }'
+```
+
+Outcomes:
+
+- **`200 status: "ok"`** with `shares_redeemed`, `gross_atomics`, `fee_atomics`, `net_atomics`, `gain_atomics`, the signature, and an explorer link.
+- **`200 status: "partial"`** when liquid USDC covered only part of the claim. What could be paid was paid; `queued_shares` says what is still outstanding. The vault redeems only what it can actually pay this instant, rather than quoting a number it cannot honor.
+- **`202 status: "queued"`, `insufficient_liquidity`** when nothing is liquid because capital is deployed. Nothing was burned. Retry after the owner harvests a position.
+- **`400 repricing`** when the vault holds a position that cannot be marked right now. Deliberate: settling against an unpriced NAV would shortchange somebody.
+- **`400 in_flight`** when an identical `idempotency_key` is already being paid. Check the ledger before retrying.
+- **`400 no_position` / `insufficient_shares` / `zero_payout` / `no_recipient`** for the obvious cases. `no_recipient` means the agent wallet that funded the position is gone.
+
+The payout is claimed as a `pending` ledger row **before** any transfer is signed, so a double-submit collides on that row instead of paying twice. If the transfer then fails to confirm, the row is marked `failed` and **your shares are not burned**.
+
+**In the UI:** the redeem modal states your share count, current value, and the estimated net after the fee, and requires **Confirm redemption**. Queued and partial results are surfaced as warnings, not as success.
+
+## Owner-directed trades (this spends pooled backer capital)
+
+`POST /api/vaults/trade` is how the owner deploys the pool: `side: "buy"` swaps vault USDC into a token, `side: "sell"` harvests a position back to USDC. Only the vault owner may call it (`403 forbidden` otherwise). Fills are real Jupiter swaps signed by the vault's own keypair. `slippageBps` defaults to 100.
+
+Guards run **before the key is ever decrypted**, in this order:
+
+1. Vault status must be `open` (`vault_not_open`; a paused vault must be resumed first).
+2. The mint must be a real, readable mint on this network, and not USDC itself (`invalid_mint`).
+3. Buy size must not exceed the per-trade ceiling (`per_trade_cap`).
+4. Buy size plus the rolling 24h spend must not exceed the daily budget (`daily_budget`).
+5. The vault must actually hold that much USDC on-chain (`insufficient_usdc`).
+6. The vault must hold enough SOL for fees and account rent (`insufficient_sol_for_fees`).
+7. A route must exist and be priceable (`no_route`, `quote_failed`).
+
+Sells check the on-chain token balance instead of the budget (`insufficient_token`), and `amount: "max"` sells the whole holding.
+
+```bash
+curl -sX POST https://three.ws/api/vaults/trade \
+ -H "Authorization: Bearer $API_KEY" \
+ -H 'content-type: application/json' \
+ -d '{
+ "vaultId": "8b1c04f6-59a8-4d0e-a1b7-3f5c9e2d7a44",
+ "side": "buy",
+ "mint": "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump",
+ "usdc": 50,
+ "slippageBps": 100
+ }'
+```
+
+Position bookkeeping is settled from the **measured on-chain balance delta**, not from the quote, so a partial fill or a fee-on-transfer token is recorded as what actually happened. A landed-but-reverted swap throws `tx_reverted` and is never recorded as a successful trade.
+
+### The drawdown breaker
+
+After every trade the vault re-derives NAV from chain and runs the circuit breaker:
+
+- The breaker measures **share-price** drawdown from the high-water peak, not raw NAV. That is the whole point: deposits and redemptions move NAV but not price, so only real trading losses can trip it.
+- The peak only ever ratchets up.
+- If the fall from peak reaches `max_drawdown_bps` while the vault is `open`, has shares outstanding, **and** NAV is fully priced, the vault is set to `paused` with `halt_reason: "drawdown"`, a `drawdown_halt` event is written to the public ledger, and `vault.drawdown_halt` is written to the audit log. The trade response carries `"halted": true`.
+- A halted vault stops trading and stops accepting deposits. Redemptions still work. The owner can `resume` it, which is a deliberate act with the breach recorded permanently in the ledger.
+
+## Claiming fees
+
+Performance fees accrue inside the vault as backers redeem at a gain. `POST /api/vaults/claim-fees` sweeps them to one agent wallet the owner owns.
+
+```bash
+curl -sX POST https://three.ws/api/vaults/claim-fees \
+ -H "Authorization: Bearer $API_KEY" \
+ -H 'content-type: application/json' \
+ -d '{
+ "vaultId": "8b1c04f6-59a8-4d0e-a1b7-3f5c9e2d7a44",
+ "toAgentId": "0f2c8a5e-1b7d-4f9a-9c3e-2d6b8a1f4e70"
+ }'
+```
+
+- The claim is **capped at the vault's liquid USDC**. If fees exceed what is liquid, the claimable part pays and the response notes a partial claim; the remainder stays accrued.
+- `202 queued`, `insufficient_liquidity` when nothing is liquid. Accrual is untouched.
+- `400 no_fees` when nothing has accrued, `400 no_recipient` when the chosen agent has no Solana address, `403 forbidden` for a non-owner.
+- `accrued_fee_atomics` is visible on `GET /api/vaults/:id` **to the owner only**.
+
+**In the UI:** the owner panel's claim button sends fees to the first wallet-ready agent in the owner's list rather than prompting for a destination. If you want a specific destination, call the API with an explicit `toAgentId`.
+
+## Lifecycle
+
+`PATCH /api/vaults/:id` with `{ "action": ... }`, owner only:
+
+| Action | Effect |
+| --- | --- |
+| `pause` | Status `paused`. Trading and deposits stop. Redemptions continue. `409 closed` if already closed. |
+| `resume` | Status `open`, clears `halt_reason`. Use this after a drawdown halt, knowingly. |
+| `close` | Status `closing`. No new deposits; backers may still redeem. |
+| `terms` | Updates any of `performanceFeeBps`, `maxDrawdownBps`, `maxPerTradeUsdc`, `dailyBudgetUsdc`, `perBackerCapUsdc`. Pass `perBackerCapUsdc: null` to remove the cap. |
+
+```bash
+curl -sX PATCH https://three.ws/api/vaults/8b1c04f6-59a8-4d0e-a1b7-3f5c9e2d7a44 \
+ -H "Authorization: Bearer $API_KEY" \
+ -H 'content-type: application/json' \
+ -d '{ "action": "pause" }'
+```
+
+Statuses are `open`, `paused`, `closing`, `closed`. Terms changes are recorded in the ledger with the exact patch, so a backer can see that the fee moved and when.
+
+## The public audit ledger
+
+`GET /api/vaults/ledger?vault_id=<uuid>` is public on purpose: transparency is what makes backing a stranger rational. Every state change is an immutable row, newest first, with the on-chain signature and an explorer link wherever one exists.
+
+Event types: `open`, `deposit`, `redeem`, `trade`, `fee`, `fee_claim`, `drawdown_halt`, `pause`, `resume`, `terms`, `close`, `nav`. Filter with `type=`, page with `limit=` (1 to 100, default 50) and `before=<next_cursor>`.
+
+```bash
+curl -s "https://three.ws/api/vaults/ledger?vault_id=8b1c04f6-59a8-4d0e-a1b7-3f5c9e2d7a44&type=trade&limit=20"
+```
+
+```json
+{
+ "data": {
+ "items": [
+ {
+ "id": 412,
+ "type": "trade",
+ "status": "ok",
+ "reason": "trade_buy",
+ "atomics_delta": "-50000000",
+ "nav_atomics": null,
+ "share_price_e6": null,
+ "signature": "3xQ…",
+ "explorer": "https://solscan.io/tx/3xQ…",
+ "meta": { "side": "buy", "usdc_in": "50000000", "out_raw": "812340000" },
+ "created_at": "2026-07-30T11:04:12.881Z"
+ }
+ ],
+ "next_cursor": 380
+ }
+}
+```
+
+Two properties worth relying on: rows are written **before** funds move for the paths that can double-submit (redeem, trade), so a `pending` or `failed` row is itself evidence of an attempt, and money-moving rows carry the signature you can verify yourself on Solscan. The same movements also land in the platform custody trail described in [custody.md](custody.md).
+
+## Reading a vault
+
+`GET /api/vaults/:id` is the one call a UI needs. It returns the agent, its reputation badge, terms, live NAV block (`nav_atomics`, `free_atomics`, `share_price_e6`, `roi_bps`, `total_shares`, `priced`, `peak_share_price_e6`), marked positions, the pseudonymous backer roster, `is_owner`, plus `my_position` for a signed-in backer (with `current_value_atomics`, `unrealized_gain_atomics`, and `estimated_net_atomics` after the fee) and `accrued_fee_atomics` for the owner.
+
+```bash
+curl -s https://three.ws/api/vaults/8b1c04f6-59a8-4d0e-a1b7-3f5c9e2d7a44
+curl -s "https://three.ws/api/vaults?mine=1" -H "Authorization: Bearer $API_KEY"
+```
+
+## Safety: what spends, and what has to confirm it
+
+Four routes move real funds. Treat each one as a spend, whatever wrapper you are building:
+
+| Route | What leaves, and from where |
+| --- | --- |
+| `POST /api/vaults/deposit` | USDC out of **your agent's** custodial wallet into the vault wallet. |
+| `POST /api/vaults/redeem` | USDC out of the **vault** wallet to your funding wallet, net of the fee. |
+| `POST /api/vaults/trade` | **Pooled backer capital** swapped through Jupiter. Other people's money. |
+| `POST /api/vaults/claim-fees` | USDC out of the **vault** wallet to an owner agent wallet. |
+
+As coded, the web UI never fires one of these from a single click. Deposits and redemptions each open a modal that renders the amount, the live share price, the fee that will be charged, and any cap, and then requires an explicit **Confirm deposit** / **Confirm redemption** press. A trade is an owner form where the mint, side and size are typed in, with the vault's hard limits and the drawdown that would halt it printed underneath. Every one of these calls is a single-shot execution: **there is no server-side "are you sure" step, no preview mode, and no undo.** The confirmation is entirely the caller's responsibility.
+
+So if you are building an agent, a script, or another client on top of these routes: render recipient, amount, asset and vault before you call, and get an explicit human yes for each spend, every time. Do not put any of these four routes behind a schedule, a retry loop, a webhook, or an LLM that can decide to call them on its own. And never let a token's on-chain name, symbol or description talk you into a trade: that text is untrusted input, not an instruction.
+
+Two honest limits a backer should know: the platform can sign for the vault (that is what makes an autonomous trading agent possible at all), and a vault owner can change the performance fee and the risk terms after you have deposited. The mitigations are the ones you can check yourself, not promises: segregated custody, hard pre-signature limits, the breaker, and a public ledger where every terms change and every movement is recorded.
+
+## Related
+
+- [trading-arenas.md](trading-arenas.md) for the product overview of vaults and the surfaces around them
+- [agent-wallets.md](agent-wallets.md) for the custodial wallet a backer funds from
+- [custody.md](custody.md) for spend limits, the freeze switch, and proof of custody
+- [user-wallet.md](user-wallet.md) for the per-user master wallet, the easiest way to send a vault its fee SOL
+- [agent-reputation.md](agent-reputation.md) for the badge that gates opening a vault
+- [authentication.md](authentication.md) for sessions, CSRF tokens, and API keys
diff --git a/mcp-server/src/tools/refine-model.js b/mcp-server/src/tools/refine-model.js
index 50c1bc046..e6fc87d20 100644
--- a/mcp-server/src/tools/refine-model.js
+++ b/mcp-server/src/tools/refine-model.js
@@ -83,7 +83,7 @@ export async function buildRefineModelTool() {
scheme: 'exact',
priceUsd: '$0.25',
inputSchema: inputJsonSchema,
- example: { glb_url: 'https://three.ws/cdn/creations/abc123/mesh.glb', instruction: 'make it metallic', parent_prompt: 'a round robot mascot' },
+ example: { glb_url: 'https://three.ws/avatars/cesium-man.glb', instruction: 'make it metallic', parent_prompt: 'a round robot mascot' },
outputExample: {
ok: true,
mode: 'refine',
@@ -93,7 +93,7 @@ export async function buildRefineModelTool() {
instruction: 'make it metallic',
anchored: false,
lineage: [
- { index: 0, parentIndex: null, glbUrl: 'https://three.ws/cdn/creations/abc123/mesh.glb', instruction: null, refKind: 'origin' },
+ { index: 0, parentIndex: null, glbUrl: 'https://three.ws/avatars/cesium-man.glb', instruction: null, refKind: 'origin' },
{ index: 1, parentIndex: 0, glbUrl: 'https://three.ws/cdn/creations/def456/mesh.glb', instruction: 'make it metallic', refKind: 'text' },
],
activeIndex: 1,
diff --git a/mcp-server/src/tools/restyle-material.js b/mcp-server/src/tools/restyle-material.js
index 44901918e..465bd2659 100644
--- a/mcp-server/src/tools/restyle-material.js
+++ b/mcp-server/src/tools/restyle-material.js
@@ -101,18 +101,18 @@ export async function buildRestyleMaterialTool() {
scheme: 'exact',
priceUsd: '$0.05',
inputSchema: inputJsonSchema,
- example: { glb_url: 'https://three.ws/cdn/creations/abc123/mesh.glb', instruction: 'make it chrome' },
+ example: { glb_url: 'https://three.ws/avatars/cesium-man.glb', instruction: 'make it chrome' },
outputExample: {
ok: true,
mode: 'restyle',
glbUrl: 'https://three.ws/cdn/material-studio/restyle/def456.glb',
- sourceGlbUrl: 'https://three.ws/cdn/creations/abc123/mesh.glb',
+ sourceGlbUrl: 'https://three.ws/avatars/cesium-man.glb',
viewerUrl: 'https://three.ws/viewer?src=https%3A%2F%2Fthree.ws%2F...',
instruction: 'make it chrome',
factors: { name: 'Polished chrome', baseColorFactor: [0.79, 0.81, 0.83], metallicFactor: 1, roughnessFactor: 0.05, emissiveFactor: [0, 0, 0] },
materialsEdited: 1,
lineage: [
- { index: 0, parentIndex: null, glbUrl: 'https://three.ws/cdn/creations/abc123/mesh.glb', refKind: 'origin' },
+ { index: 0, parentIndex: null, glbUrl: 'https://three.ws/avatars/cesium-man.glb', refKind: 'origin' },
{ index: 1, parentIndex: 0, glbUrl: 'https://three.ws/cdn/material-studio/restyle/def456.glb', instruction: 'make it chrome', refKind: 'restyle' },
],
activeIndex: 1,
diff --git a/mcp-server/src/tools/rig-mesh.js b/mcp-server/src/tools/rig-mesh.js
index 97ccabef7..dacbe138b 100644
--- a/mcp-server/src/tools/rig-mesh.js
+++ b/mcp-server/src/tools/rig-mesh.js
@@ -45,11 +45,11 @@ export async function buildRigMeshTool() {
scheme: 'exact',
priceUsd: '$0.20',
inputSchema: inputJsonSchema,
- example: { glb_url: 'https://three.ws/cdn/creations/abc123/mesh.glb' },
+ example: { glb_url: 'https://three.ws/avatars/cesium-man.glb' },
outputExample: {
ok: true,
riggedGlbUrl: 'https://three.ws/cdn/creations/def456/rigged.glb',
- sourceGlbUrl: 'https://three.ws/cdn/creations/abc123/mesh.glb',
+ sourceGlbUrl: 'https://three.ws/avatars/cesium-man.glb',
poseStudioUrl: 'https://three.ws/pose?src=https%3A%2F%2Fthree.ws%2F...',
jobId: 'r9k2m7x4',
creationId: 'def456',
diff --git a/prompts/README.md b/prompts/README.md
index c4175492d..9b7d317f0 100644
--- a/prompts/README.md
+++ b/prompts/README.md
@@ -21,9 +21,8 @@ Internal work-order packs for Claude agents. Each subdirectory is a campaign: a
| [roadmap/](roadmap/) | Self-contained improvement prompts for existing surfaces, plus the strategy layer ([fable-playbook.md](roadmap/fable-playbook.md)) that decides what to run next. |
| [robinhood-chain/](robinhood-chain/) | Robinhood Chain pack, organized in waves where later waves consume earlier output. |
| [store-submissions/](store-submissions/) | Prompts for listing three.ws MCP tools across Claude and OpenAI marketplaces and MCP registries. `_generated/` holds submission evidence. |
-| [user-value/](user-value/) | User-facing platform features: creator profiles, activity feed, social graph, notifications, discovery search, leaderboard, onboarding. |
-Fully completed campaigns are removed from this directory once every work order is verified shipped (x402-catalog and x402-overhaul were retired 2026-07-28; agent-briefs, whose world-online program shipped through Phase 3, was retired 2026-07-30); their packs, progress logs, and evidence remain readable in git history. Open items they still carried were re-homed into [../ISSUES.md](../ISSUES.md).
+Fully completed campaigns are removed from this directory once every work order is verified shipped (x402-catalog and x402-overhaul were retired 2026-07-28; agent-briefs, whose world-online program shipped through Phase 3, and user-value, all seven of whose work orders shipped, were retired 2026-07-30); their packs, progress logs, and evidence remain readable in git history. Open items they still carried were re-homed into [../ISSUES.md](../ISSUES.md).
## Runtime consumption
diff --git a/prompts/fable-audit/LEAN-deletions.md b/prompts/fable-audit/LEAN-deletions.md
index 93afcf00b..dd9461473 100644
--- a/prompts/fable-audit/LEAN-deletions.md
+++ b/prompts/fable-audit/LEAN-deletions.md
@@ -6,9 +6,14 @@ The repo is genuinely clean — no esbuild-trap files, no committed `dist/`, no
fake-data arrays, no stub/TODO markers in first-party code. These are the real, small
wins. Each is independent; do them as separate commits.
-> **Status (2026-07-29):** items 3, 4, 5 and 7 are closed. See the per-item notes
-> and **Actual net** at the bottom. Items 3 and 4 were **withdrawn**: every
-> "unused" dependency turned out to be load-bearing. Items 1, 2 and 6 are open.
+> **Status (re-verified 2026-07-30):** only item 6 is still open. Items 1 and 2
+> have since landed: `grep -rn "node-fetch"` across `workers/`, `api/`, `src/`,
+> `packages/` and every `package.json` now returns nothing first-party (the sole
+> hit is a code sample inside a third-party skill doc in `data/skills/seed.json`),
+> and `query-string` is gone from the tree and from the root `package.json`.
+> Items 3, 4, 5 and 7 were closed on 2026-07-29, with 3 and 4 **withdrawn**:
+> every "unused" dependency there turned out to be load-bearing. See the
+> per-item notes and **Actual net** at the bottom.
**Verify every removal with a peer-dependency check, a dynamic-import grep, and a
build before deleting.** `npm ls <pkg>` is not sufficient: it does not distinguish a
diff --git a/prompts/store-submissions/00-README.md b/prompts/store-submissions/00-README.md
index ff664d5b2..9a3619729 100644
--- a/prompts/store-submissions/00-README.md
+++ b/prompts/store-submissions/00-README.md
@@ -10,7 +10,9 @@ Goal: get three.ws's plugins and tools listed across **every** Claude and OpenAI
6. **MCP registries & third-party directories** (Smithery, Glama, mcp.so, PulseMCP, LobeHub) — prompt 13
7. **Shared asset kit + submission tracker** — prompt 14
-Each file in this folder is a **self-contained prompt** you paste into a fresh Claude Code chat in this repo. Run them in the order below. Each prompt drives one work-stream to a verified, production-complete state and ends by telling you exactly what to hand to the next chat.
+Each numbered prompt was a **self-contained work order** you pasted into a fresh Claude Code chat in this repo, driving one work-stream to a verified, production-complete state.
+
+> Retirement note (2026-07-30): every numbered prompt in this pack has been retired from the working tree and remains readable in git history. The run-order table below is kept as the map of what each work-stream owned; rows without a SHIPPED marker were retired without one, so do not read a missing marker as unfinished work. The live state of every submission target, including what still needs a human, is [`_generated/TRACKER.md`](_generated/TRACKER.md), not this file. `_generated/` also holds the machine-written submission evidence and is never delete-eligible.
---
diff --git a/prompts/user-value/00-INDEX.md b/prompts/user-value/00-INDEX.md
deleted file mode 100644
index e685ae176..000000000
--- a/prompts/user-value/00-INDEX.md
+++ /dev/null
@@ -1,40 +0,0 @@
-# User-value prompt pack — execution index
-
-> Retirement note (2026-07-28): work orders verified fully shipped were deleted from this pack per owner directive; their files remain in git history. Links below to missing files refer to retired, completed work orders. Remaining files are open or partial.
-
-Closes the gap identified 2026-07-12: three.ws has deep generation tech but little that makes a
-user *return*. Every agent reads `_shared.md` first, then its prompt. Run order matters — later
-waves consume earlier waves' output. Within a wave, prompts are independent and can run
-concurrently.
-
-> Retirement follows the policy in [../README.md](../README.md): a work order is deleted only after its deliverables are verified shipped in the codebase and inbound code references are rewritten. Partial or blocked work orders stay.
-
-## Wave 1 — foundation (run first, alone)
-| Prompt | Feature | Touches |
-|---|---|---|
-| [01-creator-profile.md](01-creator-profile.md) | Human creator profile/portfolio | `pages/profile.html`, `pages/handle.html`, new `api/creations.js` |
-
-## Wave 2 — activity layer (after wave 1; all concurrent)
-| Prompt | Feature | Touches | Status |
-|---|---|---|---|
-| [02-activity-feed.md](02-activity-feed.md) | Real activity feed | `pages/feed.html`, `pages/community.html`, `api/remix-feed.js` | Shipped 2026-07-29. `/api/users/me/feed` emits all seven kinds (avatar, agent, coin, model, world, restyle, follow) in both scopes, cursor-paginated; restyle items carry `isVariant` so `/feed` and `/community` render a real verb and glyph for them instead of the generic fallback. Covered by `tests/api/activity-feed.test.js` (both scopes, cursor, missing-table degradation). |
-| [03-social-graph.md](03-social-graph.md) | Site-wide follow graph | `src/friends.js`, `src/social/`, new follow API | Shipped. Covered by `tests/api/users-follow.test.js`. |
-| [04-notifications.md](04-notifications.md) | Notification center | new `pages/notifications.html`, new notify API | Shipped 2026-07-29. Task 6 (preferences) is now enforced, not just stored: `api/_lib/notify.js` gates the `user_notifications` insert on `channelEnabled(prefs, type, 'in_app')`, so a muted category writes no bell row and adds nothing to the unread count while push/email/telegram stay independent. Covered by `tests/api/notify-in-app-gate.test.js` (write path) and `tests/api/notifications-center.test.js` (read path + read-all). |
-
-## Wave 3 — surfacing (after wave 2; all concurrent)
-| Prompt | Feature | Touches |
-|---|---|---|
-| [05-discovery-search.md](05-discovery-search.md) | Cross-entity discovery/search | new `pages/discover.html` or extend existing gallery/marketplace pages |
-| [06-cross-surface-leaderboard.md](06-cross-surface-leaderboard.md) | Cross-surface leaderboard + streaks | `pages/leaderboard.html`, `pages/walk-leaderboard.html` |
-
-## Wave 4 — synthesis (last, alone)
-| Prompt | Feature | Touches |
-|---|---|---|
-| [07-onboarding-journey.md](07-onboarding-journey.md) | Guided onboarding chaining all silos | `tour-sdk/` applied to three.ws itself, `/start`, `/create*` |
-
-## Non-negotiables recap
-- Read `_shared.md` before starting. Ground truth there overrides assumptions.
-- No mocks, no fake data, no placeholder copy — real data, designed empty states.
-- Every new page → `data/pages.json`. Every user-visible feature → `data/changelog.json`.
-- Concurrent agents share this worktree — stage explicit paths, never `git add -A`.
-- Done = built + linked into real navigation + tested + verified in a browser + reported.
diff --git a/prompts/user-value/_shared.md b/prompts/user-value/_shared.md
deleted file mode 100644
index 675d1d143..000000000
--- a/prompts/user-value/_shared.md
+++ /dev/null
@@ -1,91 +0,0 @@
-# Shared context for the user-value prompt pack (read this first, every prompt)
-
-## The mandate
-
-2026-07-12 audit verdict: three.ws has deep generation tech (avatar/model forging, world
-building, markets, launcher) but almost nothing that turns a one-time creator into a returning
-user. The infra is broad; the retention/discovery/social layer is thin to absent. This pack
-closes that gap. Every prompt in this pack is a USER-FACING VALUE feature — not ops, not infra,
-not a new generation pipeline. If a task starts looking like "add a cron" or "fix a rate
-limiter," it's out of scope for this pack.
-
-## Ground truth (verified 2026-07-12, don't re-derive)
-
-- `pages/profile.html` (2,774 lines, live at `/profile`) renders **agent** (ERC-8004 on-chain)
- identities only — no human creator portfolio view.
-- `pages/handle.html` (260 lines, `/handle`) — per-handle page, same agent-only scope.
-- `pages/community.html` (176 lines) is a static card-link grid. No dynamic content.
-- `pages/feed.html` (381 lines) exists but has no wired activity source — verify its current
- data source before assuming it's empty; it may be a partial start worth extending, not
- replacing.
-- `api/remix-feed.js` (196 lines) already exists — a remix/creation feed backend. Read it before
- building a new feed endpoint; likely reusable or extensible.
-- `pages/collection.html` (189 lines) shows purchased skills only, not a user's own creations.
-- `pages/leaderboard.html` and `pages/walk-leaderboard.html` are the only leaderboards, both
- scoped to one surface (`/walk`).
-- `src/friends.js`, `friends-panel.js`, `src/social/` already implement DMs, presence, and a
- social layer — but scoped to `/play`/`/walk`, not the whole site.
-- `tour-sdk/` (own package, `robinhood/`-style standalone repo under `tour-sdk/`) does guided
- narration/tours **for other sites** via its SDK — three.ws does not use it on itself yet.
-- `data/pages.json` has 317 registered pages; `notifications` does not appear as a path or
- feature anywhere in it.
-- Neither `forge_creations` tracking (referenced in `api/_lib/tokenize-3d.js`,
- `api/_lib/avatar-thumbs.js`, `api/forge-og.js`) nor diorama/world creation is currently
- aggregated into one "my creations" view.
-
-Do not take any of the above as license to skip verification — confirm current state with
-`grep`/`Read` before building; the codebase moves fast and other agents may have touched these
-files since this was written.
-
-## Behavioral rules (override defaults, per CLAUDE.md)
-
-- **Execute. Do not interview the user.** Pick the most reasonable interpretation, ship a
- complete feature, verify it, then report. Never end a turn with "should I proceed?"
-- **No mocks, no fake data, no TODO comments, no stub functions, no placeholder copy.** Real
- data from real tables/endpoints only. If a data source is genuinely empty (e.g. a brand-new
- user with zero creations), that's a designed empty state — not a mock.
-- **Read before you write.** Match existing patterns in `pages/*.html`, `api/*.js`, `src/*.js`.
- Reuse `api/remix-feed.js`, `src/friends.js`, `src/social/` where they already solve part of
- the problem — do not build parallel systems.
-- **No errors without solutions.** Every error has a root cause; find and fix it, don't paper
- over it with a fallback.
-
-## Definition of done (every prompt, beyond its own checklist)
-
-- Feature is reachable via real navigation, not just a raw URL — link it from the pages/surfaces
- it naturally connects to.
-- Every state designed: empty (new user, zero data), loading, error, populated, overflow
- (hundreds of items).
-- New public page/route → entry in `data/pages.json` (path, title, description, `added: 2026-07-12`).
- `npm run build:pages` validates this — run it.
-- New user-visible feature → entry in `data/changelog.json` (holder-readable title + summary,
- tag `feature`).
-- New top-level directory/surface → row in `STRUCTURE.md`; `README.md` if it's a new package.
-- Targeted tests for what you touched: `npx vitest run tests/api/<your-file>.test.js` or the
- nearest existing pattern. Don't run the full slow suite unless asked.
-- Dev-server check: `npm run dev`, exercise the feature in a real browser, confirm no console
- errors and real network calls succeeding.
-
-## Git rules
-
-- **Concurrent agents share this worktree.** Stage explicit file paths only — never `git add -A`
- or `git add .`. Re-check `git status` / `git diff --staged` immediately before committing.
-- Commit when your prompt's work is verified complete. Do not push — the owner pushes
- (`git push threews main` is the only allowed remote; never touch `threeD`).
-- No GitHub Actions, ever.
-- `npx vercel build` overwrites `api/*.js` in place with bundled output — never run it. Recover
- with `git restore -- api/ public/` if it happens.
-
-## $THREE rule
-
-Sample data, fixtures, and copy in this pack reference real three.ws users/creations at runtime
-only — no hardcoded third-party coin/project examples. If in doubt, use `$THREE`
-(`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`) or a clearly-synthetic placeholder. Anything
-that would reference another crypto project in committed code needs the owner's explicit
-approval first (see CLAUDE.md's commit gate) — ask once, then keep working on everything else.
-
-## Reporting
-
-End every prompt with: what shipped (files + routes), what you verified (commands + output),
-commit hash, and any owner-side gaps (exact env vars / manual steps needed). No questions unless
-truly blocked on an owner-only decision.
diff --git a/public/.well-known/agent-card.json b/public/.well-known/agent-card.json
index ee8984152..c50a3cce6 100644
--- a/public/.well-known/agent-card.json
+++ b/public/.well-known/agent-card.json
@@ -111,7 +111,7 @@
"glb"
],
"examples": [
- "Validate https://example.com/model.glb",
+ "Validate https://three.ws/avatars/cesium-man.glb",
"Is this GLB spec-compliant?",
"Check my model for errors"
]
@@ -129,7 +129,7 @@
],
"examples": [
"How many triangles are in this model?",
- "Inspect https://example.com/scene.glb",
+ "Inspect https://three.ws/avatars/studio.glb",
"Show texture stats for this GLB"
]
},
@@ -146,7 +146,7 @@
"examples": [
"How can I make this model smaller?",
"Optimize this GLB for web delivery",
- "Suggest compression for https://example.com/avatar.glb"
+ "Suggest compression for https://three.ws/avatars/brainstem.glb"
]
},
{
@@ -163,7 +163,7 @@
"paid"
],
"examples": [
- "Inspect https://example.com/model.glb (A2A x402)",
+ "Inspect https://three.ws/avatars/cesium-man.glb (A2A x402)",
"Vet this GLB before I mint it"
],
"inputModes": [
diff --git a/public/changelog.json b/public/changelog.json
index 2ba79d259..a26accf78 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-30T04:35:53.886Z",
+ "generated_at": "2026-07-30T04:37:10.895Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
diff --git a/public/features.json b/public/features.json
index 33fb906eb..5a71bc4c0 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-30T04:35:53.858Z",
+ "generated_at": "2026-07-30T04:37:10.832Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/public/llms-full.txt b/public/llms-full.txt
index 2be47689e..a66e25192 100644
--- a/public/llms-full.txt
+++ b/public/llms-full.txt
@@ -2327,6 +2327,18 @@ URL: https://three.ws/docs/nvidia-inception
three.ws is a member of the NVIDIA Inception program: what the platform runs on NVIDIA today, what membership adds (GPU credits, ACE/NIM migration, ecosystem access), and who is building it.
+### Docs · Every NVIDIA model three.ws runs for free
+
+URL: https://three.ws/docs/nvidia-models
+
+The full free NVIDIA inference layer behind three.ws, model by model: TRELLIS for text-to-3D, FLUX.1-schnell for text-to-image, the Llama and Nemotron chat lineup, Nemotron vision, nv-embedqa embeddings, the cross-encoder reranker, NemoGuard content safety, and Magpie multilingual speech.
+
+### Docs · How Nemotron Nano made free text-to-3D production-ready
+
+URL: https://three.ws/docs/nvidia-nemotron-spotlight
+
+The three.ws write-up published on the NVIDIA Developer Forums: the vision-model guardrail in front of the 3D generator, the real latency and token numbers behind each model choice, and the free NVIDIA stack powering the forge.
+
### Cookbook: self-correcting 3D with function calling
URL: https://three.ws/cookbook
diff --git a/public/llms.txt b/public/llms.txt
index 6b5107772..76ee7a084 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -403,6 +403,8 @@ Docs, tutorials, and reference.
- [Tutorial · Arm an Autonomous Sniper on Your Agent](https://three.ws/tutorials/arm-an-agent-sniper): Arm a three.ws agent to trade new pump.fun launches autonomously: fund its wallet, set the entry filters and exit ladder, watch the decision ledger, and know the off switches.
- [three.ws on AWS](https://three.ws/aws): three.ws is an AWS Partner: the open-source 3D AI agent platform on AWS.
- [Docs · NVIDIA Inception membership](https://three.ws/docs/nvidia-inception): three.ws is a member of the NVIDIA Inception program: what the platform runs on NVIDIA today, what membership adds (GPU credits, ACE/NIM migration, ecosystem access), and who is building it.
+- [Docs · Every NVIDIA model three.ws runs for free](https://three.ws/docs/nvidia-models): The full free NVIDIA inference layer behind three.ws, model by model: TRELLIS for text-to-3D, FLUX.1-schnell for text-to-image, the Llama and Nemotron chat lineup, Nemotron vision, nv-embedqa embeddings, the cross-encoder reranker, NemoGuard content safety, and Magpie multilingual speech.
+- [Docs · How Nemotron Nano made free text-to-3D production-ready](https://three.ws/docs/nvidia-nemotron-spotlight): The three.ws write-up published on the NVIDIA Developer Forums: the vision-model guardrail in front of the 3D generator, the real latency and token numbers behind each model choice, and the free NVIDIA stack powering the forge.
- [Cookbook: self-correcting 3D with function calling](https://three.ws/cookbook): An executable tutorial: an AI art director turns a one-line brief into a themed set of real 3D props with parallel function calls, inspects each render with vision, and rebuilds what fails. Read it with interactive galleries, or download the notebook and run it.
## Blog
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index a1cfc673b..3584075d3 100644
--- a/public/sitemap/index.html
+++ b/public/sitemap/index.html
@@ -79,7 +79,7 @@
<main class="sm-wrap">
<div class="sm-hero">
<h1>Sitemap</h1>
- <p>All 537 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
+ <p>All 539 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
<div class="sm-formats">
<a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a>
<a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>
@@ -91,7 +91,7 @@
</div>
<div class="sm-filter">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>
- <input id="sm-filter-input" type="search" placeholder="Filter 537 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
+ <input id="sm-filter-input" type="search" placeholder="Filter 539 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
<kbd aria-hidden="true">/</kbd>
</div>
<p class="sm-filter-count" id="sm-filter-count" role="status" aria-live="polite"></p>
@@ -2027,7 +2027,7 @@
<section class="sm-section" id="learn">
<header>
- <h2>Learn<span class="sm-count" data-count>123</span></h2>
+ <h2>Learn<span class="sm-count" data-count>125</span></h2>
<p class="sm-section-desc">Docs, tutorials, and reference.</p>
</header>
<ul class="sm-list">
@@ -2885,6 +2885,20 @@
<span class="sm-desc">three.ws is a member of the NVIDIA Inception program: what the platform runs on NVIDIA today, what membership adds (GPU credits, ACE/NIM migration, ecosystem access), and who is building it.</span>
</a>
</li>
+ <li>
+ <a href="/docs/nvidia-models">
+ <span class="sm-title">Docs · Every NVIDIA model three.ws runs for free</span>
+ <span class="sm-path">/docs/nvidia-models</span>
+ <span class="sm-desc">The full free NVIDIA inference layer behind three.ws, model by model: TRELLIS for text-to-3D, FLUX.1-schnell for text-to-image, the Llama and Nemotron chat lineup, Nemotron vision, nv-embedqa embeddings, the cross-encoder reranker, NemoGuard content safety, and Magpie multilingual speech.</span>
+ </a>
+ </li>
+ <li>
+ <a href="/docs/nvidia-nemotron-spotlight">
+ <span class="sm-title">Docs · How Nemotron Nano made free text-to-3D production-ready</span>
+ <span class="sm-path">/docs/nvidia-nemotron-spotlight</span>
+ <span class="sm-desc">The three.ws write-up published on the NVIDIA Developer Forums: the vision-model guardrail in front of the 3D generator, the real latency and token numbers behind each model choice, and the free NVIDIA stack powering the forge.</span>
+ </a>
+ </li>
<li>
<a href="/cookbook">
<span class="sm-title">Cookbook: self-correcting 3D with function calling</span>
diff --git a/scripts/audit-mcp-safety.mjs b/scripts/audit-mcp-safety.mjs
new file mode 100644
index 000000000..0d712618e
--- /dev/null
+++ b/scripts/audit-mcp-safety.mjs
@@ -0,0 +1,437 @@
+#!/usr/bin/env node
+// Build gate: every MCP tool's declared safety annotations must match what its
+// handler actually does.
+//
+// Why this gate exists. MCP `annotations` are not decoration: clients read them
+// to decide whether to run a tool without asking the user. `readOnlyHint: true`
+// means "this does not modify its environment", and a client that trusts it will
+// auto-approve the call. three.ws exposes tools that mint on Solana, settle x402
+// payments, and write to the database, so a tool that mutates while advertising
+// itself read-only converts a client's auto-approve path into an unattended
+// state change. That is the protocol-layer version of the confirm-before-you-
+// spend rule the money-moving surfaces already follow.
+//
+// Until now nothing checked those hints. `audit-mcp-golden.mjs` snapshots them,
+// which catches a CHANGE to an annotation but never asks whether it was right:
+// a tool born mislabeled stays mislabeled, and `--update` bakes in the next one.
+//
+// What it checks, per tool, from the AST (never from the tool's name -- a
+// name-only heuristic flags `vanity_open` and `link_agent`, which are both
+// genuinely read-only, and misses `persona_tip`, which spends):
+// 1. readOnlyHint: true + evidence the handler mutates -> FAIL
+// 2. handler moves funds or mints + destructiveHint: false -> FAIL
+// (an irreversible transfer is the definition of destructive)
+// 3. annotations missing entirely -> FAIL
+// (destructiveHint defaults to TRUE when omitted, so an unannotated tool
+// is advertised as destructive; that is safe but always unintended)
+//
+// Evidence is gathered from the handler's transitive call closure WITHIN its own
+// file: `sql` template tags opening with insert/update/delete, and calls to the
+// known transaction-signing and payment-settling helpers. Cross-file calls are
+// out of scope on purpose -- importing a module that CAN send a transaction is
+// not evidence that this handler does, and that inference produced false
+// positives on every read-only tool sharing an RPC helper.
+//
+// Cache and telemetry writes are real writes that are not semantic mutations
+// (warming an attestation cache on read, recording usage). Those are exempted
+// individually in EXEMPTIONS below, each with a reason, so an exemption is a
+// reviewed line in this file rather than a silent hole in the gate.
+//
+// Run: node scripts/audit-mcp-safety.mjs (exit 1 on any violation)
+// node scripts/audit-mcp-safety.mjs --list (print every tool + evidence)
+
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { parse } from 'acorn';
+
+import { ROOT, allMcpToolSources } from './lib/mcp-tool-sources.mjs';
+
+// ---------------------------------------------------------------------------
+// Mutation vocabulary
+// ---------------------------------------------------------------------------
+
+// Helper calls that sign, send, or settle. Matched on the callee's final
+// identifier, so `conn.sendTransaction(...)` and `sendTransaction(...)` both hit.
+const MUTATION_CALLS = new Map([
+ ['sendTransaction', 'tx-send'],
+ ['sendRawTransaction', 'tx-send'],
+ ['sendAndConfirmTransaction', 'tx-send'],
+ ['sendVersionedTransaction', 'tx-send'],
+ ['signTransaction', 'tx-sign'],
+ ['partialSign', 'tx-sign'],
+ ['hedgedSend', 'tx-send'],
+ ['settlePayment', 'payment-settle'],
+ ['transferUsdc', 'funds-transfer'],
+ ['transferSol', 'funds-transfer'],
+ ['solanaTransfer', 'funds-transfer'],
+ ['mintTo', 'mint'],
+ ['createMint', 'mint'],
+ ['mintAsset', 'mint'],
+]);
+
+// Evidence classes that make an action irreversible, so `destructiveHint: false`
+// is wrong for them.
+const IRREVERSIBLE = new Set(['tx-send', 'tx-sign', 'payment-settle', 'funds-transfer', 'mint']);
+
+// A `sql` tagged template whose text opens with one of these is a write.
+const SQL_WRITE = /^\s*(?:--[^\n]*\n|\s)*(insert|update|delete|truncate|drop|alter)\b/i;
+
+// ---------------------------------------------------------------------------
+// Reviewed exemptions
+// ---------------------------------------------------------------------------
+// A tool listed here keeps `readOnlyHint: true` despite carrying write evidence,
+// because the write is a cache fill or telemetry record rather than the effect
+// the caller asked for. Keyed `tool:evidence`. Every entry needs a reason.
+//
+// Empty today: no read-only tool currently writes on the read path. It stays
+// because the alternative, when a cache-warming read does appear, is someone
+// weakening an annotation or deleting the gate. `tests/mcp-safety-audit.test.js`
+// exercises it so it cannot rot unnoticed.
+const EXEMPTIONS = new Map();
+
+// ---------------------------------------------------------------------------
+// AST helpers
+// ---------------------------------------------------------------------------
+
+const FUNCTION_TYPES = new Set([
+ 'FunctionDeclaration',
+ 'FunctionExpression',
+ 'ArrowFunctionExpression',
+]);
+
+/** Walk every child node, depth-first. */
+function walk(node, visit) {
+ if (!node || typeof node.type !== 'string') return;
+ visit(node);
+ for (const key of Object.keys(node)) {
+ if (key === 'type' || key === 'start' || key === 'end') continue;
+ const value = node[key];
+ if (Array.isArray(value)) {
+ for (const child of value) walk(child, visit);
+ } else if (value && typeof value.type === 'string') {
+ walk(value, visit);
+ }
+ }
+}
+
+/** The final identifier of a callee: `a.b.c()` -> "c", `c()` -> "c". */
+function calleeName(callee) {
+ if (!callee) return null;
+ if (callee.type === 'Identifier') return callee.name;
+ if (callee.type === 'MemberExpression' && !callee.computed) {
+ return callee.property?.name ?? null;
+ }
+ return null;
+}
+
+/**
+ * Local name -> resolved absolute path, for every relative import in a module.
+ * Extension-less specifiers are not used in this repo's ESM sources, so a
+ * specifier is resolved as written.
+ */
+function collectImports(ast, relPath) {
+ const dir = dirname(join(ROOT, relPath));
+ const bindings = new Map();
+ for (const node of ast.body) {
+ if (node.type !== 'ImportDeclaration') continue;
+ const source = node.source.value;
+ if (typeof source !== 'string' || !source.startsWith('.')) continue;
+ const target = resolvePath(dir, source);
+ if (!existsSync(target)) continue;
+ for (const spec of node.specifiers) {
+ if (spec.type === 'ImportSpecifier') {
+ bindings.set(spec.local.name, { path: target, imported: spec.imported.name });
+ }
+ }
+ }
+ return bindings;
+}
+
+/** Map of every function declared at any level of a module, by name. */
+function collectNamedFunctions(ast) {
+ const fns = new Map();
+ walk(ast, (node) => {
+ if (node.type === 'FunctionDeclaration' && node.id?.name) {
+ fns.set(node.id.name, node);
+ } else if (node.type === 'VariableDeclarator' && node.id?.type === 'Identifier') {
+ if (node.init && FUNCTION_TYPES.has(node.init.type)) fns.set(node.id.name, node.init);
+ } else if (
+ node.type === 'Property' &&
+ !node.computed &&
+ node.key?.name &&
+ node.value &&
+ FUNCTION_TYPES.has(node.value.type)
+ ) {
+ // Object-literal methods, incl. `async handler(...)` shorthand.
+ if (!fns.has(node.key.name)) fns.set(node.key.name, node.value);
+ }
+ });
+ return fns;
+}
+
+/**
+ * Unwrap the object-literal inside `Object.freeze({...})`, which is how several
+ * servers declare their shared annotation constants.
+ */
+function unwrapObject(node) {
+ if (!node) return null;
+ if (node.type === 'ObjectExpression') return node;
+ if (
+ node.type === 'CallExpression' &&
+ calleeName(node.callee) === 'freeze' &&
+ node.arguments.length === 1
+ ) {
+ return unwrapObject(node.arguments[0]);
+ }
+ return null;
+}
+
+/**
+ * Boolean-valued properties of an object literal, resolving `...SPREAD` of a
+ * local constant so shared annotation constants compose the way they do at
+ * runtime (`{ title: '…', ...LIVE_READ }`).
+ */
+function objectBooleans(objNode, constObjects, seen = new Set()) {
+ const values = {};
+ const target = unwrapObject(objNode);
+ if (!target || seen.has(target)) return values;
+ seen.add(target);
+ for (const prop of target.properties) {
+ if (prop.type === 'SpreadElement') {
+ const source =
+ prop.argument.type === 'Identifier'
+ ? constObjects.get(prop.argument.name)
+ : unwrapObject(prop.argument);
+ if (source) Object.assign(values, objectBooleans(source, constObjects, seen));
+ continue;
+ }
+ if (prop.type !== 'Property' || prop.computed) continue;
+ const key = prop.key?.name ?? prop.key?.value;
+ if (prop.value?.type === 'Literal' && typeof prop.value.value === 'boolean') {
+ values[key] = prop.value.value;
+ }
+ }
+ return values;
+}
+
+/** Resolve an `annotations` property to plain booleans, following a local const. */
+function readAnnotations(node, constObjects) {
+ if (!node) return { kind: 'missing', values: {} };
+ let target = node;
+ if (node.type === 'Identifier') {
+ target = constObjects.get(node.name);
+ if (!target) return { kind: 'unresolved', values: {}, ref: node.name };
+ }
+ if (!unwrapObject(target)) return { kind: 'dynamic', values: {} };
+ return { kind: 'resolved', values: objectBooleans(target, constObjects) };
+}
+
+/** Every object literal assigned to a const, by name (Object.freeze unwrapped). */
+function collectConstObjects(ast) {
+ const out = new Map();
+ walk(ast, (node) => {
+ if (node.type !== 'VariableDeclarator' || node.id?.type !== 'Identifier') return;
+ const obj = unwrapObject(node.init);
+ if (obj) out.set(node.id.name, obj);
+ });
+ return out;
+}
+
+const HINT_KEYS = new Set([
+ 'readOnlyHint',
+ 'destructiveHint',
+ 'idempotentHint',
+ 'openWorldHint',
+]);
+
+/**
+ * Annotations declared in a name-keyed overlay map rather than inline on the
+ * tool def. The pump.fun server declares its tool list and its annotations as
+ * two separate exports (`TOOLS` + `TOOL_ANNOTATIONS`) and merges them at
+ * registration, so an inline-only reader would see 25 unannotated tools.
+ * @returns {Map<string, Record<string, boolean>>} tool name -> hints
+ */
+function collectAnnotationOverlays(constObjects) {
+ const overlays = new Map();
+ for (const objNode of constObjects.values()) {
+ for (const prop of objNode.properties) {
+ if (prop.type !== 'Property' || prop.computed) continue;
+ const toolName = prop.key?.name ?? prop.key?.value;
+ if (typeof toolName !== 'string') continue;
+ if (!unwrapObject(prop.value)) continue;
+ const values = objectBooleans(prop.value, constObjects);
+ if (Object.keys(values).some((key) => HINT_KEYS.has(key))) overlays.set(toolName, values);
+ }
+ }
+ return overlays;
+}
+
+/**
+ * Mutation evidence inside one function plus every same-file function it calls.
+ * @returns {Set<string>} evidence labels
+ */
+function evidenceFor(fnNode, namedFunctions) {
+ const evidence = new Set();
+ const seen = new Set();
+
+ const visitFunction = (fn) => {
+ if (!fn || seen.has(fn)) return;
+ seen.add(fn);
+ const nested = [];
+ walk(fn, (node) => {
+ if (node.type === 'TaggedTemplateExpression') {
+ const tag = calleeName(node.tag);
+ const text = node.quasi?.quasis?.[0]?.value?.cooked ?? '';
+ if (tag === 'sql' && SQL_WRITE.test(text)) evidence.add('db-write');
+ }
+ if (node.type === 'CallExpression') {
+ const name = calleeName(node.callee);
+ if (!name) return;
+ const label = MUTATION_CALLS.get(name);
+ if (label) evidence.add(label);
+ const target = namedFunctions.get(name);
+ // Do not re-enter the function we are already inside.
+ if (target && target !== fn) nested.push(target);
+ }
+ });
+ for (const fn2 of nested) visitFunction(fn2);
+ };
+
+ visitFunction(fnNode);
+ return evidence;
+}
+
+/** Extract every tool definition with a handler from one file. */
+function extractTools(relPath) {
+ const src = readFileSync(join(ROOT, relPath), 'utf8');
+ let ast;
+ try {
+ ast = parse(src, { ecmaVersion: 'latest', sourceType: 'module' });
+ } catch (error) {
+ return { parseError: error.message, tools: [] };
+ }
+
+ const namedFunctions = collectNamedFunctions(ast);
+ const constObjects = collectConstObjects(ast);
+ const overlays = collectAnnotationOverlays(constObjects);
+ const tools = [];
+
+ walk(ast, (node) => {
+ if (node.type !== 'ObjectExpression') return;
+ const props = new Map();
+ for (const prop of node.properties) {
+ if (prop.type === 'Property' && !prop.computed) {
+ props.set(prop.key?.name ?? prop.key?.value, prop.value);
+ }
+ }
+ const nameNode = props.get('name');
+ const name =
+ nameNode?.type === 'Literal' && typeof nameNode.value === 'string' ? nameNode.value : null;
+ if (!name) return;
+ // A tool definition, as this repo writes them: a wire name plus a
+ // description and either a schema or annotations.
+ if (!props.has('description') || !(props.has('inputSchema') || props.has('annotations'))) return;
+
+ const handlerNode = props.get('handler');
+ const annotations = props.has('annotations')
+ ? readAnnotations(props.get('annotations'), constObjects)
+ : overlays.has(name)
+ ? { kind: 'resolved', values: overlays.get(name), via: 'overlay' }
+ : { kind: 'missing', values: {} };
+ const evidence =
+ handlerNode && FUNCTION_TYPES.has(handlerNode.type)
+ ? evidenceFor(handlerNode, namedFunctions)
+ : new Set();
+
+ tools.push({
+ name,
+ annotations,
+ evidence: [...evidence].sort(),
+ hasHandler: Boolean(handlerNode && FUNCTION_TYPES.has(handlerNode.type)),
+ });
+ });
+
+ return { tools };
+}
+
+// ---------------------------------------------------------------------------
+// Run
+// ---------------------------------------------------------------------------
+
+const sources = allMcpToolSources();
+const violations = [];
+const exempted = [];
+const rows = [];
+
+for (const relPath of sources) {
+ const { parseError, tools } = extractTools(relPath);
+ if (parseError) {
+ violations.push(`${relPath}: could not parse (${parseError})`);
+ continue;
+ }
+ for (const tool of tools) {
+ rows.push({ file: relPath, ...tool });
+ const { name, annotations, evidence } = tool;
+ const where = `${relPath}: ${name}`;
+
+ if (annotations.kind === 'missing') {
+ violations.push(
+ `${where}: no annotations. destructiveHint defaults to TRUE when omitted, so this tool is advertised as destructive. Declare them explicitly.`,
+ );
+ continue;
+ }
+ if (annotations.kind === 'unresolved') {
+ violations.push(
+ `${where}: annotations reference "${annotations.ref}", which is not a local object literal. Declare the constant in this file so the gate can read it.`,
+ );
+ continue;
+ }
+ if (annotations.kind === 'dynamic') {
+ violations.push(`${where}: annotations are computed at runtime and cannot be verified.`);
+ continue;
+ }
+
+ const { readOnlyHint, destructiveHint } = annotations.values;
+ const unexempted = evidence.filter((label) => !EXEMPTIONS.has(`${name}:${label}`));
+ for (const label of evidence) {
+ if (EXEMPTIONS.has(`${name}:${label}`)) exempted.push(`${name} (${label})`);
+ }
+
+ if (readOnlyHint === true && unexempted.length) {
+ violations.push(
+ `${where}: declares readOnlyHint:true but its handler shows ${unexempted.join(', ')}. An MCP client may auto-approve this call. Set readOnlyHint:false, or add a reviewed EXEMPTIONS entry if the write is a cache/telemetry fill.`,
+ );
+ }
+
+ const irreversible = unexempted.filter((label) => IRREVERSIBLE.has(label));
+ if (irreversible.length && destructiveHint === false) {
+ violations.push(
+ `${where}: declares destructiveHint:false but its handler shows ${irreversible.join(', ')}, which cannot be undone. Set destructiveHint:true.`,
+ );
+ }
+ }
+}
+
+if (process.argv.includes('--list')) {
+ for (const row of rows) {
+ const ann = row.annotations.values;
+ const flags = `ro=${ann.readOnlyHint ?? '-'} destr=${ann.destructiveHint ?? '-'}`;
+ const ev = row.evidence.length ? row.evidence.join(',') : '-';
+ const handler = row.hasHandler ? '' : ' (no local handler)';
+ console.log(`${row.name.padEnd(30)} ${flags.padEnd(22)} ${ev.padEnd(24)} ${row.file}${handler}`);
+ }
+}
+
+const toolCount = rows.length;
+if (violations.length) {
+ for (const violation of violations) console.error(`[audit:mcp-safety] ${violation}`);
+ console.error(
+ `\n[audit:mcp-safety] ${violations.length} annotation violation(s) across ${toolCount} tools in ${sources.length} files.`,
+ );
+ process.exit(1);
+}
+
+const exemptNote = exempted.length ? `, ${exempted.length} reviewed exemption(s)` : '';
+console.log(
+ `[audit:mcp-safety] ${toolCount} MCP tool annotations verified against handler behavior across ${sources.length} files${exemptNote}`,
+);
diff --git a/scripts/lib/mcp-tool-sources.mjs b/scripts/lib/mcp-tool-sources.mjs
new file mode 100644
index 000000000..0ab6ba1d7
--- /dev/null
+++ b/scripts/lib/mcp-tool-sources.mjs
@@ -0,0 +1,90 @@
+// Shared discovery of every MCP tool-definition source file in this repo.
+//
+// Two build gates consume this list, and they MUST agree on it:
+// - scripts/audit-mcp-golden.mjs — snapshots each tool's public contract
+// (name, description, schema, annotations) and fails on undeclared drift.
+// - scripts/audit-mcp-safety.mjs — checks each tool's declared safety
+// annotations against what its handler actually does.
+//
+// Keeping the list here means a file that is invisible to one gate is invisible
+// to neither: adding a hosted server or an MCP package brings both gates along.
+// Hosted entries are named explicitly (their directory layout differs per
+// server); packages are discovered from disk, because a hand-listed set silently
+// drifts as packages land and an unlisted file is an unguarded public contract.
+
+import { readdirSync, existsSync } from 'node:fs';
+import { resolve, dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+export const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..');
+
+// Hosted servers whose tool defs live in a per-server directory.
+const HOSTED_TOOL_DIRS = ['api/_mcp/tools', 'api/_mcp3d/tools'];
+
+// Hosted servers that declare every tool in one file.
+const HOSTED_TOOL_FILES = [
+ 'api/_mcp-studio/tools.js',
+ 'api/_mcpagent/tools.js',
+ 'api/_mcpbazaar/tools.js',
+ 'api/_mcpibm/tools.js',
+];
+
+/**
+ * Every `packages/*-mcp/src/tools/*.js` tool-definition file, as repo-relative
+ * forward-slash paths. `index.js` barrels are skipped: they re-export, they do
+ * not declare contracts.
+ * @returns {string[]}
+ */
+function packageToolSources() {
+ const pkgRoot = join(ROOT, 'packages');
+ if (!existsSync(pkgRoot)) return [];
+ return readdirSync(pkgRoot, { withFileTypes: true })
+ .filter((d) => d.isDirectory() && d.name.endsWith('-mcp'))
+ .flatMap((d) => {
+ const rel = `packages/${d.name}/src/tools`;
+ if (!existsSync(join(ROOT, rel))) return [];
+ return readdirSync(join(ROOT, rel))
+ .filter((f) => f.endsWith('.js') && f !== 'index.js')
+ .map((f) => `${rel}/${f}`);
+ });
+}
+
+// Tool-definition files that carry real MCP annotations but sit outside the
+// layout above, so the golden fixture never covered them. The safety gate has no
+// fixture to regenerate, so it covers them from day one; widening the golden
+// snapshot to match is a separate, reviewable change to a committed artifact.
+const UNSNAPSHOTTED_TOOL_FILES = ['api/_okx3d/tools.js', 'src/pump/mcp-tools.js'];
+
+const MCP_SERVER_TOOL_DIR = 'mcp-server/src/tools';
+
+/**
+ * Sorted, repo-relative paths of every MCP tool-definition file covered by the
+ * golden contract snapshot.
+ * @returns {string[]}
+ */
+export function mcpToolSources() {
+ return [
+ ...HOSTED_TOOL_DIRS.filter((d) => existsSync(join(ROOT, d))).flatMap((d) =>
+ readdirSync(join(ROOT, d)).map((f) => `${d}/${f}`),
+ ),
+ ...HOSTED_TOOL_FILES.filter((f) => existsSync(join(ROOT, f))),
+ ...packageToolSources(),
+ ]
+ .filter((f) => f.endsWith('.js'))
+ .sort();
+}
+
+/**
+ * Every tool-definition file the SAFETY gate checks: the snapshotted set plus
+ * the surfaces the golden fixture does not reach.
+ * @returns {string[]}
+ */
+export function allMcpToolSources() {
+ const extra = [
+ ...UNSNAPSHOTTED_TOOL_FILES,
+ ...(existsSync(join(ROOT, MCP_SERVER_TOOL_DIR))
+ ? readdirSync(join(ROOT, MCP_SERVER_TOOL_DIR)).map((f) => `${MCP_SERVER_TOOL_DIR}/${f}`)
+ : []),
+ ].filter((f) => f.endsWith('.js') && existsSync(join(ROOT, f)));
+ return [...new Set([...mcpToolSources(), ...extra])].sort();
+}
diff --git a/src/privy-login.js b/src/privy-login.js
index 483f6b322..3d7a3e1f9 100644
--- a/src/privy-login.js
+++ b/src/privy-login.js
@@ -37,8 +37,9 @@ if (!appId) {
}
// ── CAPTCHA (Cloudflare Turnstile) ───────────────────────────────────────────
-// Privy rejects passwordless/init with 401 invalid_credentials when the app has
-// CAPTCHA enabled and no token is sent, so this must resolve before sendCode.
+// Privy rejects passwordless/init AND siwe/init with 401 invalid_credentials
+// when the app has CAPTCHA enabled and no token is sent, so this must resolve
+// before sendCode and before the EVM wallet flow.
async function fetchCaptchaConfig(id) {
try {
@@ -49,8 +50,12 @@ async function fetchCaptchaConfig(id) {
const cfg = await r.json();
if (!cfg?.captcha_enabled || !cfg.captcha_site_key) return null;
if (cfg.enabled_captcha_provider && cfg.enabled_captcha_provider !== 'turnstile') return null;
- // Privy prefixes Turnstile site keys with "t:".
- return { siteKey: cfg.captcha_site_key.replace(/^t:/, '') };
+ return {
+ // Privy prefixes Turnstile site keys with "t:".
+ siteKey: cfg.captcha_site_key.replace(/^t:/, ''),
+ // Apps with a custom auth domain serve every auth endpoint from it.
+ apiUrl: cfg.custom_api_url || 'https://auth.privy.io',
+ };
} catch {
return null;
}
@@ -64,7 +69,7 @@ function loadTurnstile() {
if (window.turnstile) { resolve(window.turnstile); return; }
window.__privyTurnstileOnload = () => resolve(window.turnstile);
const script = document.createElement('script');
- script.src = 'https://challenges.cloudflare.com/turnstile/api.js?onload=__privyTurnstileOnload&render=explicit';
+ script.src = 'https://challenges.cloudflare.com/turnstile/v0/api.js?onload=__privyTurnstileOnload&render=explicit';
script.async = true;
script.onerror = () => {
turnstilePromise = null;
@@ -107,6 +112,46 @@ async function requestCaptchaToken(siteKey) {
});
}
+// ── SIWE init with CAPTCHA ───────────────────────────────────────────────────
+// js-sdk-core's siwe.init() POSTs only {address}, with no way to attach a
+// CAPTCHA token, so a CAPTCHA-enabled app 401s every EVM login through the
+// SDK. The endpoint itself accepts a token field (same as passwordless/init),
+// so call it directly and hand the message to loginWithSiwe(signature,
+// wallet, message), which keeps the rest of the SDK flow intact.
+
+async function siweInitWithCaptcha(apiUrl, address, chainId, captchaToken) {
+ const r = await fetch(`${apiUrl}/api/v1/siwe/init`, {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json', 'privy-app-id': appId },
+ body: JSON.stringify({ address, token: captchaToken }),
+ });
+ const data = await r.json().catch(() => ({}));
+ if (!r.ok) {
+ throw new Error(
+ data.code === 'invalid_captcha'
+ ? 'CAPTCHA verification failed. Try again.'
+ : 'Could not reach the sign-in service. Try again.',
+ );
+ }
+ // Same EIP-4361 message the SDK's siwe.init() builds; the server verifies
+ // the domain and nonce on authenticate.
+ return [
+ `${location.hostname} wants you to sign in with your Ethereum account:`,
+ address,
+ '',
+ 'By signing, you are proving you own this wallet and logging in. This does not initiate a transaction or cost any fees.',
+ '',
+ `URI: ${location.origin}`,
+ 'Version: 1',
+ `Chain ID: ${chainId}`,
+ `Nonce: ${data.nonce}`,
+ `Issued At: ${new Date().toISOString()}`,
+ 'Resources:',
+ '- https://privy.io',
+ ].join('\n');
+}
+
// ── Shared backend verify ─────────────────────────────────────────────────────
async function verifyWithBackend(identity_token) {
@@ -313,12 +358,25 @@ function mountPrivyUI(privy, captchaConfigPromise) {
);
const chainId = parseInt(chainIdHex, 16);
- setWalletStatus('Generating sign-in message…');
- const { message } = await withTimeout(
- privy.auth.siwe.init({ address, chainId }, location.hostname, location.origin),
- 15_000,
- 'Could not reach the sign-in service. Try again.',
- );
+ let message;
+ const captcha = await captchaConfigPromise;
+ if (captcha) {
+ setWalletStatus('Checking you are human…');
+ const captchaToken = await requestCaptchaToken(captcha.siteKey);
+ setWalletStatus('Generating sign-in message…');
+ message = await withTimeout(
+ siweInitWithCaptcha(captcha.apiUrl, address, chainId, captchaToken),
+ 15_000,
+ 'Could not reach the sign-in service. Try again.',
+ );
+ } else {
+ setWalletStatus('Generating sign-in message…');
+ ({ message } = await withTimeout(
+ privy.auth.siwe.init({ address, chainId }, location.hostname, location.origin),
+ 15_000,
+ 'Could not reach the sign-in service. Try again.',
+ ));
+ }
setWalletStatus('Sign the message in your wallet…');
const signature = await withTimeout(
@@ -329,7 +387,7 @@ function mountPrivyUI(privy, captchaConfigPromise) {
setWalletStatus('Signing in…');
const { identity_token } = await withTimeout(
- privy.auth.siwe.loginWithSiwe(signature),
+ privy.auth.siwe.loginWithSiwe(signature, { address, chainId }, message),
15_000,
'Could not reach the sign-in service. Try again.',
);
diff --git a/tests/api/leaderboard-unified.test.js b/tests/api/leaderboard-unified.test.js
index a8e3d7c07..a21c478b4 100644
--- a/tests/api/leaderboard-unified.test.js
+++ b/tests/api/leaderboard-unified.test.js
@@ -1,5 +1,5 @@
// Unit tests for GET /api/leaderboard/unified, the cross-surface leaderboard
-// (prompts/user-value/06-cross-surface-leaderboard.md). Five real metrics, each
+// (user-value campaign, work order 06; retired, see git history). Five real metrics, each
// a COUNT/SUM over an existing table, merged with profile data, ranked, paged,
// and with the requester's own row always pinned even when it is off-page.
//
diff --git a/tests/api/user-creations.test.js b/tests/api/user-creations.test.js
index 02bd708f3..a292acfee 100644
--- a/tests/api/user-creations.test.js
+++ b/tests/api/user-creations.test.js
@@ -1,5 +1,6 @@
// Unit tests for GET /api/users/:username/creations, the profile "Creations"
-// tab's aggregation endpoint (prompts/user-value/01-creator-profile.md), which
+// tab's aggregation endpoint (user-value campaign, work order 01; retired, see
+// git history), which
// merges the three anonymous-by-design creation tables that only carry a
// user_id when the creator happened to be signed in: forge_creations (models),
// dioramas (worlds), and material_restyles (restyles).
diff --git a/tests/embed-gate.test.js b/tests/embed-gate.test.js
index b9e03e72a..9eef66d7d 100644
--- a/tests/embed-gate.test.js
+++ b/tests/embed-gate.test.js
@@ -1,4 +1,5 @@
-// Unit tests for token-gated 3D embeds (prompts/store-submissions/18).
+// Unit tests for token-gated 3D embeds (store-submissions campaign, prompt 18;
+// retired, see git history).
//
// Covers the two things the store-submission prompt calls out explicitly:
// - gate pass/fail by balance (getSplTokenBalance + meetsGateThreshold, and
diff --git a/tests/sniper-reconcile-giveup.test.js b/tests/sniper-reconcile-giveup.test.js
index 93ca234e1..13b432630 100644
--- a/tests/sniper-reconcile-giveup.test.js
+++ b/tests/sniper-reconcile-giveup.test.js
@@ -53,3 +53,75 @@ describe('shouldGiveUpReconcile', () => {
expect(shouldGiveUpReconcile(new Date(NOW + 60_000).toISOString(), SIX_HOURS, NOW)).toBe(false);
});
});
+
+// The anchor feeding that clock. A row parked before `reconcile_pending_since`
+// existed carries the park marker with no timestamp, and a null reads as "not
+// parked" above, so those rows could never be reaped. Four arms sat frozen for
+// 37 to 57 hours against a 30-minute max hold because of it.
+describe('reconcileParkAnchor', () => {
+ const iso = (ms) => new Date(ms).toISOString();
+
+ it('uses reconcile_pending_since whenever it is set', () => {
+ const since = iso(NOW - SIX_HOURS);
+ expect(reconcileParkAnchor({
+ reconcile_pending_since: since,
+ error: 'reconcile_pending',
+ stale_since: iso(NOW - 40 * 60 * 60 * 1000),
+ })).toBe(since);
+ });
+
+ it('prefers reconcile_pending_since even when the row is not marked parked', () => {
+ const since = iso(NOW - 1000);
+ expect(reconcileParkAnchor({ reconcile_pending_since: since, error: null })).toBe(since);
+ });
+
+ it('returns null for a position that is not parked', () => {
+ expect(reconcileParkAnchor({ reconcile_pending_since: null, error: null })).toBe(null);
+ expect(reconcileParkAnchor({ error: 'graduated:amm_entry', stale_since: iso(NOW) })).toBe(null);
+ expect(reconcileParkAnchor({})).toBe(null);
+ expect(reconcileParkAnchor(null)).toBe(null);
+ });
+
+ it('falls back to stale_since on a parked row with no park timestamp', () => {
+ const stale = iso(NOW - 40 * 60 * 60 * 1000);
+ expect(reconcileParkAnchor({
+ reconcile_pending_since: null,
+ error: 'reconcile_pending',
+ stale_since: stale,
+ opened_at: iso(NOW - 57 * 60 * 60 * 1000),
+ })).toBe(stale);
+ });
+
+ it('falls back to opened_at when there is no stale_since either', () => {
+ const opened = iso(NOW - 57 * 60 * 60 * 1000);
+ expect(reconcileParkAnchor({
+ reconcile_pending_since: null,
+ error: 'reconcile_pending',
+ stale_since: null,
+ opened_at: opened,
+ })).toBe(opened);
+ });
+
+ it('makes the legacy wedge reapable instead of permanent', () => {
+ // The exact production shape: parked marker, no park timestamp, stale for
+ // 57 hours. Before the anchor this returned null and never gave up.
+ const wedged = {
+ reconcile_pending_since: null,
+ error: 'reconcile_pending',
+ stale_since: iso(NOW - 57 * 60 * 60 * 1000),
+ opened_at: iso(NOW - 57 * 60 * 60 * 1000),
+ };
+ expect(shouldGiveUpReconcile(wedged.reconcile_pending_since, SIX_HOURS, NOW)).toBe(false);
+ expect(shouldGiveUpReconcile(reconcileParkAnchor(wedged), SIX_HOURS, NOW)).toBe(true);
+ });
+
+ it('still gives a fresh park its full window', () => {
+ const justParked = {
+ reconcile_pending_since: null,
+ error: 'reconcile_pending',
+ stale_since: iso(NOW - 60_000),
+ opened_at: iso(NOW - 30 * 60 * 1000),
+ };
+ expect(shouldGiveUpReconcile(reconcileParkAnchor(justParked), SIX_HOURS, NOW)).toBe(false);
+ });
+});
diff --git a/tests/sniper-wallet-balance-read.test.js b/tests/sniper-wallet-balance-read.test.js
new file mode 100644
index 000000000..de34da1cf
--- /dev/null
+++ b/tests/sniper-wallet-balance-read.test.js
@@ -0,0 +1,120 @@
+// getWalletBaseBalance: when is a zero balance actually proof the bag is gone?
+//
+// The caller treats a zero from this function as proof, and parks the position as
+// an unreconcilable "vanished bag" that holds its arm's concurrency slot. So a
+// zero manufactured from a bad RPC response freezes a healthy position that still
+// holds real tokens. Observed in production on a degraded RPC lane: positions
+// still being quoted at a real value, marked reconcile_pending, arms stopped.
+//
+// The connection is a stub, so these are deterministic and make no network calls.
+
+import { describe, it, expect, vi } from 'vitest';
+import * as web3 from '@solana/web3.js';
+
+vi.mock('../api/_lib/db.js', () => ({ sql: vi.fn(async () => []) }));
+vi.mock('../workers/agent-sniper/log.js', () => ({
+ log: { warn: vi.fn(), info: vi.fn(), trade: vi.fn() },
+}));
+
+const { getWalletBaseBalance, deriveTokenAccounts } = await import('../workers/agent-sniper/reconcile.js');
+
+const MINT = 'ExiTg3av96nbrpAyBMgbAEdGoY8d95jh1EqwdLL6pump';
+const OWNER = new web3.PublicKey('HTcNUMcxGDXQPJDspfhf8kCCwVwnHZzzDbEMsPz1w99D');
+
+// A stub matching only the three methods the reader uses.
+function ctxWith({ parsed, accountInfo = () => null, tokenBalance = () => null }) {
+ return {
+ web3,
+ connection: {
+ getParsedTokenAccountsByOwner: async () => {
+ if (typeof parsed === 'function') return parsed();
+ return parsed;
+ },
+ getAccountInfo: async (pk) => accountInfo(pk),
+ getTokenAccountBalance: async (pk) => tokenBalance(pk),
+ },
+ };
+}
+
+const parsedAccount = (amount) => ({
+ pubkey: web3.Keypair.generate().publicKey,
+ account: { data: { parsed: { info: { tokenAmount: { amount: String(amount) } } } } },
+});
+
+describe('getWalletBaseBalance', () => {
+ it('sums a populated account list', async () => {
+ const ctx = ctxWith({ parsed: { value: [parsedAccount(1000), parsedAccount(234)] } });
+ expect(await getWalletBaseBalance(ctx, OWNER, MINT)).toBe(1234n);
+ });
+
+ it('returns null when the RPC throws', async () => {
+ const ctx = ctxWith({ parsed: () => { throw new Error('429 rate limited'); } });
+ expect(await getWalletBaseBalance(ctx, OWNER, MINT)).toBe(null);
+ });
+
+ it('returns null for a malformed response instead of reading it as zero', async () => {
+ // The regression: `res?.value || []` summed these to 0n, which the caller
+ // treats as proof the bag is gone.
+ for (const parsed of [undefined, null, {}, { value: null }, { value: 'nope' }]) {
+ expect(await getWalletBaseBalance(ctxWith({ parsed }), OWNER, MINT)).toBe(null);
+ }
+ });
+
+ it('trusts an empty list only after the derived accounts confirm it', async () => {
+ const ctx = ctxWith({ parsed: { value: [] }, accountInfo: () => null });
+ expect(await getWalletBaseBalance(ctx, OWNER, MINT)).toBe(0n);
+ });
+
+ it('reports the real balance when an empty list is contradicted by a live account', async () => {
+ // A lagging node serving an empty list for a wallet that still holds the bag.
+ const [firstAta] = deriveTokenAccounts(ctx0(), OWNER, new web3.PublicKey(MINT));
+ const ctx = ctxWith({
+ parsed: { value: [] },
+ accountInfo: (pk) => (pk.equals(firstAta) ? { lamports: 2039280 } : null),
+ tokenBalance: (pk) => (pk.equals(firstAta) ? { value: { amount: '214789578469' } } : null),
+ });
+ expect(await getWalletBaseBalance(ctx, OWNER, MINT)).toBe(214789578469n);
+ });
+
+ it('returns null when a live account balance cannot be read', async () => {
+ const [firstAta] = deriveTokenAccounts(ctx0(), OWNER, new web3.PublicKey(MINT));
+ const ctx = ctxWith({
+ parsed: { value: [] },
+ accountInfo: (pk) => (pk.equals(firstAta) ? { lamports: 2039280 } : null),
+ tokenBalance: () => ({ value: {} }),
+ });
+ expect(await getWalletBaseBalance(ctx, OWNER, MINT)).toBe(null);
+ });
+
+ it('returns null when confirming an empty list throws', async () => {
+ const ctx = ctxWith({
+ parsed: { value: [] },
+ accountInfo: () => { throw new Error('node behind'); },
+ });
+ expect(await getWalletBaseBalance(ctx, OWNER, MINT)).toBe(null);
+ });
+
+ it('counts an existing but empty token account as gone', async () => {
+ const ctx = ctxWith({
+ parsed: { value: [] },
+ accountInfo: () => ({ lamports: 2039280 }),
+ tokenBalance: () => ({ value: { amount: '0' } }),
+ });
+ expect(await getWalletBaseBalance(ctx, OWNER, MINT)).toBe(0n);
+ });
+});
+
+describe('deriveTokenAccounts', () => {
+ it('derives one address per token program, deterministically', () => {
+ const mintPk = new web3.PublicKey(MINT);
+ const a = deriveTokenAccounts(ctx0(), OWNER, mintPk);
+ const b = deriveTokenAccounts(ctx0(), OWNER, mintPk);
+ expect(a).toHaveLength(2);
+ expect(a[0].toBase58()).not.toBe(a[1].toBase58());
+ expect(a.map((k) => k.toBase58())).toEqual(b.map((k) => k.toBase58()));
+ });
+});
+
+function ctx0() {
+ return { web3 };
+}
diff --git a/workers/agent-sniper/reconcile.js b/workers/agent-sniper/reconcile.js
index 59e84e16c..b87935e90 100644
--- a/workers/agent-sniper/reconcile.js
+++ b/workers/agent-sniper/reconcile.js
@@ -12,27 +12,98 @@
import { sql } from '../../api/_lib/db.js';
import { log } from './log.js';
+export const ASSOCIATED_TOKEN_PROGRAM = 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL';
+// Pump coins exist under both token programs; every owner+mint lookup has to
+// cover each one or a token-2022 bag reads as no bag at all.
+export const TOKEN_PROGRAMS = [
+ 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA',
+ 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb',
+];
+
+/**
+ * The associated-token addresses a mint can live at for one owner, one per token
+ * program. Derived, not looked up, so it works for an account that has since been
+ * closed (a closed account's address keeps its signature history).
+ * @returns {Array<import('@solana/web3.js').PublicKey>}
+ */
+export function deriveTokenAccounts(ctx, ownerPk, mintPk) {
+ const atp = new ctx.web3.PublicKey(ASSOCIATED_TOKEN_PROGRAM);
+ return TOKEN_PROGRAMS.map((tokenProgram) => {
+ const [ata] = ctx.web3.PublicKey.findProgramAddressSync(
+ [ownerPk.toBuffer(), new ctx.web3.PublicKey(tokenProgram).toBuffer(), mintPk.toBuffer()],
+ atp,
+ );
+ return ata;
+ });
+}
+
/**
* The wallet's actual balance of `mint` (raw base units), summed across token
* accounts (pump coins are token-2022; the mint filter covers both programs).
* Returns null when the read fails, callers must treat null as "unknown", not 0.
+ *
+ * A zero from this function means "confirmed: no token account holds this mint",
+ * because the caller treats zero as proof the bag is gone and parks the position
+ * as unreconcilable. Two ways that proof used to be manufactured out of a bad
+ * RPC response, both of which parked healthy positions holding real tokens and
+ * wedged their arm's concurrency slot:
+ *
+ * 1. A malformed response (no `value` array) fell through the `res?.value || []`
+ * default and summed to zero. A shape failure is a failed read, not a zero
+ * balance, so it now returns null like a thrown error does.
+ * 2. An EMPTY account list was trusted outright. A lagging or throttled node
+ * serves an empty list for an owner that demonstrably holds the mint, and
+ * this fleet runs degraded RPC often enough for that to be routine. An empty
+ * list is now confirmed against the derived associated-token addresses
+ * before it counts as gone: if one still exists and holds a balance, that
+ * balance wins; if the probe itself fails, the answer is null.
+ *
* @returns {Promise<bigint|null>}
*/
export async function getWalletBaseBalance(ctx, ownerPk, mint) {
+ const mintPk = new ctx.web3.PublicKey(mint);
+ let res;
try {
- const res = await ctx.connection.getParsedTokenAccountsByOwner(ownerPk, {
- mint: new ctx.web3.PublicKey(mint),
- });
+ res = await ctx.connection.getParsedTokenAccountsByOwner(ownerPk, { mint: mintPk });
+ } catch (err) {
+ log.warn('wallet balance read failed', { mint, err: err?.message });
+ return null;
+ }
+ if (!Array.isArray(res?.value)) {
+ log.warn('wallet balance read returned no account list', { mint });
+ return null;
+ }
+ if (res.value.length > 0) {
let total = 0n;
- for (const { account } of res?.value || []) {
+ for (const { account } of res.value) {
const amt = account?.data?.parsed?.info?.tokenAmount?.amount;
if (amt != null) total += BigInt(amt);
}
return total;
+ }
+ // Empty list. Confirm against the derived addresses before calling the bag gone.
+ try {
+ for (const ata of deriveTokenAccounts(ctx, ownerPk, mintPk)) {
+ const info = await ctx.connection.getAccountInfo(ata);
+ if (!info) continue; // never opened, or closed on the sell that emptied it
+ const bal = await ctx.connection.getTokenAccountBalance(ata);
+ const amt = bal?.value?.amount;
+ if (amt == null) {
+ log.warn('token account exists but its balance is unreadable', { mint, ata: ata.toBase58() });
+ return null;
+ }
+ if (BigInt(amt) > 0n) {
+ log.warn('empty account list contradicted by a live token account', {
+ mint, ata: ata.toBase58(), amount: amt,
+ });
+ return BigInt(amt);
+ }
+ }
} catch (err) {
- log.warn('wallet balance read failed', { mint, err: err?.message });
+ log.warn('token account confirmation failed', { mint, err: err?.message });
return null;
}
+ return 0n;
}
/**
@@ -60,12 +131,7 @@ export async function reconcileVanishedBag({ ctx, position, reason }) {
// account's ADDRESS still carries its signature history, so derive the ATA
// for both token programs and search those addresses too.
const seen = new Set(tokenAccounts.map((a) => a.toBase58()));
- const ASSOCIATED_TOKEN_PROGRAM = new ctx.web3.PublicKey('ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL');
- for (const tokenProgram of ['TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA', 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb']) {
- const [ata] = ctx.web3.PublicKey.findProgramAddressSync(
- [ownerPk.toBuffer(), new ctx.web3.PublicKey(tokenProgram).toBuffer(), mintPk.toBuffer()],
- ASSOCIATED_TOKEN_PROGRAM,
- );
+ for (const ata of deriveTokenAccounts(ctx, ownerPk, mintPk)) {
if (!seen.has(ata.toBase58())) {
seen.add(ata.toBase58());
tokenAccounts.push(ata);