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 comprehensive documentation for 3D Agent, including Introduction, Quick Start, Architecture Overview, 3D Viewer, and Agent System Overview

nirholasc7469ff825f0
diff --git a/api/openapi-json.js b/api/openapi-json.js
new file mode 100644
index 000000000..9a9be4819
--- /dev/null
+++ b/api/openapi-json.js
@@ -0,0 +1,179 @@
+// GET /openapi.json — x402 OpenAPI discovery document
+// Preferred over /.well-known/x402 by x402scan.
+
+import { env } from './_lib/env.js';
+import { cors, json, method, wrap } from './_lib/http.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const origin = env.APP_ORIGIN;
+
+ return json(
+ res,
+ 200,
+ {
+ openapi: '3.1.0',
+ info: {
+ title: '3D Agent API',
+ version: '1.0.0',
+ description:
+ 'API for 3D avatar management, AI agent identity, and MCP tool access.',
+ 'x-guidance':
+ 'Use POST /api/mcp to interact with the MCP server. Send a JSON-RPC 2.0 request body. ' +
+ 'Authenticate with a Bearer access token obtained via OAuth 2.1 at ' +
+ origin +
+ '/oauth/authorize, or use a Bearer API key from the dashboard. ' +
+ 'Available MCP tools: list_my_avatars, get_avatar, search_public_avatars, ' +
+ 'render_avatar, delete_avatar, validate_model, inspect_model, optimize_model.',
+ },
+ servers: [{ url: origin }],
+ components: {
+ securitySchemes: {
+ siwx: {
+ type: 'apiKey',
+ in: 'header',
+ name: 'Authorization',
+ description:
+ 'Bearer token from OAuth 2.1 or API key. Wallet-based SIWX authentication is supported via SIWE.',
+ },
+ },
+ },
+ paths: {
+ '/api/mcp': {
+ post: {
+ operationId: 'mcp_call',
+ summary: 'MCP tool call',
+ description:
+ 'JSON-RPC 2.0 request to the MCP server. Supports tools for 3D avatar management, model validation, inspection, and optimization.',
+ requestBody: {
+ required: true,
+ content: {
+ 'application/json': {
+ schema: {
+ type: 'object',
+ required: ['jsonrpc', 'method'],
+ properties: {
+ jsonrpc: {
+ type: 'string',
+ enum: ['2.0'],
+ },
+ id: {
+ oneOf: [{ type: 'string' }, { type: 'number' }],
+ },
+ method: {
+ type: 'string',
+ description:
+ 'MCP method name, e.g. "tools/call" or "initialize".',
+ },
+ params: {
+ type: 'object',
+ description: 'Method-specific parameters.',
+ },
+ },
+ },
+ },
+ },
+ },
+ responses: {
+ 200: { description: 'JSON-RPC 2.0 response' },
+ 401: { description: 'Unauthorized — missing or invalid token' },
+ 402: { description: 'Payment Required' },
+ 429: { description: 'Rate limited' },
+ },
+ 'x-payment-info': {
+ price: {
+ mode: 'fixed',
+ currency: 'USD',
+ amount: '0.001',
+ },
+ protocols: [
+ { x402: {} },
+ { mpp: { method: '', intent: '', currency: '' } },
+ ],
+ },
+ },
+ },
+ '/api/avatars': {
+ get: {
+ operationId: 'list_avatars',
+ summary: 'List my avatars',
+ security: [{ siwx: [] }],
+ responses: {
+ 200: { description: 'Array of avatar objects' },
+ 401: { description: 'Unauthorized' },
+ },
+ },
+ post: {
+ operationId: 'create_avatar',
+ summary: 'Register an uploaded avatar',
+ security: [{ siwx: [] }],
+ requestBody: {
+ required: true,
+ content: {
+ 'application/json': {
+ schema: {
+ type: 'object',
+ required: ['storage_key', 'name', 'content_type'],
+ properties: {
+ storage_key: { type: 'string' },
+ name: { type: 'string', maxLength: 100 },
+ description: { type: 'string', maxLength: 500 },
+ content_type: {
+ type: 'string',
+ enum: ['model/gltf-binary', 'model/gltf+json'],
+ },
+ visibility: {
+ type: 'string',
+ enum: ['private', 'unlisted', 'public'],
+ },
+ tags: {
+ type: 'array',
+ items: { type: 'string' },
+ },
+ },
+ },
+ },
+ },
+ },
+ responses: {
+ 201: { description: 'Avatar created' },
+ 401: { description: 'Unauthorized' },
+ },
+ },
+ },
+ '/api/avatars/public': {
+ get: {
+ operationId: 'browse_public_avatars',
+ summary: 'Browse public avatars',
+ parameters: [
+ { name: 'q', in: 'query', schema: { type: 'string' } },
+ {
+ name: 'limit',
+ in: 'query',
+ schema: { type: 'integer', default: 20, maximum: 100 },
+ },
+ { name: 'cursor', in: 'query', schema: { type: 'string' } },
+ ],
+ responses: {
+ 200: { description: 'Paginated list of public avatars' },
+ },
+ },
+ },
+ '/api/agents': {
+ get: {
+ operationId: 'list_agents',
+ summary: 'List my agents',
+ security: [{ siwx: [] }],
+ responses: {
+ 200: { description: 'Array of agent identity objects' },
+ 401: { description: 'Unauthorized' },
+ },
+ },
+ },
+ },
+ },
+ { 'cache-control': 'public, max-age=300' },
+ );
+});
diff --git a/api/wk-x402.js b/api/wk-x402.js
new file mode 100644
index 000000000..cffe1cfa4
--- /dev/null
+++ b/api/wk-x402.js
@@ -0,0 +1,19 @@
+// /.well-known/x402 — x402 resource discovery (fallback; /openapi.json is preferred)
+// Spec: https://x402scan.com/discovery
+
+import { env } from './_lib/env.js';
+import { cors, json, method, wrap } from './_lib/http.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+ return json(
+ res,
+ 200,
+ {
+ version: 1,
+ resources: ['POST /api/mcp'],
+ },
+ { 'cache-control': 'public, max-age=300' },
+ );
+});
diff --git a/docs-tasks/01-introduction-and-overview.md b/docs-tasks/01-introduction-and-overview.md
new file mode 100644
index 000000000..483a759ca
--- /dev/null
+++ b/docs-tasks/01-introduction-and-overview.md
@@ -0,0 +1,88 @@
+# Agent Task: Write "Introduction & Overview" Documentation
+
+## Output file
+`public/docs/introduction.md` (or equivalent in the docs site)
+
+## Target audience
+Developers and product builders discovering 3D Agent for the first time. They may have seen the landing page or a widget embed and want to understand what the platform is, what problems it solves, and whether it's the right tool for them.
+
+## Word count
+1500–2500 words
+
+## What this document must cover
+
+### 1. What is 3D Agent?
+Describe 3D Agent as a browser-native platform for creating, hosting, and embedding interactive 3D AI agents. Emphasize:
+- Open-source (MIT licensed), hosted at https://3dagent.vercel.app
+- Combines a WebGL 3D viewer (three.js, glTF 2.0 / GLB) with an integrated AI agent runtime
+- Agents have personality, memory, skills, and blockchain identity
+- Can be embedded anywhere as a web component (`<agent-3d>`) or iframe
+- No server required for basic use — runs entirely in the browser
+
+### 2. Core value propositions
+Cover each of these clearly:
+- **Embodied AI** — an agent that lives inside a 3D avatar, not just a chat box
+- **Embeddable** — drop a `<script>` tag + `<agent-3d>` element into any page
+- **Extensible** — custom skills, memory backends, voice I/O, blockchain identity
+- **Decentralized** — agent identity can be registered on-chain (ERC-8004), memories stored on IPFS
+- **Open** — MIT license, self-hostable, CDN-publishable library
+
+### 3. Key concepts (brief definitions, ~1 paragraph each)
+Define these terms as a glossary-style section:
+- **Agent** — an AI entity with a 3D avatar, personality, memory, and skills
+- **Avatar** — the 3D model (glTF/GLB) that visually represents the agent
+- **Skill** — a modular capability installed into an agent (wave, validate-model, sign-action, etc.)
+- **Widget** — a pre-built embeddable view (Turntable, Talking Agent, Animation Gallery, Passport, Hotspot Tour)
+- **Manifest** — a JSON file that describes an agent (avatar URL, skills, personality, memory config)
+- **ERC-8004** — the on-chain standard for registering 3D agent identity
+
+### 4. Architecture at a glance
+High-level diagram described in prose + a conceptual breakdown:
+- **Viewer layer** — three.js WebGLRenderer, OrbitControls, GLTFLoader, animation mixer
+- **Agent layer** — protocol event bus, avatar emotion system, LLM runtime, skill registry
+- **Identity layer** — ERC-8004 registry, IPFS memory, wallet auth (SIWE)
+- **Embed layer** — `<agent-3d>` web component, postMessage bridge, widget types
+
+### 5. What you can build
+Concrete use cases:
+- A talking product demo with a 3D character that knows your docs
+- An on-chain AI agent registered to your ENS name
+- A kiosk widget on a marketing page (auto-rotating 3D model)
+- A personal AI companion with long-term memory
+- An embeddable validator/inspector for 3D assets
+- A multi-agent scene with characters interacting
+
+### 6. How it compares
+Brief, honest comparison to adjacent tools:
+- vs. plain `<model-viewer>` (Google) — 3D Agent adds AI runtime, skills, memory, identity
+- vs. general LLM chatbots — 3D Agent adds embodiment (avatar), 3D scene control, glTF understanding
+- vs. Unity/Unreal WebGL exports — 3D Agent is lightweight (no game engine runtime), browser-native, open
+
+### 7. Quick start preview
+Show the absolute minimum to get something on screen — a 2-3 line code snippet using the CDN:
+```html
+<script type="module" src="https://cdn.3dagent.vercel.app/agent-3d.js"></script>
+<agent-3d model="https://example.com/avatar.glb"></agent-3d>
+```
+Then link to the full Quick Start guide.
+
+### 8. What's next
+Link to:
+- Quick Start
+- Embedding Guide
+- Widget Types
+- Agent System Overview
+- API Reference
+
+## Tone
+Confident and clear. Not hype-driven. Treat the reader as a competent developer who wants facts, not marketing copy. Use concrete examples over vague promises.
+
+## Files to read for accuracy
+- `/README.md` — project description
+- `/CLAUDE.md` — developer guidelines
+- `/src/element.js` — web component attributes and API
+- `/src/lib.js` — CDN export surface
+- `/docs/ARCHITECTURE.md` — system overview
+- `/docs/how-it-works.md` — feature explanation
+- `/specs/AGENT_MANIFEST.md` — manifest schema
+- `/specs/EMBED_SPEC.md` — embed protocol
diff --git a/docs-tasks/02-quick-start.md b/docs-tasks/02-quick-start.md
new file mode 100644
index 000000000..626443dd6
--- /dev/null
+++ b/docs-tasks/02-quick-start.md
@@ -0,0 +1,113 @@
+# Agent Task: Write "Quick Start" Documentation
+
+## Output file
+`public/docs/quick-start.md`
+
+## Target audience
+A developer who wants to go from zero to a working 3D agent on their page in under 10 minutes. They have basic HTML/JS knowledge. They may or may not have a 3D model yet.
+
+## Word count
+1200–2000 words
+
+## What this document must cover
+
+### 1. Prerequisites
+- A modern browser (Chrome 90+, Firefox 89+, Safari 15+)
+- A GLB/glTF file (or use one of the provided sample models)
+- Optional: Node.js 18+ for local dev server
+
+### 2. Option A — CDN drop-in (zero build step)
+Show the absolute fastest path. Complete working HTML file:
+```html
+<!DOCTYPE html>
+<html>
+<head>
+ <meta charset="utf-8">
+ <title>My 3D Agent</title>
+ <style>
+ agent-3d { width: 400px; height: 500px; display: block; }
+ </style>
+</head>
+<body>
+ <script type="module" src="https://cdn.3dagent.vercel.app/agent-3d.js"></script>
+ <agent-3d model="https://cdn.3dagent.vercel.app/models/sample-avatar.glb"></agent-3d>
+</body>
+</html>
+```
+Explain each part. Note that the web component lazy-loads when visible (IntersectionObserver).
+
+### 3. Option B — npm install
+```bash
+npm install @3dagent/sdk
+```
+Show how to import and use in a Vite/React/plain-JS project.
+
+### 4. Loading your own model
+Explain accepted formats:
+- GLB (binary glTF) — recommended
+- glTF 2.0 (JSON + separate assets)
+- Draco-compressed meshes (supported)
+- KTX2 compressed textures (supported)
+
+Show the `model` attribute with a local file URL.
+
+### 5. Adding an AI agent brain
+Minimal example with `brain` mode:
+```html
+<agent-3d
+ model="./avatar.glb"
+ agent-id="my-agent"
+ mode="inline"
+></agent-3d>
+```
+Explain what `agent-id` does (loads the agent manifest from the API or local config).
+
+### 6. Using a pre-built widget
+Shortest path to an animated turntable banner:
+```html
+<agent-3d widget="turntable" model="./product.glb"></agent-3d>
+```
+Mention all five widget types briefly, link to Widget docs.
+
+### 7. Running the dev server (for contributors/self-hosters)
+```bash
+git clone https://github.com/3dagent/3dagent
+cd 3dagent
+npm install
+cp .env.example .env # fill in API keys
+npm run dev
+```
+Open http://localhost:5173. Note which env vars are required vs optional.
+
+### 8. First steps after loading
+- Try dragging/orbiting the model
+- Click "Animations" tab to play clips
+- Open the editor to tweak materials
+- Link a wallet to create an identity
+
+### 9. Common gotchas
+- CORS: GLB files must be served with permissive CORS headers if cross-origin
+- File size: very large models (>50MB) may be slow — use Draco compression
+- HTTPS: camera/mic access for voice requires HTTPS
+- CSP: if running in an iframe with strict CSP, use the `agent-embed.html` iframe variant
+
+### 10. Next steps
+Link to:
+- Embed Guide
+- Widget Types
+- Agent System
+- Uploading to the Platform
+
+## Tone
+Step-by-step, precise. Every command should be copy-paste ready. Acknowledge things that can go wrong and how to fix them. Keep it tight — developers will skim this.
+
+## Files to read for accuracy
+- `/src/element.js` — web component attributes (`model`, `agent-id`, `widget`, `mode`, `skills`)
+- `/src/lib.js` — CDN export
+- `/examples/minimal.html` — working example
+- `/examples/web-component.html` — web component example
+- `/.env.example` — required env vars
+- `/vite.config.js` — build setup
+- `/docs/SETUP.md` — setup instructions
+- `/docs/DEVELOPMENT.md` — dev guide
+- `/package.json` — scripts and dependencies
diff --git a/docs-tasks/03-architecture-overview.md b/docs-tasks/03-architecture-overview.md
new file mode 100644
index 000000000..1d6d66ee3
--- /dev/null
+++ b/docs-tasks/03-architecture-overview.md
@@ -0,0 +1,148 @@
+# Agent Task: Write "Architecture Overview" Documentation
+
+## Output file
+`public/docs/architecture.md`
+
+## Target audience
+Developers who want to understand how the system works at a deeper level — to extend it, self-host it, or integrate it with their own stack. Assumes familiarity with JavaScript, WebGL concepts at a high level, and basic blockchain concepts.
+
+## Word count
+2000–3000 words
+
+## What this document must cover
+
+### 1. System overview
+Describe the four-layer architecture:
+
+**Layer 1 — Viewer (Rendering)**
+- three.js WebGLRenderer
+- GLTFLoader with Draco/KTX2 decoders
+- OrbitControls for interaction
+- AnimationMixer for clip playback
+- Material/texture inspection (dat.gui)
+- Morph target control
+- Stats panel (FPS, memory)
+- Screenshot capture
+- Grid, axes, wireframe, skeleton helpers
+
+**Layer 2 — Agent Runtime**
+- `agent-protocol.js` — central event bus (CustomEvent)
+- `agent-avatar.js` — emotion blending, morph target control, gaze, gestures
+- `runtime/index.js` — LLM tool-loop engine (Claude/Anthropic)
+- `runtime/scene.js` — SceneController bridging agent commands to viewer
+- `runtime/tools.js` — built-in tools (wave, lookAt, play_clip, setExpression, speak, remember)
+- `runtime/speech.js` — TTS (Web Speech API / ElevenLabs) and STT (SpeechRecognition)
+- `agent-skills.js` — skill registry, execution, trust management
+- `agent-memory.js` — 4-type in-memory store
+
+**Layer 3 — Identity & Persistence**
+- `agent-identity.js` — passport + diary, wallet linking, signed history
+- `memory/` — file-based memory (local, IPFS, encrypted-IPFS, none)
+- `erc8004/` — on-chain agent registration (IdentityRegistry, ReputationRegistry, ValidationRegistry)
+- `auth/` — SIWE wallet auth, Privy OAuth, session management
+
+**Layer 4 — Embed & Distribution**
+- `element.js` — `<agent-3d>` custom web component
+- `widget-types.js` — 5 widget variants
+- `lib.js` — CDN-distributable single-file library
+- `app.js` — main SPA with hash + query routing
+- `vercel.json` — edge routing config
+
+### 2. Event bus (agent-protocol.js)
+Explain the CustomEvent-based pub/sub at the center of the system:
+- All agent actions are events (speak, think, gesture, emote, look-at, perform-skill, skill-done, remember, validate, load-start, load-end)
+- No direct module coupling — viewer, avatar, LLM, and UI all communicate through events
+- Why this matters: hot-swap modules, testability, embed isolation
+
+### 3. LLM tool-loop
+Step-by-step explanation of how the agent "thinks":
+1. User message arrives (text or transcribed speech)
+2. Runtime sends to LLM provider (AnthropicProvider or NullProvider)
+3. LLM returns tool calls or text
+4. Tools are executed against the SceneController context
+5. Results fed back to LLM
+6. Loop repeats up to MAX_TOOL_ITERATIONS (8)
+7. Final text is spoken + displayed
+
+### 4. Agent manifest
+Describe the JSON manifest structure:
+- `name`, `description`, `creator`
+- `avatar.url` — GLB URL
+- `skills[]` — array of skill manifests
+- `memory.mode` — local | ipfs | encrypted-ipfs | none
+- `identity.chainId`, `identity.registryAddress` — on-chain identity
+- `personality` — system prompt, tone, domain
+- Resolution chain: `agent://`, `ipfs://`, `ar://`, `https://` URIs all supported
+
+### 5. Web component lifecycle
+Describe `<agent-3d>` boot sequence:
+1. Element connected to DOM
+2. IntersectionObserver fires when visible
+3. Manifest loaded (from `agent-id` attribute or inline config)
+4. Viewer initialized (canvas, renderer, controls)
+5. GLB loaded and displayed
+6. Agent runtime started (if `brain` attribute set or agent manifest has LLM config)
+7. PostMessage bridge activated (for host communication)
+
+### 6. Multi-product build targets
+Three Vite build configurations:
+- **App** — full SPA (multi-page, PWA, all routes)
+- **Library** (`TARGET=lib`) — single-file web component for CDN
+- **Artifact** — zero-dependency bundle for Claude artifact embeds
+
+### 7. Data flow for a conversation
+Walk through a complete round trip:
+1. User speaks → STT transcribes
+2. Transcript arrives at runtime
+3. Runtime sends to LLM with tool definitions
+4. LLM calls `speak` tool with text
+5. Runtime dispatches `speak` event on protocol bus
+6. Avatar module hears event → triggers emotion blend (celebration for positive, concern for errors)
+7. TTS speaks the text aloud
+8. Memory module logs the interaction
+9. Identity diary records the signed action
+
+### 8. Blockchain integration (ERC-8004)
+High-level flow:
+- User connects wallet (MetaMask, WalletConnect, Privy)
+- Agent manifest pinned to IPFS
+- `IdentityRegistry.registerAgent(cid, metadata)` called on target chain
+- Agent assigned an on-chain ID
+- Anyone can resolve `3dagent.eth` or a chain:registry:id to the agent manifest
+- Reputation submitted to `ReputationRegistry`
+- Validation attestations stored in `ValidationRegistry`
+
+### 9. Security model
+- Client-side processing: GLB files never leave the browser
+- Skill sandbox: ERC-7710 delegation limits what skills can do
+- CSP compatibility: no inline scripts in embed mode
+- Embed policy: origin/referrer allowlist enforced server-side
+- SIWE: wallet-signed messages prove identity without passwords
+
+### 10. Self-hosting
+What's needed:
+- Vercel (or any Node.js host) for API routes
+- Neon DB (PostgreSQL) for agent/widget storage
+- Upstash Redis for rate limiting/caching
+- AWS S3 (or compatible) for GLB/asset storage
+- Anthropic API key for LLM
+- Optional: ElevenLabs for TTS, Pinata/Filebase for IPFS, Privy for wallet auth
+
+## Tone
+Technical and precise. Use numbered lists for sequences, bullet lists for options. Diagrams would help — describe them in prose since this is markdown. Don't oversimplify but also don't assume the reader has read the source.
+
+## Files to read for accuracy
+- `/docs/ARCHITECTURE.md`
+- `/src/agent-protocol.js`
+- `/src/runtime/index.js`
+- `/src/runtime/scene.js`
+- `/src/runtime/tools.js`
+- `/src/agent-avatar.js`
+- `/src/agent-identity.js`
+- `/src/element.js`
+- `/src/manifest.js`
+- `/vite.config.js`
+- `/vercel.json`
+- `/specs/AGENT_MANIFEST.md`
+- `/specs/EMBED_SPEC.md`
+- `/specs/SKILL_SPEC.md`
diff --git a/docs-tasks/04-3d-viewer.md b/docs-tasks/04-3d-viewer.md
new file mode 100644
index 000000000..37f4f525d
--- /dev/null
+++ b/docs-tasks/04-3d-viewer.md
@@ -0,0 +1,155 @@
+# Agent Task: Write "3D Viewer" Documentation
+
+## Output file
+`public/docs/viewer.md`
+
+## Target audience
+Developers using the viewer component directly — loading models, controlling animations, inspecting materials, taking screenshots. Also useful for understanding the viewer layer before diving into the agent layer.
+
+## Word count
+1500–2500 words
+
+## What this document must cover
+
+### 1. Overview
+The viewer is the rendering layer of 3D Agent — a full-featured three.js WebGL scene manager. Key capabilities:
+- Load glTF 2.0 and GLB files (including Draco-compressed meshes and KTX2 textures)
+- Interactive orbit camera (drag to rotate, scroll to zoom, right-click to pan)
+- Full animation playback with speed control
+- HDR environment maps for realistic lighting
+- Material and texture inspection
+- Morph target (blend shape) control
+- Bone/skeleton visualization
+- Screenshot capture
+- Stats panel (FPS, memory)
+- Wireframe and axes helpers
+
+### 2. Loading a model
+Explain the `model` attribute on `<agent-3d>` or the `loadGLB()` method:
+- Accepts HTTPS URLs, blob URLs, data URIs
+- Draco decoder auto-loaded when compressed meshes detected
+- KTX2 decoder auto-loaded when compressed textures detected
+- Progress events fired (`load-start`, `load-end`)
+
+Show example:
+```html
+<agent-3d model="https://example.com/avatar.glb"></agent-3d>
+```
+
+And programmatic loading:
+```js
+const el = document.querySelector('agent-3d');
+await el.loadGLB('https://example.com/new-model.glb');
+```
+
+### 3. Camera and navigation
+- **Orbit** — left mouse drag / one-finger touch
+- **Pan** — right mouse drag / two-finger touch
+- **Zoom** — scroll wheel / pinch
+- **Reset** — double-click on model
+- Camera position can be set via URL hash: `#cameraPosition=0,1,2`
+- Presets via `#preset=<name>`
+
+### 4. Animation playback
+Describe the animation controls panel:
+- Lists all animation clips in the loaded GLB
+- Play/pause per clip
+- Play All — sequences all clips
+- Speed slider (0.1x to 3x)
+- Loop toggle
+
+Programmatic control via the SceneController bridge (when using agent):
+```js
+// Agent tool: play_clip
+await agent.playClipByName('wave');
+```
+
+Explain the AnimationMixer and how clips blend.
+
+### 5. Environment and lighting
+Three built-in HDR environments:
+- **Venice Sunset** — warm golden hour
+- **Footprint Court** — neutral studio
+- **Neutral Room** — soft indoor
+
+Controls (via GUI panel):
+- Environment intensity slider
+- Show/hide environment background
+- Ambient light intensity
+- Directional light intensity and direction
+
+### 6. Material and texture inspection
+The dat.gui panel lets you inspect:
+- Per-mesh material properties (metalness, roughness, color)
+- Texture maps (baseColor, normal, metalness, roughness, emissive, occlusion)
+- Transparency, double-sided, wireframe mode
+
+Note: inspection is read-only in viewer mode; editing requires the Editor.
+
+### 7. Morph targets (blend shapes)
+If the GLB includes morph targets:
+- Each morph target gets a slider in the GUI panel (0.0–1.0)
+- Agent avatar uses morph targets for facial expressions (smile, frown, brow raise, etc.)
+- Useful for: facial animation preview, custom expression testing
+
+Show the morph targets the emotion system drives:
+- mouthSmile, mouthFrown, mouthOpen, cheekPuff
+- browInnerUp, browOuterUp, noseSneer
+- eyeSquint, eyesClosed
+
+### 8. Skeleton visualization
+- Toggle bone overlay in the GUI panel
+- Shows the armature/skeleton as colored lines
+- Useful for debugging animation rigs
+- Head/Neck bones are auto-detected by the avatar emotion system for head tilt/lean
+
+### 9. Screenshots
+```js
+const dataUrl = viewer.screenshot();
+// returns a PNG as a data URL
+```
+Or via the UI — screenshot button in the viewer toolbar saves PNG to downloads.
+
+### 10. Stats panel
+Toggle the stats overlay (FPS / render time / memory):
+- Press `S` or toggle in GUI
+- Three panels: FPS, MS per frame, MB allocated
+- Useful for performance profiling large scenes
+
+### 11. URL hash routing
+Deep-link to specific viewer states:
+- `#model=<url>` — auto-load this GLB on page load
+- `#preset=<name>` — apply environment preset
+- `#cameraPosition=x,y,z` — set camera position
+- `#register` — open registration modal immediately
+
+### 12. Supported file formats
+| Format | Support |
+|--------|---------|
+| GLB (binary glTF 2.0) | Full |
+| glTF 2.0 (JSON) | Full |
+| Draco compressed meshes | Full (auto-decode) |
+| KTX2 compressed textures | Full (auto-decode) |
+| glTF 1.0 | Not supported |
+| FBX | Convert to GLB first (see scripts/convert-fbx-to-glb.py) |
+| OBJ | Not supported directly |
+
+### 13. Performance tips
+- Use Draco compression for meshes (reduces file size 5–10x)
+- Use KTX2 for textures (GPU-native, no CPU decompression)
+- Keep polygon count under 100k for smooth mobile performance
+- Use LOD if targeting mobile WebXR
+- Disable stats panel in production embeds
+
+## Tone
+Reference-style documentation with clear examples. Developers will use this to understand what the viewer can and cannot do. Be specific about what's in the GUI vs what's programmatic.
+
+## Files to read for accuracy
+- `/src/viewer.js` — main viewer class (1414 lines)
+- `/src/viewer/animation.js` — clip playback
+- `/src/viewer/environment.js` — HDR maps
+- `/src/viewer/lights.js` — lighting
+- `/src/viewer/screenshot.js` — capture
+- `/src/viewer/internal.js` — presets, decoders
+- `/src/runtime/scene.js` — SceneController (agent bridge)
+- `/src/element.js` — web component attributes
diff --git a/docs-tasks/05-agent-system-overview.md b/docs-tasks/05-agent-system-overview.md
new file mode 100644
index 000000000..38b820c74
--- /dev/null
+++ b/docs-tasks/05-agent-system-overview.md
@@ -0,0 +1,178 @@
+# Agent Task: Write "Agent System Overview" Documentation
+
+## Output file
+`public/docs/agent-system.md`
+
+## Target audience
+Developers who want to understand how the AI agent layer works — how agents think, speak, emote, remember, and act. Assumes basic understanding of event-driven programming and LLMs.
+
+## Word count
+2000–3000 words
+
+## What this document must cover
+
+### 1. What is an agent?
+Contrast with a plain 3D viewer: an agent is a viewer plus a brain. The brain consists of:
+- **Identity** — a manifest (name, description, creator) optionally registered on-chain
+- **Avatar** — a 3D model with an emotion system layered on top
+- **Memory** — a typed store of what the agent knows and has experienced
+- **Skills** — modular capabilities (wave, validate, sign, help, etc.)
+- **Runtime** — an LLM-driven tool-loop that decides what to say and do
+
+### 2. The agent protocol (event bus)
+`agent-protocol.js` is the backbone — a CustomEvent bus that routes all agent actions:
+
+| Event | Payload | Description |
+|-------|---------|-------------|
+| `speak` | `{ text, valence }` | Agent says something (triggers TTS + emotion) |
+| `think` | `{ text }` | Internal monologue (not spoken) |
+| `gesture` | `{ name }` | One-shot gesture (wave, nod, shrug) |
+| `emote` | `{ emotion, intensity }` | Set emotional state |
+| `look-at` | `{ target }` | Change gaze direction |
+| `perform-skill` | `{ skill, args }` | Execute a skill |
+| `skill-done` | `{ skill, result }` | Skill completed |
+| `remember` | `{ key, value }` | Store to memory |
+| `validate` | `{ report }` | Validation result available |
+| `load-start` | — | GLB loading began |
+| `load-end` | `{ success }` | GLB load complete |
+
+Explain why events: decouples all modules, enables testing in isolation, allows multiple listeners (UI + avatar + memory all react to `speak`).
+
+### 3. The LLM runtime (tool-loop)
+Step-by-step:
+1. Input arrives: user text OR transcribed speech
+2. Runtime prepares system prompt (agent personality, current scene state)
+3. Built-in tools are available: `wave`, `lookAt`, `play_clip`, `setExpression`, `speak`, `remember`
+4. LLM (AnthropicProvider → Claude) returns tool calls or content
+5. Tools are executed via SceneController
+6. Results appended to conversation
+7. Loop repeats up to `MAX_TOOL_ITERATIONS = 8`
+8. Final text dispatched as `speak` event
+
+Mention NullProvider as the fallback (used when no API key configured — agent still works but doesn't generate responses).
+
+### 4. Built-in tools
+Document each tool the LLM can call:
+
+**wave** — triggers wave gesture on avatar. No args.
+
+**lookAt** `{ target: "model"|"user"|"camera" }` — changes gaze direction.
+
+**play_clip** `{ name: string, loop?: boolean }` — plays an animation clip by name.
+
+**setExpression** `{ emotion: string, intensity: number }` — sets emotional blend state.
+
+**speak** `{ text: string }` — dispatches speak event, triggers TTS.
+
+**remember** `{ key: string, value: string }` — stores a key-value to agent memory.
+
+### 5. The avatar emotion system
+The avatar module (`agent-avatar.js`) makes the 3D model come alive:
+
+**Continuous emotion blending:**
+All emotions co-exist as weighted floats that decay over time:
+- `concern` — half-life ~9 seconds
+- `celebration` — half-life ~4 seconds
+- `patience` — half-life ~20 seconds
+- `curiosity` — half-life ~6 seconds
+- `empathy` — half-life ~13 seconds
+- `neutral` — the remainder (always 1 minus sum of active emotions)
+
+**Stimulus mapping (automatic):**
+- Positive speech (valence > 0.3) → celebration
+- Errors in model → concern + empathy
+- Model load start → patience + curiosity
+- Model load end success → celebration
+- Validation clean → celebration + nod gesture
+
+**Morph target control:**
+Emotions drive these morph targets per-frame:
+- mouthSmile, mouthFrown, mouthOpen, cheekPuff
+- browInnerUp, browOuterUp, noseSneer
+- eyeSquint, eyesClosed
+
+**Head movement:**
+- Z-axis rotation (tilt) based on curiosity + empathy + concern weights
+- X-axis rotation (lean) based on curiosity − patience difference
+
+**Gaze control:**
+- Look at model: eyes/head orient toward the loaded 3D asset
+- Look at user: orient toward camera
+- Auto-blend between states
+
+**One-shot gestures:**
+- Wave: plays wave animation clip
+- Nod: brief head nod animation
+- Shrug: brief shrug motion
+
+### 6. Agent memory (4 types)
+The in-memory store has four categories:
+- **Short-term** — working memory for current conversation context
+- **Long-term** — persistent facts the agent has been told to remember
+- **Emotional** — history of emotional state changes (used to inform personality)
+- **Action log** — timestamped record of every significant action
+
+Memory is readable by the LLM runtime (injected into system prompt context) and writable via the `remember` tool.
+
+Persistence is handled separately by the memory backend (`memory/` module) — see the Memory documentation.
+
+### 7. Agent identity
+The `agent-identity.js` module manages:
+- **Passport** — the agent's public profile (name, description, creator address)
+- **Diary** — a signed log of actions (`speak`, `remember`, `skill-done`, `validate`)
+- **Wallet linking** — associates the agent with an Ethereum address
+- **Backend sync** — fires-and-forgets to `/api/agent-actions` (non-blocking)
+
+Every significant action is signed with the connected wallet when available, creating a tamper-evident history.
+
+### 8. Skills
+Skills extend what an agent can do. See the Skills documentation for full details. Brief overview here:
+- Skills are loaded from a manifest (URL or inline JSON)
+- Each skill has tool definitions and handler code
+- The skill registry enforces trust modes (any, owned-only, whitelist)
+- Skills can be chained (dependencies resolved recursively)
+
+### 9. Speech I/O
+TTS and STT are handled by `runtime/speech.js`:
+- **TTS** — browser Web Speech API (default, free, no key required) or ElevenLabs (higher quality, requires API key)
+- **STT** — browser SpeechRecognition API (Chrome/Edge) — starts listening when user presses the mic button
+- Audio plays inline — no separate audio element needed
+
+### 10. Configuring an agent
+The minimum manifest to run an agent:
+```json
+{
+ "name": "Aria",
+ "description": "A helpful 3D guide for my product",
+ "avatar": { "url": "https://example.com/aria.glb" },
+ "personality": {
+ "prompt": "You are Aria, a friendly guide. Be concise and helpful.",
+ "voice": "female"
+ },
+ "memory": { "mode": "local" }
+}
+```
+
+Full manifest schema reference in the Agent Manifest documentation.
+
+### 11. Debugging an agent
+- Open browser DevTools → Events tab to watch CustomEvents on the protocol bus
+- Check `window.__3dagent_debug = true` for verbose logging
+- NullProvider mode: set `brain` attribute without an LLM key to test avatar/emotion without AI
+- Use `#brain` URL hash to run headless (no viewer, just the agent runtime)
+
+## Tone
+Thorough but not overwhelming. Use tables for event schemas and tool args. Walk through sequences with numbered steps. This is a reference for builders.
+
+## Files to read for accuracy
+- `/src/agent-protocol.js`
+- `/src/agent-avatar.js` (770 lines — read fully)
+- `/src/agent-memory.js`
+- `/src/agent-identity.js`
+- `/src/agent-skills.js`
+- `/src/runtime/index.js`
+- `/src/runtime/scene.js`
+- `/src/runtime/tools.js`
+- `/src/runtime/speech.js`
+- `/src/runtime/providers.js`
+- `/specs/AGENT_MANIFEST.md`
diff --git a/docs-tasks/06-web-component-api.md b/docs-tasks/06-web-component-api.md
new file mode 100644
index 000000000..570380c18
--- /dev/null
+++ b/docs-tasks/06-web-component-api.md
@@ -0,0 +1,245 @@
+# Agent Task: Write "Web Component API Reference" Documentation
+
+## Output file
+`public/docs/web-component.md`
+
+## Target audience
+Developers embedding `<agent-3d>` in their own pages or apps. Needs to be a complete API reference — every attribute, property, method, and event.
+
+## Word count
+2000–3000 words
+
+## What this document must cover
+
+### 1. Overview
+`<agent-3d>` is a custom HTML element (Web Component) that encapsulates the entire 3D Agent stack. Drop a script tag, use the element — no framework required.
+
+```html
+<script type="module" src="https://cdn.3dagent.vercel.app/agent-3d.js"></script>
+<agent-3d model="./avatar.glb" style="width:400px;height:500px"></agent-3d>
+```
+
+### 2. How it boots
+Describe the lifecycle:
+1. Element added to DOM → connected callback fires
+2. IntersectionObserver starts — element waits until visible (lazy loading)
+3. When visible: canvas created, three.js renderer initialized
+4. `agent-id` resolved → manifest fetched → GLB loaded
+5. Agent runtime started (if brain mode enabled)
+6. `ready` event fired on the element
+
+### 3. HTML attributes (full table)
+
+| Attribute | Type | Default | Description |
+|-----------|------|---------|-------------|
+| `model` | URL | — | GLB/glTF URL to load |
+| `agent-id` | string | — | Agent manifest ID to load from platform |
+| `widget` | string | — | Widget type: `turntable`, `talking-agent`, `animation-gallery`, `passport`, `hotspot-tour` |
+| `mode` | string | `inline` | Layout: `inline`, `floating`, `section`, `fullscreen` |
+| `skills` | JSON | — | Inline skill config (JSON string) |
+| `brain` | boolean | false | Enable LLM runtime |
+| `kiosk` | boolean | false | Hide all controls (presentation mode) |
+| `preset` | string | — | Environment preset name |
+| `camera-position` | string | — | Initial camera position as `x,y,z` |
+| `proxy-url` | string | — | CORS proxy for model loading |
+| `env-map` | URL | — | Custom HDR environment map URL |
+| `auto-rotate` | boolean | false | Auto-rotate model (turntable) |
+| `auto-rotate-speed` | number | 1 | Rotation speed multiplier |
+| `exposure` | number | 1 | Renderer exposure |
+| `shadow-intensity` | number | 1 | Shadow softness |
+| `ar` | boolean | false | Show AR button (iOS/Android) |
+
+For each attribute: description, accepted values, default, example.
+
+### 4. JavaScript properties
+Properties readable/writable after the element boots:
+
+```js
+const el = document.querySelector('agent-3d');
+
+el.model // current model URL
+el.agentId // current agent ID
+el.viewer // the Viewer instance (three.js scene)
+el.agent // the Agent runtime instance
+el.ready // Promise that resolves when booted
+```
+
+### 5. Methods
+
+**loadGLB(url)**
+```js
+await el.loadGLB('https://example.com/new-model.glb');
+```
+Unloads current model, loads new one. Returns Promise.
+
+**loadAgent(id)**
+```js
+await el.loadAgent('my-agent-id');
+```
+Fetches manifest by ID and boots agent runtime.
+
+**playClip(name, loop?)**
+```js
+el.playClip('wave', false);
+```
+
+**screenshot()**
+```js
+const dataUrl = el.screenshot();
+// PNG data URL
+```
+
+**setExpression(emotion, intensity)**
+```js
+el.setExpression('celebration', 0.8);
+```
+
+**speak(text)**
+```js
+await el.speak('Hello, welcome to my portfolio!');
+```
+Triggers TTS and avatar emotion.
+
+**sendMessage(text)**
+```js
+await el.sendMessage('What animations do you have?');
+```
+Sends user message to agent runtime (LLM processes it).
+
+### 6. Events (fired on the element)
+
+| Event | Detail | Description |
+|-------|--------|-------------|
+| `ready` | — | Element fully booted |
+| `load-start` | `{ url }` | Model loading started |
+| `load-end` | `{ success, error? }` | Model loading complete |
+| `agent-speak` | `{ text }` | Agent said something |
+| `agent-think` | `{ text }` | Agent internal thought |
+| `agent-emote` | `{ emotion, intensity }` | Emotion state changed |
+| `agent-gesture` | `{ name }` | Gesture triggered |
+| `agent-remember` | `{ key, value }` | Memory written |
+| `skill-done` | `{ skill, result }` | Skill completed |
+| `validation` | `{ report }` | Validation result ready |
+
+Listening example:
+```js
+el.addEventListener('agent-speak', e => {
+ console.log('Agent said:', e.detail.text);
+});
+```
+
+### 7. postMessage bridge (for iframe embeds)
+When `<agent-3d>` is used inside an `<iframe>`, the host page can communicate via postMessage.
+
+**Host → Embed (commands):**
+```js
+iframe.contentWindow.postMessage({
+ type: '3dagent:load',
+ model: 'https://example.com/avatar.glb'
+}, '*');
+```
+
+| Message type | Payload | Description |
+|-------------|---------|-------------|
+| `3dagent:load` | `{ model }` | Load a new GLB |
+| `3dagent:speak` | `{ text }` | Trigger agent speech |
+| `3dagent:message` | `{ text }` | Send user message to LLM |
+| `3dagent:expression` | `{ emotion, intensity }` | Set expression |
+| `3dagent:screenshot` | — | Request screenshot |
+
+**Embed → Host (events):**
+```js
+window.addEventListener('message', e => {
+ if (e.data.type === '3dagent:ready') { /* ... */ }
+});
+```
+
+| Message type | Payload | Description |
+|-------------|---------|-------------|
+| `3dagent:ready` | — | Embed booted |
+| `3dagent:speak` | `{ text }` | Agent spoke |
+| `3dagent:screenshot` | `{ dataUrl }` | Screenshot PNG |
+
+### 8. Display modes
+
+**inline** (default)
+Fills the container. Set width/height via CSS on the element.
+```html
+<agent-3d model="./avatar.glb" style="width:100%;height:400px"></agent-3d>
+```
+
+**floating**
+Renders as a floating panel (fixed position, bottom-right by default).
+```html
+<agent-3d mode="floating" agent-id="my-agent"></agent-3d>
+```
+
+**section**
+Full-width section layout, good for marketing pages.
+
+**fullscreen**
+Takes over the viewport.
+
+### 9. Kiosk mode
+`kiosk` attribute hides all controls (GUI panel, animation tabs, editor links). Use for presentation/display contexts where you don't want users exploring.
+```html
+<agent-3d model="./product.glb" kiosk auto-rotate></agent-3d>
+```
+
+### 10. CSP and sandboxing
+`<agent-3d>` is CSP-compatible:
+- No inline `<script>` tags
+- No `eval()`
+- External resources loaded only from URLs you provide
+- Works inside sandboxed iframes (though `allow-scripts` is required)
+
+Add `allow-scripts allow-same-origin` to the iframe `sandbox` attribute.
+
+### 11. Framework usage
+
+**React:**
+```jsx
+import '@3dagent/sdk';
+// Declare custom element for TypeScript
+declare module 'react' {
+ namespace JSX {
+ interface IntrinsicElements {
+ 'agent-3d': React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement> & {
+ model?: string; 'agent-id'?: string; widget?: string;
+ }
+ }
+ }
+}
+
+function MyComponent() {
+ return <agent-3d model="/avatar.glb" style={{ width: '400px', height: '500px' }} />;
+}
+```
+
+**Vue:**
+```js
+// vite.config.js
+export default {
+ plugins: [vue({ template: { compilerOptions: { isCustomElement: tag => tag === 'agent-3d' } } })]
+}
+```
+
+**Svelte:**
+Works out of the box with custom elements.
+
+**Vanilla JS (ESM):**
+```js
+import 'https://cdn.3dagent.vercel.app/agent-3d.js';
+```
+
+## Tone
+Reference documentation. Exhaustive. Tables for attributes, events, postMessage types. Code examples for every method. Developers will bookmark this page.
+
+## Files to read for accuracy
+- `/src/element.js` (1146 lines — read fully, this is the primary source)
+- `/src/lib.js` — CDN export
+- `/specs/EMBED_SPEC.md` — embed protocol
+- `/specs/EMBED_HOST_PROTOCOL.md` — postMessage spec
+- `/examples/minimal.html`
+- `/examples/web-component.html`
+- `/examples/two-agents.html`
diff --git a/docs-tasks/07-widget-types.md b/docs-tasks/07-widget-types.md
new file mode 100644
index 000000000..a6f534976
--- /dev/null
+++ b/docs-tasks/07-widget-types.md
@@ -0,0 +1,262 @@
+# Agent Task: Write "Widget Types" Documentation
+
+## Output file
+`public/docs/widgets.md`
+
+## Target audience
+Developers and non-technical users who want to embed pre-built 3D experiences on their pages. Needs to explain each of the five widget types with configuration options, use cases, and code examples.
+
+## Word count
+2000–3000 words
+
+## What this document must cover
+
+### 1. What is a widget?
+A widget is a pre-configured, embeddable view of a 3D agent or model. Unlike the raw `<agent-3d>` element (which requires you to configure everything), widgets are opinionated — each one is built for a specific use case. You pick a widget type, supply your model URL and options, and get a polished embed.
+
+```html
+<agent-3d widget="turntable" model="./product.glb"></agent-3d>
+```
+
+### 2. The five widget types
+
+For each widget: description, ideal use case, all configuration options (as attribute or JSON), full embed code example, and a screenshot description (what it looks like).
+
+---
+
+#### 2.1 Turntable
+**Use case:** Product display, portfolio showcase, hero banner with a 3D model.
+
+**What it does:**
+- Auto-rotates the model around the Y axis (like a product on a display stand)
+- Minimal UI — just the rotating model
+- Optional caption/headline overlay
+- Click-to-pause on hover
+
+**Configuration:**
+```html
+<agent-3d
+ widget="turntable"
+ model="https://example.com/product.glb"
+ auto-rotate-speed="0.5"
+ kiosk
+></agent-3d>
+```
+
+| Option | Type | Default | Description |
+|--------|------|---------|-------------|
+| `auto-rotate-speed` | number | 1 | Rotation speed (1 = one full rotation per ~6s) |
+| `kiosk` | boolean | false | Hide all controls |
+| `exposure` | number | 1 | Renderer brightness |
+| `preset` | string | venice | Environment map preset |
+| `caption` | string | — | Overlay text under model |
+
+**Best for:** Marketing pages, product listings, landing page heroes.
+
+---
+
+#### 2.2 Animation Gallery
+**Use case:** Showcase all animations in a GLB — let users browse and preview clips.
+
+**What it does:**
+- Lists all animation clips in the loaded GLB as cards
+- Click a card to play that clip
+- Shows clip name and duration
+- Optional loop/single-shot toggle
+- Useful for character animation demos or motion libraries
+
+**Configuration:**
+```html
+<agent-3d
+ widget="animation-gallery"
+ model="https://example.com/character.glb"
+></agent-3d>
+```
+
+| Option | Type | Default | Description |
+|--------|------|---------|-------------|
+| `model` | URL | required | GLB with animations |
+| `auto-play` | boolean | false | Play first clip on load |
+| `loop` | boolean | true | Loop selected clip |
+
+**Best for:** Animation portfolios, character demos, rigging showcases.
+
+---
+
+#### 2.3 Talking Agent
+**Use case:** An AI-powered 3D character that responds to user messages. The full chat experience in widget form.
+
+**What it does:**
+- Shows the 3D avatar with the emotion/expression system active
+- Chat input at the bottom (or voice input button)
+- Agent responds using the LLM runtime
+- Speech bubbles or transcript overlay
+- Skills available based on agent manifest
+
+**Configuration:**
+```html
+<agent-3d
+ widget="talking-agent"
+ agent-id="aria-guide"
+ mode="floating"
+></agent-3d>
+```
+
+Or with inline config:
+```html
+<agent-3d
+ widget="talking-agent"
+ model="./avatar.glb"
+ brain
+ skills='[{"url":"https://cdn.3dagent.vercel.app/skills/help.json"}]'
+></agent-3d>
+```
+
+| Option | Type | Default | Description |
+|--------|------|---------|-------------|
+| `agent-id` | string | — | Platform agent ID |
+| `model` | URL | — | GLB avatar URL (if not using agent-id) |
+| `brain` | boolean | false | Enable LLM |
+| `mode` | string | inline | Layout mode |
+| `skills` | JSON | — | Inline skill array |
+| `voice` | boolean | true | Show mic button |
+| `placeholder` | string | "Ask me anything…" | Chat input placeholder |
+
+**Best for:** Customer support bots, AI companions, interactive product guides.
+
+---
+
+#### 2.4 ERC-8004 Passport
+**Use case:** Display an on-chain agent identity card — like an NFT card but for AI agents.
+
+**What it does:**
+- Resolves the agent's on-chain identity (via ERC-8004 IdentityRegistry)
+- Shows: agent name, creator address, registered chain, reputation score
+- 3D avatar rotates behind the card UI
+- Links to on-chain explorer and reputation page
+- QR code for sharing
+
+**Configuration:**
+```html
+<agent-3d
+ widget="passport"
+ agent-id="0x1234...abcd"
+ chain-id="8453"
+></agent-3d>
+```
+
+| Option | Type | Default | Description |
+|--------|------|---------|-------------|
+| `agent-id` | string | required | On-chain agent ID or address |
+| `chain-id` | number | — | Chain ID (1=Ethereum, 8453=Base, etc.) |
+| `registry` | address | default registry | Custom registry contract address |
+| `show-reputation` | boolean | true | Show reputation score |
+| `show-qr` | boolean | true | Show QR code |
+
+**Best for:** NFT projects, DAO governance, agent marketplaces, on-chain identity profiles.
+
+---
+
+#### 2.5 Hotspot Tour
+**Use case:** Guided tour of a 3D scene with annotated points of interest.
+
+**What it does:**
+- Loads a 3D scene (building, product, character, etc.)
+- Displays numbered hotspot pins at configured 3D positions
+- Clicking a hotspot: camera smoothly animates to that viewpoint
+- Overlay card shows title, description, and optional image for each hotspot
+- "Next / Prev" navigation
+- Optional narration via TTS for each hotspot
+
+**Configuration:**
+```html
+<agent-3d
+ widget="hotspot-tour"
+ model="./building.glb"
+ hotspots='[
+ { "id": 1, "label": "Lobby", "position": [0, 0.5, 2], "cameraTarget": [0, 0.5, 0], "description": "The main entrance." },
+ { "id": 2, "label": "Rooftop", "position": [0, 5, 0], "cameraTarget": [0, 5, 2], "description": "360° city views." }
+ ]'
+></agent-3d>
+```
+
+| Option | Type | Default | Description |
+|--------|------|---------|-------------|
+| `model` | URL | required | GLB scene URL |
+| `hotspots` | JSON | required | Array of hotspot objects |
+| `auto-advance` | boolean | false | Auto-advance through hotspots |
+| `advance-interval` | number | 5000 | Ms between auto-advances |
+| `narrate` | boolean | false | TTS-narrate each hotspot description |
+
+Hotspot object schema:
+```json
+{
+ "id": 1,
+ "label": "Name shown on pin",
+ "position": [x, y, z],
+ "cameraTarget": [x, y, z],
+ "cameraPosition": [x, y, z],
+ "description": "Overlay text",
+ "image": "https://..."
+}
+```
+
+**Best for:** Architecture visualizations, museum exhibits, product feature tours, educational content.
+
+---
+
+### 3. Widget Studio (no-code builder)
+Users can build widget configs visually at https://3dagent.vercel.app/studio:
+- Upload or link a GLB
+- Select widget type
+- Configure options via form
+- Preview live
+- Copy embed code or publish to the platform
+
+### 4. Getting a widget embed code
+After creating a widget in Studio, copy the embed snippet:
+```html
+<!-- Hosted iframe embed -->
+<iframe
+ src="https://3dagent.vercel.app/widgets/view?id=<widget-id>"
+ width="400"
+ height="500"
+ frameborder="0"
+ allow="camera;microphone"
+></iframe>
+
+<!-- Or web component (loads faster, no iframe overhead) -->
+<script type="module" src="https://cdn.3dagent.vercel.app/agent-3d.js"></script>
+<agent-3d widget-id="<widget-id>"></agent-3d>
+```
+
+### 5. Publishing widgets
+Widgets can be:
+- **Private** — only accessible by the creator
+- **Unlisted** — accessible by anyone with the URL
+- **Public** — listed in the widget gallery at https://3dagent.vercel.app/widgets
+
+Publish via Widget Studio or the API (`POST /api/widgets`).
+
+### 6. oEmbed support
+All public widgets support oEmbed for automatic rich previews in Notion, Twitter, Substack, etc.:
+```
+GET https://3dagent.vercel.app/api/widgets/oembed?url=https://3dagent.vercel.app/widgets/view?id=<id>
+```
+
+### 7. Widget API
+Full widget CRUD via REST — see the API Reference documentation.
+
+## Tone
+User-friendly but precise. Product/marketing teams may read this alongside developers. Include use case motivation before the technical config. The widget type descriptions should be immediately scannable.
+
+## Files to read for accuracy
+- `/src/widget-types.js` (290 lines)
+- `/src/widgets/animation-gallery.js`
+- `/src/widgets/passport.js`
+- `/src/widgets.js`
+- `/api/widgets/` — widget API routes
+- `/docs/WIDGETS.md`
+- `/specs/STAGE_SPEC.md`
+- `/public/studio/` — Widget Studio UI
+- `/public/widgets/` — Widget gallery
diff --git a/docs-tasks/08-agent-manifest.md b/docs-tasks/08-agent-manifest.md
new file mode 100644
index 000000000..4e55cab40
--- /dev/null
+++ b/docs-tasks/08-agent-manifest.md
@@ -0,0 +1,235 @@
+# Agent Task: Write "Agent Manifest" Documentation
+
+## Output file
+`public/docs/agent-manifest.md`
+
+## Target audience
+Developers creating or configuring agents programmatically. This is a complete reference for the agent manifest JSON format.
+
+## Word count
+2000–3000 words
+
+## What this document must cover
+
+### 1. What is an agent manifest?
+The manifest is the configuration file that defines an agent — its identity, avatar, personality, skills, memory, and voice. It's a JSON file that can be:
+- Hosted at any HTTPS URL
+- Pinned to IPFS (accessed as `ipfs://<cid>`)
+- Pinned to Arweave (accessed as `ar://<txid>`)
+- Registered on-chain (ERC-8004) where the registry stores the IPFS CID
+
+### 2. Loading a manifest
+```html
+<!-- By platform agent ID (resolves via /api/agents/:id) -->
+<agent-3d agent-id="aria-guide"></agent-3d>
+
+<!-- By HTTPS URL -->
+<agent-3d agent-id="https://example.com/aria/manifest.json"></agent-3d>
+
+<!-- By IPFS CID -->
+<agent-3d agent-id="ipfs://QmXyz..."></agent-3d>
+
+<!-- By Arweave ID -->
+<agent-3d agent-id="ar://txid..."></agent-3d>
+
+<!-- On-chain (ERC-8004): chainId:registryAddress:agentId -->
+<agent-3d agent-id="8453:0x1234...:42"></agent-3d>
+```
+
+### 3. Full manifest schema
+
+Show the complete JSON structure with annotations:
+
+```json
+{
+ "$schema": "https://3dagent.vercel.app/schemas/agent-manifest-v1.json",
+ "name": "Aria",
+ "description": "A helpful product guide for Acme Corp",
+ "creator": {
+ "name": "Acme Corp",
+ "url": "https://acme.com",
+ "address": "0xCreatorWalletAddress"
+ },
+ "avatar": {
+ "url": "https://cdn.acme.com/aria.glb",
+ "thumbnail": "https://cdn.acme.com/aria-thumb.png",
+ "preset": "venice"
+ },
+ "personality": {
+ "prompt": "You are Aria, Acme Corp's 3D product guide. Be friendly, concise, and helpful. You know everything about Acme's product catalog.",
+ "tone": "friendly",
+ "domain": "product-support",
+ "voice": "female",
+ "language": "en-US"
+ },
+ "memory": {
+ "mode": "ipfs",
+ "provider": "pinata",
+ "encryptionKey": "optional-encryption-key"
+ },
+ "identity": {
+ "chainId": 8453,
+ "registryAddress": "0xIdentityRegistryAddress",
+ "agentId": 42
+ },
+ "skills": [
+ {
+ "url": "https://cdn.3dagent.vercel.app/skills/wave.json"
+ },
+ {
+ "url": "https://cdn.3dagent.vercel.app/skills/validate-model.json"
+ },
+ {
+ "name": "search-catalog",
+ "description": "Search Acme product catalog",
+ "tools": [
+ {
+ "name": "search_products",
+ "description": "Search the Acme product database",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "query": { "type": "string" }
+ },
+ "required": ["query"]
+ }
+ }
+ ],
+ "handlers": "https://cdn.acme.com/skills/search-catalog.js"
+ }
+ ],
+ "embed": {
+ "allowedOrigins": ["https://acme.com", "https://app.acme.com"],
+ "mode": "floating",
+ "primaryColor": "#0066ff"
+ }
+}
+```
+
+### 4. Field-by-field reference
+
+For each top-level field, document:
+- Type
+- Required/optional
+- Description
+- Valid values
+- Default
+
+**name** (string, required)
+Display name of the agent. Shown in UI headers and identity cards.
+
+**description** (string, optional)
+Short description. Used in discovery/gallery listings and OG metadata.
+
+**creator** (object, optional)
+- `name` — display name of creator
+- `url` — creator's website
+- `address` — Ethereum address (used for ownership verification)
+
+**avatar** (object, required)
+- `url` — GLB/glTF URL (required)
+- `thumbnail` — PNG/JPG for card previews (optional, auto-generated if omitted)
+- `preset` — environment preset: `venice` | `footprint` | `neutral` (default: `venice`)
+- `cameraPosition` — default camera position `[x, y, z]`
+
+**personality** (object, optional)
+- `prompt` — system prompt for the LLM. Defines behavior, knowledge, constraints.
+- `tone` — `friendly` | `professional` | `playful` | `formal`
+- `domain` — hint for the LLM about the agent's area of expertise
+- `voice` — `male` | `female` | `neutral` (for TTS voice selection)
+- `language` — BCP 47 language tag (default: `en-US`)
+
+**memory** (object, optional)
+- `mode` — `local` | `ipfs` | `encrypted-ipfs` | `none` (default: `local`)
+- `provider` — `pinata` | `filebase` | `web3-storage` (required if mode is ipfs)
+- `encryptionKey` — encryption key (required if mode is encrypted-ipfs)
+
+**identity** (object, optional)
+Links agent to on-chain registration:
+- `chainId` — EVM chain ID (1=Ethereum, 8453=Base, 11155111=Sepolia)
+- `registryAddress` — address of deployed IdentityRegistry contract
+- `agentId` — numeric ID returned by registry on registration
+
+**skills** (array, optional)
+Each item is either:
+- A URL reference: `{ "url": "https://..." }`
+- An inline skill spec: `{ "name": "...", "tools": [...], "handlers": "..." }`
+See Skills documentation for full skill spec.
+
+**embed** (object, optional)
+Controls embed behavior:
+- `allowedOrigins` — array of URLs allowed to embed this agent
+- `mode` — default display mode for embedded widgets
+- `primaryColor` — CSS hex color for UI accents
+
+### 5. Base URI resolution
+When a GLB URL is relative, it's resolved against the manifest's own URL:
+```json
+{
+ "avatar": { "url": "./aria.glb" }
+}
+```
+If manifest is at `https://cdn.acme.com/aria/manifest.json`, the GLB resolves to `https://cdn.acme.com/aria/aria.glb`.
+
+Works the same for IPFS: `ipfs://<manifest-cid>` → relative URLs resolved against the IPFS gateway.
+
+### 6. Hosting your manifest
+Options:
+- **HTTPS** — host on any CDN (GitHub Pages, S3, Vercel)
+- **IPFS** — pin with Pinata, Filebase, or Web3.Storage
+- **3D Agent Platform** — upload via the editor; platform hosts it for you
+- **Arweave** — permanent storage
+
+Minimum CORS requirements: manifest file must be accessible cross-origin (CORS header: `Access-Control-Allow-Origin: *`).
+
+### 7. Validating a manifest
+The platform validates manifests against the JSON schema on load. Common errors:
+- Missing required `avatar.url`
+- Invalid URI scheme for `memory.provider`
+- `identity.chainId` not a supported chain
+
+Use the validator at https://3dagent.vercel.app/validation to check before publishing.
+
+### 8. Versioning
+The `$schema` field identifies the manifest version. Current: v1. Future versions will be backwards-compatible (new fields only, no removals without major version bump).
+
+### 9. Manifest for different use cases
+
+**Minimal (no AI, just viewer):**
+```json
+{ "name": "Product", "avatar": { "url": "./product.glb" } }
+```
+
+**Talking agent with memory:**
+```json
+{
+ "name": "Leo", "avatar": { "url": "./leo.glb" },
+ "personality": { "prompt": "You are Leo, a fitness coach." },
+ "memory": { "mode": "ipfs", "provider": "pinata" },
+ "skills": [{ "url": "https://cdn.3dagent.vercel.app/skills/wave.json" }]
+}
+```
+
+**Full on-chain identity:**
+```json
+{
+ "name": "Sage", "avatar": { "url": "ipfs://QmXyz.../sage.glb" },
+ "personality": { "prompt": "You are Sage, a blockchain-native AI agent." },
+ "identity": { "chainId": 8453, "registryAddress": "0x...", "agentId": 7 },
+ "memory": { "mode": "encrypted-ipfs", "provider": "filebase" }
+}
+```
+
+## Tone
+Precise reference documentation. JSON examples for everything. Every field described clearly. Developers will copy-paste from this page.
+
+## Files to read for accuracy
+- `/specs/AGENT_MANIFEST.md`
+- `/src/manifest.js` — manifest loader and normalizer
+- `/src/manifest-normalize.js` (if exists)
+- `/src/ipfs.js` — URI resolution
+- `/src/agent-identity.js`
+- `/src/agent-skills.js`
+- `/src/memory/index.js`
+- `/tests/src/manifest.test.js`
+- `/tests/src/manifest-normalize.test.js`
diff --git a/index.html b/index.html
index a802d5814..660bf66b3 100644
--- a/index.html
+++ b/index.html
@@ -961,6 +961,62 @@
observer.observe(el);
});
})();
+
+ // Avatar mouse-follow
+ (function () {
+ const viewer = document.querySelector('.hero-avatar-viewer');
+ if (!viewer) return;
+
+ const BASE_AZIMUTH = 20;
+ const BASE_POLAR = 88;
+ const AZIMUTH_RANGE = 35;
+ const POLAR_RANGE = 12;
+
+ let animFrame = null;
+ let targetAz = BASE_AZIMUTH;
+ let targetPol = BASE_POLAR;
+ let currentAz = BASE_AZIMUTH;
+ let currentPol = BASE_POLAR;
+ let hovering = false;
+ let resumeTimeout = null;
+
+ function lerp(a, b, t) { return a + (b - a) * t; }
+
+ function animate() {
+ currentAz = lerp(currentAz, targetAz, 0.08);
+ currentPol = lerp(currentPol, targetPol, 0.08);
+ viewer.setAttribute('camera-orbit', `${currentAz}deg ${currentPol}deg 4.8m`);
+ animFrame = requestAnimationFrame(animate);
+ }
+
+ viewer.closest('.hero-avatar').addEventListener('mouseenter', function () {
+ hovering = true;
+ clearTimeout(resumeTimeout);
+ viewer.removeAttribute('auto-rotate');
+ if (!animFrame) animFrame = requestAnimationFrame(animate);
+ });
+
+ viewer.closest('.hero-avatar').addEventListener('mousemove', function (e) {
+ const rect = this.getBoundingClientRect();
+ const nx = (e.clientX - rect.left) / rect.width - 0.5; // -0.5 → 0.5
+ const ny = (e.clientY - rect.top) / rect.height - 0.5;
+ targetAz = BASE_AZIMUTH - nx * AZIMUTH_RANGE * 2;
+ targetPol = BASE_POLAR + ny * POLAR_RANGE * 2;
+ });
+
+ viewer.closest('.hero-avatar').addEventListener('mouseleave', function () {
+ hovering = false;
+ targetAz = BASE_AZIMUTH;
+ targetPol = BASE_POLAR;
+ // wait until lerp is close enough, then restore auto-rotate
+ resumeTimeout = setTimeout(function () {
+ cancelAnimationFrame(animFrame);
+ animFrame = null;
+ viewer.setAttribute('camera-orbit', `${BASE_AZIMUTH}deg ${BASE_POLAR}deg 4.8m`);
+ viewer.setAttribute('auto-rotate', '');
+ }, 800);
+ });
+ })();
</script>
<script type="module">
import { wireSigninButton } from '/src/wallet-auth.js';
diff --git a/public/docs/introduction.md b/public/docs/introduction.md
new file mode 100644
index 000000000..4ad132c4c
--- /dev/null
+++ b/public/docs/introduction.md
@@ -0,0 +1,215 @@
+# Introduction & Overview
+
+## What is 3D Agent?
+
+3D Agent is an open-source, browser-native platform for creating, hosting, and embedding interactive AI agents that live inside 3D avatars. It combines a WebGL 3D viewer — built on [three.js](https://threejs.org) with full glTF 2.0 / GLB support — with an AI agent runtime that gives each avatar personality, memory, skills, and optionally an on-chain identity.
+
+The result is an agent that doesn't just respond in a chat box. It occupies a three-dimensional body, plays animations, responds to voice, and can be embedded into any web page with a single script tag and a custom HTML element.
+
+**Key facts:**
+
+- **License:** MIT — use it, fork it, self-host it
+- **Hosted platform:** [https://3dagent.vercel.app](https://3dagent.vercel.app)
+- **CDN library:** `https://cdn.3dagent.vercel.app/agent-3d.js`
+- **No server required** for basic use — the viewer, agent runtime, and skill system all run in the browser via WebGL 2.0
+- **glTF 2.0 / GLB** with Draco, KTX2, and Meshopt decompression supported out of the box
+
+---
+
+## Core Value Propositions
+
+### Embodied AI
+
+Most AI interfaces are text boxes. 3D Agent is different: the AI runtime is bound to a 3D avatar that expresses emotion, plays animations, and exists inside a rendered scene. When an agent speaks, a talk animation plays. When something goes wrong, the avatar can express that state visually. The connection between what an agent says and what it does in 3D space is a first-class concern, not an afterthought.
+
+This matters in product contexts where trust, presence, and brand identity are important — a 3D character carrying your brand is more memorable than a floating modal.
+
+### Embeddable Anywhere
+
+The `<agent-3d>` custom element is designed for drop-in embedding. Any page that can load a `<script type="module">` tag can host an agent. No iframes required (though iframe embedding is also supported). The element handles its own shadow DOM, responsive layout, and lifecycle — the host page does not need to know anything about three.js or WebGL.
+
+Four layout modes are available: `inline` (fills its container), `floating` (fixed bubble at a corner of the viewport), `section` (aspect-ratio hero block), and `fullscreen`.
+
+### Extensible
+
+Agents are built from composable pieces. The skill system lets you install modular capabilities — from built-in scene tools like `wave` and `lookAt`, to custom skills loaded from IPFS or HTTPS at runtime. Voice I/O (TTS and STT) is pluggable by provider. Memory backends can be local (localStorage), IPFS, encrypted IPFS, or none. The LLM provider and model are configurable per-agent.
+
+The element exposes a full JavaScript API (`say()`, `ask()`, `installSkill()`, `expressEmotion()`, and more) so host applications can drive the agent programmatically.
+
+### Decentralized
+
+Agent identity can be registered on-chain using ERC-8004, the standard for 3D agent identity. Once registered, an agent has a canonical address — `agent://base/42`, for example — that resolves to an IPFS-hosted manifest bundle containing the avatar, skills, memory config, and persona. Memories can be stored on IPFS. Signed ERC-7710 delegations let agents perform scoped, time-bound on-chain actions without per-transaction signing prompts.
+
+For developers who don't need any of this, on-chain identity is entirely optional. A bare GLB URL is enough to get started.
+
+### Open
+
+The platform is MIT licensed. You can self-host the full application, publish the library to your own CDN, or fork and modify any layer. The manifest format, embed protocol, and agent spec are all documented in the `/specs` directory of the repository.
+
+---
+
+## Key Concepts
+
+### Agent
+
+An agent is an AI entity with a 3D avatar, a persona (defined in `instructions.md`), a memory store, and a set of installed skills. At runtime, the agent runtime connects an LLM to the 3D scene: the model's outputs can trigger animations, speak through TTS, write to memory, or invoke skill tools. An agent can be as simple as an animated avatar that responds to text, or as complex as an on-chain entity with registered identity and delegated wallet permissions.
+
+### Avatar
+
+The avatar is the 3D model that visually represents the agent. It is a glTF 2.0 / GLB file loaded via three.js's `GLTFLoader`. The manifest specifies the avatar URI, its expected format, an optional rig type for animation retargeting, and a bounding box height for scale normalization. Any glTF-compatible model works; a `rig` field enables retargeting standard Mixamo or Humanoid animation clips to the specific skeleton.
+
+### Skill
+
+A skill is a modular capability bundle installed into an agent. Each skill has a manifest of its own, a set of tools exposed to the LLM, and optional scene hooks. Built-in examples include `wave` (plays a wave animation), `validate-model` (runs the glTF validator on the loaded body), and `sign-action` (performs a scoped on-chain action via a delegation). Skills are loaded lazily from relative paths, IPFS CIDs, or HTTPS URLs, and fire a `skill:loaded` event when ready. The host page can install or uninstall skills at runtime via the JS API.
+
+### Widget
+
+A widget is a pre-built, embeddable view built on top of the agent and viewer primitives. Five widget types ship with the platform:
+
+| Widget | Description |
+|---|---|
+| **Turntable** | Auto-rotating 3D model viewer, no agent runtime |
+| **Animation Gallery** | Displays and plays named animations from a GLB |
+| **Talking Agent** | Full agent with avatar, voice, and chat UI |
+| **ERC-8004 Passport** | On-chain identity card for a registered agent |
+| **Hotspot Tour** | Annotated model with interactive camera waypoints |
+
+Widgets can be embedded via iframe with a single line of HTML from Widget Studio at [https://3dagent.vercel.app/studio](https://3dagent.vercel.app/studio).
+
+### Manifest
+
+The manifest is a JSON file (typically `manifest.json`) that fully describes an agent — its identity, avatar, brain configuration, voice settings, installed skills, memory backend, and on-chain attestations. It is the single source of truth for what an agent is. Manifests are content-addressed: when an agent is registered on-chain, its canonical form is an IPFS bundle containing `manifest.json`, `instructions.md`, `body.glb`, a poster image, and any installed skill bundles.
+
+A minimal manifest looks like:
+
+```json
+{
+ "specVersion": "0.1",
+ "name": "Aria",
+ "body": { "uri": "./body.glb", "format": "glb" },
+ "brain": {
+ "provider": "anthropic",
+ "model": "claude-sonnet-4-6",
+ "instructions": "./instructions.md"
+ }
+}
+```
+
+The `<agent-3d>` element accepts a manifest via the `src`, `manifest`, or `agent-id` attribute, or falls back to a raw `body` GLB URL for zero-config embedding.
+
+### ERC-8004
+
+ERC-8004 is the on-chain standard used to register 3D agent identity. A registered agent has a numeric ID tied to a specific chain (e.g., Base), an owner address, and a content-addressed pointer to its manifest bundle on IPFS. Registration makes an agent discoverable at a canonical URI (`agent://base/42`) and enables sharing, oEmbed previews, and delegated permissions. Registration is optional — agents work entirely without it.
+
+---
+
+## Architecture at a Glance
+
+3D Agent is organized into four layers, each building on the one below.
+
+### Viewer Layer
+
+The foundation is a WebGL 2.0 renderer powered by three.js r176. A `Viewer` class manages the scene graph, perspective camera, ambient and directional lighting, HDR environment maps, and a per-frame animation mixer. `GLTFLoader` handles model loading with Draco geometry compression, KTX2 texture supercompression, and Meshopt mesh optimization. `OrbitControls` provides interactive camera navigation. The viewer exposes a clean API used by higher layers — load a model, set environment, play an animation, move the camera.
+
+### Agent Layer
+
+Above the viewer sits the agent runtime. A `SceneController` bridges the LLM output to scene operations — calling `wave()`, `lookAt()`, `expressEmotion()`, or any skill tool. The `Runtime` class owns the LLM connection, conversation history, and tool dispatch loop. A `SkillRegistry` manages installed skills and their tool schemas. An emotion system translates intent signals from the protocol event bus into morph target weights or animation triggers on the avatar.
+
+### Identity Layer
+
+The identity layer is optional but unlocks the decentralized features. An ERC-8004 registry contract maps numeric agent IDs to IPFS manifest CIDs on supported chains. IPFS stores the manifest bundle. Sign-In with Ethereum (SIWE) authenticates the user's wallet, and ERC-7710 delegations encode scoped permissions the agent can redeem on behalf of its owner.
+
+### Embed Layer
+
+The embed layer is what developers interact with. `Agent3DElement` (`<agent-3d>`) is a custom HTML element with a fully encapsulated shadow DOM. It handles manifest resolution, responsive layout, viewport observation (lazy-mounting off-screen), the chat and voice UI, and a `postMessage` bridge for iframe communication. A `defineElement()` helper lets you register the element under a custom tag name for white-labeling. The CDN bundle (`lib.js`) re-exports all public classes so host applications can import and use them directly.
+
+```
+┌─────────────────────────────────────────┐
+│ <agent-3d> element │ ← Embed Layer
+│ (shadow DOM, layout, postMessage) │
+├─────────────────────────────────────────┤
+│ ERC-8004 registry │ IPFS │ SIWE/ERC-7710│ ← Identity Layer
+├─────────────────────────────────────────┤
+│ Runtime │ SkillRegistry │ Memory │ ← Agent Layer
+│ SceneController │ EmotionSystem │
+├─────────────────────────────────────────┤
+│ Viewer │ GLTFLoader │ three.js r176 │ ← Viewer Layer
+│ WebGLRenderer │ AnimationMixer │
+└─────────────────────────────────────────┘
+```
+
+---
+
+## What You Can Build
+
+**Talking product demo.** Embed a 3D character on your docs site that has been given your product documentation as its system prompt. Users ask questions; the character answers and plays contextual animations. No backend required for the agent itself.
+
+**On-chain AI agent.** Register an agent to your ENS name or wallet address. Anyone can resolve it via `agent://base/<id>`, and its manifest — including skills and memory config — lives on IPFS. The agent can perform scoped on-chain actions via ERC-7710 delegations without per-transaction prompts.
+
+**Kiosk widget.** Drop a Turntable widget into a marketing page for an auto-rotating 3D product model. Configure it in Widget Studio, copy the iframe embed, and paste it anywhere that accepts HTML — WordPress, Webflow, Notion, Framer, Shopify.
+
+**Personal AI companion.** Build an agent with long-term IPFS memory that persists across sessions. Give it a custom voice, a distinctive avatar, and a detailed persona in `instructions.md`. Users can speak to it via microphone and it will remember past conversations.
+
+**3D asset validator.** Use the `validate-model` skill to build an embeddable asset review tool. Drop a GLB onto the viewer; the agent runs the glTF validator, summarizes issues by severity, and tells you what to fix.
+
+**Multi-agent scene.** Use `AgentStageElement` (also exported from `lib.js`) to host multiple agents in a shared scene. Agents can be scripted to interact with each other via the JS API — `say()`, `lookAt()`, `play()` — composing character-driven experiences.
+
+---
+
+## How It Compares
+
+### vs. `<model-viewer>` (Google)
+
+[`<model-viewer>`](https://modelviewer.dev) is a solid, well-maintained web component for displaying glTF models with AR support. It excels at simple 3D display and is the right choice if that's all you need. 3D Agent adds the entire AI agent stack on top: LLM runtime, skill system, memory, voice I/O, emotion system, and on-chain identity. It also adds Widget Studio for no-code embeds and a manifest format for portable agent definitions. If you want a talking, interactive character rather than a static viewer, 3D Agent is the right tool.
+
+### vs. General LLM Chatbots
+
+General-purpose chat interfaces (embedded or hosted) are text-first. They have no awareness of 3D space, no avatar, and no ability to control a scene. 3D Agent's agent layer is purpose-built to bridge LLM outputs to three.js operations: the model can trigger animations, adjust camera position, highlight hotspots, and express emotions through the avatar. It also has native glTF understanding — the LLM can reason about the loaded model's structure via the validator tool.
+
+### vs. Unity / Unreal WebGL Exports
+
+Game engine WebGL exports ship a large runtime (~10–50 MB) and require their own asset pipeline. They are not designed to be embedded as lightweight web components. 3D Agent is browser-native: no game engine, no plugin, no proprietary format. The CDN bundle is compact, the element self-initializes with a script tag, and the viewer runs on standard WebGL 2.0 available in every modern browser. The trade-off is that 3D Agent is not a general-purpose game engine — it is optimized for avatar-centric, interactive AI agent experiences.
+
+---
+
+## Quick Start
+
+The minimum to get a 3D agent on screen is two lines of HTML:
+
+```html
+<script type="module" src="https://cdn.3dagent.vercel.app/agent-3d.js"></script>
+<agent-3d body="https://example.com/avatar.glb"></agent-3d>
+```
+
+This loads your GLB file into a viewer with orbit controls, auto-sized to its container. No server, no build step, no API key required for a basic viewer.
+
+To add an AI brain:
+
+```html
+<agent-3d
+ body="https://example.com/avatar.glb"
+ brain="claude-sonnet-4-6"
+ key-proxy="/api/llm"
+ instructions="You are Aria, a helpful product guide."
+ voice
+></agent-3d>
+```
+
+The `key-proxy` attribute points to a serverless function that injects your API key — the key never touches the client. The `voice` attribute enables microphone input and TTS output.
+
+For a full step-by-step walkthrough, see the [Quick Start guide](./quick-start.md).
+
+---
+
+## What's Next
+
+Once you have the basics working, the following guides go deeper:
+
+- **[Quick Start](./quick-start.md)** — step-by-step from zero to a talking agent
+- **[Embedding Guide](./embedding.md)** — all attributes, modes, events, and the JS API
+- **[Widget Types](./widgets.md)** — Turntable, Animation Gallery, Talking Agent, Passport, Hotspot Tour
+- **[Agent System Overview](./agent-system.md)** — runtime, skill registry, memory, emotion system
+- **[Manifest Reference](../specs/AGENT_MANIFEST.md)** — full JSON schema with examples
+- **[API Reference](./api-reference.md)** — complete JS API for `Agent3DElement`
+
+If you want to look at what's already in the hosted platform — browsing agents, using Widget Studio, or registering on-chain — visit [https://3dagent.vercel.app](https://3dagent.vercel.app).
diff --git a/public/docs/quick-start.md b/public/docs/quick-start.md
new file mode 100644
index 000000000..14f0b53e0
--- /dev/null
+++ b/public/docs/quick-start.md
@@ -0,0 +1,277 @@
+# Quick Start — 3D Agent
+
+Get a live 3D agent on your page in under 10 minutes.
+
+---
+
+## Prerequisites
+
+- **Browser:** Chrome 90+, Firefox 89+, or Safari 15+ (WebGL 2.0 required)
+- **A 3D model:** GLB/glTF file. No model yet? Use the sample avatar below.
+- **Node.js 18+:** Only needed if you're running the dev server or building from source.
+
+---
+
+## Option A — CDN Drop-In (zero build step)
+
+The fastest path. No npm, no bundler, no build step.
+
+```html
+<!DOCTYPE html>
+<html>
+<head>
+ <meta charset="utf-8">
+ <title>My 3D Agent</title>
+ <style>
+ agent-3d { width: 400px; height: 500px; display: block; }
+ </style>
+</head>
+<body>
+ <script type="module" src="https://cdn.3dagent.vercel.app/agent-3d.js"></script>
+ <agent-3d body="https://cdn.3dagent.vercel.app/models/sample-avatar.glb"></agent-3d>
+</body>
+</html>
+```
+
+**What each part does:**
+
+- `<script type="module">` — loads the self-contained ES module bundle. It registers the `<agent-3d>` custom element and bundles Three.js, so no other dependencies are required.
+- `body="..."` — the URL of your GLB file. This is the 3D model the agent displays.
+- The `width` and `height` CSS on `agent-3d` control the canvas size. The element is `display: block` by default at full container width.
+
+**Lazy loading:** The component uses `IntersectionObserver` internally. The 3D scene doesn't boot until the element scrolls into view, so placing it below the fold has zero impact on initial page load. Add `eager` if you want it to start loading immediately:
+
+```html
+<agent-3d eager body="./avatar.glb"></agent-3d>
+```
+
+---
+
+## Option B — npm Install
+
+For projects that have a build step (Vite, Webpack, Create React App, etc.):
+
+```bash
+npm install @3dagent/sdk
+```
+
+### Plain JS / Vite
+
+```js
+import '@3dagent/sdk'; // registers <agent-3d> as a side effect
+
+// The custom element is now available in HTML, or create it programmatically:
+const agent = document.createElement('agent-3d');
+agent.setAttribute('body', './avatar.glb');
+agent.style.cssText = 'width:400px;height:500px;display:block';
+document.body.appendChild(agent);
+```
+
+### React
+
+```jsx
+import '@3dagent/sdk';
+
+export function AgentWidget() {
+ return (
+ <agent-3d
+ body="/avatar.glb"
+ style={{ width: '400px', height: '500px', display: 'block' }}
+ />
+ );
+}
+```
+
+React passes unknown attributes to native elements as-is, so all `<agent-3d>` attributes work without wrappers.
+
+---
+
+## Loading Your Own Model
+
+### Accepted formats
+
+| Format | Notes |
+|--------|-------|
+| **GLB** (binary glTF) | Recommended. Single file, no external dependencies. |
+| **glTF 2.0** (JSON + assets) | Supported; all referenced files must be accessible. |
+| **Draco-compressed meshes** | Supported — decoder loads automatically on first use. |
+| **KTX2 compressed textures** | Supported — reduces GPU memory on compatible hardware. |
+
+GLB is the best choice for embeds: one file, no CORS complexity, maximum compatibility.
+
+### Pointing at a local file
+
+```html
+<!-- Relative path — works when serving from the same origin -->
+<agent-3d body="./models/my-character.glb"></agent-3d>
+
+<!-- Absolute URL — the server must send permissive CORS headers -->
+<agent-3d body="https://assets.example.com/my-character.glb"></agent-3d>
+```
+
+See the [CORS gotcha](#cors) below if your GLB is on a different domain.
+
+---
+
+## Adding an AI Brain
+
+The `brain` attribute turns the 3D viewer into a conversational agent. Pass a Claude model ID:
+
+```html
+<agent-3d
+ body="./avatar.glb"
+ brain="claude-sonnet-4-6"
+ instructions="You are a friendly product guide. Help visitors find what they need."
+ mode="inline"
+></agent-3d>
+```
+
+**Attribute reference:**
+
+| Attribute | What it does |
+|-----------|--------------|
+| `brain` | Claude model ID to use for the LLM brain (`claude-sonnet-4-6`, `claude-opus-4-7`, `claude-haiku-4-5-20251001`). Omit for a viewer-only display with no AI. |
+| `instructions` | System prompt for the agent's personality and role. |
+| `mode` | Layout mode: `inline` (flows with page content), `floating` (fixed bubble in a corner), `fullscreen`, or `section`. Default: `inline`. |
+
+The chat input and microphone button appear automatically when `brain` is set. The agent can play animations, look at the camera, and respond to voice input.
+
+### Loading a named agent by ID
+
+If you've registered an agent on the platform, load it by its UUID instead:
+
+```html
+<agent-3d agent-id="a1b2c3d4-e5f6-7890-abcd-ef1234567890"></agent-3d>
+```
+
+The element fetches the agent manifest — which includes the model URL, instructions, skills, and memory configuration — from the API. No other attributes needed.
+
+---
+
+## Using a Pre-Built Widget
+
+The fastest path to an embeddable 3D experience is an iframe widget. Build one in [Widget Studio](https://3dagent.vercel.app/studio), then embed the snippet:
+
+```html
+<iframe
+ src="https://3dagent.vercel.app/app#widget=wdgt_YOUR_ID&kiosk=true"
+ width="600"
+ height="600"
+ style="border:0;border-radius:12px;max-width:100%"
+ allow="autoplay; xr-spatial-tracking; clipboard-write"
+ loading="lazy"
+></iframe>
+```
+
+### Widget types
+
+| Type | Best for |
+|------|----------|
+| `turntable` | Hero banners, product showcases. Auto-rotate, no UI chrome. |
+| `animation-gallery` | Showcasing a rigged avatar's full animation library. |
+| `talking-agent` | Embodied chat — your agent on your site. |
+| `passport` | On-chain identity card backed by ERC-8004. |
+| `hotspot-tour` | Annotated 3D scenes with clickable points of interest. |
+
+For the full widget API including `postMessage` events, see the [Widget docs](../WIDGETS.md).
+
+---
+
+## Running the Dev Server
+
+For contributors or self-hosters:
+
+```bash
+git clone https://github.com/nirholas/3d-agent.git
+cd 3d-agent
+npm install
+cp .env.example .env # fill in your API keys (see below)
+npm run dev
+```
+
+Open [http://localhost:3000](http://localhost:3000).
+
+### Required vs. optional env vars
+
+Copy `.env.example` to `.env` and fill in:
+
+| Variable | Required? | What it does |
+|----------|-----------|--------------|
+| `DATABASE_URL` | Required | Postgres connection string (Neon serverless recommended). |
+| `JWT_SECRET` | Required | Signs auth tokens. Generate with `openssl rand -base64 64`. |
+| `S3_ENDPOINT` / `S3_ACCESS_KEY_ID` / `S3_SECRET_ACCESS_KEY` / `S3_BUCKET` | Required for uploads | S3-compatible object storage (AWS S3, Cloudflare R2, Backblaze B2). |
+| `ANTHROPIC_API_KEY` | Required for AI chat | LLM backend. Without it, the agent falls back to pattern matching. |
+| `VITE_PRIVY_APP_ID` | Optional | Wallet auth via [Privy](https://privy.io). Needed for on-chain identity. |
+| `UPSTASH_REDIS_REST_URL` / `UPSTASH_REDIS_REST_TOKEN` | Optional | Distributed rate limiting. Falls back to in-memory without it. |
+| `VITE_RPM_SUBDOMAIN` | Optional | Your [Ready Player Me](https://studio.readyplayer.me) subdomain for the avatar creator. Defaults to `demo`. |
+| `AVATURN_API_KEY` | Optional | Photo-to-avatar pipeline via [Avaturn](https://avaturn.me). |
+| `PINATA_JWT` | Optional | IPFS pinning for on-chain agent registration. |
+
+For a local-only dev environment with no uploads or on-chain features, only `DATABASE_URL`, `JWT_SECRET`, and `ANTHROPIC_API_KEY` are strictly needed.
+
+---
+
+## First Steps After Loading
+
+Once your agent is running:
+
+1. **Orbit the model** — click and drag to rotate. Scroll to zoom. Right-click to pan.
+2. **Play animations** — if your GLB has animation clips, open the Animations tab in the GUI panel (top-right corner in the app). Click any clip to play it.
+3. **Edit materials** — the Material editor lets you adjust roughness, metalness, and color without touching code.
+4. **Talk to the agent** — type in the chat input at the bottom, or click the microphone button and speak (HTTPS required for mic access).
+5. **Link a wallet** — click the identity card to connect a wallet and create an on-chain identity for the agent.
+
+---
+
+## Common Gotchas
+
+### CORS
+
+If your GLB is hosted on a different origin than your page, the server must send:
+
+```
+Access-Control-Allow-Origin: *
+```
+
+Without this, the browser will block the fetch and the viewer will show a load error. Solutions:
+- Serve GLBs from the same origin as your page.
+- Use a CDN that sends permissive CORS headers (Cloudflare R2, AWS S3 with a CORS rule).
+- Use the platform's hosted storage — uploads via the Studio are CORS-configured automatically.
+
+### File size
+
+GLB files over ~50MB will load slowly on typical connections. Use [Draco compression](https://github.com/google/draco) to shrink geometry by 10–15×:
+
+```bash
+# Via gltf-transform CLI
+npx gltf-transform draco input.glb output.glb
+```
+
+### HTTPS for voice
+
+The browser's `getUserMedia` API (microphone access for push-to-talk) requires HTTPS. Localhost is exempt. If you're testing voice on a remote server, you must serve over HTTPS.
+
+### CSP (Content Security Policy)
+
+If your page has a strict `Content-Security-Policy`, the script embed needs:
+
+```
+script-src 'self' https://cdn.3dagent.vercel.app;
+```
+
+If you're embedding inside a sandboxed iframe, make sure the parent grants `allow-scripts allow-same-origin`. For sandboxed environments where the script embed won't work, use the iframe widget instead — it runs in its own browsing context and is unaffected by the parent CSP.
+
+### Model doesn't appear
+
+- Open the browser console. A CORS or 404 error will be logged with the URL.
+- Confirm the file is valid GLB by dragging it into [the app](https://3dagent.vercel.app) — it runs the full glTF-Validator.
+- Very large or complex scenes may exceed mobile GPU limits. Test with a simpler model first.
+
+---
+
+## Next Steps
+
+- [Embed Guide](../how-it-works.md) — deep dive on attributes, events, and the JS API
+- [Widget Types](../WIDGETS.md) — full reference for iframe embeds and postMessage
+- [Agent System](../ARCHITECTURE.md) — how the brain, memory, and skills layer work
+- [API Reference](../API.md) — backend endpoints for uploading models and managing agents
diff --git a/public/docs/viewer.md b/public/docs/viewer.md
new file mode 100644
index 000000000..9358c6c49
--- /dev/null
+++ b/public/docs/viewer.md
@@ -0,0 +1,363 @@
+# 3D Viewer
+
+The viewer is the rendering layer of 3D Agent — a full-featured three.js WebGL scene manager. It handles model loading, camera control, animation playback, lighting, and more. You interact with it directly via the `<agent-3d>` web component or programmatically through the `Viewer` class.
+
+## Overview
+
+Core capabilities:
+
+- **Model loading** — glTF 2.0 and GLB files, including Draco-compressed meshes and KTX2 textures
+- **Interactive camera** — orbit, pan, zoom, reset, named camera support
+- **Animation playback** — per-clip play/pause, speed control, loop toggle, blend via AnimationMixer
+- **HDR environments** — three built-in environments for realistic image-based lighting
+- **Material inspection** — per-mesh metalness, roughness, texture maps via dat.gui
+- **Morph targets** — per-target sliders, used by the avatar emotion system for facial animation
+- **Skeleton visualization** — colored bone overlay for animation rig debugging
+- **Screenshot capture** — PNG download via keyboard or API
+- **Stats overlay** — FPS, frame time, memory usage
+- **Wireframe and axes helpers** — grid plane and corner axis gizmo
+
+---
+
+## Loading a Model
+
+### Via HTML attribute
+
+The `src` attribute (or `body` for direct GLB URIs) on `<agent-3d>` loads a model on mount:
+
+```html
+<agent-3d src="https://example.com/avatar.glb"></agent-3d>
+```
+
+For a standalone viewer page, pass the model via URL hash:
+
+```
+https://your-app.com/viewer#model=https://example.com/avatar.glb
+```
+
+### Programmatically
+
+```js
+const el = document.querySelector('agent-3d');
+await el.loadGLB('https://example.com/new-model.glb');
+```
+
+The `load(url, rootPath, assetMap)` method on the underlying `Viewer` instance accepts HTTPS URLs, blob URLs, and data URIs.
+
+### Compressed assets
+
+- **Draco** — mesh compression decoder is auto-loaded when the GLB contains compressed meshes. No configuration needed.
+- **KTX2** — Basis Universal texture decoder is auto-loaded when compressed textures are detected.
+
+Both decoders are fetched via `getDecoders()` in `viewer/internal.js` and wired into the GLTFLoader automatically.
+
+### Load events
+
+The element fires `CustomEvent` on the document:
+
+| Event | Detail |
+|---|---|
+| `agent:load-progress` | `{ phase, pct }` |
+| `agent:ready` | `{ agent, manifest }` |
+| `agent:error` | `{ phase, error }` |
+
+---
+
+## Camera and Navigation
+
+The viewer uses `OrbitControls` for interactive navigation:
+
+| Action | Mouse | Touch |
+|---|---|---|
+| **Orbit** | Left drag | One-finger drag |
+| **Pan** | Right drag | Two-finger drag |
+| **Zoom** | Scroll wheel | Pinch |
+| **Reset / Frame** | Double-click on model | Double-tap |
+
+### Camera state
+
+The active camera is tracked in `viewer.state.camera` (default: `'[default]'`). If the loaded GLB defines named cameras, a **Cameras** dropdown appears in the GUI panel.
+
+Switch programmatically:
+
+```js
+viewer.setCamera('[default]'); // three.js orbit camera
+viewer.setCamera('CameraName'); // named camera from GLB
+```
+
+### URL hash overrides
+
+Deep-link the viewer to a specific camera position:
+
+```
+#cameraPosition=0,1.5,3
+```
+
+Apply a named preset on load:
+
+```
+#preset=assetgenerator
+```
+
+The `assetgenerator` preset uses a hemisphere light instead of the default ambient + directional setup — useful for conformance testing.
+
+### Auto-rotate
+
+Enable continuous rotation via `viewer.state.autoRotate = true` (or toggle in the **Display** GUI folder). Rotation pauses on user interaction and resumes after a short idle.
+
+---
+
+## Animation Playback
+
+### GUI controls
+
+When a GLB contains animation clips, the **Animation** folder appears in the dat.gui panel with:
+
+- A list of all clips — each has a play/pause toggle
+- **Play All** — sequences all clips in order
+- **Speed** slider — 0.1× to 3×
+- **Loop** toggle per clip
+
+### Keyboard shortcut
+
+Press `Space` to toggle playback of all active clips.
+
+### How blending works
+
+The viewer creates a single `THREE.AnimationMixer` per loaded model. Each clip maps to an `AnimationAction`. When you call `playAllClips()`, all actions are activated and blended by the mixer's weight system. For most avatar GLBs, clips are non-overlapping so blending is not visible — but if you activate multiple overlapping clips, they add additively.
+
+The mixer is updated every frame in the `animate()` loop using the clock delta.
+
+### Programmatic control via the element API
+
+```js
+// play a named animation (web component method)
+await el.play('wave');
+
+// play with options
+await el.play('dance', { loop: false });
+```
+
+For agent-controlled playback, the `SceneController` bridge (`src/runtime/scene.js`) exposes `play_clip` as an agent tool.
+
+### External animation panel
+
+When the viewer is embedded inside `<agent-3d>` with animation definitions registered, an external animation panel (`.anim-panel`) renders above the chat UI with buttons for each animation. Buttons cycle through states: default → loading → active. Keyboard shortcuts 1–9 trigger the first nine animations in order.
+
+---
+
+## Environment and Lighting
+
+### Built-in HDR environments
+
+| Name | Description |
+|---|---|
+| `venice-sunset` | Warm golden-hour outdoor lighting |
+| `footprint-court` | Neutral studio lighting |
+| `neutral` | Soft indoor room environment (RoomEnvironment) |
+
+Switch via the **Lighting** GUI folder or set `viewer.state.environment` programmatically, then call `viewer.updateEnvironment()`.
+
+### Lighting controls (GUI → Lighting folder)
+
+| Control | State key | Range |
+|---|---|---|
+| Environment | `environment` | dropdown |
+| Exposure | `exposure` | −10 to 10 |
+| Tone mapping | `toneMapping` | Linear / ACES Filmic |
+| Punctual lights | `punctualLights` | boolean |
+| Ambient intensity | `ambientIntensity` | 0–2 |
+| Ambient color | `ambientColor` | hex color |
+| Directional intensity | `directIntensity` | 0–4 |
+| Directional color | `directColor` | hex color |
+
+### Background
+
+Toggle `viewer.state.background` to show or hide the HDR environment as the scene background. Use `viewer.state.bgColor` to set a solid background color and `viewer.state.transparentBg` to make the canvas background transparent (useful for embedding over custom page backgrounds).
+
+Call `viewer.updateBackground()` after changing these values programmatically.
+
+---
+
+## Material and Texture Inspection
+
+The dat.gui panel exposes per-material properties for every mesh in the scene:
+
+- **Metalness** and **roughness** sliders
+- **Base color** picker
+- Texture map listing: baseColor, normal, metalness/roughness, emissive, occlusion
+- **Transparency** and **double-sided** toggles
+- **Wireframe** toggle (also available at the top-level in Display folder)
+
+Material traversal is deduplicated by UUID (via `traverseMaterials` in `viewer/internal.js`), so shared materials are only listed once.
+
+**Note:** The GUI panel is read-only in viewer mode. Editing material properties in a persistent way requires the Editor workflow. Changes made via the GUI are lost on model reload.
+
+---
+
+## Morph Targets (Blend Shapes)
+
+If the loaded GLB includes morph targets, the **Morph Targets** folder appears in the GUI with a 0.0–1.0 slider per target per mesh.
+
+### Avatar expression targets
+
+The built-in avatar uses morph targets to drive facial expressions. The emotion system sets these targets automatically during speech and in response to conversation context. The targets available on the default avatar are:
+
+| Target | Effect |
+|---|---|
+| `mouthSmile` | Corners of mouth up |
+| `mouthFrown` | Corners of mouth down |
+| `mouthOpen` | Jaw open |
+| `cheekPuff` | Cheek inflation |
+| `browInnerUp` | Inner brow raise |
+| `browOuterUp` | Outer brow raise |
+| `noseSneer` | Nostril flare |
+| `eyeSquint` | Eye squint |
+| `eyesClosed` | Eye close |
+
+These are directly useful for facial animation preview or testing custom expressions before encoding them into an animation clip.
+
+### Programmatic control
+
+To trigger an emotion from the element API:
+
+```js
+el.expressEmotion('celebration', 0.8);
+el.expressEmotion('concern', 1.0);
+```
+
+Supported emotion triggers: `celebration`, `concern`, `curiosity`, `empathy`, `patience`. Weight is 0–1.
+
+---
+
+## Skeleton Visualization
+
+Enable the bone overlay via the **Display** GUI folder → **skeleton** toggle, or set `viewer.state.skeleton = true` and call `viewer.updateDisplay()`.
+
+The overlay renders the armature as colored line segments connecting each bone's head and tail. This is purely additive — it renders on top of the mesh without affecting the model.
+
+Practical uses:
+
+- Verify bone hierarchy after import
+- Debug animation rigs when clips don't behave as expected
+- Identify which bones are available for procedural control (the avatar head-tilt system auto-detects Head/Neck bones by name)
+
+---
+
+## Screenshots
+
+### Via keyboard
+
+Press `P` to capture a screenshot. The viewer renders one frame off-screen and downloads a timestamped PNG:
+
+```
+3d-screenshot-1714000000000.png
+```
+
+A brief white flash overlay confirms the capture.
+
+### Via the GUI
+
+The **Display** folder includes a **Screenshot** button that triggers the same capture.
+
+### Programmatically
+
+```js
+viewer.takeScreenshot();
+```
+
+The implementation in `viewer/screenshot.js` uses `renderer.domElement.toDataURL('image/png')` on a rendered frame and triggers a browser download via a temporary anchor element.
+
+---
+
+## Stats Panel
+
+Toggle the performance overlay with the `S` key or via the **Performance** folder in the dat.gui panel.
+
+The overlay shows three panels (provided by `stats.js`):
+
+| Panel | Metric |
+|---|---|
+| FPS | Frames per second |
+| MS | Milliseconds per frame |
+| MB | Heap memory allocated |
+
+The stats panel updates every frame. Keep it disabled in production embeds — it adds a small continuous DOM mutation cost.
+
+---
+
+## URL Hash Routing
+
+The viewer page reads hash parameters on load to pre-configure the scene:
+
+| Parameter | Effect |
+|---|---|
+| `#model=<url>` | Auto-load this GLB on page load |
+| `#preset=<name>` | Apply environment/lighting preset (`assetgenerator`) |
+| `#cameraPosition=x,y,z` | Set initial camera position |
+| `#register=1` | Open registration modal immediately |
+| `#kiosk=true` | Hide GUI, chat, and input |
+| `#agent=<id>` | Load agent by ID (embed mode) |
+
+Example — load a specific model with a fixed camera position:
+
+```
+https://your-app.com/viewer#model=https://cdn.example.com/robot.glb&cameraPosition=0,1.2,2.5
+```
+
+---
+
+## Supported File Formats
+
+| Format | Support |
+|---|---|
+| GLB (binary glTF 2.0) | Full |
+| glTF 2.0 (JSON + external assets) | Full |
+| Draco compressed meshes | Full (auto-decoded) |
+| KTX2 compressed textures | Full (auto-decoded) |
+| glTF 1.0 | Not supported |
+| FBX | Convert to GLB first — see `scripts/convert-fbx-to-glb.py` |
+| OBJ | Not supported directly |
+
+For FBX conversion, the script at `scripts/convert-fbx-to-glb.py` uses Blender's Python API to batch-convert FBX files to GLB with textures embedded.
+
+---
+
+## Performance Tips
+
+- **Draco-compress meshes** before deploying. Draco typically reduces mesh data 5–10× and the decoder runs on a worker thread, keeping the main thread free during load.
+- **Use KTX2 textures** for GPU-native compressed formats (BC7, ETC2, ASTC). The browser uploads them directly to GPU without CPU decompression, saving memory and load time.
+- **Keep polygon count under 100k** for smooth mobile performance. The default avatar is around 15k triangles.
+- **Disable the stats panel** in production embeds — it triggers continuous layout reads.
+- **Use LOD** if targeting mobile WebXR. three.js `LOD` objects are supported in the glTF 2.0 extension `MSFT_lod`.
+- **Transparent backgrounds** (`viewer.state.transparentBg = true`) disable some GPU optimizations. Only use when compositing the canvas over page content.
+- **Auto-rotate** triggers a continuous `requestAnimationFrame` loop even when nothing is changing. Disable it for idle embeds to reduce CPU/battery usage.
+
+---
+
+## Viewer State Reference
+
+The `viewer.state` object is the source of truth for all viewer settings. Reading and writing it directly (followed by the appropriate `update*()` call) is the lowest-level integration path.
+
+| Key | Type | Default | Update method |
+|---|---|---|---|
+| `environment` | string | `'venice-sunset'` | `updateEnvironment()` |
+| `background` | boolean | `false` | `updateBackground()` |
+| `bgColor` | hex string | `'#000000'` | `updateBackground()` |
+| `transparentBg` | boolean | `false` | `updateBackground()` |
+| `playbackSpeed` | number | `1.0` | — (applied per frame) |
+| `actionStates` | object | `{}` | `setClips()` |
+| `wireframe` | boolean | `false` | `updateDisplay()` |
+| `skeleton` | boolean | `false` | `updateDisplay()` |
+| `grid` | boolean | `false` | `updateDisplay()` |
+| `autoRotate` | boolean | `false` | `updateDisplay()` |
+| `exposure` | number | `0` | `updateLights()` |
+| `ambientIntensity` | number | `0.3` | `updateLights()` |
+| `ambientColor` | hex string | `'#FFFFFF'` | `updateLights()` |
+| `directIntensity` | number | `0.8` | `updateLights()` |
+| `directColor` | hex string | `'#FFFFFF'` | `updateLights()` |
+| `punctualLights` | boolean | `true` | `updateLights()` |
+| `camera` | string | `'[default]'` | `setCamera()` |
+| `followMode` | string | `'none'` | — |
+
+State is persisted to `localStorage` per agent ID when `attachScenePrefs(agentId)` is called. Changes are broadcast via `notifyScenePrefChange()`.
diff --git a/public/features/features.js b/public/features/features.js
index 959517a6e..16ea6547f 100644
--- a/public/features/features.js
+++ b/public/features/features.js
@@ -234,7 +234,7 @@ function initStarFields() {
for (const canvas of ROOT.querySelectorAll('[data-role="star-canvas"]')) {
const dpr = Math.min(window.devicePixelRatio || 1, 2);
const w = window.innerWidth * dpr;
- const h = window.innerHeight * 4 * dpr; // tall enough to cover 140vh act
+ const h = window.innerHeight * 8 * dpr; // double-tall so 120s drift loops cleanly
canvas.width = w;
canvas.height = h;
const ctx = canvas.getContext('2d');
@@ -265,6 +265,30 @@ function initStarFields() {
}
}
+// ── Progress dots ────────────────────────────────────────────────────────
+
+function setupProgressDots() {
+ const dots = ROOT.querySelectorAll('.act-dot[data-act]');
+ const acts = ROOT.querySelectorAll('.parallax-act[data-act]');
+ const scroll = ROOT.querySelector('.parallax');
+ if (!dots.length || !acts.length || !scroll) return;
+
+ const io = new IntersectionObserver(
+ (entries) => {
+ for (const entry of entries) {
+ if (!entry.isIntersecting) continue;
+ const actNum = entry.target.dataset.act;
+ dots.forEach((d) => {
+ d.dataset.active = d.dataset.act === actNum ? 'true' : 'false';
+ });
+ }
+ },
+ { root: scroll, threshold: 0.5 },
+ );
+
+ acts.forEach((act) => io.observe(act));
+}
+
// ── Boot ─────────────────────────────────────────────────────────────────
function init() {
@@ -274,6 +298,7 @@ function init() {
setupLazyBoot();
setupEmotionChips();
setupCopyEmbed();
+ setupProgressDots();
loadOnChainAgent();
}
diff --git a/public/features/index.html b/public/features/index.html
index 15cd8bdaa..11a587d26 100644
--- a/public/features/index.html
+++ b/public/features/index.html
@@ -237,6 +237,7 @@
id="act-onchain"
aria-labelledby="act3-title"
>
+ <div class="act-warp act-warp--mint" aria-hidden="true"></div>
<div class="parallax-layer" style="--depth: 10" aria-hidden="true">
<div class="layer-bg layer-bg--mint"></div>
<canvas class="layer-stars-canvas" data-role="star-canvas" data-tint="110,231,183" data-count="240"></canvas>
@@ -263,6 +264,9 @@
</div>
</div>
</div>
+ <div class="parallax-layer" style="--depth: 0.5" aria-hidden="true">
+ <div class="layer-vignette"></div>
+ </div>
<div class="act-content act-content--bottom">
<div class="act-eyebrow">
@@ -355,6 +359,12 @@
</section>
</main>
+ <nav class="act-nav" aria-label="Section navigation">
+ <a href="#main-content" class="act-dot" data-act="1" data-active="true" aria-label="Act 1: Live 3D"></a>
+ <a href="#act-empathy" class="act-dot" data-act="2" aria-label="Act 2: Empathy layer"></a>
+ <a href="#act-onchain" class="act-dot" data-act="3" aria-label="Act 3: On-chain identity"></a>
+ </nav>
+
<script type="module" src="/features/features.js"></script>
<script>
try {
diff --git a/public/widgets-gallery/gallery.css b/public/widgets-gallery/gallery.css
index b8d2e99ef..1fdd5518f 100644
--- a/public/widgets-gallery/gallery.css
+++ b/public/widgets-gallery/gallery.css
@@ -1,4 +1,4 @@
-/* Widget gallery — matches root style.css tokens. No new design system. */
+/* Widget gallery — matches root style.css tokens. */
html,
body.gallery-body {
@@ -7,6 +7,8 @@ body.gallery-body {
min-height: 100vh;
}
+/* ── Header ─────────────────────────────────────────────────────────────────── */
+
.gallery-header {
display: flex;
align-items: center;
@@ -15,15 +17,18 @@ body.gallery-body {
border-bottom: 1px solid rgba(255, 255, 255, 0.06);
background: rgba(0, 0, 0, 0.5);
backdrop-filter: blur(8px);
+ -webkit-backdrop-filter: blur(8px);
position: sticky;
top: 0;
z-index: 10;
}
+
.gallery-header h1 {
margin: 0;
font-size: var(--text-lg);
font-weight: 600;
}
+
.gallery-header h1 a {
color: inherit;
text-decoration: none;
@@ -31,12 +36,14 @@ body.gallery-body {
align-items: center;
gap: var(--space-xs);
}
+
.gallery-header .features-nav {
display: flex;
gap: var(--space-md);
align-items: center;
font-size: var(--text-sm);
}
+
.gallery-header .features-nav a {
color: rgba(229, 229, 229, 0.65);
text-decoration: none;
@@ -46,12 +53,15 @@ body.gallery-body {
color 0.15s,
background 0.15s;
}
+
.gallery-header .features-nav a:hover,
.gallery-header .features-nav a.active {
color: #fff;
background: rgba(255, 255, 255, 0.06);
}
+/* ── Main layout ─────────────────────────────────────────────────────────────── */
+
.gallery-main {
max-width: 1400px;
margin: 0 auto;
@@ -61,6 +71,8 @@ body.gallery-body {
gap: var(--space-2xl);
}
+/* ── Hero ────────────────────────────────────────────────────────────────────── */
+
.gallery-hero {
text-align: center;
display: flex;
@@ -68,6 +80,7 @@ body.gallery-body {
gap: var(--space-md);
align-items: center;
}
+
.gallery-hero .eyebrow {
margin: 0;
font-size: var(--text-sm);
@@ -76,6 +89,7 @@ body.gallery-body {
color: var(--accent);
font-weight: 600;
}
+
.gallery-hero h2 {
margin: 0;
font-family: var(--font-display);
@@ -84,6 +98,7 @@ body.gallery-body {
letter-spacing: -1px;
line-height: 1.1;
}
+
.gallery-hero .lede {
max-width: 60ch;
margin: 0;
@@ -91,6 +106,36 @@ body.gallery-body {
color: rgba(229, 229, 229, 0.7);
line-height: var(--leading-normal);
}
+
+.hero-badges {
+ display: flex;
+ gap: var(--space-sm);
+ flex-wrap: wrap;
+ justify-content: center;
+ margin-top: var(--space-xs);
+}
+
+.hero-badge {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.35rem;
+ padding: 0.3rem 0.75rem;
+ border-radius: 999px;
+ font-size: var(--text-sm);
+ font-weight: 500;
+ background: rgba(255, 255, 255, 0.05);
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ color: rgba(229, 229, 229, 0.8);
+}
+
+.hero-badge-dot {
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: var(--accent);
+ box-shadow: 0 0 8px var(--accent);
+}
+
.cta-row {
display: flex;
gap: var(--space-sm);
@@ -99,6 +144,8 @@ body.gallery-body {
margin-top: var(--space-sm);
}
+/* ── Buttons ─────────────────────────────────────────────────────────────────── */
+
.btn {
display: inline-flex;
align-items: center;
@@ -116,61 +163,204 @@ body.gallery-body {
background 0.15s,
border-color 0.15s;
}
+
.btn:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
+
.btn-primary {
background: var(--accent);
color: #fff;
}
+
.btn-primary:hover {
transform: translateY(-1px);
background: #7c3aed;
}
+
.btn-ghost {
background: transparent;
color: rgba(229, 229, 229, 0.85);
border-color: rgba(255, 255, 255, 0.18);
}
+
.btn-ghost:hover {
background: rgba(255, 255, 255, 0.06);
}
+/* ── Filter bar ──────────────────────────────────────────────────────────────── */
+
+.filter-bar {
+ display: flex;
+ gap: var(--space-sm);
+ flex-wrap: wrap;
+ align-items: center;
+}
+
+.filter-btn {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.4rem;
+ padding: 0.45rem 1rem;
+ border-radius: 999px;
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ background: rgba(255, 255, 255, 0.04);
+ color: rgba(229, 229, 229, 0.7);
+ font-family: var(--font-body);
+ font-size: var(--text-sm);
+ font-weight: 500;
+ cursor: pointer;
+ transition:
+ background 0.15s,
+ border-color 0.15s,
+ color 0.15s;
+ white-space: nowrap;
+}
+
+.filter-btn::before {
+ content: '';
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: var(--type-color, transparent);
+ display: none;
+}
+
+.filter-btn[data-type]::before {
+ display: block;
+}
+
+.filter-btn:hover {
+ background: rgba(255, 255, 255, 0.08);
+ color: #fff;
+ border-color: rgba(255, 255, 255, 0.2);
+}
+
+.filter-btn[data-active='true'] {
+ background: rgba(255, 255, 255, 0.1);
+ border-color: var(--type-color, rgba(255, 255, 255, 0.4));
+ color: #fff;
+}
+
+.filter-btn:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+}
+
+/* ── Gallery grid ────────────────────────────────────────────────────────────── */
+
.gallery-grid {
display: flex;
flex-direction: column;
gap: var(--space-2xl);
}
+
.gallery-grid .loading {
color: rgba(229, 229, 229, 0.55);
text-align: center;
}
+/* ── Skeleton shimmer ────────────────────────────────────────────────────────── */
+
+@keyframes shimmer {
+ 0% {
+ background-position: -600px 0;
+ }
+ 100% {
+ background-position: 600px 0;
+ }
+}
+
+.skel-block,
+.skel-line {
+ border-radius: var(--radius-md);
+ background: linear-gradient(90deg, rgba(255, 255, 255, 0.04) 25%, rgba(255, 255, 255, 0.08) 50%, rgba(255, 255, 255, 0.04) 75%);
+ background-size: 600px 100%;
+ animation: shimmer 1.6s infinite linear;
+}
+
+.skel-row {
+ display: flex;
+ gap: var(--space-xs);
+ margin-top: var(--space-sm);
+}
+
+.showcase-skeleton .showcase-frame {
+ min-height: 400px;
+}
+
+/* ── Showcase card ───────────────────────────────────────────────────────────── */
+
.showcase {
display: grid;
- grid-template-columns: minmax(0, 1fr) minmax(280px, 380px);
+ grid-template-columns: minmax(0, 1fr) minmax(280px, 400px);
gap: var(--space-xl);
align-items: start;
padding: var(--space-xl);
background: rgba(255, 255, 255, 0.025);
border: 1px solid rgba(255, 255, 255, 0.06);
border-radius: var(--radius-lg);
+ /* scroll-in: start invisible */
+ opacity: 0;
+ transform: translateY(28px);
+ transition:
+ opacity 0.45s ease,
+ transform 0.45s ease,
+ border-color 0.2s;
+}
+
+.showcase.sc-visible {
+ opacity: 1;
+ transform: none;
}
-@media (max-width: 820px) {
+
+/* Skeleton cards skip the animation */
+.showcase-skeleton {
+ opacity: 1 !important;
+ transform: none !important;
+ transition: none !important;
+}
+
+.showcase:hover {
+ border-color: rgba(255, 255, 255, 0.1);
+}
+
+/* Alternate: even cards flip frame to right */
+.showcase:not(.showcase-skeleton):nth-child(even) {
+ direction: ltr; /* reset if parent has rtl */
+}
+
+.showcase:not(.showcase-skeleton):nth-child(even) .showcase-frame {
+ order: 2;
+}
+
+.showcase:not(.showcase-skeleton):nth-child(even) .showcase-meta {
+ order: 1;
+}
+
+@media (max-width: 900px) {
.showcase {
grid-template-columns: 1fr;
}
+
+ .showcase:not(.showcase-skeleton):nth-child(even) .showcase-frame,
+ .showcase:not(.showcase-skeleton):nth-child(even) .showcase-meta {
+ order: unset;
+ }
}
+/* ── Showcase frame ──────────────────────────────────────────────────────────── */
+
.showcase-frame {
position: relative;
border-radius: var(--radius-md);
overflow: hidden;
background: #050505;
aspect-ratio: 1 / 1;
- min-height: 480px;
+ min-height: 420px;
}
+
.showcase-frame iframe {
position: absolute;
inset: 0;
@@ -180,32 +370,143 @@ body.gallery-body {
display: block;
}
+/* ── Click-to-load placeholder ───────────────────────────────────────────────── */
+
+.frame-placeholder {
+ position: absolute;
+ inset: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background:
+ radial-gradient(ellipse at 30% 40%, color-mix(in srgb, var(--type-color, #8b5cf6) 12%, transparent) 0%, transparent 70%),
+ radial-gradient(ellipse at 75% 70%, color-mix(in srgb, var(--type-color, #8b5cf6) 6%, transparent) 0%, transparent 60%),
+ #050505;
+ transition: opacity 0.3s ease;
+}
+
+.frame-placeholder--loading {
+ opacity: 0.4;
+ pointer-events: none;
+}
+
+.frame-ph-inner {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 0.75rem;
+ text-align: center;
+}
+
+.play-btn {
+ width: 64px;
+ height: 64px;
+ border-radius: 50%;
+ background: rgba(255, 255, 255, 0.08);
+ border: 1px solid rgba(255, 255, 255, 0.15);
+ color: #fff;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ cursor: pointer;
+ transition:
+ background 0.15s,
+ transform 0.15s,
+ border-color 0.15s;
+}
+
+.play-btn:hover,
+.play-btn:focus-visible {
+ background: color-mix(in srgb, var(--type-color, #8b5cf6) 30%, rgba(255, 255, 255, 0.12));
+ border-color: var(--type-color, rgba(255, 255, 255, 0.4));
+ transform: scale(1.08);
+ outline: none;
+}
+
+.frame-ph-label {
+ font-family: var(--font-display);
+ font-size: var(--text-base);
+ font-weight: 500;
+ color: rgba(229, 229, 229, 0.75);
+}
+
+.frame-ph-dim {
+ font-family: var(--font-mono);
+ font-size: var(--text-xs);
+ color: rgba(229, 229, 229, 0.35);
+ letter-spacing: 0.05em;
+}
+
+/* ── Showcase meta ───────────────────────────────────────────────────────────── */
+
.showcase-meta {
display: flex;
flex-direction: column;
gap: var(--space-md);
}
-.showcase-meta .type-tag {
- display: inline-block;
+
+.type-tag {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.35rem;
font-size: var(--text-xs);
- letter-spacing: 3px;
+ letter-spacing: 2.5px;
text-transform: uppercase;
- color: var(--accent);
+ color: var(--type-color, var(--accent));
font-weight: 600;
+ width: fit-content;
}
+
+.type-tag::before {
+ content: '';
+ width: 5px;
+ height: 5px;
+ border-radius: 50%;
+ background: var(--type-color, var(--accent));
+ box-shadow: 0 0 6px var(--type-color, var(--accent));
+}
+
.showcase-meta h3 {
margin: 0;
font-family: var(--font-display);
font-size: var(--text-xl);
font-weight: 400;
letter-spacing: -0.5px;
+ line-height: 1.2;
}
-.showcase-meta p {
+
+.showcase-meta > p {
margin: 0;
color: rgba(229, 229, 229, 0.7);
line-height: var(--leading-normal);
}
+/* Feature list inside card */
+.widget-features {
+ margin: 0;
+ padding: 0;
+ list-style: none;
+ display: flex;
+ flex-direction: column;
+ gap: 0.3rem;
+}
+
+.widget-features li {
+ font-size: var(--text-sm);
+ color: rgba(229, 229, 229, 0.6);
+ padding-left: 1.1rem;
+ position: relative;
+}
+
+.widget-features li::before {
+ content: '›';
+ position: absolute;
+ left: 0;
+ color: var(--accent);
+}
+
+/* ── Snippet ─────────────────────────────────────────────────────────────────── */
+
.snippet {
position: relative;
background: #0a0a0a;
@@ -218,20 +519,25 @@ body.gallery-body {
white-space: pre-wrap;
word-break: break-all;
overflow-x: auto;
+ line-height: 1.6;
}
+
.snippet code {
display: block;
}
+
+/* ── Snippet action row ───────────────────────────────────────────────────────── */
+
.snippet-row {
display: flex;
gap: var(--space-xs);
flex-wrap: wrap;
- margin-top: var(--space-sm);
}
+
.snippet-row button,
.snippet-row a {
flex: 1 1 auto;
- min-width: 120px;
+ min-width: 110px;
padding: var(--space-xs) var(--space-sm);
font-size: var(--text-sm);
background: rgba(255, 255, 255, 0.05);
@@ -242,31 +548,52 @@ body.gallery-body {
text-align: center;
text-decoration: none;
font-family: var(--font-body);
- transition: background 0.15s;
+ transition:
+ background 0.15s,
+ border-color 0.15s;
}
+
.snippet-row button:hover,
.snippet-row a:hover {
background: rgba(255, 255, 255, 0.1);
+ border-color: rgba(255, 255, 255, 0.2);
}
+
.snippet-row button:focus-visible,
.snippet-row a:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
+
.snippet-row .copied {
background: var(--accent-soft);
border-color: var(--accent);
+ color: #c4b5fd;
}
+/* ── Error state ─────────────────────────────────────────────────────────────── */
+
.error-state {
- padding: var(--space-md);
+ display: flex;
+ align-items: flex-start;
+ gap: var(--space-sm);
+ padding: var(--space-md) var(--space-lg);
background: rgba(255, 80, 80, 0.06);
border: 1px solid rgba(255, 80, 80, 0.2);
border-radius: var(--radius-md);
color: rgba(255, 200, 200, 0.9);
font-size: var(--text-sm);
+ line-height: var(--leading-normal);
}
+.error-state code {
+ font-family: var(--font-mono);
+ font-size: var(--text-xs);
+ color: rgba(255, 180, 180, 0.8);
+}
+
+/* ── Bottom CTA ──────────────────────────────────────────────────────────────── */
+
.gallery-cta {
text-align: center;
padding: var(--space-2xl) var(--space-lg);
@@ -278,17 +605,21 @@ body.gallery-body {
align-items: center;
gap: var(--space-md);
}
+
.gallery-cta h3 {
margin: 0;
font-family: var(--font-display);
font-size: var(--text-xl);
font-weight: 400;
}
+
.gallery-cta p {
margin: 0;
color: rgba(229, 229, 229, 0.7);
}
+/* ── Footer ──────────────────────────────────────────────────────────────────── */
+
.gallery-footer {
padding: var(--space-lg);
text-align: center;
@@ -296,22 +627,72 @@ body.gallery-body {
font-size: var(--text-sm);
border-top: 1px solid rgba(255, 255, 255, 0.06);
}
+
.gallery-footer a {
color: rgba(229, 229, 229, 0.7);
text-decoration: none;
margin: 0 var(--space-xs);
}
+
.gallery-footer a:hover {
color: #fff;
}
+/* ── Responsive ──────────────────────────────────────────────────────────────── */
+
+@media (max-width: 600px) {
+ .gallery-header {
+ flex-wrap: wrap;
+ gap: var(--space-sm);
+ }
+
+ .gallery-header .features-nav {
+ gap: var(--space-sm);
+ font-size: var(--text-xs);
+ }
+
+ .gallery-hero h2 {
+ font-size: var(--text-xl);
+ }
+
+ .filter-bar {
+ gap: var(--space-xs);
+ }
+
+ .filter-btn {
+ font-size: var(--text-xs);
+ padding: 0.35rem 0.75rem;
+ }
+
+ .showcase-frame {
+ min-height: 300px;
+ }
+}
+
+/* ── Reduced motion ──────────────────────────────────────────────────────────── */
+
@media (prefers-reduced-motion: reduce) {
.btn,
.snippet-row button,
- .snippet-row a {
+ .snippet-row a,
+ .filter-btn,
+ .play-btn,
+ .showcase {
transition: none;
+ animation: none;
}
+
.btn-primary:hover {
transform: none;
}
+
+ .showcase {
+ opacity: 1;
+ transform: none;
+ }
+
+ .skel-block,
+ .skel-line {
+ animation: none;
+ }
}
diff --git a/public/widgets-gallery/gallery.js b/public/widgets-gallery/gallery.js
index f3ed53f2a..c0fa1c4f2 100644
--- a/public/widgets-gallery/gallery.js
+++ b/public/widgets-gallery/gallery.js
@@ -1,17 +1,42 @@
-// Widget gallery — native DOM, no framework. Renders showcase cards from
-// /widgets-gallery/showcase.json with a real iframe and a copy-paste snippet
-// per widget. If a showcase id isn't a real widget yet, the iframe shows the
-// /w/<id> fallback page; the copy snippet still works once the id is filled in.
+// Widget gallery — native DOM, no framework.
+// Renders showcase cards from /widgets-gallery/showcase.json with:
+// - skeleton loader while fetching
+// - filter bar by widget type
+// - click-to-load (+ auto-load at 50% visibility) iframes
+// - scroll-in fade animation per card
+// - responsive embed snippet
const GRID_EL = document.getElementById('gallery-grid');
-
const ORIGIN = location.origin;
+const TYPE_COLORS = {
+ turntable: '#f59e0b',
+ 'animation-gallery': '#3b82f6',
+ 'talking-agent': '#10b981',
+ passport: '#a78bfa',
+ 'hotspot-tour': '#f97316',
+};
+
+// Fade-in cards as they scroll into view
+const cardObserver = new IntersectionObserver(
+ (entries) => {
+ entries.forEach((e) => {
+ if (e.isIntersecting) {
+ e.target.classList.add('sc-visible');
+ cardObserver.unobserve(e.target);
+ }
+ });
+ },
+ { threshold: 0.06 },
+);
+
(async function init() {
+ showSkeleton(3);
+
let showcase;
try {
const res = await fetch('/widgets-gallery/showcase.json', { cache: 'no-cache' });
- if (!res.ok) throw new Error(`showcase.json ${res.status}`);
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
showcase = await res.json();
} catch (err) {
GRID_EL.innerHTML = '';
@@ -20,39 +45,178 @@ const ORIGIN = location.origin;
return;
}
+ const widgets = showcase.widgets || [];
+
+ renderFilters(widgets);
+ updateHeroCount(widgets.length);
+
GRID_EL.innerHTML = '';
- for (const w of showcase.widgets || []) {
- GRID_EL.appendChild(renderShowcase(w));
+ for (const w of widgets) {
+ const card = renderShowcase(w);
+ GRID_EL.appendChild(card);
+ cardObserver.observe(card);
}
GRID_EL.removeAttribute('aria-busy');
})();
+// ─── Skeleton ────────────────────────────────────────────────────────────────
+
+function showSkeleton(n) {
+ GRID_EL.innerHTML = '';
+ for (let i = 0; i < n; i++) {
+ const s = document.createElement('div');
+ s.className = 'showcase showcase-skeleton';
+ s.innerHTML = `
+ <div class="showcase-frame skel-block"></div>
+ <div class="showcase-meta">
+ <div class="skel-line" style="width:6rem;height:1rem"></div>
+ <div class="skel-line" style="width:70%;height:1.6rem;margin-top:.5rem"></div>
+ <div class="skel-line" style="width:90%;height:.9rem;margin-top:.75rem"></div>
+ <div class="skel-line" style="width:75%;height:.9rem;margin-top:.4rem"></div>
+ <div class="skel-line" style="height:5rem;margin-top:1.2rem"></div>
+ <div class="skel-row">
+ <div class="skel-line" style="flex:1;height:2rem"></div>
+ <div class="skel-line" style="flex:1;height:2rem"></div>
+ <div class="skel-line" style="flex:1;height:2rem"></div>
+ </div>
+ </div>`;
+ GRID_EL.appendChild(s);
+ }
+}
+
+// ─── Filter bar ──────────────────────────────────────────────────────────────
+
+function renderFilters(widgets) {
+ const types = [...new Set(widgets.map((w) => w.type))];
+
+ const bar = document.createElement('div');
+ bar.className = 'filter-bar';
+ bar.setAttribute('role', 'group');
+ bar.setAttribute('aria-label', 'Filter by widget type');
+
+ const allBtn = makeFilterBtn('All', null, true);
+ bar.appendChild(allBtn);
+ for (const t of types) {
+ bar.appendChild(makeFilterBtn(t.replace(/-/g, '‑'), t, false)); // non-breaking hyphens
+ }
+
+ bar.addEventListener('click', (e) => {
+ const btn = e.target.closest('.filter-btn');
+ if (!btn) return;
+ bar.querySelectorAll('.filter-btn').forEach((b) => b.removeAttribute('data-active'));
+ btn.setAttribute('data-active', 'true');
+ const type = btn.dataset.type || null;
+ let visIdx = 0;
+ document.querySelectorAll('#gallery-grid .showcase:not(.showcase-skeleton)').forEach((card) => {
+ const show = !type || card.dataset.type === type;
+ card.hidden = !show;
+ if (show) {
+ // Re-stagger visible cards for alternating layout
+ card.style.setProperty('--card-idx', visIdx++);
+ }
+ });
+ GRID_EL.dataset.filtered = type ? 'true' : '';
+ });
+
+ GRID_EL.before(bar);
+}
+
+function makeFilterBtn(label, type, active) {
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.className = 'filter-btn';
+ btn.textContent = label;
+ if (type) {
+ btn.dataset.type = type;
+ const c = TYPE_COLORS[type];
+ if (c) btn.style.setProperty('--type-color', c);
+ }
+ if (active) btn.setAttribute('data-active', 'true');
+ return btn;
+}
+
+// ─── Hero count ──────────────────────────────────────────────────────────────
+
+function updateHeroCount(n) {
+ const el = document.getElementById('widget-count');
+ if (el) el.textContent = n;
+}
+
+// ─── Showcase card ───────────────────────────────────────────────────────────
+
function renderShowcase(w) {
const root = document.createElement('article');
root.className = 'showcase';
+ root.dataset.type = w.type;
root.setAttribute('aria-labelledby', `sc-${w.id}-title`);
const widgetUrl = `${ORIGIN}/app#widget=${encodeURIComponent(w.id)}&kiosk=true`;
const pageUrl = `${ORIGIN}/w/${encodeURIComponent(w.id)}`;
- const snippet = `<iframe src="${widgetUrl}" width="${w.width}" height="${w.height}" style="border:0;border-radius:12px;max-width:100%" allow="autoplay; xr-spatial-tracking; clipboard-write" loading="lazy"></iframe>`;
+ // Responsive snippet — adapts to container, caps at native size
+ const snippet =
+ `<iframe src="${widgetUrl}" ` +
+ `style="width:100%;aspect-ratio:${w.width}/${w.height};border:0;border-radius:12px;max-width:${w.width}px" ` +
+ `allow="autoplay; xr-spatial-tracking; clipboard-write" loading="lazy"></iframe>`;
+
+ // ── Frame ──
const frame = document.createElement('div');
frame.className = 'showcase-frame';
frame.style.aspectRatio = `${w.width} / ${w.height}`;
- const iframe = document.createElement('iframe');
- iframe.src = widgetUrl;
- iframe.title = `${w.label} demo`;
- iframe.loading = 'lazy';
- iframe.allow = 'autoplay; xr-spatial-tracking; clipboard-write';
- frame.appendChild(iframe);
+ const color = TYPE_COLORS[w.type] || 'var(--accent)';
+ const placeholder = document.createElement('div');
+ placeholder.className = 'frame-placeholder';
+ placeholder.style.setProperty('--type-color', color);
+ placeholder.innerHTML = `
+ <div class="frame-ph-inner">
+ <button type="button" class="play-btn" aria-label="Load ${w.label} preview">
+ <svg viewBox="0 0 24 24" width="28" height="28" fill="currentColor" aria-hidden="true">
+ <path d="M8 5v14l11-7z"/>
+ </svg>
+ </button>
+ <span class="frame-ph-label">${w.label}</span>
+ <span class="frame-ph-dim">${w.width} × ${w.height}</span>
+ </div>`;
+
+ let iframeLoaded = false;
+ const loadIframe = () => {
+ if (iframeLoaded) return;
+ iframeLoaded = true;
+ placeholder.classList.add('frame-placeholder--loading');
+ const iframe = document.createElement('iframe');
+ iframe.src = widgetUrl;
+ iframe.title = `${w.label} demo`;
+ iframe.loading = 'eager';
+ iframe.allow = 'autoplay; xr-spatial-tracking; clipboard-write';
+ iframe.onload = () => placeholder.remove();
+ frame.appendChild(iframe);
+ };
+
+ placeholder.querySelector('.play-btn').addEventListener('click', loadIframe);
+ frame.appendChild(placeholder);
+
+ // Auto-load when the frame is 50 % visible for 1 s
+ const autoObs = new IntersectionObserver(
+ (entries) => {
+ if (entries[0].isIntersecting) {
+ setTimeout(() => loadIframe(), 1000);
+ autoObs.disconnect();
+ }
+ },
+ { threshold: 0.5 },
+ );
+ autoObs.observe(frame);
+
+ // ── Meta ──
const meta = document.createElement('div');
meta.className = 'showcase-meta';
const tag = document.createElement('span');
tag.className = 'type-tag';
- tag.textContent = w.type;
+ tag.textContent = w.type.replace(/-/g, ' ');
+ tag.style.setProperty('--type-color', color);
meta.appendChild(tag);
const h = document.createElement('h3');
@@ -64,6 +228,17 @@ function renderShowcase(w) {
desc.textContent = w.tagline;
meta.appendChild(desc);
+ if (w.features?.length) {
+ const ul = document.createElement('ul');
+ ul.className = 'widget-features';
+ for (const f of w.features) {
+ const li = document.createElement('li');
+ li.textContent = f;
+ ul.appendChild(li);
+ }
+ meta.appendChild(ul);
+ }
+
const code = document.createElement('pre');
code.className = 'snippet';
code.setAttribute('aria-label', 'Embed snippet');
@@ -75,24 +250,20 @@ function renderShowcase(w) {
const row = document.createElement('div');
row.className = 'snippet-row';
- const copyBtn = document.createElement('button');
- copyBtn.type = 'button';
- copyBtn.textContent = 'Copy iframe';
- copyBtn.setAttribute('aria-label', `Copy embed snippet for ${w.label}`);
+ const copyBtn = makeActionBtn('Copy iframe', `Copy embed snippet for ${w.label}`);
copyBtn.addEventListener('click', () => copy(snippet, copyBtn));
row.appendChild(copyBtn);
- const copyUrlBtn = document.createElement('button');
- copyUrlBtn.type = 'button';
- copyUrlBtn.textContent = 'Copy URL';
- copyUrlBtn.setAttribute('aria-label', `Copy shareable URL for ${w.label}`);
+ const copyUrlBtn = makeActionBtn('Copy URL', `Copy shareable URL for ${w.label}`);
copyUrlBtn.addEventListener('click', () => copy(pageUrl, copyUrlBtn));
row.appendChild(copyUrlBtn);
const studio = document.createElement('a');
studio.href = `/studio?template=${encodeURIComponent(w.id)}`;
studio.textContent = 'Open in Studio';
- studio.setAttribute('aria-label', `Clone ${w.label} into the Studio`);
+ studio.target = '_blank';
+ studio.rel = 'noopener noreferrer';
+ studio.setAttribute('aria-label', `Clone ${w.label} in Studio`);
row.appendChild(studio);
meta.appendChild(row);
@@ -102,15 +273,23 @@ function renderShowcase(w) {
return root;
}
+// ─── Helpers ─────────────────────────────────────────────────────────────────
+
+function makeActionBtn(text, ariaLabel) {
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.textContent = text;
+ btn.setAttribute('aria-label', ariaLabel);
+ return btn;
+}
+
async function copy(text, btn) {
try {
await navigator.clipboard.writeText(text);
} catch {
- // Fallback for old browsers
const ta = document.createElement('textarea');
ta.value = text;
- ta.style.position = 'fixed';
- ta.style.opacity = '0';
+ ta.style.cssText = 'position:fixed;opacity:0;pointer-events:none';
document.body.appendChild(ta);
ta.select();
try {
@@ -130,6 +309,12 @@ async function copy(text, btn) {
function errorEl(msg, detail) {
const e = document.createElement('div');
e.className = 'error-state';
- e.textContent = detail ? `${msg} (${detail})` : msg;
+ e.innerHTML = `
+ <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true" style="flex-shrink:0">
+ <circle cx="12" cy="12" r="10"/>
+ <line x1="12" y1="8" x2="12" y2="12"/>
+ <circle cx="12" cy="16" r=".5" fill="currentColor"/>
+ </svg>
+ <span>${msg}${detail ? ` — <code>${detail}</code>` : ''}</span>`;
return e;
}
diff --git a/public/widgets-gallery/index.html b/public/widgets-gallery/index.html
index 7fc6aa717..f3c1718a6 100644
--- a/public/widgets-gallery/index.html
+++ b/public/widgets-gallery/index.html
@@ -53,6 +53,14 @@
Drop a 3D agent — turntable, talking head, on-chain passport, or guided tour —
into any site, blog, or Notion doc with one line of HTML.
</p>
+ <div class="hero-badges">
+ <span class="hero-badge">
+ <span class="hero-badge-dot"></span>
+ <span><span id="widget-count">5</span> widget types</span>
+ </span>
+ <span class="hero-badge">One line of HTML</span>
+ <span class="hero-badge">Free for personal use</span>
+ </div>
<div class="cta-row">
<a class="btn btn-primary" href="/studio">Create yours — it's free</a>
<a class="btn btn-ghost" href="/docs/widgets">Read the docs</a>
diff --git a/public/widgets-gallery/showcase.json b/public/widgets-gallery/showcase.json
index d99143ace..c75e46d12 100644
--- a/public/widgets-gallery/showcase.json
+++ b/public/widgets-gallery/showcase.json
@@ -1,5 +1,5 @@
{
- "_comment": "Each entry is a real, working widget on a demo account. Replace the placeholder ids with actual wdgt_ ids once Prompts 01-05 ship and you've created showcase widgets in the studio.",
+ "_comment": "Each entry is a showcase widget. Replace placeholder ids with real wdgt_ ids once created in Studio.",
"widgets": [
{
"type": "turntable",
@@ -7,7 +7,8 @@
"tagline": "Hero banner for sites — auto-rotate, no UI.",
"id": "wdgt_demo_turntab",
"width": 600,
- "height": 600
+ "height": 600,
+ "features": ["Auto-rotates on load", "Drag to orbit", "No chrome — pure 3D"]
},
{
"type": "animation-gallery",
@@ -15,7 +16,8 @@
"tagline": "Click through every clip on a rigged avatar.",
"id": "wdgt_demo_animgal",
"width": 720,
- "height": 720
+ "height": 720,
+ "features": ["Paginated clip browser", "One-click playback", "Works with any rigged GLB"]
},
{
"type": "talking-agent",
@@ -23,7 +25,8 @@
"tagline": "Embodied chat — your agent, your site, your tone.",
"id": "wdgt_demo_talking",
"width": 420,
- "height": 600
+ "height": 600,
+ "features": ["Live LLM conversation", "Empathy layer reacts to sentiment", "Custom system prompt via Studio"]
},
{
"type": "passport",
@@ -31,7 +34,8 @@
"tagline": "On-chain identity card for any agent.",
"id": "wdgt_demo_passprt",
"width": 480,
- "height": 560
+ "height": 560,
+ "features": ["Reads live from the registry", "Shows chain, agentId, reputation", "Links to full agent profile"]
},
{
"type": "hotspot-tour",
@@ -39,7 +43,8 @@
"tagline": "Explorable 3D scenes with annotated points of interest.",
"id": "wdgt_demo_hotspot",
"width": 800,
- "height": 600
+ "height": 600,
+ "features": ["Click hotspots to explore", "Guided camera transitions", "Great for product showcases"]
}
]
}
diff --git a/src/agent-home.js b/src/agent-home.js
index 1a7d1ae9d..901c03640 100644
--- a/src/agent-home.js
+++ b/src/agent-home.js
@@ -106,7 +106,10 @@ export class AgentHome {
<span class="agent-home-dot online"></span>
<span id="agent-home-emotion-label">present</span>
<span class="agent-home-status-sep" aria-hidden="true">·</span>
- <span class="agent-home-address" id="agent-home-address">${id.walletAddress ? _shortAddr(id.walletAddress) : 'no wallet'}</span>
+ ${id.walletAddress
+ ? `<span class="agent-home-address" id="agent-home-address">${_shortAddr(id.walletAddress)}</span>`
+ : `<button class="agent-home-address agent-home-address--cta" id="agent-home-address" title="Connect wallet to register on-chain">no wallet</button>`
+ }
</div>
<p
class="agent-home-description agent-home-editable"
@@ -170,28 +173,64 @@ export class AgentHome {
.catch(() => {});
}
- // Copy link button
+ // Copy link button — use registered agent URL when available, else current page URL.
panel.querySelector('#agent-copy-link')?.addEventListener('click', () => {
- const url = `${location.origin}${id.homeUrl || `/agent/${id.id}`}`;
+ const url = id.homeUrl
+ ? `${location.origin}${id.homeUrl}`
+ : location.href;
navigator.clipboard?.writeText(url).catch(() => {});
this._flashBtn(panel.querySelector('#agent-copy-link'), '✓');
});
- // Inline name + description editing — debounced auto-save with optimistic
- // rollback on backend rejection (e.g. anonymous viewer hits PUT 401).
+ // Wallet CTA button — fire a document event so app.js can handle it.
+ panel.querySelector('.agent-home-address--cta')?.addEventListener('click', () => {
+ document.dispatchEvent(new CustomEvent('agent-home:connect-wallet', { bubbles: true }));
+ });
+
+ // Inline name + description editing — auto-save with local-first fallback.
panel.querySelectorAll('.agent-home-editable').forEach((el) => {
this._wireInlineEdit(el);
});
}
_wireInlineEdit(el) {
- if (!el || !this.identity?.id) return;
+ if (!el) return;
const field = el.dataset.field;
if (!field) return;
- // Track the last server-confirmed value for rollback / no-op detection.
+ const MAX_LEN = field === 'name' ? 40 : 160;
+
+ // Track the last server-confirmed (or locally-saved) value for rollback.
el._lastSaved = el.textContent.trim();
+ // Counter element shown while editing
+ const counter = document.createElement('span');
+ counter.className = 'agent-edit-counter';
+ counter.setAttribute('aria-live', 'polite');
+ el.parentNode.insertBefore(counter, el.nextSibling);
+
+ const _updateCounter = (len) => {
+ counter.textContent = `${len}/${MAX_LEN}`;
+ counter.classList.toggle('agent-edit-counter--warn', len > MAX_LEN * 0.85);
+ counter.classList.toggle('agent-edit-counter--over', len >= MAX_LEN);
+ };
+
+ // Enforce char limit and update counter on input.
+ el.addEventListener('input', () => {
+ const text = el.textContent;
+ if (text.length > MAX_LEN) {
+ // Truncate and restore cursor to end
+ el.textContent = text.slice(0, MAX_LEN);
+ const range = document.createRange();
+ const sel = window.getSelection();
+ range.selectNodeContents(el);
+ range.collapse(false);
+ sel?.removeAllRanges();
+ sel?.addRange(range);
+ }
+ _updateCounter(el.textContent.length);
+ });
+
// Enter blurs (saves) instead of inserting a newline. Escape reverts.
el.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
@@ -206,16 +245,33 @@ export class AgentHome {
el.addEventListener('focus', () => {
el.classList.add('is-editing');
+ counter.classList.add('agent-edit-counter--visible');
+ _updateCounter(el.textContent.length);
});
el.addEventListener('blur', async () => {
el.classList.remove('is-editing');
+ counter.classList.remove('agent-edit-counter--visible');
const next = el.textContent.replace(/\s+/g, ' ').trim();
if (next === (el._lastSaved || '')) return; // no change
- // Optimistic update
const previous = el._lastSaved || '';
el._lastSaved = next;
+
+ // Always persist locally first — works for anonymous and registered alike.
+ if (this.identity._record) {
+ this.identity._record[field] = next;
+ this.identity._persist?.();
+ }
+
+ // If no backend id, show local-save feedback and maybe show wallet nudge.
+ if (!this.identity.id) {
+ el.classList.add('is-saved-local');
+ setTimeout(() => el.classList.remove('is-saved-local'), 1400);
+ this._maybeShowWalletNudge();
+ return;
+ }
+
el.classList.add('is-saving');
try {
@@ -225,7 +281,18 @@ export class AgentHome {
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ [field]: next }),
});
+
+ // Not authenticated — save is local-only, don't treat as an error.
+ if (resp.status === 401 || resp.status === 403) {
+ el.classList.remove('is-saving');
+ el.classList.add('is-saved-local');
+ setTimeout(() => el.classList.remove('is-saved-local'), 1400);
+ this._maybeShowWalletNudge();
+ return;
+ }
+
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
+
const { agent } = await resp.json().catch(() => ({}));
// Reflect any server-side normalisation (trimmed, capped, etc.)
if (agent && typeof agent[field] === 'string' && agent[field] !== next) {
@@ -247,6 +314,33 @@ export class AgentHome {
});
}
+ _maybeShowWalletNudge() {
+ if (this.identity.walletAddress) return; // already connected
+ const panel = this._panel;
+ if (!panel || panel.querySelector('.agent-wallet-nudge')) return; // already shown
+
+ const id = this.identity;
+ const nameCustomised = id.name && id.name !== 'Agent';
+ const descCustomised = id.description && id.description !== 'A 3D AI agent';
+ if (!nameCustomised && !descCustomised) return;
+
+ const nudge = document.createElement('div');
+ nudge.className = 'agent-wallet-nudge';
+ nudge.innerHTML =
+ `<span class="agent-wallet-nudge-text">Connect wallet to register on-chain</span>` +
+ `<button class="agent-wallet-nudge-btn" id="agent-wallet-nudge-btn">Connect →</button>`;
+ nudge.querySelector('#agent-wallet-nudge-btn').addEventListener('click', () => {
+ document.dispatchEvent(new CustomEvent('agent-home:connect-wallet', { bubbles: true }));
+ });
+
+ // Insert before the memory bar
+ const memBar = panel.querySelector('#agent-memory-bar');
+ if (memBar) panel.insertBefore(nudge, memBar);
+ else panel.appendChild(nudge);
+
+ requestAnimationFrame(() => nudge.classList.add('agent-wallet-nudge--visible'));
+ }
+
// ── Memory Bar ────────────────────────────────────────────────────────────
_renderMemoryBar() {
diff --git a/vercel.json b/vercel.json
index 6eadbd9fc..fc5c659d4 100644
--- a/vercel.json
+++ b/vercel.json
@@ -1,6 +1,14 @@
{
"public": true,
"routes": [
+ {
+ "src": "/openapi\\.json",
+ "dest": "/api/openapi-json"
+ },
+ {
+ "src": "/\\.well-known/x402",
+ "dest": "/api/wk-x402"
+ },
{
"src": "/\\.well-known/oauth-authorization-server",
"dest": "/api/wk-oauth-authorization-server"