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.

feat: x402 audit improvements, avatar updates, concierge page, feature task docs

nirholascea5dd78b060
diff --git a/api/_lib/x402-spec.js b/api/_lib/x402-spec.js
index 8305bfa22..a4774dd03 100644
--- a/api/_lib/x402-spec.js
+++ b/api/_lib/x402-spec.js
@@ -327,7 +327,8 @@ const FACILITATOR_TIMEOUT_MS_DEFAULT = (() => {
const TRANSIENT_FACILITATOR_STATUS = new Set([502, 503, 504]);
function summarizeUpstream(data, text) {
- return String(data.error || data.message || data.invalidReason || text.slice(0, 200) || '').slice(0, 300);
+ // CDP surfaces the reason under `errorMessage`; PayAI under `error`/`message`.
+ return String(data.error || data.message || data.errorMessage || data.invalidReason || text.slice(0, 200) || '').slice(0, 300);
}
async function callFacilitator(network, path, body, { timeoutMs, idempotencyKey, retries = 1 } = {}) {
@@ -401,6 +402,17 @@ async function callFacilitator(network, path, body, { timeoutMs, idempotencyKey,
// pass through so verifyPayment can emit a clean 402 to the caller.
if (path === '/verify' && data.isValid === false) return data;
const detail = summarizeUpstream(data, text);
+ // A 400 from /verify means the facilitator rejected the *payment
+ // payload itself* (malformed X-PAYMENT header, wrong scheme, etc.) —
+ // that's a client error, not an upstream outage. CDP signals it with
+ // an `errorMessage` and no `isValid` field, so the PayAI passthrough
+ // above misses it and we'd otherwise 502. Normalize to an
+ // invalid-payment result so verifyPayment emits a clean 402 and the
+ // caller is re-prompted to pay, instead of seeing a server error.
+ if (path === '/verify' && res.status === 400) {
+ console.warn(`[x402] facilitator /verify rejected payload (host=${host}, network=${network}): ${detail}`);
+ return { isValid: false, invalidReason: detail || 'payment payload rejected by facilitator' };
+ }
// Transient upstream 5xx — the payment network or settlement service
// blinked. Retry once for idempotent calls; the Idempotency-Key keeps
// a re-sent settle from double-paying.
diff --git a/api/_lib/x402/audit-log.js b/api/_lib/x402/audit-log.js
index 81cd86f22..20d267595 100644
--- a/api/_lib/x402/audit-log.js
+++ b/api/_lib/x402/audit-log.js
@@ -17,6 +17,7 @@
// (payer, created_at), and (event_type, created_at).
import { sql } from '../db.js';
+import { withDbRetry } from '../db-retry.js';
/**
* Fire-and-forget audit log write. Swallows all errors.
@@ -40,7 +41,9 @@ import { sql } from '../db.js';
export function logPaymentEvent(event) {
queueMicrotask(async () => {
try {
- await sql`
+ // A transient Neon "fetch failed" must not silently drop a payment
+ // event — retry the connection-level blip (the write never committed).
+ await withDbRetry(() => sql`
INSERT INTO x402_audit_log
(event_type, route, resource_url, payer, network, amount_atomics,
asset, tx_hash, settlement_status, facilitator_response,
@@ -60,7 +63,7 @@ export function logPaymentEvent(event) {
${event.ipAddress ?? null},
${event.userAgent ?? null},
${event.metadata ? JSON.stringify(event.metadata) : null})
- `;
+ `);
} catch (err) {
console.error('[x402-audit] insert failed', {
eventType: event.eventType,
diff --git a/api/avatars/index.js b/api/avatars/index.js
index fae243da6..de04f5b21 100644
--- a/api/avatars/index.js
+++ b/api/avatars/index.js
@@ -7,6 +7,7 @@ import { headObject, r2 } from '../_lib/r2.js';
import { HeadObjectCommand } from '@aws-sdk/client-s3';
import { env } from '../_lib/env.js';
import { sql } from '../_lib/db.js';
+import { withDbRetry } from '../_lib/db-retry.js';
import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
import { parse, createAvatarBody } from '../_lib/validate.js';
import { recordEvent } from '../_lib/usage.js';
@@ -122,6 +123,11 @@ async function handleCreate(req, res) {
if (!body.parent_avatar_id) {
queueMicrotask(async () => {
try {
+ // Transient Neon "fetch failed" blips must not leave a new avatar
+ // without its agent. The claim is naturally idempotent and the
+ // insert is guarded by NOT EXISTS below, so the whole sequence is
+ // safe to retry on a connection-level failure.
+ await withDbRetry(async () => {
// First try to claim an existing agent that has no avatar yet.
const linked = await sql`
WITH agent_to_update AS (
@@ -138,20 +144,26 @@ async function handleCreate(req, res) {
WHERE agent_identities.id = agent_to_update.id
RETURNING agent_identities.id
`;
- // No existing agent to claim — create a default one.
+ // No existing agent to claim — create a default one. The NOT EXISTS
+ // guard keeps a retried insert (after a lost response) from
+ // creating a second agent for the same avatar.
if (!linked.length) {
await sql`
INSERT INTO agent_identities (user_id, name, avatar_id, is_public, created_at, updated_at)
- VALUES (
+ SELECT
${auth.userId},
${avatar.name || 'My Agent'},
${avatar.id},
false,
NOW(),
NOW()
+ WHERE NOT EXISTS (
+ SELECT 1 FROM agent_identities
+ WHERE user_id = ${auth.userId} AND avatar_id = ${avatar.id}
)
`;
}
+ });
} catch (err) {
console.error('[avatars] auto-agent failed', {
avatarId: avatar.id,
diff --git a/docs/feature-tasks/01-multiview-to-3d.md b/docs/feature-tasks/01-multiview-to-3d.md
new file mode 100644
index 000000000..5d7f651f7
--- /dev/null
+++ b/docs/feature-tasks/01-multiview-to-3d.md
@@ -0,0 +1,26 @@
+# Task: Multiview-to-3D reconstruction
+
+## Goal
+Let users supply **multiple reference images of the same object from different angles** (e.g. front / back / left / right) and reconstruct a single, higher-fidelity 3D mesh from them. Today the generation pipeline only accepts one `image_url`, which caps geometric accuracy for anything with detail on unseen sides.
+
+## Why this matters
+Single-image reconstruction hallucinates the back of every object. Feeding 2–4 calibrated views removes that guesswork and is the single biggest quality lever available without changing models — the backends we already use (Hunyuan3D, TRELLIS) support multi-view conditioning.
+
+## Where it lives
+- Generation entrypoint: [api/forge.js](../../api/forge.js)
+- Model providers: [api/_providers/replicate.js](../../api/_providers/replicate.js), [api/_providers/gcp.js](../../api/_providers/gcp.js)
+- Forge UI: [pages/forge.html](../../pages/forge.html)
+- MCP tool surface: `mesh_forge` (wherever it is registered under `api/_mcp3d/`)
+
+## Requirements
+1. **API contract:** accept `image_urls: string[]` (1–4 images) in addition to the existing single `image_url` (keep backward compatibility — a single string still works). Validate count, fetch/validate each image at the boundary.
+2. **Provider routing:** when >1 image is supplied, route to a backend that supports multi-view conditioning and pass all views. If a chosen backend does not support multi-view, fall back gracefully and surface which mode was used in the job result. No silent downgrade without reporting it.
+3. **UI:** extend [pages/forge.html](../../pages/forge.html) so a user can add up to 4 view slots with drag/drop + file picker, labelled (front/back/left/right or freeform). Show thumbnails, allow removal/reorder. Every state designed: empty slot, uploading, uploaded, error.
+4. **MCP:** extend `mesh_forge` to accept the array form. Keep pricing/x402 behavior consistent with the existing tool.
+5. **Job result:** record how many views were used and which backend handled it, surfaced in the polling response.
+
+## Done when
+- Single-image and multi-image both work end-to-end through `/forge` and through the MCP tool.
+- Real generation succeeds with real images (no mocks); model-viewer renders the result.
+- Backward compatibility verified: existing single-`image_url` callers unaffected.
+- Follow CLAUDE.md: real APIs only, every UI state designed, no TODOs, `git diff` self-reviewed.
diff --git a/docs/feature-tasks/02-fbx-export.md b/docs/feature-tasks/02-fbx-export.md
new file mode 100644
index 000000000..7c3f8a6d2
--- /dev/null
+++ b/docs/feature-tasks/02-fbx-export.md
@@ -0,0 +1,25 @@
+# Task: FBX export (with skeleton)
+
+## Goal
+Add **FBX** as an export format for generated and rigged models, including the skeleton + skin weights for rigged outputs. This is a hard blocker for Unity and Unreal users, who overwhelmingly expect FBX with a bone hierarchy.
+
+## Why this matters
+We export GLB / OBJ / STL / PLY / USDZ / 3MF but **not FBX**. Game-engine pipelines treat FBX as the default interchange format, especially for animated/rigged characters. Without it, a whole segment of users can't use our output without a manual Blender round-trip.
+
+## Where it lives
+- Mesh conversion worker: [workers/remesh/main.py](../../workers/remesh/main.py) (trimesh + open3d; `convert` operation already exists)
+- HTTP route: [api/forge-remesh.js](../../api/) (the `forge-remesh` endpoint)
+- Rigging pipeline that produces skeletons: [workers/avatar-pipeline-controller/main.py](../../workers/avatar-pipeline-controller/main.py)
+- MCP `remesh_model` tool under `api/_mcp3d/`
+
+## Requirements
+1. Add `fbx` to the supported output formats of the convert/remesh path.
+2. **Preserve rig data** when converting a rigged GLB → FBX: bone hierarchy, skin weights, and any blendshapes must survive the conversion. A static mesh converts as a plain FBX. trimesh alone does not write FBX with skeletons — evaluate Blender headless (`bpy`) or the FBX SDK / `assimp` and pick the one that round-trips bones correctly. Justify the choice in the PR.
+3. Wire `fbx` as a selectable export option everywhere GLB/OBJ/etc are offered (UI export menus, remesh API, MCP tool enum).
+4. Validate the output: a rigged FBX should import into Blender/Unity with its skeleton intact. Document the verification.
+
+## Done when
+- A rigged GLB converts to an FBX that retains its skeleton + skin weights (verified by re-import).
+- A static mesh converts to a valid FBX.
+- `fbx` selectable in UI, REST, and MCP; real conversion, no mocks.
+- Follow CLAUDE.md: finish completely, no stubs, self-review the diff.
diff --git a/docs/feature-tasks/03-parts-segmentation.md b/docs/feature-tasks/03-parts-segmentation.md
new file mode 100644
index 000000000..320c42ed9
--- /dev/null
+++ b/docs/feature-tasks/03-parts-segmentation.md
@@ -0,0 +1,24 @@
+# Task: Parts segmentation (split 3D model into semantic parts)
+
+## Goal
+Automatically split a generated mesh into **meaningful, separable parts** with clean boundaries (e.g. head / torso / arms / legs for a character; wheels / body / windows for a vehicle). Output each part as an addressable sub-mesh that can be hidden, recolored, replaced, or exported individually.
+
+## Why this matters
+Segmented models are dramatically more useful for games and animation: swap a weapon, recolor one panel, rig parts independently, or LOD them separately. This is a clear differentiator we currently lack entirely.
+
+## Where it lives
+- New worker alongside existing ones: [workers/](../../workers/) (model after [workers/remesh/main.py](../../workers/remesh/main.py) for structure — FastAPI + trimesh)
+- New HTTP route in [api/](../../api/) (e.g. `forge-segment`)
+- New MCP tool under `api/_mcp3d/tools/` (model after the existing studio tools)
+- Viewer integration so segmented parts are visible/selectable
+
+## Requirements
+1. **Segmentation engine:** implement real part segmentation. Evaluate options (a learned 3D part-segmentation model via Replicate/GPU worker, or a geometry-based approach — connected components + region growing on curvature/UV islands). Pick one that produces semantically clean parts, not arbitrary chunks. Justify the choice.
+2. **Output:** return a GLB whose parts are separate named meshes/nodes, plus a parts manifest (id, name, bbox, face count). Optionally allow exporting a single part.
+3. **Viewer:** in the model viewer (model-viewer / Three.js), let users click a part to isolate/highlight it, toggle visibility, and download an individual part. Every state designed.
+4. **MCP + API:** expose `segment_model` as an x402-priced tool consistent with the others, and a REST endpoint.
+
+## Done when
+- Feeding a real generated GLB returns cleanly separated, named parts rendered and selectable in the viewer.
+- Per-part isolation, visibility toggle, and per-part export all work.
+- Real implementation, no placeholder splits; follow CLAUDE.md throughout.
diff --git a/docs/feature-tasks/04-quad-remesh-low-poly.md b/docs/feature-tasks/04-quad-remesh-low-poly.md
new file mode 100644
index 000000000..924a21a0a
--- /dev/null
+++ b/docs/feature-tasks/04-quad-remesh-low-poly.md
@@ -0,0 +1,23 @@
+# Task: Quad remesh + smart low-poly
+
+## Goal
+Add **quad-based remeshing** and a **smart low-poly** mode that produces clean, game-ready topology with a user-chosen target resolution — not just triangle-soup decimation.
+
+## Why this matters
+Today's remesh does quadric *triangle* decimation. Game and animation pipelines want **quad** topology (clean edge loops, deformation-friendly) and tunwrapped low-poly variants for real-time rendering. Without it, our output needs a manual retopo pass before it's usable in production.
+
+## Where it lives
+- Mesh worker: [workers/remesh/main.py](../../workers/remesh/main.py) (currently trimesh + open3d quadric decimation)
+- HTTP route: `forge-remesh` in [api/](../../api/)
+- MCP `remesh_model` tool under `api/_mcp3d/`
+
+## Requirements
+1. **Quad remesh:** integrate a real quad remesher (e.g. Instant Meshes / `quadwild` / Blender `bpy` remesh, or an equivalent library). Output predominantly-quad topology with target face/vertex count. Justify the tool choice and license-check it (must be commercial-OK per CLAUDE.md).
+2. **Smart low-poly mode:** a preset that produces a low-poly variant (e.g. target buckets like 1k / 5k / 20k faces) while preserving silhouette, then **re-bakes/transfers UVs + normals** so textures still map. Don't just decimate and drop the textures.
+3. Expose `remesh_mode` (`triangle` | `quad` | `lowpoly`) + target count across UI, REST, and MCP.
+4. Preserve UVs and re-project the existing texture onto the remeshed result wherever possible.
+
+## Done when
+- Quad remesh produces clean quad-dominant topology at the requested resolution (verify in Blender wireframe).
+- Low-poly mode produces a usable real-time variant that still renders with its texture.
+- All three modes selectable in UI/REST/MCP; real implementation; CLAUDE.md followed.
diff --git a/docs/feature-tasks/05-magic-brush-local-retexture.md b/docs/feature-tasks/05-magic-brush-local-retexture.md
new file mode 100644
index 000000000..b582dd807
--- /dev/null
+++ b/docs/feature-tasks/05-magic-brush-local-retexture.md
@@ -0,0 +1,23 @@
+# Task: Magic Brush — local region retexturing
+
+## Goal
+Let users **repaint a specific region** of a model's texture from a text prompt (and/or color) without regenerating the entire surface. Fix a seam, recolor one panel, add a logo to a chest plate — surgically.
+
+## Why this matters
+Our current retexture is all-or-nothing: any fix means regenerating the whole surface and losing everything else. A local brush is faster, cheaper, and gives users real control over the result.
+
+## Where it lives
+- Texture worker: [workers/texture/main.py](../../workers/texture/main.py) (SDXL + ControlNet depth, multi-view back-projection)
+- MCP `retexture_model` tool: [api/_mcp3d/tools/studio.js](../../api/_mcp3d/tools/studio.js)
+- Viewer / studio UI where models are displayed and edited
+
+## Requirements
+1. **Region selection:** in the 3D viewer let the user paint a mask directly on the model surface (brush with adjustable radius), or select a part/material. Produce a UV-space mask from the surface selection.
+2. **Masked inpainting:** extend the texture pipeline to inpaint **only** the masked UV region from a prompt/color, blending edges so the seam is invisible. The rest of the texture is untouched (load and preserve the existing texture as the base).
+3. **Iterative:** support repeated brush passes on the same model without quality loss; each pass operates on the latest texture.
+4. Expose via UI (brush tool with prompt box), and add a `retexture_region` capability to the MCP tool consistent with x402 pricing.
+
+## Done when
+- A user can paint a region, type a prompt, and see only that area change — edges blend cleanly.
+- Multiple sequential edits compose correctly.
+- Real SDXL inpainting (no mocks), every UI state designed; CLAUDE.md followed.
diff --git a/docs/feature-tasks/06-stylization-filters.md b/docs/feature-tasks/06-stylization-filters.md
new file mode 100644
index 000000000..f0878f414
--- /dev/null
+++ b/docs/feature-tasks/06-stylization-filters.md
@@ -0,0 +1,29 @@
+# Task: One-click stylization filters (LEGO / Voxel / Voronoi / etc.)
+
+## Goal
+Add instant **geometric stylization filters** that transform any mesh into a stylized variant — voxelized (blocky), brick/stud (LEGO-like), Voronoi/wireframe shell, low-poly faceted, and similar — with a single click.
+
+## Why this matters
+Stylization is high-delight, highly shareable ("screenshot and post" material per CLAUDE.md), and turns one generated asset into many. It's pure geometry processing, so it's fast and cheap — no model inference needed.
+
+## Where it lives
+- New stylization step in the mesh worker family: [workers/](../../workers/) (model after [workers/remesh/main.py](../../workers/remesh/main.py))
+- REST route in [api/](../../api/)
+- MCP tool under `api/_mcp3d/tools/`
+- Forge / studio UI: a "Stylize" panel with filter thumbnails
+
+## Requirements
+1. Implement real geometry transforms (trimesh / open3d / custom):
+ - **Voxel:** voxelize to a grid, rebuild as cubes at chosen resolution.
+ - **Brick/stud:** voxel grid + stud caps on top faces.
+ - **Voronoi shell:** surface-sample → Voronoi cells → open lattice shell.
+ - **Faceted low-poly:** decimate + flat-shade hard normals.
+ Make the filter set extensible so more can be added later.
+2. Each filter takes a resolution/intensity parameter with sensible defaults and a live-ish preview thumbnail.
+3. Preserve a reasonable color/material from the source where the style allows; otherwise apply a tasteful default material.
+4. Expose in UI (filter gallery with hover previews), REST, and MCP (x402-priced).
+
+## Done when
+- Each filter produces a correct, renderable GLB from a real input mesh.
+- UI gallery with hover/active/focus states; empty + error states designed.
+- Real geometry processing, no placeholders; CLAUDE.md followed.
diff --git a/docs/feature-tasks/07-animation-preset-library.md b/docs/feature-tasks/07-animation-preset-library.md
new file mode 100644
index 000000000..ce3c08b84
--- /dev/null
+++ b/docs/feature-tasks/07-animation-preset-library.md
@@ -0,0 +1,25 @@
+# Task: Animation preset library (one-click animate a rigged model)
+
+## Goal
+Give users a curated library of **ready-to-apply animation presets** (idle, walk, run, jump, wave, dance, etc.) that can be applied to any rigged model with one click and exported as an animated GLB/FBX.
+
+## Why this matters
+We auto-rig models but there's no easy path from "rigged" to "moving." A preset library closes that loop and makes rigged output immediately demo-able and useful. The Mixamo-fetch plumbing already exists — this turns it into a real, curated, wired feature.
+
+## Where it lives
+- Existing Mixamo plumbing: `fetch-mixamo-catalog` (locate under [workers/](../../workers/) or [scripts/](../../scripts/))
+- Rigging pipeline / skeleton format: [workers/avatar-pipeline-controller/main.py](../../workers/avatar-pipeline-controller/main.py)
+- Pose studio (keyframe/timeline already present): the `/pose` page
+- Viewer with `AnimationClip` support (Three.js)
+
+## Requirements
+1. **Curated preset set:** assemble a real, license-clear set of animation clips covering common actions. Store them as retargetable clips keyed to our standard skeleton. Document the source and license of each.
+2. **Retargeting:** apply a preset to an arbitrary rigged model whose skeleton matches (or can be mapped to) our standard rig. Handle bone-name mapping; report clearly if a model can't be retargeted.
+3. **UI:** an animation gallery (thumbnails/looping previews) on the model/pose page. Click to preview on the loaded model, then apply. Designed hover/active/focus, empty, and error states.
+4. **Export:** export the animated result as GLB (and FBX once [02-fbx-export.md](02-fbx-export.md) lands) with the animation baked in.
+5. Optionally expose `apply_animation` via MCP (x402-priced).
+
+## Done when
+- A user loads a rigged model, picks a preset, previews it animating, and exports an animated GLB.
+- Retargeting works across at least a few differently-proportioned rigged models.
+- Real clips with documented licensing (no placeholder/empty animations); CLAUDE.md followed.
diff --git a/docs/feature-tasks/08-native-geometry-highres.md b/docs/feature-tasks/08-native-geometry-highres.md
new file mode 100644
index 000000000..4fcaa5fc1
--- /dev/null
+++ b/docs/feature-tasks/08-native-geometry-highres.md
@@ -0,0 +1,26 @@
+# Task: Higher-resolution geometry + native geometry generation path
+
+## Goal
+Raise the geometric ceiling and accuracy of generated meshes by (a) supporting higher polygon targets and (b) adding a **geometry-first generation path** that produces mesh geometry directly rather than always going through an intermediate image.
+
+## Why this matters
+Our pipeline is image-intermediate (text → image → mesh), which caps geometric accuracy and detail — the mesh can only be as good as a single synthesized view implies. A native/geometry-first backend plus higher poly ceilings closes the fidelity gap for detailed assets and gives power users a high-detail option.
+
+## Where it lives
+- Generation entrypoint: [api/forge.js](../../api/forge.js)
+- Providers: [api/_providers/replicate.js](../../api/_providers/replicate.js), [api/_providers/gcp.js](../../api/_providers/gcp.js)
+- Rigging/finishing pipeline: [workers/avatar-pipeline-controller/main.py](../../workers/avatar-pipeline-controller/main.py)
+
+## Requirements
+1. **Higher poly targets:** expose a quality/resolution tier (e.g. draft / standard / high) that maps to higher output poly budgets where the backend supports it. Make sure downstream remesh/rig/storage handle large meshes without breaking.
+2. **Native geometry backend:** evaluate and integrate at least one backend that generates 3D geometry directly (native 3D diffusion / geometry-first model) as an alternative route to the current image-intermediate path. License must be commercial-OK. Justify the choice.
+3. **Routing:** let the request select the path (`mode: image | geometry`) with a sensible default; record which path/backend produced each job in the result.
+4. **Performance + cost:** surface expected time/cost difference between tiers/paths so the UI can communicate it; keep the existing fast path as default.
+
+## Done when
+- A high tier produces visibly higher-detail meshes than the default, end-to-end.
+- The geometry-first path produces valid, riggable GLBs through the full pipeline.
+- Job results report tier + backend + path; real backends only; CLAUDE.md followed.
+
+## Note
+This is the most research-heavy task — start by surveying available commercial-OK backends and benchmarking quality/cost/latency before wiring. Report the benchmark before committing to one.
diff --git a/docs/feature-tasks/README.md b/docs/feature-tasks/README.md
new file mode 100644
index 000000000..24a939b9c
--- /dev/null
+++ b/docs/feature-tasks/README.md
@@ -0,0 +1,17 @@
+# Feature task prompts
+
+Standalone, assign-to-an-agent prompts for closing gaps in the 3D generation pipeline. Each file is self-contained: hand it to an agent as the task. All tasks must follow the rules in [CLAUDE.md](../../CLAUDE.md) — real APIs, no mocks, every state designed, self-reviewed diffs.
+
+| # | Task | Impact | Rough effort |
+|---|------|--------|--------------|
+| 01 | [Multiview-to-3D](01-multiview-to-3d.md) | High — biggest quality lever | Medium |
+| 02 | [FBX export](02-fbx-export.md) | High — unblocks game-engine users | Small–Medium |
+| 03 | [Parts segmentation](03-parts-segmentation.md) | High — clear differentiator | Large |
+| 04 | [Quad remesh + low-poly](04-quad-remesh-low-poly.md) | High — game-ready topology | Medium |
+| 05 | [Magic Brush local retexture](05-magic-brush-local-retexture.md) | Medium — user control | Medium–Large |
+| 06 | [Stylization filters](06-stylization-filters.md) | Medium — shareable delight | Medium |
+| 07 | [Animation preset library](07-animation-preset-library.md) | Medium — closes rig→motion loop | Medium |
+| 08 | [Higher-res / native geometry](08-native-geometry-highres.md) | High — fidelity ceiling | Large (research-first) |
+
+## Suggested order
+Ship in roughly this order: **02 → 01 → 04 → 03 → 06 → 07 → 05 → 08**. FBX export and multiview are the cheapest high-impact wins; native geometry (08) is research-first and biggest.
diff --git a/docs/index.html b/docs/index.html
index 81650a852..d05095eda 100644
--- a/docs/index.html
+++ b/docs/index.html
@@ -624,6 +624,7 @@
{ label: 'three.ws Selfie (Avaturn)', path: 'avaturn' },
{ label: 'ERC-8004', path: 'erc8004' },
{ label: 'Solana agents', path: 'solana' },
+ { label: 'Deploy agents on-chain (bulk)', path: 'onchain-agents' },
{ label: 'Solana pump.fun signals', path: 'solana-pumpfun' },
{ label: 'Mint mark ("3ws")', path: 'mint-mark' },
{ label: 'Agents in X Spaces', path: 'x-spaces' },
diff --git a/docs/onchain-agents.md b/docs/onchain-agents.md
new file mode 100644
index 000000000..9cdff4592
--- /dev/null
+++ b/docs/onchain-agents.md
@@ -0,0 +1,290 @@
+# Deploying Agents On-Chain (Bulk)
+
+Give every three.ws agent a real on-chain identity: a **Metaplex Core NFT** minted into the **three.ws Agents collection** on Solana. This is the bulk/admin counterpart to the single-agent, user-signed flow in [Solana agents](solana.md) — it deploys many agents server-side, with a live recording dashboard and a CLI runner.
+
+> Not pump.fun. These are NFTs (on-chain identity), not tokens. The only coin three.ws ever references is `$THREE`; it appears in each asset's metadata as a link, nothing more.
+
+---
+
+## What you get
+
+For every agent, one **Metaplex Core asset** that is:
+
+- **minted into the three.ws Agents collection** — authority-managed, so three.ws can curate on-chain metadata on the owner's behalf;
+- **owned by the agent** (its own custodial Solana wallet) or held in **authority custody** until claimed — see [Custody model](#custody-model);
+- carrying an on-chain **Attributes plugin** (platform, links, `$THREE`, schema — real bytes in the asset account) and an enforced **5% Royalties plugin**;
+- pointing at a pinned **manifest** (Metaplex token-metadata + `agent-manifest/0.1`) on IPFS, so Phantom / Solscan / Magic Eden render it.
+
+The live mainnet collection: [`56Gnsb7Jjg1N9c8V7EAnDC4HmQbQjsEueSUA3EK5272H`](https://solscan.io/account/56Gnsb7Jjg1N9c8V7EAnDC4HmQbQjsEueSUA3EK5272H).
+
+---
+
+## Architecture
+
+One module holds the mint logic; two surfaces drive it.
+
+```
+ ┌───────────────────────────────────────────┐
+ │ api/_lib/onchain-deploy.js │
+ │ (single source of truth) │
+ │ • buildAuthorityUmi() │
+ │ • resolveAgentCollection() ← env|db|deploy│
+ │ • loadCollectionAsset() │
+ │ • fetchUndeployedAgents() │
+ │ • deployAgentOnce() ← pin + mint + persist│
+ └───────────────┬───────────────┬────────────┘
+ │ │
+ ┌────────────────────────────┘ └───────────────────────────┐
+ ▼ ▼
+ api/admin/bulk-launch.js scripts/deploy-agents-onchain.mjs
+ (SSE dashboard endpoint) (CLI runner — canary + full run)
+ ▼ ▼
+ pages/bulk-launch.html → /admin/bulk-launch node --env-file=.env … --confirm
+```
+
+Both surfaces call the same functions, so they mint **identical** assets. Files:
+
+| File | Role |
+|---|---|
+| [api/_lib/onchain-deploy.js](../api/_lib/onchain-deploy.js) | Shared mint logic — collection resolution, manifest pin, Core mint, DB persist. |
+| [api/admin/bulk-launch.js](../api/admin/bulk-launch.js) | Admin SSE endpoint (`GET /api/admin/bulk-launch`) streaming live progress. |
+| [pages/bulk-launch.html](../pages/bulk-launch.html) | Live dashboard at `/admin/bulk-launch` — funder balance, stats, animated cards. |
+| [scripts/deploy-agents-onchain.mjs](../scripts/deploy-agents-onchain.mjs) | CLI runner — dry-run preview, canary, full fleet. |
+| [api/_lib/solana-collection.js](../api/_lib/solana-collection.js) | Collection authority + address helpers. |
+| [api/_lib/three-brand.js](../api/_lib/three-brand.js) | Manifest + on-chain attributes builders. |
+
+---
+
+## The collection
+
+Every agent is minted **into** a single Metaplex Core *collection* account, "three.ws Agents". The collection's update authority is a three.ws-held keypair, which makes every member asset **authority-managed**: the owner holds (and can transfer/sell) the asset, while three.ws can edit its on-chain metadata on request.
+
+`resolveAgentCollection()` finds the collection in this order, and only deploys once:
+
+1. **Env** — `SOLANA_AGENT_COLLECTION_MAINNET` / `_DEVNET` (keeps the interactive deploy + edit paths aligned).
+2. **DB** — the `app_settings` table, key `solana_agent_collection_<network>`.
+3. **Deploy** — first run with neither set deploys the collection (funded + signed by the authority), then persists its address to `app_settings`.
+
+> After the first run, set `SOLANA_AGENT_COLLECTION_MAINNET=<address>` in your environment so the single-agent flow in [Solana agents](solana.md) mints into the *same* collection.
+
+---
+
+## Custody model
+
+`deployAgentOnce()` resolves the asset **owner** like this:
+
+1. **Agent already has a wallet** (`meta.solana_address`) → mint to it. The agent owns its identity directly.
+2. **No wallet + `JWT_SECRET` present** (i.e. on production) → generate a per-agent custodial Solana wallet, encrypt the secret with the platform key, store it, and mint to it. The agent owns its identity; three.ws can recover the key.
+3. **No wallet + no `JWT_SECRET`** (e.g. a local CLI run) → mint to the **collection authority** as custodian (`custody: true`). Transferable to the agent/user later via a claim flow.
+
+The owner of a Core asset does **not** sign the mint, so **agent wallets never need SOL**. Only the authority/funder wallet spends.
+
+> Run the full fleet where `JWT_SECRET` lives (production) if you want per-agent ownership for agents that don't yet have a wallet. A local run will custody those under the authority instead.
+
+---
+
+## Cost & the funder wallet
+
+One funded wallet does everything — it is the **collection authority**, the **mint fee payer**, and the **collection deployer**. Resolved from `SOLANA_AGENT_COLLECTION_AUTHORITY_KEY` (falls back to `LAUNCH_FUNDER_SECRET`).
+
+| Action | Approx cost |
+|---|---|
+| Deploy the collection (once) | ~0.003 SOL |
+| Mint one agent asset | ~0.004 SOL (rent + fee) |
+
+So ~0.05 SOL canaries a handful; **~0.004 × N** covers a fleet of N (≈ 7.5 SOL for ~1,850 agents). The runner checks the balance before each mint and pauses cleanly if it runs low — top up and re-run.
+
+---
+
+## Metadata
+
+Two layers, both real:
+
+- **Off-chain manifest** (`buildAgentManifest`) — a superset of the Metaplex token-metadata standard and `agent-manifest/0.1`: name, image (avatar thumbnail), `animation_url` (the GLB body), `external_url` (the agent's three.ws page), attributes, the platform brand block, and the `$THREE` link. Pinned to **IPFS via Pinata** (`PINATA_JWT`) → falls back to web3.storage → falls back to R2 with a real CIDv1. Never a stub.
+- **On-chain Attributes plugin** (`buildAgentOnchainAttributes`) — a curated ~11-pair subset written into the asset account itself: `platform`, `url`, `agent`, `agent_url`, `x`, `github`, `$THREE`, `$THREE_url`, `standard`, `schema`, `created`. Byte-clamped to keep the whole transaction under Solana's 1232-byte limit.
+
+---
+
+## What gets recorded
+
+On a confirmed mint, `deployAgentOnce()` writes to `agent_identities.meta`:
+
+```json
+{
+ "chain_type": "solana",
+ "network": "mainnet",
+ "sol_mint_address": "<asset pubkey>",
+ "collection": "56Gnsb7Jjg1N9c8V7EAnDC4HmQbQjsEueSUA3EK5272H",
+ "update_authority": "threews",
+ "onchain": {
+ "chain": "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",
+ "family": "solana",
+ "cluster": "mainnet",
+ "sol_asset": "<asset pubkey>",
+ "metadata_uri": "https://ipfs.io/ipfs/<cid>",
+ "owner": "<owner pubkey>",
+ "custody": true,
+ "tx_hash": "<signature>",
+ "confirmed_at": "<iso>"
+ }
+}
+```
+
+`sol_mint_address` is the canonical key every read path uses (explore, discover, profiles). It also makes re-runs **idempotent**: an agent that already has it is skipped. (Devnet runs are isolated under `meta.devnet` so they never block a real mainnet mint.) An `agent_actions` row (`type: solana.deploy`) is logged, and on mainnet a truthful `agent-onchain` feed event fires.
+
+---
+
+## Setup
+
+Add to `.env` (the wallet that signs + pays must hold SOL on the target network):
+
+```bash
+# Authority = mint fee payer = collection deployer (one funded wallet)
+SOLANA_AGENT_COLLECTION_AUTHORITY_KEY=<bs58 secret>
+
+# IPFS pinning for manifests (preferred; see below)
+PINATA_JWT=<jwt>
+
+# Database (production agents)
+DATABASE_URL=postgresql://…
+
+# Optional but recommended for the full run — a keyed RPC beats the
+# rate-limited public endpoint for hundreds of sends.
+SOLANA_RPC_URL=https://mainnet.helius-rpc.com/?api-key=…
+```
+
+**Getting a `PINATA_JWT`:** [app.pinata.cloud](https://app.pinata.cloud) → API Keys → New Key → **Admin** → copy the JWT (the code pins via the legacy `pinFileToIPFS` endpoint, which an Admin JWT authorizes). The dashboard on production already has these env vars.
+
+---
+
+## Tutorial 1 — Dry run (no SOL, no writes)
+
+Preview exactly which agents would deploy:
+
+```bash
+node --env-file=.env scripts/deploy-agents-onchain.mjs --limit 3 --dry-run
+```
+
+```
+three.ws — on-chain agent deploy (Metaplex Core)
+ network: mainnet limit: 3 DRY RUN
+ funder: p8STS4g7KCp77fYxXsEADNRUWHQUbq4T5xBs3RiMPnX (0.0754 SOL)
+
+Found 3 agent(s) without an on-chain identity on mainnet:
+ • Chain Watcher 2 (660444ae)
+ • Event Scanner 5 (9f0ede49)
+ • Governance Bot 13 (4a46e416)
+
+Dry run — no SOL spent, no writes. Re-run with --confirm to deploy.
+```
+
+---
+
+## Tutorial 2 — The canary (3 agents, CLI)
+
+Always deploy a few first and verify before the fleet. A live run requires `--confirm` (it spends real SOL):
+
+```bash
+node --env-file=.env scripts/deploy-agents-onchain.mjs --limit 3 --confirm
+```
+
+```
+Collection [deployed]: 56Gnsb7Jjg1N9c8V7EAnDC4HmQbQjsEueSUA3EK5272H (deploy sig 3iRcPUVd…)
+[1/3] Chain Watcher 2 … ✓ A1Enk7aPqLdJjhQ3xtN5sDpnVacYDLGChR7YnusJMGGS
+ https://solscan.io/account/A1Enk7aPqLdJjhQ3xtN5sDpnVacYDLGChR7YnusJMGGS
+[2/3] Event Scanner 5 … ✓ 2sBBq8TE8LRMGGLJwKwnwMotEoXUBxvoehvorkbCqAo7
+[3/3] Governance Bot 13 … ✓ 8XKAXv7MxGD6mW2xE33EPc9YVexteaMKDNmVbJqmRRjw
+Done — deployed: 3, errors: 0.
+```
+
+The first run also deploys the collection. Re-runs reuse it and skip already-deployed agents.
+
+**Flags:**
+
+| Flag | Default | Meaning |
+|---|---|---|
+| `--network` | `mainnet` | `mainnet` or `devnet`. |
+| `--limit N` | `3` | Max agents this run. |
+| `--dry-run` | off | Preview only — no SOL, no writes. |
+| `--confirm` | off | Required for a live run. |
+
+---
+
+## Tutorial 3 — The live dashboard
+
+For the visual recording, use the admin dashboard (production has all the env vars):
+
+1. Open **`/admin/bulk-launch`** (admin-gated via `requireAdmin`).
+2. The sidebar shows the funder address (click to copy) and live SOL balance.
+3. Set **Network**, **Agents per run** (start at 3), and optionally tick **Dry run**.
+4. Click **Deploy On-Chain**. The collection deploys on the first run, then each agent's card animates in the moment its asset confirms — with avatar, owner, asset address, and a Solscan link.
+
+Under the hood it's an [SSE](https://developer.mozilla.org/docs/Web/API/Server-sent_events) stream from `GET /api/admin/bulk-launch?network=&limit=&dry_run=`:
+
+| Event | Payload |
+|---|---|
+| `init` | `{ total, network, funder, funder_balance_sol, dry_run }` |
+| `collection` | `{ address, source: env\|db\|deployed, authority, signature? }` |
+| `wallet` | `{ agent_id, name, owner }` (a custodial wallet was created) |
+| `deployed` | `{ agent_id, name, asset, owner, metadata_uri, signature, explorer_url, avatar_thumb }` |
+| `paused` | `{ funder_balance_sol, deployed, reason }` (funder low on SOL) |
+| `error` | `{ agent_id, name, error }` |
+| `done` | `{ deployed, errors, skipped }` |
+
+---
+
+## Tutorial 4 — The full fleet
+
+Once the canary checks out and the funder holds enough SOL (~0.004 × N):
+
+```bash
+# CLI, in batches:
+node --env-file=.env scripts/deploy-agents-onchain.mjs --limit 500 --confirm
+# …re-run until "Found 0 agent(s)". Re-runs are safe.
+```
+
+…or set **Agents per run = 500** on the dashboard and click Deploy, repeating until none remain. Run on **production** if you want per-agent ownership for wallet-less agents (see [Custody model](#custody-model)).
+
+---
+
+## Verifying on-chain
+
+```js
+import { createUmi } from '@metaplex-foundation/umi-bundle-defaults';
+import { mplCore, fetchAsset, fetchCollection } from '@metaplex-foundation/mpl-core';
+import { publicKey } from '@metaplex-foundation/umi';
+
+const umi = createUmi(process.env.SOLANA_RPC_URL).use(mplCore());
+const asset = await fetchAsset(umi, publicKey('<asset pubkey>'));
+
+asset.updateAuthority.type; // 'Collection' ← in the collection
+asset.updateAuthority.address; // the collection pubkey
+asset.royalties.basisPoints; // 500
+asset.attributes.attributeList.length; // 11
+await (await fetch(asset.uri)).json(); // resolvable manifest
+```
+
+A confirmed canary asset shows `inCollection=true`, `royalty=500bps`, `attrs=11`, and a resolvable IPFS URI; the matching DB row has `meta.sol_mint_address` and `meta.collection` set.
+
+---
+
+## Troubleshooting
+
+| Symptom | Cause & fix |
+|---|---|
+| Assets mint but `updateAuthority.type !== 'Collection'` | mpl-core's `create` wants the collection as an **object** (`{publicKey, oracles, lifecycleHooks}`), not a bare pubkey — passing an address silently mints standalone. The shared module fetches the real collection via `loadCollectionAsset()`; never pass a bare pubkey to `create({ collection })`. |
+| `Missing required env var: JWT_SECRET` | A wallet-less agent tried to generate a custodial wallet. Either run on production (where `JWT_SECRET` lives) for per-agent wallets, or accept authority custody — the module falls back to custody automatically when the key is absent. |
+| `funder needs ~0.005 SOL to deploy the collection` | First-run collection deploy needs SOL. Top up the authority wallet. |
+| Run pauses: `funder wallet is low on SOL` | Top up and re-run; already-deployed agents are skipped. |
+| `solana rpc 429` / send timeouts | The public endpoint is rate-limited. Set `SOLANA_RPC_URL` to a Helius/QuickNode/Triton endpoint for the full run. |
+| Manifest URI doesn't resolve | `PINATA_JWT` missing/invalid and no R2 configured. Set a valid `PINATA_JWT` (or `WEB3_STORAGE_TOKEN`, or the `S3_*` set). |
+| An agent re-deploys unexpectedly | It shouldn't — `meta.sol_mint_address IS NULL` is the skip guard. If you intentionally re-mint, clear `sol_mint_address`/`onchain` from its `meta` first. |
+
+---
+
+## See also
+
+- [Solana agents](solana.md) — the single-agent, user-signed registration flow.
+- [ERC-8004](erc8004.md) — the EVM on-chain identity path.
+- [Agent manifest](agent-manifest.md) — the metadata schema.
+- [Mint mark ("3ws")](mint-mark.md) — vanity marking for three.ws launches.
diff --git a/docs/solana.md b/docs/solana.md
index cae5691fa..3e31319ac 100644
--- a/docs/solana.md
+++ b/docs/solana.md
@@ -4,6 +4,8 @@ Register an agent on Solana as a Metaplex Core NFT. The flow mirrors the [ERC-80
This document covers what is supported today, the end-to-end registration flow, and what is intentionally **not** on Solana yet.
+> Deploying many agents at once (server-side, into the three.ws Agents collection, with a live dashboard)? See [Deploy agents on-chain (bulk)](onchain-agents.md).
+
---
## What's supported today
diff --git a/examples/three-concierge.html b/examples/three-concierge.html
new file mode 100644
index 000000000..ef29e4151
--- /dev/null
+++ b/examples/three-concierge.html
@@ -0,0 +1,958 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
+ <title>Trinity — a 3D agent defined entirely in JSON · three.ws</title>
+ <meta
+ name="description"
+ content="Trinity, the three.ws concierge, mounted live from a JSON manifest: a glTF body, browser voice, skills, and scene tools — wired end to end."
+ />
+ <style>
+ :root {
+ --bg: #07070b;
+ --bg-soft: #0e0e16;
+ --panel: rgba(20, 20, 30, 0.72);
+ --panel-border: rgba(255, 255, 255, 0.08);
+ --ink: #f4f4f8;
+ --ink-dim: #a3a3b4;
+ --ink-faint: #6b6b7e;
+ --accent: #7c5cff;
+ --accent-2: #22d3ee;
+ --ok: #34d399;
+ --warn: #fbbf24;
+ --err: #fb7185;
+ --radius: 16px;
+ --radius-sm: 10px;
+ --mono: ui-monospace, 'SF Mono', 'JetBrains Mono', Menlo, monospace;
+ --sans: system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
+ }
+
+ * {
+ box-sizing: border-box;
+ }
+
+ html,
+ body {
+ margin: 0;
+ min-height: 100%;
+ }
+
+ body {
+ font-family: var(--sans);
+ color: var(--ink);
+ background:
+ radial-gradient(
+ 1100px 700px at 18% -10%,
+ rgba(124, 92, 255, 0.18),
+ transparent 60%
+ ),
+ radial-gradient(
+ 900px 600px at 95% 5%,
+ rgba(34, 211, 238, 0.12),
+ transparent 55%
+ ),
+ var(--bg);
+ background-attachment: fixed;
+ -webkit-font-smoothing: antialiased;
+ }
+
+ a {
+ color: var(--accent-2);
+ text-decoration: none;
+ }
+ a:hover {
+ text-decoration: underline;
+ }
+
+ .wrap {
+ max-width: 1280px;
+ margin: 0 auto;
+ padding: clamp(20px, 4vw, 56px) clamp(16px, 3vw, 40px) 64px;
+ }
+
+ header.masthead {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 16px;
+ flex-wrap: wrap;
+ margin-bottom: clamp(20px, 3vw, 36px);
+ }
+
+ .brand {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ }
+ .brand .mark {
+ width: 38px;
+ height: 38px;
+ border-radius: 11px;
+ background: linear-gradient(135deg, var(--accent), var(--accent-2));
+ display: grid;
+ place-items: center;
+ font-weight: 800;
+ font-size: 18px;
+ color: #0b0b12;
+ box-shadow: 0 8px 30px rgba(124, 92, 255, 0.35);
+ }
+ .brand h1 {
+ font-size: 15px;
+ margin: 0;
+ letter-spacing: 0.2px;
+ }
+ .brand p {
+ margin: 2px 0 0;
+ font-size: 12px;
+ color: var(--ink-faint);
+ }
+
+ .source-pill {
+ font-family: var(--mono);
+ font-size: 12px;
+ color: var(--ink-dim);
+ background: var(--panel);
+ border: 1px solid var(--panel-border);
+ padding: 8px 12px;
+ border-radius: 999px;
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ }
+ .source-pill b {
+ color: var(--ink);
+ font-weight: 600;
+ }
+
+ .hero {
+ margin-bottom: clamp(20px, 3vw, 32px);
+ }
+ .hero h2 {
+ font-size: clamp(26px, 4.4vw, 44px);
+ line-height: 1.05;
+ margin: 0 0 12px;
+ letter-spacing: -0.02em;
+ }
+ .hero h2 .grad {
+ background: linear-gradient(120deg, var(--accent), var(--accent-2));
+ -webkit-background-clip: text;
+ background-clip: text;
+ color: transparent;
+ }
+ .hero p {
+ font-size: clamp(14px, 1.6vw, 17px);
+ color: var(--ink-dim);
+ max-width: 60ch;
+ margin: 0;
+ }
+
+ .stage {
+ display: grid;
+ grid-template-columns: minmax(0, 1.55fr) minmax(300px, 1fr);
+ gap: clamp(16px, 2vw, 24px);
+ align-items: start;
+ }
+ @media (max-width: 880px) {
+ .stage {
+ grid-template-columns: 1fr;
+ }
+ }
+
+ .viewer-card {
+ position: relative;
+ border-radius: var(--radius);
+ border: 1px solid var(--panel-border);
+ overflow: hidden;
+ background:
+ radial-gradient(120% 90% at 50% 0%, rgba(124, 92, 255, 0.1), transparent 55%),
+ linear-gradient(180deg, #14141e, #0a0a11);
+ min-height: 520px;
+ box-shadow: 0 30px 80px rgba(0, 0, 0, 0.45);
+ }
+
+ agent-3d {
+ display: block;
+ width: 100%;
+ height: clamp(460px, 64vh, 680px);
+ --agent-accent: var(--accent);
+ --agent-surface: rgba(15, 15, 24, 0.92);
+ --agent-on-surface: var(--ink);
+ }
+
+ /* Poster + error slots rendered by the element before/at failure */
+ .poster,
+ .errslot {
+ position: absolute;
+ inset: 0;
+ display: grid;
+ place-items: center;
+ text-align: center;
+ padding: 24px;
+ gap: 10px;
+ }
+ .poster .spin {
+ width: 34px;
+ height: 34px;
+ border-radius: 50%;
+ border: 3px solid rgba(255, 255, 255, 0.14);
+ border-top-color: var(--accent);
+ animation: spin 0.9s linear infinite;
+ }
+ @keyframes spin {
+ to {
+ transform: rotate(360deg);
+ }
+ }
+ .poster span,
+ .errslot span {
+ color: var(--ink-dim);
+ font-size: 13px;
+ }
+
+ /* Top-left live status chip overlaid on the viewer */
+ .statusbar {
+ position: absolute;
+ top: 14px;
+ left: 14px;
+ right: 14px;
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ pointer-events: none;
+ z-index: 5;
+ }
+ .chip {
+ pointer-events: auto;
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ font-size: 12px;
+ font-weight: 600;
+ padding: 7px 12px;
+ border-radius: 999px;
+ background: rgba(10, 10, 16, 0.7);
+ border: 1px solid var(--panel-border);
+ backdrop-filter: blur(8px);
+ }
+ .dot {
+ width: 8px;
+ height: 8px;
+ border-radius: 50%;
+ background: var(--warn);
+ box-shadow: 0 0 0 0 rgba(251, 191, 36, 0.6);
+ animation: pulse 1.6s infinite;
+ }
+ .dot.ok {
+ background: var(--ok);
+ animation: none;
+ }
+ .dot.err {
+ background: var(--err);
+ animation: none;
+ }
+ @keyframes pulse {
+ 0% {
+ box-shadow: 0 0 0 0 rgba(251, 191, 36, 0.5);
+ }
+ 70% {
+ box-shadow: 0 0 0 7px rgba(251, 191, 36, 0);
+ }
+ 100% {
+ box-shadow: 0 0 0 0 rgba(251, 191, 36, 0);
+ }
+ }
+ .progress-track {
+ pointer-events: none;
+ position: absolute;
+ left: 0;
+ right: 0;
+ bottom: 0;
+ height: 3px;
+ background: transparent;
+ z-index: 6;
+ }
+ .progress-track i {
+ display: block;
+ height: 100%;
+ width: 0%;
+ background: linear-gradient(90deg, var(--accent), var(--accent-2));
+ transition: width 0.3s ease;
+ }
+
+ /* Right rail */
+ .rail {
+ display: flex;
+ flex-direction: column;
+ gap: 16px;
+ }
+ .panel {
+ background: var(--panel);
+ border: 1px solid var(--panel-border);
+ border-radius: var(--radius);
+ padding: 16px;
+ backdrop-filter: blur(10px);
+ }
+ .panel h3 {
+ margin: 0 0 12px;
+ font-size: 12px;
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+ color: var(--ink-faint);
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ }
+
+ .kv {
+ display: grid;
+ grid-template-columns: auto 1fr;
+ gap: 6px 12px;
+ font-size: 13px;
+ }
+ .kv dt {
+ color: var(--ink-faint);
+ }
+ .kv dd {
+ margin: 0;
+ color: var(--ink);
+ font-family: var(--mono);
+ font-size: 12px;
+ text-align: right;
+ word-break: break-word;
+ }
+
+ .taglist {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+ margin-top: 10px;
+ }
+ .tag {
+ font-size: 11px;
+ font-family: var(--mono);
+ color: var(--ink-dim);
+ border: 1px solid var(--panel-border);
+ border-radius: 7px;
+ padding: 4px 8px;
+ transition:
+ border-color 0.2s,
+ color 0.2s;
+ }
+ .tag.live {
+ color: var(--ok);
+ border-color: rgba(52, 211, 153, 0.4);
+ }
+
+ .btn-grid {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 8px;
+ }
+ button.action,
+ .field button {
+ font: inherit;
+ font-size: 13px;
+ font-weight: 600;
+ color: var(--ink);
+ background: rgba(255, 255, 255, 0.04);
+ border: 1px solid var(--panel-border);
+ border-radius: var(--radius-sm);
+ padding: 10px 12px;
+ cursor: pointer;
+ transition:
+ transform 0.12s,
+ background 0.2s,
+ border-color 0.2s;
+ }
+ button.action:hover,
+ .field button:hover {
+ background: rgba(124, 92, 255, 0.16);
+ border-color: rgba(124, 92, 255, 0.5);
+ }
+ button.action:active,
+ .field button:active {
+ transform: translateY(1px);
+ }
+ button.action:focus-visible,
+ .field button:focus-visible,
+ input:focus-visible,
+ select:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+ }
+ button.action:disabled {
+ opacity: 0.4;
+ cursor: not-allowed;
+ }
+
+ select.action {
+ font: inherit;
+ font-size: 13px;
+ color: var(--ink);
+ background: rgba(255, 255, 255, 0.04);
+ border: 1px solid var(--panel-border);
+ border-radius: var(--radius-sm);
+ padding: 10px 12px;
+ width: 100%;
+ cursor: pointer;
+ }
+
+ .field {
+ display: flex;
+ gap: 8px;
+ margin-top: 10px;
+ }
+ .field input {
+ flex: 1;
+ min-width: 0;
+ font: inherit;
+ font-size: 13px;
+ color: var(--ink);
+ background: rgba(0, 0, 0, 0.3);
+ border: 1px solid var(--panel-border);
+ border-radius: var(--radius-sm);
+ padding: 10px 12px;
+ }
+ .field input::placeholder {
+ color: var(--ink-faint);
+ }
+
+ .hint {
+ font-size: 12px;
+ color: var(--ink-faint);
+ margin: 10px 0 0;
+ line-height: 1.5;
+ }
+
+ /* Chat / brain panel */
+ .chatlog {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ max-height: 240px;
+ overflow-y: auto;
+ margin-bottom: 10px;
+ }
+ .msg {
+ font-size: 13px;
+ line-height: 1.5;
+ padding: 9px 12px;
+ border-radius: 12px;
+ max-width: 88%;
+ animation: rise 0.25s ease;
+ }
+ @keyframes rise {
+ from {
+ opacity: 0;
+ transform: translateY(6px);
+ }
+ }
+ .msg.user {
+ align-self: flex-end;
+ background: linear-gradient(135deg, var(--accent), #6246e0);
+ color: #fff;
+ }
+ .msg.agent {
+ align-self: flex-start;
+ background: rgba(255, 255, 255, 0.05);
+ border: 1px solid var(--panel-border);
+ }
+ .msg.system {
+ align-self: stretch;
+ max-width: 100%;
+ background: rgba(251, 191, 36, 0.08);
+ border: 1px solid rgba(251, 191, 36, 0.3);
+ color: var(--ink);
+ }
+ .msg.system b {
+ color: var(--warn);
+ }
+ .msg.system code {
+ font-family: var(--mono);
+ font-size: 12px;
+ background: rgba(0, 0, 0, 0.4);
+ padding: 1px 5px;
+ border-radius: 5px;
+ }
+
+ /* Event log */
+ details.events summary {
+ cursor: pointer;
+ font-size: 12px;
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+ color: var(--ink-faint);
+ list-style: none;
+ }
+ details.events summary::-webkit-details-marker {
+ display: none;
+ }
+ details.events[open] summary {
+ margin-bottom: 10px;
+ }
+ .log {
+ font-family: var(--mono);
+ font-size: 11.5px;
+ line-height: 1.6;
+ max-height: 200px;
+ overflow-y: auto;
+ color: var(--ink-dim);
+ }
+ .log .t {
+ color: var(--ink-faint);
+ }
+ .log .e {
+ color: var(--accent-2);
+ }
+ .log .e.err {
+ color: var(--err);
+ }
+ .log .e.ok {
+ color: var(--ok);
+ }
+
+ .foot {
+ margin-top: 28px;
+ font-size: 12px;
+ color: var(--ink-faint);
+ text-align: center;
+ }
+
+ @media (prefers-reduced-motion: reduce) {
+ *,
+ *::before,
+ *::after {
+ animation-duration: 0.001ms !important;
+ transition-duration: 0.001ms !important;
+ }
+ }
+ </style>
+ </head>
+ <body>
+ <div class="wrap">
+ <header class="masthead">
+ <div class="brand">
+ <div class="mark">3</div>
+ <div>
+ <h1>three.ws</h1>
+ <p>3D agents, defined in JSON</p>
+ </div>
+ </div>
+ <span class="source-pill">
+ mounted from <b>./three-concierge/manifest.json</b>
+ </span>
+ </header>
+
+ <section class="hero">
+ <h2>
+ Meet <span class="grad">Trinity</span> — a 3D agent that lives in a JSON file.
+ </h2>
+ <p>
+ Nothing here is hand-rolled. The avatar, voice, skills, and scene tools below
+ are read straight from an
+ <a href="./three-concierge/manifest.json">agent manifest</a>, resolved by the
+ <code>&lt;agent-3d&gt;</code> web component, and rendered with Three.js.
+ </p>
+ </section>
+
+ <div class="stage">
+ <!-- ── Viewer ─────────────────────────────────────────── -->
+ <div class="viewer-card">
+ <div class="statusbar">
+ <span class="chip"
+ ><i class="dot" id="statusDot"></i
+ ><span id="statusText">Booting…</span></span
+ >
+ </div>
+
+ <agent-3d
+ id="trinity"
+ kiosk
+ eager
+ skill-trust="any"
+ camera-controls
+ auto-rotate
+ shadows
+ environment="neutral"
+ background="transparent"
+ voice
+ aria-label="Trinity, the three.ws concierge — interactive 3D avatar"
+ >
+ <div class="poster" slot="poster">
+ <div class="spin"></div>
+ <span>Loading Trinity from the manifest…</span>
+ </div>
+ <div class="errslot" slot="error">
+ <span
+ >Couldn't reach Trinity's model. Check the network tab and
+ retry.</span
+ >
+ </div>
+ </agent-3d>
+
+ <div class="progress-track"><i id="progressBar"></i></div>
+ </div>
+
+ <!-- ── Control rail ───────────────────────────────────── -->
+ <div class="rail">
+ <div class="panel">
+ <h3>Manifest <span id="readyBadge"></span></h3>
+ <dl class="kv">
+ <dt>Name</dt>
+ <dd id="mName">—</dd>
+ <dt>Body</dt>
+ <dd id="mBody">—</dd>
+ <dt>Format</dt>
+ <dd id="mFormat">—</dd>
+ <dt>Brain</dt>
+ <dd id="mBrain">—</dd>
+ <dt>Voice</dt>
+ <dd id="mVoice">—</dd>
+ </dl>
+ <div
+ class="taglist"
+ id="skillTags"
+ aria-label="Skills declared in the manifest"
+ ></div>
+ </div>
+
+ <div class="panel">
+ <h3>
+ Scene tools
+ <span
+ style="
+ text-transform: none;
+ color: var(--ink-faint);
+ font-weight: 400;
+ "
+ >no brain needed</span
+ >
+ </h3>
+ <div class="btn-grid">
+ <button class="action" data-tool="wave" disabled>👋 Wave</button>
+ <button class="action" data-tool="look" disabled>👀 Look at me</button>
+ <button class="action" data-tool="cheer" disabled>🎉 Cheer</button>
+ <button class="action" data-tool="celebrate" disabled>
+ 🙌 Celebrate
+ </button>
+ </div>
+ <select
+ class="action"
+ id="clipSelect"
+ style="margin-top: 8px"
+ disabled
+ aria-label="Play an animation clip"
+ >
+ <option value="">Play an animation clip…</option>
+ </select>
+ <div class="field">
+ <input
+ id="ttsInput"
+ type="text"
+ placeholder="Type a line for Trinity to speak…"
+ autocomplete="off"
+ disabled
+ />
+ <button id="ttsBtn" disabled aria-label="Speak the line">
+ 🔊 Speak
+ </button>
+ </div>
+ <p class="hint">
+ “Speak” uses the browser's built-in speech synthesis and plays Trinity's
+ talk animation — real voice, zero credentials.
+ </p>
+ </div>
+
+ <div class="panel">
+ <h3>Talk to Trinity</h3>
+ <div class="chatlog" id="chatlog" aria-live="polite"></div>
+ <div class="field">
+ <input
+ id="chatInput"
+ type="text"
+ placeholder="Ask Trinity something…"
+ autocomplete="off"
+ disabled
+ />
+ <button id="chatBtn" disabled aria-label="Send message">Send</button>
+ </div>
+ </div>
+
+ <div class="panel">
+ <details class="events" open>
+ <summary>Live event stream</summary>
+ <div class="log" id="log" aria-live="polite"></div>
+ </details>
+ </div>
+ </div>
+ </div>
+
+ <p class="foot">
+ Body · voice · skills · tools — all resolved from one JSON file. See the
+ <a href="../specs/EMBED_SPEC.md">embed spec</a> and
+ <a href="../specs/AGENT_MANIFEST.md">manifest spec</a>.
+ </p>
+ </div>
+
+ <script type="module">
+ const el = document.getElementById('trinity');
+ const $ = (id) => document.getElementById(id);
+
+ // The manifest loader only accepts absolute http(s)/ipfs/agent sources,
+ // so resolve the bundle path against this page's URL and set it BEFORE
+ // the element registers and boots (hence the dynamic import below).
+ const MANIFEST_URL = new URL('./three-concierge/manifest.json', location.href).href;
+ el.setAttribute('manifest', MANIFEST_URL);
+ $('readyBadge') /* noop ref to ensure DOM is parsed */;
+
+ // ── Live event log ────────────────────────────────────────
+ const logEl = $('log');
+ let booted = performance.now();
+ function logLine(event, detail, kind = '') {
+ const t = ((performance.now() - booted) / 1000).toFixed(2);
+ const row = document.createElement('div');
+ const d = detail
+ ? ` ${typeof detail === 'string' ? detail : JSON.stringify(detail)}`
+ : '';
+ row.innerHTML =
+ `<span class="t">${t.padStart(6, ' ')}s</span> ` +
+ `<span class="e ${kind}">${event}</span>` +
+ `<span class="d">${d.length > 80 ? d.slice(0, 80) + '…' : d}</span>`;
+ logEl.appendChild(row);
+ logEl.scrollTop = logEl.scrollHeight;
+ }
+
+ // ── Status chip + progress ────────────────────────────────
+ function setStatus(text, state = '') {
+ $('statusText').textContent = text;
+ $('statusDot').className = `dot ${state}`;
+ }
+
+ el.addEventListener('agent:load-progress', (e) => {
+ const { phase, pct } = e.detail;
+ $('progressBar').style.width = `${Math.round((pct || 0) * 100)}%`;
+ setStatus(`Loading ${phase}…`);
+ logLine('agent:load-progress', `${phase} ${(pct * 100) | 0}%`);
+ });
+
+ el.addEventListener('skill:loaded', (e) => {
+ logLine('skill:loaded', e.detail.name, 'ok');
+ markSkillLive(e.detail.name);
+ });
+
+ el.addEventListener('skill:tool-called', (e) => {
+ logLine('skill:tool-called', e.detail.tool, 'ok');
+ });
+
+ el.addEventListener('brain:message', (e) => {
+ logLine('brain:message', e.detail.role);
+ if (e.detail.role === 'assistant' && e.detail.content) {
+ addMsg('agent', e.detail.content);
+ }
+ });
+
+ el.addEventListener('voice:speech-start', () =>
+ logLine('voice:speech-start', null, 'ok'),
+ );
+ el.addEventListener('voice:speech-end', () => logLine('voice:speech-end'));
+
+ el.addEventListener('agent:error', (e) => {
+ const phase = e.detail?.phase;
+ logLine('agent:error', `${phase}: ${e.detail?.error?.message || ''}`, 'err');
+ // A send-phase error means the LLM brain isn't reachable for this
+ // local manifest — surface the honest, actionable state.
+ if (phase === 'send') showBrainGuidance();
+ else setStatus('Load error — see event log', 'err');
+ });
+
+ // ── Ready: bind manifest data + enable controls ───────────
+ el.addEventListener('agent:ready', (e) => {
+ const m = e.detail.manifest || {};
+ $('progressBar').style.width = '100%';
+ setTimeout(() => ($('progressBar').style.width = '0%'), 600);
+ setStatus('Live', 'ok');
+ $('readyBadge').innerHTML =
+ '<span class="tag live" style="text-transform:none">● ready</span>';
+
+ $('mName').textContent = m.name || 'Trinity';
+ $('mBody').textContent = (m.body?.uri || '').split('/').pop() || '—';
+ $('mFormat').textContent = m.body?.format || '—';
+ $('mBrain').textContent = m.brain?.model || m.brain?.provider || '—';
+ $('mVoice').textContent = m.voice?.tts?.provider
+ ? `${m.voice.tts.provider} tts`
+ : '—';
+
+ renderSkillTags(m.skills || []);
+ enableSceneControls();
+ populateClips();
+ logLine('agent:ready', m.name, 'ok');
+ });
+
+ // ── Skills as live-lighting tags ──────────────────────────
+ // skill:loaded events arrive DURING load, before agent:ready renders
+ // the tags — so track loaded names and reconcile in both directions.
+ const skillSlugs = new Map();
+ const loadedSkills = new Set();
+ const norm = (s) => s.toLowerCase().replace(/[\s_.-]+/g, '');
+ function namesMatch(slug, name) {
+ const a = norm(slug),
+ b = norm(name);
+ return a === b || a.includes(b) || b.includes(a);
+ }
+ function renderSkillTags(skills) {
+ const box = $('skillTags');
+ box.innerHTML = '';
+ for (const s of skills) {
+ const slug = (s.uri || '').replace(/\/$/, '').split('/').pop();
+ const tag = document.createElement('span');
+ tag.className = 'tag';
+ tag.textContent = slug;
+ if ([...loadedSkills].some((n) => namesMatch(slug, n))) {
+ tag.classList.add('live');
+ tag.title = 'loaded';
+ }
+ box.appendChild(tag);
+ skillSlugs.set(slug, tag);
+ }
+ }
+ function markSkillLive(name) {
+ loadedSkills.add(name);
+ for (const [slug, tag] of skillSlugs) {
+ if (namesMatch(slug, name)) {
+ tag.classList.add('live');
+ tag.title = 'loaded';
+ }
+ }
+ }
+
+ // ── Scene tools (run off the SceneController — no LLM) ─────
+ function enableSceneControls() {
+ document
+ .querySelectorAll('button.action[data-tool]')
+ .forEach((b) => (b.disabled = false));
+ $('ttsInput').disabled = false;
+ $('ttsBtn').disabled = false;
+ $('clipSelect').disabled = false;
+ $('chatInput').disabled = false;
+ $('chatBtn').disabled = false;
+ }
+
+ document.querySelectorAll('button.action[data-tool]').forEach((btn) => {
+ btn.addEventListener('click', () => {
+ const tool = btn.dataset.tool;
+ if (tool === 'wave') el.wave();
+ else if (tool === 'look') el.lookAt('user');
+ else if (tool === 'cheer') el.playEmote('cheer');
+ else if (tool === 'celebrate') el.playEmote('celebrate');
+ logLine('scene-tool', tool);
+ });
+ });
+
+ function populateClips() {
+ const clips = el._listAvailableClips?.() || [];
+ const sel = $('clipSelect');
+ for (const c of clips) {
+ const o = document.createElement('option');
+ o.value = c.name;
+ o.textContent = `${c.icon} ${c.label}`;
+ sel.appendChild(o);
+ }
+ if (clips.length <= 0) {
+ sel.options[0].textContent = 'No baked clips on this model';
+ }
+ sel.addEventListener('change', () => {
+ if (sel.value) {
+ el.play(sel.value);
+ logLine('scene-tool', `play ${sel.value}`);
+ }
+ });
+ }
+
+ // ── Real browser TTS + talk animation (no brain) ──────────
+ function speakLine(text) {
+ if (!text.trim()) return;
+ el.speak(text); // talk animation
+ if ('speechSynthesis' in window) {
+ const u = new SpeechSynthesisUtterance(text);
+ u.rate = 1.0;
+ speechSynthesis.cancel();
+ speechSynthesis.speak(u);
+ logLine('tts', 'speechSynthesis', 'ok');
+ } else {
+ logLine('tts', 'unsupported', 'err');
+ }
+ }
+ $('ttsBtn').addEventListener('click', () => {
+ speakLine($('ttsInput').value);
+ $('ttsInput').value = '';
+ });
+ $('ttsInput').addEventListener('keydown', (e) => {
+ if (e.key === 'Enter') $('ttsBtn').click();
+ });
+
+ // ── Chat → real platform path via el.ask() ────────────────
+ const chatlog = $('chatlog');
+ function addMsg(role, text) {
+ const m = document.createElement('div');
+ m.className = `msg ${role}`;
+ if (role === 'system') m.innerHTML = text;
+ else m.textContent = text;
+ chatlog.appendChild(m);
+ chatlog.scrollTop = chatlog.scrollHeight;
+ return m;
+ }
+ let brainGuidanceShown = false;
+ function showBrainGuidance() {
+ if (brainGuidanceShown) return;
+ brainGuidanceShown = true;
+ addMsg(
+ 'system',
+ "<b>Trinity's brain isn't connected.</b> The avatar, voice, skills, " +
+ 'and scene tools all run locally from the manifest — but live LLM chat ' +
+ 'needs a registered agent so calls can route through the platform proxy. ' +
+ 'Register Trinity to get an <code>agent-id</code>, then swap ' +
+ '<code>manifest=…</code> for <code>agent-id=…</code> to light this up.',
+ );
+ }
+
+ async function sendChat() {
+ const input = $('chatInput');
+ const text = input.value.trim();
+ if (!text) return;
+ addMsg('user', text);
+ input.value = '';
+ input.disabled = true;
+ $('chatBtn').disabled = true;
+ logLine('ask()', text);
+ try {
+ const reply = await el.ask(text);
+ if (reply) addMsg('agent', reply);
+ } catch (err) {
+ // honest, designed failure — not a fake reply
+ showBrainGuidance();
+ } finally {
+ input.disabled = false;
+ $('chatBtn').disabled = false;
+ input.focus();
+ }
+ }
+ $('chatBtn').addEventListener('click', sendChat);
+ $('chatInput').addEventListener('keydown', (e) => {
+ if (e.key === 'Enter') sendChat();
+ });
+
+ // ── Boot ──────────────────────────────────────────────────
+ // Register <agent-3d> only now that the manifest URL is set and every
+ // listener above is attached — so the first load-progress/ready event
+ // is captured. Defining the element upgrades the in-DOM node and fires
+ // its connectedCallback, which begins the boot.
+ setStatus('Booting…');
+ logLine('boot', MANIFEST_URL.split('/').slice(-2).join('/'));
+ import('./../src/element.js').catch((err) => {
+ setStatus('Failed to load component', 'err');
+ logLine('import-error', err.message, 'err');
+ });
+ </script>
+ </body>
+</html>
diff --git a/examples/three-concierge/agent-card.json b/examples/three-concierge/agent-card.json
index a2a0aa1d9..a2c16e5a9 100644
--- a/examples/three-concierge/agent-card.json
+++ b/examples/three-concierge/agent-card.json
@@ -5,7 +5,7 @@
],
"name": "Trinity",
"description": "The three.ws concierge. Guides you through the platform, launches and trades $three on pump.fun, and lives as a 3D avatar you can talk to.",
- "image": "/avatars/thumbs/default.webp",
+ "image": "/avatars/thumbs/default.png",
"active": true,
"x402Support": true,
"services": [
diff --git a/examples/three-concierge/manifest.json b/examples/three-concierge/manifest.json
index 9d003d4e7..f56f7f105 100644
--- a/examples/three-concierge/manifest.json
+++ b/examples/three-concierge/manifest.json
@@ -3,7 +3,7 @@
"spec": "agent-manifest/0.2",
"name": "Trinity",
"description": "The three.ws concierge. Guides you through the platform, launches and trades $three on pump.fun, and lives as a 3D avatar you can talk to.",
- "image": "/avatars/thumbs/default.webp",
+ "image": "/avatars/thumbs/default.png",
"tags": ["concierge", "three.ws", "solana", "pump.fun", "guide"],
"body": {
"uri": "/avatars/default.glb",
diff --git a/vercel.json b/vercel.json
index 14ed9b334..b7de80ac5 100644
--- a/vercel.json
+++ b/vercel.json
@@ -51,6 +51,14 @@
"includeFiles": "examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json",
"maxDuration": 60
},
+ "api/brain/chat.js": {
+ "includeFiles": "examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json",
+ "maxDuration": 120
+ },
+ "api/chat.js": {
+ "includeFiles": "examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json",
+ "maxDuration": 60
+ },
"api/**/*.js": {
"includeFiles": "examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json",
"maxDuration": 30