Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
Enhance agent home page layout and styling; add sticky header with navigation links
nirholasaf8e16dc79ee
diff --git a/README.md b/README.mdindex 265ffcded..b20c5b2e5 100644--- a/README.md+++ b/README.md@@ -1,534 +1,1003 @@-----title: three.ws-description: three.ws is an open-source, browser-native 3D model viewer built on three.js. It renders glTF 2.0 and GLB files directly in WebGL. No plugins, no server uploads, no installs. Create your own models and agents or just open the site, drop a file, and inspect your model instantly.----+# three.ws++**Give your AI a body.** three.ws is an open-source, browser-native 3D AI agent platform. Drop a GLB file, add an LLM brain, register on-chain, and embed anywhere — no plugins, no server uploads, no installs required.<video width="100%" height="auto" autoplay loop muted playsinline><source src="https://github.com/nirholas/3D-Agent/raw/refs/heads/main/public/skills.mp4" type="video/mp4">- Your browser does not support the video tag.+ Your browser does not support the video tag.</video>-<p align="center">- <a href="https://three.ws/"><strong>🌐 Live at three.ws</strong></a> · - <a href="#-quickstart"><strong>Get Started</strong></a> · - <a href="#-features"><strong>Features</strong></a> · - <a href="#-tutorials"><strong>Tutorials</strong></a> · - <a href="#-documentation"><strong>Docs</strong></a> · - <a href="https://github.com/nirholas/3d-agent/issues/new"><strong>Feedback</strong></a>-</p>-----## 🧠 What is three.ws?--**three.ws** is an open-source, browser-native 3D model viewer built on [three.js](https://threejs.org/) (r176). It renders **glTF 2.0** and **GLB** files directly in WebGL — no plugins, no server uploads, no installs. Just open [three.ws](https://three.ws/), drop a file, and inspect your model instantly.+## Table of Contents++- [What is three.ws?](#what-is-threews)+- [Key Features](#key-features)+- [Architecture](#architecture)+- [Tech Stack](#tech-stack)+- [Getting Started](#getting-started)+- [Project Structure](#project-structure)+- [The Agent System](#the-agent-system)+ - [Event Bus (Agent Protocol)](#event-bus-agent-protocol)+ - [LLM Runtime](#llm-runtime)+ - [Empathy Layer](#empathy-layer)+ - [Skills](#skills)+ - [Memory](#memory)+- [Web Component & Embedding](#web-component--embedding)+- [Widget System](#widget-system)+- [API Reference](#api-reference)+- [Authentication & OAuth 2.1](#authentication--oauth-21)+- [MCP Server](#mcp-server)+- [On-Chain Identity (ERC-8004)](#on-chain-identity-erc-8004)+- [Database Schema](#database-schema)+- [Build & Deployment](#build--deployment)+- [Environment Variables](#environment-variables)+- [Testing](#testing)+- [Contributing](#contributing)+- [License](#license)-It's built for **3D artists** previewing exports, **game developers** debugging assets, **web developers** integrating models, and **anyone curious** about 3D on the web.+----<br/>+## What is three.ws?----+three.ws is a full-stack system for creating, deploying, and embedding 3D AI agents. It combines a WebGL model viewer, an LLM-driven agent runtime, on-chain identity contracts, and a distributable web component into one cohesive platform.-<br/>+At its core, it does four things:-## 🪟 Widget Studio — embeddable 3D, no code+1. **Render** — loads and validates glTF 2.0 / GLB models in WebGL 2.0 with zero server-side processing. Drag a file onto the browser and it renders instantly with full Draco, KTX2, and Meshopt decompression.-Save any avatar as a **widget** — a configured, shareable view that any site can drop in with one line of HTML. Five types: **Turntable** (auto-rotate hero banner), **Animation Gallery** (clip browser), **Talking Agent** (embodied chat), **ERC-8004 Passport** (on-chain identity card), **Hotspot Tour** (annotated 3D scene).+2. **Embody** — wraps any avatar with an LLM brain. The agent listens to the user, thinks with Claude, executes tools (animations, gestures, memory operations, skill calls), and expresses emotion through morph-target blending on the 3D model in real time.-```html-<iframe- src="https://three.ws/app#widget=wdgt_abc123"- width="600"- height="600"- style="border:0"-></iframe>-```+3. **Register** — optionally mints the agent as an ERC-8004 token on any EVM chain, giving it a stable on-chain identity, a wallet address, signed action history, and a reputation score that cannot be forged.-- **[Open the Studio →](https://three.ws/studio)** — pick avatar, pick type, generate embed.-- **[Browse the gallery →](https://three.ws/widgets)** — live demos of every widget type.-- **[Read the docs →](https://three.ws/docs/widgets)** — URL params, postMessage API, oEmbed, privacy.+4. **Embed** — distributes the agent as an `<agent-3d>` web component that anyone can drop into a page, or as one of five purpose-built widget types (turntable, animation gallery, talking agent, passport card, hotspot tour) with Open Graph and oEmbed support built in.-Widget URLs (`/w/<id>`) get rich Open Graph cards in Slack/Discord/X and auto-embed via oEmbed in WordPress, Ghost, and Notion.+The backend is a set of Vercel serverless functions backed by Neon Postgres for metadata, Cloudflare R2 for model storage, and Upstash Redis for rate limiting. It exposes a full OAuth 2.1 authorization server and an MCP (Model Context Protocol) endpoint so external AI systems can drive avatars programmatically.-<br/>+three.ws is production-ready and serves [three.ws](https://three.ws) live. The entire stack — viewer, agent runtime, contracts, backend, and web component — is open source under Apache 2.0.----<br/>+## Key Features++**3D Viewer**+- WebGL 2.0 rendering via three.js r176+- glTF 2.0 and GLB with Draco geometry compression, KTX2 texture compression, and Meshopt mesh optimization+- Khronos-spec glTF validation with line-level error reporting+- HDR environment maps, PBR materials, skinned mesh animations, morph targets, and embedded cameras+- OrbitControls (pan, zoom, rotate) with configurable auto-rotation+- Real-time parameter tweaking (lights, exposure, morph weights) via dat.GUI++**Agent Runtime**+- LLM brain powered by Claude (Anthropic API) with a structured tool-loop architecture+- Up to 8 tool iterations per turn before returning final output+- Built-in tools: `wave`, `lookAt`, `play_clip`, `setExpression`, `speak`, `remember`+- Composable skill system — install skills from IPFS, Arweave, or HTTP; each skill is a self-contained bundle with a description, tool definitions, and async handlers+- Weighted emotion blending (celebration, concern, curiosity, empathy, patience) driven by protocol events, not a finite-state machine+- Web Speech API for STT/TTS out of the box; ElevenLabs integration for production-quality voice++**Identity & On-Chain**+- ERC-8004 smart contracts (IdentityRegistry, ReputationRegistry, ValidationRegistry) deployable on any EVM chain+- Each agent is an ERC-721 token with a stable `agentId`, owner wallet, delegated signer (EIP-712), and IPFS-pinned manifest+- Signed action log — every `speak`, `remember`, `skill-done`, and `validate` event is recorded on-chain-optionally or in the database with a cryptographic signature+- EIP-7710 delegated permissions for composable agent-to-agent authorization+- Solana support (SIWS sign-in, Solana wallet linking, Metaplex NFT option)++**Embedding & Distribution**+- `<agent-3d>` custom element — drop it anywhere with no framework dependency+- Five widget variants: turntable, animation gallery, talking agent, ERC-8004 passport card, hotspot tour+- Widget Studio — point-and-click embed code generator+- Open Graph metadata and oEmbed support for rich social previews when links are shared+- Versioned CDN bundles at `/agent-3d/x.y.z/agent-3d.js`++**Backend & Integrations**+- OAuth 2.1 server (RFC 6749 + PKCE, RFC 7591 dynamic registration, RFC 7009 revocation, RFC 7662 introspection, RFC 8414 discovery)+- Developer API keys with scope and expiry+- MCP (Model Context Protocol) over HTTP with JSON-RPC 2.0 for tool-calling from external AI systems+- Ready Player Me, Avaturn (photo-to-avatar), and Privy (embedded wallet) integrations+- DCA strategy execution and on-chain subscription scheduling via cron jobs+- OpenAPI 3.1 spec generated at `/openapi.json`-## ✨ Features+----<br/>+## Architecture-<p align="center">- <img src="assets/features.svg" width="650" height="320" alt="Features overview"/>-</p>+The platform is organized into four layers. All layers communicate through a single event bus (`agent-protocol`) rather than direct calls.-<br/>+```+┌────────────────────────────────────────────────────────────┐+│ Layer 4: Embed & Distribution │+│ <agent-3d> web component · CDN library · 5 widget types │+│ Widget Studio · oEmbed · Open Graph cards │+└────────────────────────────────────────────────────────────┘+ ↓ protocol events+┌────────────────────────────────────────────────────────────┐+│ Layer 3: Identity & Persistence │+│ Agent passport · ERC-8004 on-chain registry │+│ Signed action log · Memory store · Wallet linking │+└────────────────────────────────────────────────────────────┘+ ↓ protocol events+┌────────────────────────────────────────────────────────────┐+│ Layer 2: Agent Runtime │+│ LLM tool-loop · Built-in tools · Skill registry │+│ Empathy Layer (emotion blending) · TTS/STT │+└────────────────────────────────────────────────────────────┘+ ↓ protocol events+┌────────────────────────────────────────────────────────────┐+│ Layer 1: Viewer │+│ three.js r176 · glTF / GLB · Draco / KTX2 / Meshopt │+│ Animations · Morph targets · HDR · Validation │+└────────────────────────────────────────────────────────────┘+```-### Full Feature Breakdown+The event bus decouples every component. The avatar emotion system reacts to `speak` events without knowing the runtime exists. The identity module records actions without knowing the UI exists. This makes the system testable, embeddable in isolation, and composable across pages.-| Category | What You Get |-| :---------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------ |-| **File Support** | `.glTF` and `.GLB` (glTF 2.0), with multi-file drag-and-drop (textures, bins) |-| **Compression** | Draco mesh compression, KTX2 texture compression, Meshopt decoder |-| **Lighting** | Ambient + directional lights, HDR environment maps (Venice Sunset, Footprint Court), neutral room environment, exposure & tone mapping (Linear / ACES Filmic) |-| **Display** | Wireframe overlay, skeleton visualization, grid + axes helpers, background color picker, auto-rotate, point size control |-| **Animation** | Full clip playback with per-clip toggle, playback speed control, play-all |-| **Morph Targets** | Real-time slider control for every morph target on every mesh |-| **Cameras** | Switch between default orbit camera and any cameras embedded in the glTF |-| **Validation** | Integrated [glTF-Validator](https://github.com/KhronosGroup/gltf-validator) — errors, warnings, hints, and info-level messages in a structured report |-| **Performance** | Live FPS/MS/MB stats panel via `stats.js` |-| **Deep Linking** | Load models via URL hash: `#model=url&preset=...&cameraPosition=x,y,z` |-| **Privacy** | 100% client-side — your files never leave your browser |+The backend is stateless serverless functions. All persistent state lives in Postgres (Neon), object storage (Cloudflare R2), or on-chain. Cron jobs handle scheduled blockchain operations (ERC-8004 crawl, DCA execution, subscription execution).-<br/>+---++## Tech Stack++**Frontend**+| Technology | Version | Purpose |+|---|---|---|+| three.js | r176 | WebGL 2.0 rendering |+| Vite | 7.3.2 | Build tooling + HMR |+| Vitest | 4.1.4 | Unit testing |+| viem | 2.18.0 | Ethereum wallet + SIWE |+| ethers | 6.16.0 | Contract interaction |+| @solana/web3.js | 1.98.4 | Solana RPC + signing |+| jose | 5.9.6 | JWT handling |+| zod | 3.23.8 | Schema validation |+| gltf-validator | 2.0.0-dev.3.10 | Khronos spec compliance |+| dat.gui | 0.7.9 | Real-time parameter UI |+| simple-dropzone | 0.8.3 | Drag-and-drop file handling |+| vhtml | 2.2.0 | JSX → HTML string rendering |++**Backend (Vercel serverless)**+| Technology | Purpose |+|---|---|+| Neon Postgres | Primary database |+| Cloudflare R2 | Avatar / model object storage |+| Upstash Redis | Rate limiting |+| Anthropic SDK | Claude LLM (claude-sonnet-4-6 / claude-opus-4-7) |+| Resend | Transactional email |+| Sentry | Error monitoring |+| @aws-sdk/client-s3 | R2 presigned upload URLs |++**Smart Contracts**+| Technology | Purpose |+|---|---|+| Solidity 0.8+ | ERC-8004 contracts |+| Foundry | Compile, test, deploy |+| ERC-721 | Agent token standard |+| EIP-712 | Typed structured signing |+| EIP-7710 | Delegated permissions |----<br/>+## Getting Started-## 🚀 Quickstart+### Prerequisites-<br/>+- Node.js 20++- npm 10++- A Neon Postgres database (or any Postgres 15+)+- A Cloudflare R2 bucket (or any S3-compatible store)+- An Anthropic API key (for the LLM backend)-<p align="center">- <img src="assets/quickstart.svg" width="520" height="200" alt="Quickstart steps"/>-</p>+### Installation```bash-git clone https://github.com/nirholas/3d-agent.git+git clone https://github.com/nirholas/3D-Agent.gitcd 3D-Agentnpm install-npm run dev```-Open **http://localhost:3000** for the landing page, or **http://localhost:3000/app** to open the viewer and drop any `.glb` or `.gltf` file onto the page.+### Environment Setup-<br/>+Copy the example env file and fill in required values:-### Available Scripts+```bash+cp .env.example .env.local+```-| Command | What It Does |-| :------------------------- | :-------------------------------------------------------------------- |-| `npm run dev` | Starts Vite dev server on port 3000 with hot reload |-| `npm run dev:lib` | Dev server in library-build mode (`TARGET=lib`) |-| `npm run build` | Production build to `dist/` |-| `npm run build:lib` | Build the embeddable library bundle to `dist-lib/` |-| `npm run build:artifact` | Build the standalone artifact bundle (`vite.config.artifact.js`) |-| `npm run build:all` | `build` + `build:lib` + `publish:lib` |-| `npm run publish:lib` | Run `scripts/publish-lib.mjs` to publish versioned `agent-3d` bundles |-| `npm run test` | Run Vitest test suite |-| `npm run verify` | `prettier --check .` + `vite build` |-| `npm run format` | Run Prettier write across the repo |-| `npm run deploy` | `build:all` + `vercel --prod` |-| `npm run clean` | Wipe `dist/` and `dist-lib/` |-| `npm run generate-icons` | Regenerate PWA icons (`scripts/generate-pwa-icons.mjs`) |-| `npm run fetch-animations` | Download animation assets (`scripts/download-animations.mjs`) |+At minimum, set:-<br/>+```env+PUBLIC_APP_ORIGIN=http://localhost:3000+DATABASE_URL=postgres://user:pass@host/db+JWT_SECRET=<run: openssl rand -base64 64>+ANTHROPIC_API_KEY=sk-ant-...+```----+See [Environment Variables](#environment-variables) for the full reference.-<br/>+### Initialize the Database-## 🏗️ Architecture+The schema is idempotent — run it against your Postgres instance to create all tables:-<br/>+```bash+psql $DATABASE_URL < api/_lib/schema.sql+```-<p align="center">- <img src="assets/architecture.svg" width="650" height="340" alt="Architecture diagram"/>-</p>+### Start the Dev Server+```bash+npm run dev```-3D-Agent/-├── index.html → Landing page shell-├── app.html → Viewer / deploy app (also served at /app, /deploy, /a/*)-├── home.html → Authenticated home-├── create.html → Avatar + agent creation flow-├── features.html → Features marketing page-├── agent-home.html → Agent detail page-├── agent-edit.html → Agent editing UI-├── agent-embed.html, a-embed.html, embed.html → Embed surfaces-├── style.css, home.css, features.css → Styling-├── src/-│ ├── app.js → Entry: dropzone, URL parsing, orchestration-│ ├── viewer.js → Three.js renderer, scene, camera, GUI-│ ├── viewer/ → Lights, environment, animation, screenshot helpers-│ ├── validator.js → glTF-Validator integration & report generation-│ ├── environments.js → HDR environment map definitions-│ ├── components/ → JSX components (validator, animation panel, footer, model-viewer element)-│ ├── widgets.js, widgets/, widget-types.js → Widget Studio (turntable, gallery, talking agent, passport, hotspot tour)-│ ├── agents-directory.js, agent-*.js → Agent creation, identity, skills, memory, embed modal-│ ├── auth/, wallet/, wallet-auth.js → Session + wallet (SIWE / Privy) auth-│ ├── erc8004/, attestations/, reputation-* → ERC-8004 passport + reputation-│ ├── erc7710/, claim-transfer.js → Delegated permissions-│ ├── cz-flow.js, cz/ → CZ claim demo flow-│ ├── memory/, permissions/, pinning/ → Agent memory, permissions, IPFS pinning-│ ├── artifact/, runtime/, editor/ → Embeddable artifact + editor runtime-│ ├── ar/ → AR quick-look helpers-│ └── skills/ → Agent skills registry-├── api/ → Vercel serverless functions-│ ├── agents/, widgets/, avatars/ → CRUD + embed/OG/oembed/view endpoints-│ ├── auth/, oauth/, session/, sessions/ → Session + OAuth 2.1 server-│ ├── mcp.js, llm/ → MCP endpoint + LLM proxy-│ ├── erc8004/, cz/, dca-strategies.js, subscriptions.js → On-chain + scheduled flows-│ ├── cron/ → erc8004-crawl, index-delegations, run-dca, run-subscriptions-│ ├── animations/, tts/, pinning/, api-keys/ → Supporting services-│ └── _lib/ → Shared server helpers + `schema.sql`-├── public/ → Static subapps (studio, dashboard, widgets-gallery, agent, artifact, cz, my-agents, discover, validation, hydrate, lobehub, wallet, login.html, register.html) and default avatars-├── contracts/ → Smart contract sources-├── sdk/, lobehub-plugin/ → Embedding SDK + Lobehub plugin-├── scripts/ → Build, publish, icon, animation scripts-├── docs/ → Architecture, API, Deployment, Development, MCP, Setup, Widgets docs-├── tests/ → Vitest suite-├── vercel.json → Routes, rewrites, cron schedules-├── vite.config.js, vite.config.artifact.js → Build configs-└── package.json → Dependencies & scripts-```--<br/>--### Tech Stack--| Layer | Technology |-| :---------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| **Rendering** | [three.js](https://threejs.org/) r176 — WebGL 2.0 |-| **Model Loading** | `GLTFLoader` + `DRACOLoader` + `KTX2Loader` + `MeshoptDecoder` |-| **Controls** | `OrbitControls` — pan, zoom, rotate |-| **GUI** | [dat.gui](https://github.com/dataarts/dat.gui) + [tweakpane](https://tweakpane.github.io/docs/) — real-time parameter tweaking |-| **Validation** | [gltf-validator](https://github.com/KhronosGroup/gltf-validator) — Khronos spec compliance |-| **Templating** | [vhtml](https://github.com/developit/vhtml) — JSX → HTML string rendering |-| **Drag & Drop** | [simple-dropzone](https://github.com/donmccurdy/simple-dropzone) |-| **Build** | [Vite](https://vitejs.dev/) 7 — sub-second HMR |-| **Backend** | Vercel serverless functions · [Neon](https://neon.tech/) Postgres · Cloudflare R2 · [Upstash](https://upstash.com/) Redis |-| **Auth** | Session JWT ([`jose`](https://github.com/panva/jose)) · [SIWE](https://eips.ethereum.org/EIPS/eip-4361) / [viem](https://viem.sh/) + [ethers](https://ethers.org/) · [Privy](https://www.privy.io/) |-| **Testing** | [Vitest](https://vitest.dev/) |-| **Hosting** | [Vercel](https://vercel.com/) — edge CDN + cron |--<br/>----+Opens at `http://localhost:3000`. The viewer is at `/app`, the dashboard at `/home`, and the agent creation flow at `/create`.++### Quick Viewer Test-<br/>+Navigate to `http://localhost:3000/app` and drag any GLB file onto the canvas. The model loads instantly with PBR materials, animations, and full glTF validation.-## 🔗 URL Parameters+To try the agent, navigate to `/create`, upload a GLB, and configure a brain (requires `ANTHROPIC_API_KEY` in your env).-Load models and configure the viewer directly via URL hash parameters. This is useful for embedding, sharing specific views, or automated testing.+---++## Project Structure```-https://three.ws/#model=URL&kiosk=true&preset=assetgenerator&cameraPosition=1,2,3+3D-Agent/+├── index.html # Marketing landing page+├── app.html # Main viewer (drag-and-drop + deploy mode)+├── home.html # Authenticated dashboard+├── create.html # Avatar + agent creation wizard+├── agent-home.html # Agent detail & action timeline+├── agent-edit.html # Agent editing UI+├── agent-embed.html # Chromeless embed variant+├── a-embed.html # On-chain agent embed+│+├── src/ # Frontend JavaScript (~80 modules, ~15k lines)+│ ├── viewer.js # three.js renderer core (1,534 lines)+│ ├── app.js # SPA entry + URL routing (460 lines)+│ ├── agent-protocol.js # Event bus (200-action ring buffer)+│ ├── agent-avatar.js # Empathy Layer (morph targets, emotion) (694 lines)+│ ├── agent-identity.js # Passport, diary, signed action history+│ ├── element.js # <agent-3d> custom element+│ ├── runtime/+│ │ ├── index.js # LLM tool-loop engine+│ │ ├── providers.js # AnthropicProvider, NullProvider+│ │ ├── scene.js # SceneController bridge to three.js+│ │ ├── tools.js # Built-in tools (wave, speak, remember...)+│ │ └── speech.js # TTS + STT+│ ├── memory/+│ │ └── index.js # File-based memory (local/ipfs/encrypted-ipfs/none)+│ ├── skills/+│ │ ├── index.js # SkillRegistry+│ │ └── <name>/ # Bundled skills (SKILL.md, tools.json, handlers.js)+│ ├── erc8004/+│ │ ├── abi.js # Contract ABIs + deployment addresses+│ │ ├── agent-registry.js # connectWallet, registerAgent, pinToIPFS+│ │ └── reputation.js # submitFeedback, getReputation+│ └── widgets/ # Five widget type implementations+│+├── api/ # Vercel serverless functions (~153 endpoints, ~3.6k lines)+│ ├── agents.js # Agent CRUD (321 lines)+│ ├── chat.js # LLM chat endpoint (298 lines)+│ ├── mcp.js # MCP server over HTTP (759 lines)+│ ├── agent-actions.js # Record signed actions (122 lines)+│ ├── agent-memory.js # Memory CRUD + recall (188 lines)+│ ├── auth/ # Login, register, SIWE, Privy, sessions+│ ├── oauth/ # OAuth 2.1 server (authorize, token, register...)+│ ├── avatars/ # Avatar CRUD + presigned upload+│ ├── widgets/ # Widget CRUD + OG + oEmbed+│ ├── erc8004/ # Blockchain hydrate, import, pin+│ ├── cron/ # Scheduled jobs (crawl, DCA, subscriptions)+│ └── _lib/ # Shared helpers (db, auth, r2, validate, email...)+│ └── schema.sql # Idempotent Postgres migrations+│+├── public/ # Static subapps + assets+│ ├── studio/ # Widget Studio SPA+│ ├── dashboard/ # User dashboard SPA+│ ├── validation/ # glTF validator tool+│ ├── discover/ # Agent discovery SPA+│ └── animations/ # Animation clip library+│+├── contracts/ # Foundry + Solidity (ERC-8004)+│ ├── src/+│ │ ├── IdentityRegistry.sol # ERC-721 agent tokens (EIP-712)+│ │ ├── ReputationRegistry.sol # Signed reviewer feedback+│ │ └── ValidationRegistry.sol # Validator attestations+│ ├── script/Deploy.s.sol+│ ├── test/IdentityRegistry.test.sol+│ └── DEPLOYMENTS.md # Chain deployment addresses+│+├── docs/ # Architecture, API, deployment guides+├── specs/ # Formal specs (manifest, embed, skill, memory...)+├── tests/ # Vitest test suite (~30 files)+├── scripts/ # Build tools (publish, icon gen, animations)+│+├── vite.config.js # App build config+├── vite.config.artifact.js # Standalone artifact bundle+├── vercel.json # Routes, rewrites, crons, headers+└── package.json # Scripts + dependencies```-| Parameter | Type | Description |-| :--------------- | :-------- | :------------------------------------------------------------ |-| `model` | `string` | URL to a `.glb` or `.gltf` file to load on page open |-| `kiosk` | `boolean` | Hides the header and validation UI for clean embedding |-| `preset` | `string` | Set to `assetgenerator` for glTF asset generator testing mode |-| `cameraPosition` | `x,y,z` | Initial camera position as comma-separated floats |+---++## The Agent System++### Event Bus (Agent Protocol)++`src/agent-protocol.js` implements a lightweight `EventTarget` subclass that is the nervous system of the platform. Every component — avatar, runtime, identity, UI — communicates exclusively through this bus. There are no direct method calls between layers.++The bus maintains a 200-action ring buffer for debugging and replay. Embed variants expose a filtered subset of events through `postMessage` to the host page.++**Core event types:**++| Event | Payload | Who emits | Who listens |+|---|---|---|---|+| `speak` | `{ text, sentiment: -1..1 }` | runtime, skills | avatar (emotion), identity (log), chat UI |+| `think` | `{ thought }` | runtime | home (timeline), avatar |+| `gesture` | `{ name, duration }` | avatar, skills | avatar (one-shot clip) |+| `emote` | `{ trigger, weight: 0..1 }` | avatar | avatar (emotion inject) |+| `look-at` | `{ target: 'user'\|'camera'\|'center' }` | skills | scene controller |+| `perform-skill` | `{ skill, args, animationHint }` | runtime | skill registry |+| `skill-done` | `{ skill, result }` | skills | avatar, identity |+| `skill-error` | `{ skill, error }` | skills | avatar, identity |+| `remember` | `{ type, content, ... }` | skills, runtime | memory, identity |+| `load-start` / `load-end` | `{ uri, error? }` | viewer | avatar (emotion) |+| `validate` | `{ errors, warnings }` | validator | avatar, identity |+| `presence` | `{ state }` | element | home UI |++Identity-relevant events (`speak`, `remember`, `sign`, `skill-done`, `validate`, `load-end`) are fire-and-forwarded to `POST /api/agent-actions` for durable logging.++### LLM Runtime-**Example — embed a model in kiosk mode:**+`src/runtime/index.js` implements the `Runtime` class, which drives the agent's LLM-powered brain.+**Tool-loop flow:**++1. User message (text or STT transcript) arrives+2. System prompt is assembled: manifest instructions + recalled memory + skill descriptions+3. Claude is called with the conversation history and all available tools+4. Tool calls are dispatched in order — each built-in tool or skill handler receives a rich context object:+ ```js+ { viewer, memory, llm, speak, listen, fetch, loadGLB, loadClip, loadJSON, call, stage, agentId }+ ```+5. Tool results are appended to conversation history as `tool_result` messages+6. Steps 3–5 repeat until Claude returns with no tool calls, or the iteration limit (8) is hit+7. Final text response is optionally spoken via TTS++**Providers** (`src/runtime/providers.js`):+- `AnthropicProvider` — connects to the Anthropic API, supports streaming+- `NullProvider` — no-op for testing and offline mode++**Built-in tools** (`src/runtime/tools.js`):++| Tool | Description |+|---|---|+| `wave` | Play a wave gesture animation |+| `lookAt` | Direct the agent's gaze (user, camera, or scene center) |+| `play_clip` | Play a named animation clip from the model or animation library |+| `setExpression` | Set a named morph target weight directly |+| `speak` | Emit text through TTS and the protocol bus |+| `remember` | Write a memory entry (user, feedback, project, or reference type) |++Skills can define additional tools that override or augment the built-ins. The skill registry is loaded from the agent manifest before each conversation turn.++### Empathy Layer++`src/agent-avatar.js` implements the Empathy Layer — a continuous weighted emotion blend that drives the avatar's facial morph targets and head orientation in real time.++Emotions are not a finite-state machine. Each emotion is a float (0..1) that decays linearly per frame at a different rate. Protocol events inject spikes:++| Trigger | Emotion | Spike |+|---|---|---|+| `speak` (positive sentiment) | celebration | +0.7 |+| `speak` (negative sentiment) | concern | +0.5 |+| `skill-error` | concern + empathy | +0.6 / +0.5 |+| `load-start` | patience + curiosity | +0.4 / +0.3 |+| `validate` (clean) | celebration | +0.5 |+| `validate` (errors) | concern | +0.6 |++Decay half-lives (approximate):+- Patience: ~20s — persists during long operations+- Empathy: ~13s — lingers after emotional events+- Concern: ~12s — sustained worry+- Curiosity: ~8s — alert, fades moderately+- Celebration: ~6s — brief, upbeat++The blended emotion mix drives morph target values each frame. For example:+- Celebration → `mouthSmile 0.85`, `mouthOpen 0.2`+- Concern → `mouthFrown 0.55`, `browInnerUp 0.6`+- Empathy → `eyeSquint 0.4`, `browInnerUp 0.5`++Head tilt and lean are also driven by the blend — curiosity tilts the head, patience leans slightly back.++This architecture means the avatar feels responsive and emotionally coherent without any hand-authored animation triggers.++### Skills++Skills are self-contained capability bundles that extend the agent's tool set. Each skill lives in its own directory:++```+skills/wave/+├── SKILL.md # Human-readable description and usage instructions+├── tools.json # Tool definitions (name, description, input JSON schema)+└── handlers.js # Async handler functions (default export)+```++**tools.json example:**+```json+[+ {+ "name": "wave",+ "description": "Plays a waving gesture on the avatar for the specified duration.",+ "inputSchema": {+ "type": "object",+ "properties": {+ "duration_ms": { "type": "integer", "minimum": 500, "maximum": 5000 }+ }+ }+ }+]```-https://three.ws/#model=https://example.com/model.glb&kiosk=true++**handlers.js example:**+```js+export default {+ async wave(args, ctx) {+ const { viewer, speak } = ctx;+ await viewer.playClipByName('wave');+ return { ok: true, output: 'Waved!' };+ }+};```-<br/>+Skills are loaded from the agent manifest at runtime. The `SkillRegistry` supports three trust modes:+- `any` — install skills from any source (development only)+- `owned-only` — only skills the agent owner has registered+- `whitelist` — only approved skill URIs++Skills are distributed over IPFS, Arweave, or HTTP. The public skills registry is at `/public/skills-index.json`.++### Memory+`src/memory/index.js` implements a file-based memory system (mirroring this project's own Claude memory system). Memories are Markdown files with YAML frontmatter, organized by type:++```markdown+---+type: user+key: user_role+name: User's Role+created: 2024-01-15T10:30:00Z+salience: 0.95----<br/>--## 🗺️ Routes & Endpoints--Routing is driven by [`vercel.json`](vercel.json). High-level map:--### Pages--| Path | Serves |-| :--------------------------------------------------------------- | :--------------------------------------- |-| `/` | `index.html` — landing |-| `/app`, `/deploy`, `/a/*` | `app.html` — viewer + deploy flow |-| `/home` | `home.html` |-| `/features` | `features.html` |-| `/create` | `create.html` — avatar + agent creation |-| `/agent`, `/agent/<id>` | Agent detail page |-| `/agent/<id>/edit`, `/embed` | Agent edit + embed surfaces |-| `/studio`, `/widgets`, `/widgets/...` | Widget Studio + gallery |-| `/w/<id>` | Rendered widget page (with OG + oEmbed) |-| `/dashboard`, `/dashboard/...` | Authenticated dashboard (storage, usage) |-| `/my-agents`, `/discover` | Directories |-| `/artifact`, `/hydrate`, `/cz`, `/validation`, `/lobehub/iframe` | Standalone subapps |-| `/login`, `/register` | Auth pages |-| `/docs/widgets` | Widgets documentation |--### API--| Path | Purpose |-| :--------------------------------------------------------------------------------- | :-------------------------------------------- |-| `/api/agents`, `/api/agents/<id>` | Agent CRUD, wallet, sign, embed-policy, usage |-| `/api/agents/suggest`, `/api/agents/by-wallet` | Lookup helpers |-| `/api/agent-actions`, `/api/agent-memory` | Agent actions + memory store |-| `/api/widgets`, `/api/widgets/<id>` | Widget CRUD, duplicate, stats, view |-| `/api/widgets/oembed`, `/api/widgets/<id>/og` | oEmbed + Open Graph card |-| `/api/avatars/<id>/...` | Storage mode + IPFS pinning |-| `/api/auth/...`, `/oauth/...` | Sessions + OAuth 2.1 authorization server |-| `/.well-known/oauth-authorization-server`, `/.well-known/oauth-protected-resource` | Discovery docs |-| `/api/mcp` | Model Context Protocol endpoint |-| `/api/llm/anthropic` | LLM proxy |-| `/api/erc8004/hydrate`, `/api/erc8004/import`, `/api/erc8004/pin` | ERC-8004 passport tools |-| `/api/dca-strategies`, `/api/subscriptions.js` | Scheduled on-chain actions |-| `/api/cz/claim` | CZ claim flow |-| `/api/chat`, `/api/tts/*`, `/api/animations/*` | Chat, TTS, animation services |-| `/a/<chain>/<id>`, `/a/<chain>/<id>/embed`, `/api/a/<chain>/<id>/og` | Attestation pages + OG |--### Cron jobs--Scheduled in `vercel.json` → `crons`:--| Schedule | Handler |-| :------------- | :---------------------------- |-| `*/15 * * * *` | `/api/cron/erc8004-crawl` |-| `*/5 * * * *` | `/api/cron/index-delegations` |-| `0 * * * *` | `/api/cron/run-dca` |-| `0 * * * *` | `/api/cron/run-subscriptions` |--<br/>+User is a game developer interested in character animation.+```++A `MEMORY.md` index file is auto-maintained. At the start of each conversation turn, the memory store is scanned and high-salience entries are injected into the system prompt.++**Storage modes:**+- `local` — stored in the browser's local storage (default for development)+- `ipfs` — pinned to IPFS via Pinata or Web3.Storage+- `encrypted-ipfs` — encrypted before pinning (user holds the key)+- `none` — stateless, no memory between sessions++Memory types (`user`, `feedback`, `project`, `reference`) follow the same taxonomy used by this codebase's own Claude guidelines.----<br/>+## Web Component & Embedding-## 📖 Tutorials+The `<agent-3d>` custom element (`src/element.js`) is the primary distribution mechanism. It lazy-boots on intersection (IntersectionObserver), so off-screen agents don't load until visible.-<br/>+**Basic usage:**+```html+<script src="https://three.ws/agent-3d/latest/agent-3d.js"></script>-### 1. Preview a Local Model+<agent-3d+ body="https://example.com/my-avatar.glb"+ brain="https://example.com/manifest.json"+ mode="chat"+></agent-3d>+```-<p align="center">- <img src="assets/tutorial-steps.svg" width="500" height="80" alt="Step 1: Open three.ws · Step 2: Drop .glb file · Step 3: Inspect"/>-</p>+**Key attributes:**-Just drag any `.glb` or `.gltf` file (along with its textures and `.bin` if separate) onto the page. The viewer auto-detects the root glTF file and resolves all relative resource URIs.+| Attribute | Type | Description |+|---|---|---|+| `body` | URL | GLB model URL |+| `brain` | URL | Agent manifest JSON URL |+| `agent-id` | string | Registered agent ID (resolves manifest automatically) |+| `mode` | `view` \| `chat` \| `embed` | Interaction mode |+| `eager` | boolean | Load immediately without intersection check |+| `sandbox` | boolean | Disable network calls (offline mode) |+| `width` / `height` | number | iframe dimensions when generating embed code |-**Multi-file glTF?** Select _all_ the files (`.gltf` + `.bin` + textures) and drop them together. The viewer maps them by relative path, so your model loads correctly even with external resources.+The element fires a `postMessage` API for host-page communication (documented in `specs/EMBED_HOST_PROTOCOL.md`). Hosts can send events to the agent and receive `speak`, `think`, and `skill-done` events back.-<br/>+**Versioned CDN bundles** are published at `/agent-3d/x.y.z/agent-3d.js`. Use `latest` for auto-updates or pin to a version for stability:+```html+<script src="https://three.ws/agent-3d/1.5.1/agent-3d.js"></script>+```-### 2. Tweak Lighting & Environment+----The **Lighting** panel in the GUI sidebar gives you full control:+## Widget System-1. **Environment Map** — choose between `None`, `Neutral` (studio), `Venice Sunset` (warm), or `Footprint Court` (outdoor daylight)-2. **Tone Mapping** — switch between `Linear` (raw) and `ACES Filmic` (cinematic)-3. **Exposure** — slide from –10 to +10 to simulate camera exposure-4. **Ambient / Direct** — independently control intensity and color of ambient fill and key directional light-5. **Background** — toggle the environment map as the scene background, or pick a solid color+The Widget Studio (`/studio`) lets anyone build a shareable, embeddable 3D experience without writing code. Pick an avatar, pick a widget type, configure it, and get an iframe snippet.-<br/>+**Five widget types:**-### 3. Play & Control Animations+| Widget | Description |+|---|---|+| **Turntable** | Auto-rotating model showcase with configurable background, lighting, and camera |+| **Animation Gallery** | Paginated grid of named clips; click any to play it on the model |+| **Talking Agent** | Full chat interface with the LLM brain; embed a conversational agent anywhere |+| **ERC-8004 Passport** | On-chain identity card — shows agent name, owner, reputation score, and verification badge |+| **Hotspot Tour** | 3D hotspots pinned to world-space coordinates; click to reveal text annotations |-If your model has animation clips, the **Animation** panel appears automatically:+Each widget has:+- A public URL at `/w/<id>` with server-rendered Open Graph metadata for rich link previews+- An oEmbed endpoint at `/api/widgets/oembed` for WordPress, Ghost, Notion embedding+- An iframe embed URL at `/api/widgets/<id>/view`+- A view counter tracked at `/api/widgets/<id>/stats`+- A duplicate API at `/api/widgets/<id>/duplicate`-- Each clip gets its own checkbox — toggle individual animations on/off-- **Playback Speed** — slow down to 0 for freeze-frame or study-- **Play All** — fire every clip simultaneously+Widgets are stored as JSON config in Postgres, pointing at an avatar in R2.-<br/>+----### 4. Debug with Wireframe & Skeleton+## API Reference++The full OpenAPI 3.1 spec is available at `/openapi.json`. The key API surface is organized below.++### Agent API++| Method | Route | Auth | Description |+|---|---|---|---|+| GET | `/api/agents` | session | List your agents |+| POST | `/api/agents` | session | Create an agent |+| GET | `/api/agents/:id` | — | Get agent detail |+| PATCH | `/api/agents/:id` | session | Update agent |+| DELETE | `/api/agents/:id` | session | Delete agent |+| GET | `/api/agents/:id/manifest` | — | Download manifest JSON |+| POST | `/api/agents/:id/sign` | session | Sign a message with agent wallet |+| GET/POST | `/api/agents/:id/embed-policy` | session | Manage iframe origin allowlist |+| POST | `/api/agents/register-prep` | session | Prep EVM on-chain registration |+| POST | `/api/agents/register-confirm` | session | Confirm EVM registration |+| POST | `/api/agent-actions` | session | Record signed agent action |++### Avatar API++| Method | Route | Auth | Description |+|---|---|---|---|+| GET | `/api/avatars` | — | List public avatars |+| POST | `/api/avatars` | session | Create avatar record |+| GET | `/api/avatars/:id` | — | Get avatar detail |+| PATCH | `/api/avatars/:id` | session | Update metadata |+| DELETE | `/api/avatars/:id` | session | Soft-delete avatar |+| POST | `/api/avatars/:id/presign` | session | Get presigned R2 upload URL |+| POST | `/api/avatars/:id/pin-ipfs` | session | Pin to IPFS |++**Three-step upload flow:**+```+1. POST /api/avatars/:id/presign → { url, storage_key }+2. PUT <presigned_url> ← raw GLB bytes+3. POST /api/avatars → register metadata with storage_key+```-Open the **Display** panel:+### Widget API-- **Wireframe** — see the mesh topology and triangle density-- **Skeleton** — visualize bones and joint hierarchy (great for rigging QA)-- **Grid** — ground plane + axes helper for spatial reference-- **Point Size** — if your model uses point clouds, control the render size+| Method | Route | Auth | Description |+|---|---|---|---|+| GET | `/api/widgets` | session | List your widgets |+| POST | `/api/widgets` | session | Create widget |+| PATCH | `/api/widgets/:id` | session | Update widget |+| DELETE | `/api/widgets/:id` | session | Delete widget |+| POST | `/api/widgets/:id/duplicate` | session | Clone widget |+| GET | `/api/widgets/:id/stats` | — | View stats |+| GET | `/api/widgets/oembed` | — | oEmbed card |-<br/>+### Memory API-### 5. Validate Your Model+| Method | Route | Auth | Description |+|---|---|---|---|+| GET | `/api/agent-memory/:id` | session | Fetch agent memory store |+| POST | `/api/agent-memory/:id` | session | Append memory entries |+| PUT | `/api/agent-memory/:id` | session | Replace memory store |-Every model you load is automatically validated against the [glTF 2.0 specification](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html). Click the validation bar at the bottom to expand a full report:+### Chat & LLM-- **Errors** — spec violations that will likely cause rendering issues-- **Warnings** — non-fatal issues that may affect portability-- **Hints** — optimization suggestions-- **Info** — metadata (vertex count, draw calls, materials, extensions used)+| Method | Route | Auth | Description |+|---|---|---|---|+| POST | `/api/chat` | session \| api-key | Chat with agent (Claude backend) |+| POST | `/api/llm/anthropic` | session | Anthropic API proxy |-<br/>+### Cron Jobs-### 6. Embed in Your Own Site+Scheduled via `vercel.json`, these run automatically in production:-Use an `<iframe>` with kiosk mode for clean embedding:+| Schedule | Endpoint | Purpose |+|---|---|---|+| Every 15 min | `/api/cron/erc8004-crawl` | Index new agents from blockchain |+| Every 5 min | `/api/cron/index-delegations` | Index EIP-7710 delegations |+| Hourly | `/api/cron/run-dca` | Execute DCA strategy orders |+| Hourly | `/api/cron/run-subscriptions` | Execute recurring subscriptions |-```html-<iframe- src="https://three.ws/#model=https://your-cdn.com/model.glb&kiosk=true"- width="800"- height="600"- frameborder="0"- allow="autoplay; fullscreen"-></iframe>+---++## Authentication & OAuth 2.1++three.ws supports three authentication methods:++**1. Email + Password (Session cookie)**+```+POST /api/auth/register → create account+POST /api/auth/login → JWT session cookie+GET /api/auth/me → current user+POST /api/auth/logout → revoke session+```++**2. Wallet (SIWE / SIWS)**+```+POST /api/auth/siwe → get nonce challenge+POST /api/auth/siwe/verify → verify EIP-4361 signed message → session+POST /api/auth/siws → Solana equivalent+```++**3. Developer API Keys**+```+POST /api/api-keys → create key (set scope + expiry)+DELETE /api/api-keys/:id → revoke key+Authorization: Bearer sk-... → authenticate requests```-> **CORS note:** The model URL must allow cross-origin requests. If you hit CORS errors, serve the model from the same domain or configure your CDN to allow `https://three.ws/` as an origin.+**OAuth 2.1 Server (RFC 6749 + PKCE)**-<br/>+For third-party apps and MCP integrations:++```+GET /oauth/authorize → consent screen+POST /oauth/authorize → submit consent → auth code+POST /oauth/token → exchange code for tokens+POST /oauth/register → RFC 7591 dynamic client reg+POST /oauth/revoke → RFC 7009 token revocation+POST /oauth/introspect → RFC 7662 token check+GET /.well-known/oauth-authorization-server → RFC 8414 discovery+GET /.well-known/oauth-protected-resource → RFC 9728 resource discovery+```++Token scopes: `avatars:read`, `avatars:write`, `agents:read`, `agents:write`, `mcp`.++Access tokens are short-lived JWTs (1 hour). Refresh tokens are opaque strings stored hashed in Postgres.----<br/>+## MCP Server-## 💡 Ideas & Roadmap+`api/mcp.js` (759 lines) implements the [Model Context Protocol](https://modelcontextprotocol.io) 2025-06-18 specification over HTTP with JSON-RPC 2.0. It enables external AI systems (including Claude Desktop, other agents, or custom integrations) to drive avatars programmatically.-<br/>+**Endpoint:** `POST /api/mcp`+**Auth:** OAuth 2.1 Bearer token with `mcp` scope-<p align="center">- <img src="assets/roadmap.svg" width="650" height="260" alt="Roadmap"/>-</p>+**Available tools:**-- **AI Model Analysis** — describe meshes, materials, and suggest optimizations-- **Screenshot / Video Export** — capture PNGs or record animated WebM walkthroughs-- **Measurement Tools** — click two points to measure distances, angles, bounding boxes-- **Texture Inspector** — view individual texture channels (baseColor, normal, metallic-roughness, AO, emissive)-- **Side-by-Side Diff** — compare two versions of the same model-- **AR Quick Look** — launch your model in WebXR on supported devices-- **Scene Graph Explorer** — visual tree of all nodes, meshes, materials, and their properties-- **Material Editor** — tweak PBR params (roughness, metalness, colors) live in the viewport-- **Annotation System** — pin notes to specific vertices or mesh regions-- **File Format Expansion** — `.fbx`, `.obj`, `.usdz` import support-- **CLI Tool** — `npx 3d-agent inspect model.glb` for headless validation in CI/CD pipelines+| Tool | Description |+|---|---|+| `list_my_avatars` | List all avatars owned by the authenticated user |+| `get_avatar` | Fetch metadata and download URL for a specific avatar |+| `search_public_avatars` | Search the public avatar library by name, tag, or description |+| `render_avatar` | Generate a preview render of an avatar (returns image URL) |+| `delete_avatar` | Permanently delete an avatar |+| `validate_model` | Run Khronos glTF validation and return error report |+| `inspect_model` | Inspect model internals (mesh count, material list, animation names, texture sizes) |+| `optimize_model` | Optimize a model (Draco compression, texture downscale, mesh simplification) |-<br/>+**MCP discovery:** configured in `.mcp.json` at the repo root for Claude Desktop integration.++**SSE stream:** `GET /api/mcp` returns a Server-Sent Events stream for real-time notifications from long-running operations (validation, optimization).----<br/>+## On-Chain Identity (ERC-8004)++ERC-8004 is a draft standard for verifiable 3D agent identity. The `contracts/` directory contains a full Foundry implementation.++### Contracts++**IdentityRegistry.sol** — the primary contract. Each agent is an ERC-721 token with:+- `agentId` — stable numeric ID (the token ID)+- `owner` — EVM address of the agent's owner+- `delegatedSigner` — optional secondary address for runtime signing (EIP-712 typed signature)+- `tokenURI` — IPFS URL of the agent manifest JSON+- `metadata` — on-chain name, description, image pointer-## 🧪 Examples+**ReputationRegistry.sol** — stores signed feedback scores. Each reviewer can submit one score per agent. Scores are averaged for an on-chain reputation metric.-<br/>+**ValidationRegistry.sol** — records validator attestations for off-chain proofs (glTF validation reports, skill audits, security reviews).-### Load the Khronos Sample Models+### Deployment Addresses-The glTF working group maintains a library of test models. Try these:+See `contracts/DEPLOYMENTS.md` for current mainnet and testnet addresses.++### Registration Flow (EVM)```-https://three.ws/#model=https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/DamagedHelmet/glTF-Binary/DamagedHelmet.glb+1. POST /api/agents/register-prep → { manifest, typedData }+ (uploads manifest to IPFS, builds EIP-712 typed data for signing)++2. User signs typedData with their wallet++3. POST /api/agents/register-confirm → { txHash, agentId }+ (submits transaction, waits for confirmation, updates agent record)```+The agent is now an ERC-721 token. Its manifest lives on IPFS. Its action history is anchored to its `agentId`. Any third party can verify the agent's identity, owner, and reputation without trusting three.ws.++### On-Chain Indexing++`api/cron/erc8004-crawl.js` runs every 15 minutes to index new IdentityRegistry mint events. Indexed agents appear in `/discover` and can be imported via `/hydrate`.++---++## Database Schema++The Postgres schema (`api/_lib/schema.sql`) is fully idempotent — all migrations use `CREATE TABLE IF NOT EXISTS` patterns. Safe to re-run on any environment.++**Core tables:**++```sql+-- Users+users (id, email, password_hash, display_name, avatar_url, plan, wallet_address, deleted_at)++-- 3D model files+avatars (id, owner_id, slug, name, description, storage_key, visibility,+ tags, checksum_sha256, version, deleted_at)++-- Sessions+sessions (id, user_id, token_hash, user_agent, ip, expires_at, revoked_at)++-- Developer API keys+api_keys (id, user_id, prefix, token_hash, scope, expires_at, revoked_at)++-- Agent identities+agent_identities (id, user_id, name, description, avatar_id, skills,+ meta, wallet_address, erc8004_agent_id, deleted_at)++-- Signed action log+agent_actions (id, agent_id, type, payload, source_skill,+ signature, signer_address, created_at)++-- Memory store+agent_memories (id, agent_id, type, content, tags, context,+ salience, expires_at, created_at)```-https://three.ws/#model=https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/FlightHelmet/glTF/FlightHelmet.gltf++**OAuth tables:**++```sql+oauth_clients (client_id, client_secret_hash, redirect_uris, grant_types, scope, ...)+oauth_auth_codes (code, client_id, user_id, code_challenge, expires_at, consumed_at)+oauth_refresh_tokens(token_hash, client_id, user_id, scope, expires_at, revoked_at, ...)```+**Wallet & signing:**++```sql+user_wallets (user_id, address, chain_type, chain_id, is_primary)+siwe_nonces (nonce, address, issued_at, expires_at, consumed_at)+siws_nonces (same shape for Solana)```-https://three.ws/#model=https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/Fox/glTF-Binary/Fox.glb++**Usage & quotas:**++```sql+usage_events (user_id, api_key_id, client_id, avatar_id, kind, tool, status, bytes, latency_ms)+plan_quotas (plan, max_avatars, max_bytes_per_avatar, max_total_bytes)```-### Use the JavaScript API (Advanced)+---++## Build & Deployment-The viewer exposes its internals on `window.VIEWER` for debugging:+### npm Scripts-```javascript-// Access the loaded glTF JSON-console.log(window.VIEWER.json);+| Command | Description |+|---|---|+| `npm run dev` | Vite dev server on port 3000 with HMR |+| `npm run build` | Production build to `dist/` |+| `npm run build:lib` | Build `<agent-3d>` web component library to `dist-lib/` |+| `npm run build:artifact` | Build standalone Claude artifact viewer bundle |+| `npm run build:all` | build + build:lib + publish:lib |+| `npm run publish:lib` | Publish versioned CDN bundles to `/agent-3d/` |+| `npm run test` | Run Vitest suite |+| `npm run verify` | Prettier check + Vite build (pre-deploy gate) |+| `npm run format` | Prettier write (entire repo) |+| `npm run deploy` | build:all + vercel --prod |+| `npm run clean` | Remove dist/ and dist-lib/ |+| `npm run fetch-animations` | Download animation clip assets |+| `npm run generate-icons` | Generate PWA icon set |-// Access the Three.js scene graph-console.log(window.VIEWER.scene);+### Vercel Deployment-// Traverse all meshes-window.VIEWER.scene.traverse((node) => {- if (node.isMesh) {- console.log(node.name, node.geometry.attributes);- }-});+The project is built for Vercel. Deployment is one command:++```bash+npm run deploy```-### Custom Environment Maps+This runs `build:all` then `vercel --prod`. Routing, rewrites, cache headers, and cron schedules are defined in `vercel.json`.++For preview deployments, push a branch — Vercel auto-deploys it with a preview URL.++**Environment variables** must be set in the Vercel dashboard (not in `.env` files). See [Environment Variables](#environment-variables) for the full list.++### Self-Hosting-Add your own HDR environments by editing `src/environments.js`:+For a traditional server deployment:-```javascript-{- id: 'my-studio',- name: 'My Studio',- path: 'https://your-cdn.com/studio_1k.exr',- format: '.exr',+1. Build: `npm run build` → `dist/`+2. Serve `dist/` as static files (nginx, Caddy, Express)+3. Run `api/` endpoints via Node.js (wrap with Express or use the Vercel dev adapter)+4. Connect to Postgres (Neon or self-hosted)+5. Connect to S3-compatible storage (R2, MinIO, AWS S3)+6. Schedule cron jobs with node-cron or systemd timers++**Minimal nginx config:**+```nginx+server {+ listen 80;+ root /var/www/3d-agent/dist;+ index index.html;++ location /api {+ proxy_pass http://localhost:3001;+ }++ location / {+ try_files $uri $uri/ /index.html;+ }}```-The viewer uses `EXRLoader` + `PMREMGenerator` to process equirectangular HDR maps into prefiltered environment cubemaps.+----<br/>+## Environment Variables----+### Required (Backend)-<br/>+```env+# App+PUBLIC_APP_ORIGIN=https://three.ws # No trailing slash-## 🤝 Contributing+# Database+DATABASE_URL=postgres://user:pass@host/db # Neon or any Postgres 15+-1. Fork the repo-2. Create a feature branch: `git checkout -b feat/my-feature`-3. Make your changes and test locally with `npm run dev`-4. Submit a pull request+# Object storage (Cloudflare R2 or S3-compatible)+S3_ENDPOINT=https://...+S3_ACCESS_KEY_ID=...+S3_SECRET_ACCESS_KEY=...+S3_BUCKET=3d-agent-avatars+S3_PUBLIC_DOMAIN=https://cdn.three.ws # CDN base URL for public model URLs-File issues and feature requests at [github.com/nirholas/3d-agent/issues](https://github.com/nirholas/3d-agent/issues).+# Redis (rate limiting)+UPSTASH_REDIS_REST_URL=...+UPSTASH_REDIS_REST_TOKEN=...-See [CONTRIBUTING.md](CONTRIBUTING.md) for the full guide.+# Auth+JWT_SECRET=<base64> # openssl rand -base64 64+JWT_KID=k1 # Key ID (rotate by incrementing)+PASSWORD_ROUNDS=11 # bcrypt cost factor-<br/>+# LLM+ANTHROPIC_API_KEY=sk-ant-...+CHAT_MODEL=claude-sonnet-4-6+CHAT_MAX_TOKENS=1024+```----+### Optional (Backend)-<br/>+```env+# Email (required for registration flow)+RESEND_API_KEY=...-## 📖 Documentation+# Error monitoring+SENTRY_DSN=...-For deeper technical detail, see the `docs/` directory:+# Privy (social/embedded wallets)+PRIVY_APP_ID=...+PRIVY_APP_SECRET=...-| Document | Description |-| :--------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| **[Architecture](docs/ARCHITECTURE.md)** | Data flow, module responsibilities, Three.js setup, validation pipeline, GUI structure, styling architecture, and security considerations |-| **[API Reference](docs/API.md)** | Complete reference for all classes (`App`, `Viewer`, `Validator`), methods, properties, state objects, components, and the `window.VIEWER` debugging API |-| **[Deployment](docs/DEPLOYMENT.md)** | Build pipeline, Vercel deploy, routing, CORS config, custom domains, iframe embedding, self-hosting (nginx, Docker), CDN strategy, and troubleshooting |-| **[Development](docs/DEVELOPMENT.md)** | Local setup, code style, how-things-work guide, common tasks (new GUI controls, components, environments), debugging techniques, browser compatibility, and performance notes |-| **[Backend Setup](docs/SETUP.md)** | Environment variables, Neon/R2/Upstash provisioning, schema migration, CORS, and deploy |-| **[Widgets](docs/WIDGETS.md)** | Widget types, URL params, postMessage API, oEmbed, and privacy model |-| **[Pages](docs/PAGES.md)** | Full audit of every user-facing page URL (marketing, app, dashboard, agent, studio, widgets, legal, etc.) |-| **[MCP](docs/MCP.md)** | Model Context Protocol endpoint (`/api/mcp`) + OAuth integration |-| **[Contributing](CONTRIBUTING.md)** | Bug reporting, feature requests, PR workflow, commit conventions, code guidelines, and testing checklist |+# Avatar regeneration+AVATURN_API_KEY=...+AVATAR_REGEN_PROVIDER=none # none | avaturn-<br/>+# EIP-7710 permissions relayer+PERMISSIONS_RELAYER_ENABLED=false+AGENT_RELAYER_KEY=0x...+AGENT_RELAYER_ADDRESS=0x...++# Per-chain RPC URLs (add chains as needed)+RPC_URL_84532=https://sepolia.base.org+RPC_URL_8453=https://mainnet.base.org++# IPFS pinning+PINATA_JWT=...+WEB3_STORAGE_TOKEN=... # Fallback+```++### Optional (Frontend, prefixed `VITE_`)++```env+VITE_RPM_SUBDOMAIN=demo # Ready Player Me subdomain+VITE_PRIVY_APP_ID=...+VITE_AVATURN_EDITOR_URL=https://editor.avaturn.me/+VITE_AVATURN_DEVELOPER_ID=...+```++---++## Testing++The test suite uses Vitest. API tests mock the database and auth layer; frontend tests mock the viewer.++```bash+npm run test # All tests+npm run test -- tests/api/agents # Specific file+npm run verify # prettier check + vite build+```++**Test coverage:**++| Area | Files |+|---|---|+| Agent CRUD | `tests/api/agents.test.js` |+| Widget CRUD | `tests/api/widgets.test.js` |+| OAuth flow | `tests/api/oauth-authorize.test.js`, `oauth-token.test.js` |+| SIWE wallet auth | `tests/api/siwe.test.js` |+| LLM proxy | `tests/api/llm-anthropic.test.js` |+| Schema validation | `tests/api/validate.test.js` |+| API keys | `tests/api/api-keys.test.js` |+| Crypto utilities | `tests/api/crypto.test.js` |+| Embed CORS policy | `tests/api/embed-policy.test.js` |+| Animation slots | `tests/src/animation-slots.test.js` |+| Widget types | `tests/src/widget-types.test.js` |++Smart contract tests are in `contracts/test/` and run via Foundry:+```bash+cd contracts && forge test+```----<br/>+## Contributing-## 📚 Resources+See [CONTRIBUTING.md](CONTRIBUTING.md) for the full contributor guide.-| Resource | Link |-| :----------------- | :------------------------------------------------------------------------------------- |-| **glTF 2.0 Spec** | [registry.khronos.org/glTF](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html) |-| **Sample Models** | [KhronosGroup/glTF-Sample-Assets](https://github.com/KhronosGroup/glTF-Sample-Assets) |-| **three.js Docs** | [threejs.org/docs](https://threejs.org/docs/) |-| **GLTFLoader** | [three.js GLTFLoader](https://threejs.org/docs/#examples/en/loaders/GLTFLoader) |-| **glTF Validator** | [KhronosGroup/gltf-validator](https://github.com/KhronosGroup/gltf-validator) |-| **Sketchfab** | [sketchfab.com](https://sketchfab.com/) — download free glTF models |-| **Mixamo** | [mixamo.com](https://www.mixamo.com/) — free rigged & animated characters |-| **Poly Haven** | [polyhaven.com](https://polyhaven.com/) — free HDRIs, textures, and 3D models |+**Quick rules:**+- Match existing style — no reformatting adjacent code+- Every changed line should trace to the task+- Add tests for new API endpoints+- Run `npm run verify` before opening a PR (Prettier + build check)+- Keep PRs focused — one concern per PR-<br/>+**Branch conventions:**+- `feat/...` — new features+- `fix/...` — bug fixes+- `refactor/...` — structural changes without behavior changes+- `docs/...` — documentation only++**Development tips:**+- The viewer runs standalone at `/app` — no auth, no backend required+- Use `mode=view` in the `<agent-3d>` element to test rendering without a brain+- Set `CHAT_MODEL=claude-haiku-4-5-20251001` locally to keep API costs low during development+- The MCP server can be tested with `curl` — it's plain JSON-RPC over HTTP----<br/>+## License++Apache 2.0 — see [LICENSE](LICENSE).-<p align="center">- <img src="assets/footer-banner.svg" width="400" height="60" alt="Built by nirholas"/>-</p>+The three.js library (`node_modules/three`) is MIT licensed. The gltf-validator (`node_modules/gltf-validator`) is Apache 2.0. See each dependency's license for details.++----<p align="center">- <sub>Apache 2.0 License · Made with three.js · Hosted on Vercel</sub>-</p>+*Built with [three.js](https://threejs.org), [Claude](https://claude.ai), and a belief that AI deserves a body.*diff --git a/agent-home.html b/agent-home.htmlindex da2fd5282..688566107 100644--- a/agent-home.html+++ b/agent-home.html@@ -121,12 +121,17 @@}.agent-page-header {+ position: sticky;+ top: 0;+ z-index: 100;display: flex;align-items: center;gap: 1rem;padding: 0.75rem 1.618rem;border-bottom: 1px solid rgba(255, 255, 255, 0.08);- background: #000;+ background: rgba(0, 0, 0, 0.85);+ backdrop-filter: blur(12px);+ -webkit-backdrop-filter: blur(12px);}.agent-page-header a {@@ -135,6 +140,7 @@font-size: 0.764rem;display: inline-flex;align-items: center;+ transition: color 0.15s;}.agent-page-header a:hover {@@ -147,6 +153,22 @@display: block;}+ .agent-header-nav {+ display: flex;+ align-items: center;+ gap: 1.25rem;+ margin-left: 1.5rem;+ }++ .agent-header-nav a {+ font-size: 0.8rem;+ color: rgba(255, 255, 255, 0.45);+ }++ .agent-header-nav a:hover {+ color: rgba(255, 255, 255, 0.9);+ }+.agent-stage {max-width: 720px;margin: 2.5rem auto 0;@@ -238,16 +260,28 @@}.agent-page-title {- font-size: 1.618rem;+ font-size: 2rem;font-weight: 300;- color: #fff;- letter-spacing: -0.02em;+ background: linear-gradient(135deg, #fff 0%, rgba(255,255,255,0.7) 100%);+ -webkit-background-clip: text;+ -webkit-text-fill-color: transparent;+ background-clip: text;+ letter-spacing: -0.03em;margin: 0 0 0.618rem;}+ .agent-page-hero::after {+ content: '';+ display: block;+ width: 40px;+ height: 1px;+ background: rgba(255, 255, 255, 0.15);+ margin: 1rem auto 0;+ }+.agent-page-subtitle {- font-size: 0.764rem;- color: rgba(255, 255, 255, 0.55);+ font-size: 0.82rem;+ color: rgba(255, 255, 255, 0.5);line-height: 1.618;}@@ -263,8 +297,9 @@.agent-page-card-wrap .agent-home-panel {background: rgba(12, 12, 18, 0.98);- border: 1px solid rgba(255, 255, 255, 0.08);+ border: 1px solid rgba(255, 255, 255, 0.1);border-radius: 12px;+ box-shadow: 0 0 0 1px rgba(255,255,255,0.03), 0 8px 32px rgba(0,0,0,0.6);}.agent-embed-hint {@@ -360,10 +395,12 @@}.agent-embed-label {- font-size: 0.618rem;- color: rgba(255, 255, 255, 0.25);- margin: 0 0 0.382rem;- font-weight: 400;+ font-size: 0.7rem;+ color: rgba(255, 255, 255, 0.4);+ margin: 0 0 0.618rem;+ font-weight: 500;+ text-transform: uppercase;+ letter-spacing: 0.1em;}.agent-embed-preview-link {@@ -385,12 +422,12 @@}.agent-skills-title {- font-size: 0.618rem;- color: rgba(255, 255, 255, 0.25);- margin: 0 0 0.618rem;+ font-size: 0.7rem;+ color: rgba(255, 255, 255, 0.4);+ margin: 0 0 0.75rem;text-transform: uppercase;- letter-spacing: 0.08em;- font-weight: 400;+ letter-spacing: 0.1em;+ font-weight: 500;}.agent-skills-grid {@@ -401,21 +438,27 @@.agent-skill-card {background: rgba(255, 255, 255, 0.04);- border: 1px solid rgba(255, 255, 255, 0.07);+ border: 1px solid rgba(255, 255, 255, 0.08);border-radius: 8px;- padding: 0.618rem;+ padding: 0.75rem;+ transition: border-color 0.15s, background 0.15s;+ }++ .agent-skill-card:hover {+ border-color: rgba(255, 255, 255, 0.2);+ background: rgba(255, 255, 255, 0.07);}.agent-skill-card-name {font-size: 0.764rem;font-weight: 500;- color: rgba(255, 255, 255, 0.7);+ color: rgba(255, 255, 255, 0.85);margin-bottom: 0.236rem;}.agent-skill-card-desc {font-size: 0.618rem;- color: rgba(255, 255, 255, 0.3);+ color: rgba(255, 255, 255, 0.4);line-height: 1.382;}@@ -430,9 +473,17 @@<body><a href="#main" class="skip-link">Skip to main content</a><header class="agent-page-header" style="justify-content: space-between">- <a href="/" aria-label="Back to three.ws home">- <img src="/three.svg" alt="three.ws" class="agent-header-logo" />- </a>+ <div style="display:inline-flex;align-items:center">+ <a href="/" aria-label="Back to three.ws home">+ <img src="/three.svg" alt="three.ws" class="agent-header-logo" />+ </a>+ <nav class="agent-header-nav" aria-label="Primary">+ <a href="/discover">Discover</a>+ <a href="/create">Create</a>+ <a href="/features">Features</a>+ <a href="/studio">Studio</a>+ </nav>+ </div><!-- BEGIN:AGENT_HOME_ORPHANS_DOM --><div id="agent-share-btn-mount"></div><!-- END:AGENT_HOME_ORPHANS_DOM -->diff --git a/api/_lib/erc8004-chains.js b/api/_lib/erc8004-chains.jsindex 970a3b36f..43ee3cb9d 100644--- a/api/_lib/erc8004-chains.js+++ b/api/_lib/erc8004-chains.js@@ -21,6 +21,7 @@ export const CHAINS = [testnet: false,registry: IDENTITY_REGISTRY_MAINNET,explorer: 'https://basescan.org',+ rpcUrl: 'https://mainnet.base.org',},{id: 42161,@@ -28,6 +29,7 @@ export const CHAINS = [testnet: false,registry: IDENTITY_REGISTRY_MAINNET,explorer: 'https://arbiscan.io',+ rpcUrl: 'https://arb1.arbitrum.io/rpc',},{id: 56,@@ -35,6 +37,7 @@ export const CHAINS = [testnet: false,registry: IDENTITY_REGISTRY_MAINNET,explorer: 'https://bscscan.com',+ rpcUrl: 'https://bsc-dataseed1.binance.org',},{id: 1,@@ -42,6 +45,7 @@ export const CHAINS = [testnet: false,registry: IDENTITY_REGISTRY_MAINNET,explorer: 'https://etherscan.io',+ rpcUrl: 'https://eth.llamarpc.com',},{id: 10,@@ -49,6 +53,7 @@ export const CHAINS = [testnet: false,registry: IDENTITY_REGISTRY_MAINNET,explorer: 'https://optimistic.etherscan.io',+ rpcUrl: 'https://mainnet.optimism.io',},{id: 137,@@ -56,6 +61,7 @@ export const CHAINS = [testnet: false,registry: IDENTITY_REGISTRY_MAINNET,explorer: 'https://polygonscan.com',+ rpcUrl: 'https://polygon-rpc.com',},{id: 43114,@@ -63,6 +69,7 @@ export const CHAINS = [testnet: false,registry: IDENTITY_REGISTRY_MAINNET,explorer: 'https://snowtrace.io',+ rpcUrl: 'https://api.avax.network/ext/bc/C/rpc',},{id: 100,@@ -70,6 +77,7 @@ export const CHAINS = [testnet: false,registry: IDENTITY_REGISTRY_MAINNET,explorer: 'https://gnosisscan.io',+ rpcUrl: 'https://rpc.gnosischain.com',},{id: 250,@@ -77,6 +85,7 @@ export const CHAINS = [testnet: false,registry: IDENTITY_REGISTRY_MAINNET,explorer: 'https://ftmscan.com',+ rpcUrl: 'https://rpc.ankr.com/fantom',},{id: 42220,@@ -84,6 +93,7 @@ export const CHAINS = [testnet: false,registry: IDENTITY_REGISTRY_MAINNET,explorer: 'https://celoscan.io',+ rpcUrl: 'https://forno.celo.org',},{id: 59144,@@ -91,6 +101,7 @@ export const CHAINS = [testnet: false,registry: IDENTITY_REGISTRY_MAINNET,explorer: 'https://lineascan.build',+ rpcUrl: 'https://rpc.linea.build',},{id: 534352,@@ -98,6 +109,7 @@ export const CHAINS = [testnet: false,registry: IDENTITY_REGISTRY_MAINNET,explorer: 'https://scrollscan.com',+ rpcUrl: 'https://rpc.scroll.io',},{id: 5000,@@ -105,6 +117,7 @@ export const CHAINS = [testnet: false,registry: IDENTITY_REGISTRY_MAINNET,explorer: 'https://explorer.mantle.xyz',+ rpcUrl: 'https://rpc.mantle.xyz',},{id: 324,@@ -112,6 +125,7 @@ export const CHAINS = [testnet: false,registry: IDENTITY_REGISTRY_MAINNET,explorer: 'https://explorer.zksync.io',+ rpcUrl: 'https://mainnet.era.zksync.io',},{id: 1284,@@ -119,6 +133,7 @@ export const CHAINS = [testnet: false,registry: IDENTITY_REGISTRY_MAINNET,explorer: 'https://moonbeam.moonscan.io',+ rpcUrl: 'https://rpc.api.moonbeam.network',},{id: 97,@@ -126,6 +141,7 @@ export const CHAINS = [testnet: true,registry: IDENTITY_REGISTRY_TESTNET,explorer: 'https://testnet.bscscan.com',+ rpcUrl: 'https://data-seed-prebsc-1-s1.bnbchain.org:8545',},{id: 84532,@@ -133,6 +149,7 @@ export const CHAINS = [testnet: true,registry: IDENTITY_REGISTRY_TESTNET,explorer: 'https://sepolia.basescan.org',+ rpcUrl: 'https://sepolia.base.org',},{id: 421614,@@ -140,6 +157,7 @@ export const CHAINS = [testnet: true,registry: IDENTITY_REGISTRY_TESTNET,explorer: 'https://sepolia.arbiscan.io',+ rpcUrl: 'https://sepolia-rollup.arbitrum.io/rpc',},{id: 11155111,@@ -147,6 +165,7 @@ export const CHAINS = [testnet: true,registry: IDENTITY_REGISTRY_TESTNET,explorer: 'https://sepolia.etherscan.io',+ rpcUrl: 'https://rpc2.sepolia.org',},{id: 11155420,@@ -154,6 +173,7 @@ export const CHAINS = [testnet: true,registry: IDENTITY_REGISTRY_TESTNET,explorer: 'https://sepolia-optimism.etherscan.io',+ rpcUrl: 'https://sepolia.optimism.io',},{id: 80002,@@ -161,6 +181,7 @@ export const CHAINS = [testnet: true,registry: IDENTITY_REGISTRY_TESTNET,explorer: 'https://amoy.polygonscan.com',+ rpcUrl: 'https://rpc-amoy.polygon.technology',},{id: 43113,@@ -168,6 +189,7 @@ export const CHAINS = [testnet: true,registry: IDENTITY_REGISTRY_TESTNET,explorer: 'https://testnet.snowtrace.io',+ rpcUrl: 'https://api.avax-test.network/ext/bc/C/rpc',},];diff --git a/api/cron/erc8004-crawl.js b/api/cron/erc8004-crawl.jsindex 1023a151b..494a29591 100644--- a/api/cron/erc8004-crawl.js+++ b/api/cron/erc8004-crawl.js@@ -9,9 +9,10 @@** Flow per chain:* 1. Read last scanned block from erc8004_crawl_cursor.- * 2. eth_getLogs via the chain's public RPC — Registered events since that block.+ * 2. eth_getLogs over the next BLOCK_CHUNK blocks via the chain's public RPC.* 3. Decode agentId (topic1), owner (topic2), agentURI (data) and upsert.- * 4. Advance cursor.+ * 4. Fetch block timestamps for events found (eth_getBlockByNumber).+ * 5. Advance cursor to end of scanned range.** Metadata pass: pick the 20 oldest-metadata rows, fetch JSON, extract* name/description/image/services/has_3d, write back.@@ -20,24 +21,29 @@import { id as keccakId, AbiCoder, getAddress } from 'ethers';import { sql } from '../_lib/db.js';import { cors, error, json, wrap } from '../_lib/http.js';-import { env } from '../_lib/env.js';import { CHAINS } from '../_lib/erc8004-chains.js';-import { SERVER_CHAIN_META } from '../_lib/onchain.js';const REGISTERED_TOPIC = keccakId('Registered(uint256,string,address)');const ABI_CODER = AbiCoder.defaultAbiCoder();+// Blocks scanned per chain per cron invocation. Public RPCs typically allow+// 2000-block ranges; lower this if a chain's RPC rejects with "block range".+const BLOCK_CHUNK = 2_000;++// On first run (no cursor), scan this many recent blocks. Set+// ERC8004_CRAWL_LOOKBACK env var to override (e.g. larger for backfill).+const DEFAULT_LOOKBACK = parseInt(process.env.ERC8004_CRAWL_LOOKBACK || '50000', 10);+// Metadata enrichment per invocation.const METADATA_BATCH = 25;-// Per-request timeout so one stuck chain can't eat the whole cron budget.-const FETCH_TIMEOUT_MS = 8_000;+const FETCH_TIMEOUT_MS = 10_000;export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;const auth = req.headers['authorization'] || '';- const expected = env.CRON_SECRET ? `Bearer ${env.CRON_SECRET}` : null;+ const expected = process.env.CRON_SECRET ? `Bearer ${process.env.CRON_SECRET}` : null;const fromCron = req.headers['x-vercel-cron'] === '1';if (!fromCron && expected && auth !== expected) {return error(res, 401, 'unauthorized', 'cron secret required');@@ -45,7 +51,6 @@ export default wrap(async (req, res) => {const report = { chains: [], enriched: 0, errors: [] };- // 1. Crawl logs chain-by-chain.for (const chain of CHAINS) {try {const r = await crawlChain(chain);@@ -55,7 +60,6 @@ export default wrap(async (req, res) => {}}- // 2. Enrich metadata for the oldest-seen rows.try {report.enriched = await enrichMetadata(METADATA_BATCH);} catch (err) {@@ -68,37 +72,58 @@ export default wrap(async (req, res) => {// ─── Log crawl ───────────────────────────────────────────────────────────async function crawlChain(chain) {- const meta = SERVER_CHAIN_META[chain.id];- if (!meta?.rpc) return { inserted: 0, skipped: true, reason: 'no_rpc' };-const [cursor] = await sql`SELECT last_block FROM erc8004_crawl_cursor WHERE chain_id = ${chain.id}`;- const fromBlock = cursor ? Number(cursor.last_block) + 1 : 0;- const latestHex = await rpc(meta.rpc, 'eth_blockNumber', []);- const latest = Number(latestHex);- if (fromBlock > latest) return { inserted: 0, lastBlock: latest, fromBlock };+ const latestHex = await rpcCall(chain.rpcUrl, 'eth_blockNumber', []);+ const latestBlock = Number.parseInt(latestHex, 16);- const logs = await rpc(meta.rpc, 'eth_getLogs', [{- address: chain.registry,- topics: [REGISTERED_TOPIC],- fromBlock: '0x' + fromBlock.toString(16),- toBlock: '0x' + latest.toString(16),- }]);+ const fromBlock = cursor+ ? Number(cursor.last_block) + 1+ : Math.max(0, latestBlock - DEFAULT_LOOKBACK);- let lastBlock = fromBlock - 1;- let inserted = 0;+ if (fromBlock > latestBlock) {+ return { inserted: 0, scanned: 0, lastBlock: latestBlock, fromBlock };+ }++ const toBlock = Math.min(fromBlock + BLOCK_CHUNK - 1, latestBlock);+ const logs = await rpcCall(chain.rpcUrl, 'eth_getLogs', [+ {+ address: chain.registry,+ topics: [REGISTERED_TOPIC],+ fromBlock: '0x' + fromBlock.toString(16),+ toBlock: '0x' + toBlock.toString(16),+ },+ ]);++ // Fetch block timestamps for any blocks that produced events.+ const blockTimes = {};+ if (logs.length > 0) {+ const uniqueBlockHexes = [...new Set(logs.map((l) => l.blockNumber))];+ await Promise.all(+ uniqueBlockHexes.map(async (bn) => {+ try {+ const block = await rpcCall(chain.rpcUrl, 'eth_getBlockByNumber', [bn, false]);+ blockTimes[bn] = block ? Number.parseInt(block.timestamp, 16) : null;+ } catch {+ // registered_at will be null for this block+ }+ }),+ );+ }++ let inserted = 0;for (const log of logs) {try {const agentId = BigInt(log.topics[1]).toString();const ownerHex = '0x' + log.topics[2].slice(-40);const owner = getAddress(ownerHex).toLowerCase();const [agentURI] = ABI_CODER.decode(['string'], log.data);- const blockNumber = Number(log.blockNumber);- const timestamp = Number(log.timeStamp);- const registeredAt = new Date(timestamp * 1000).toISOString();+ const blockNumber = Number.parseInt(log.blockNumber, 16);+ const ts = blockTimes[log.blockNumber];+ const registeredAt = ts ? new Date(ts * 1000).toISOString() : null;await sql`INSERT INTO erc8004_agents_index@@ -109,27 +134,26 @@ async function crawlChain(chain) {${agentURI || null}, ${blockNumber}, ${log.transactionHash},${registeredAt}, now())ON CONFLICT (chain_id, agent_id) DO UPDATE SET- owner = excluded.owner,+ owner = excluded.owner,agent_uri = COALESCE(excluded.agent_uri, erc8004_agents_index.agent_uri),last_seen_at = now()`;inserted += 1;- if (blockNumber > lastBlock) lastBlock = blockNumber;} catch (decodeErr) {console.warn('[crawl] decode failed', chain.id, log.transactionHash, decodeErr.message);}}- const newCursor = Math.max(lastBlock, fromBlock - 1, latest);+ // Always advance cursor to toBlock so the next run continues from here.await sql`INSERT INTO erc8004_crawl_cursor (chain_id, last_block, updated_at)- VALUES (${chain.id}, ${newCursor}, now())+ VALUES (${chain.id}, ${toBlock}, now())ON CONFLICT (chain_id) DO UPDATE SET- last_block = GREATEST(erc8004_crawl_cursor.last_block, excluded.last_block),+ last_block = GREATEST(erc8004_crawl_cursor.last_block, ${toBlock}),updated_at = now()`;- return { inserted, lastBlock: newCursor, fromBlock };+ return { inserted, scanned: toBlock - fromBlock + 1, lastBlock: toBlock, fromBlock };}// ─── Metadata enrichment ─────────────────────────────────────────────────@@ -151,7 +175,8 @@ async function enrichMetadata(limit) {if (!meta) {await sql`UPDATE erc8004_agents_index- SET metadata_error = 'fetch failed', last_metadata_at = now()+ SET metadata_error = 'fetch failed',+ last_metadata_at = now()WHERE chain_id = ${row.chain_id} AND agent_id = ${row.agent_id}`;continue;@@ -197,17 +222,23 @@ async function enrichMetadata(limit) {// ─── Helpers ─────────────────────────────────────────────────────────────-async function rpc(url, method, params) {- const res = await fetch(url, {- method: 'POST',- headers: { 'content-type': 'application/json' },- body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),- signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),- });- if (!res.ok) throw new Error(`HTTP ${res.status}`);- const body = await res.json();- if (body.error) throw new Error(`RPC ${body.error.code}: ${body.error.message}`);- return body.result;+async function rpcCall(url, method, params) {+ const ac = new AbortController();+ const t = setTimeout(() => ac.abort(), FETCH_TIMEOUT_MS);+ try {+ const res = await fetch(url, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),+ signal: ac.signal,+ });+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ const data = await res.json();+ if (data.error) throw new Error(`RPC ${data.error.code}: ${data.error.message}`);+ return data.result;+ } finally {+ clearTimeout(t);+ }}async function fetchAgentMetadata(uri) {diff --git a/public/features/index.html b/public/features/index.htmlindex 9d0b5168d..4c3e0c75b 100644--- a/public/features/index.html+++ b/public/features/index.html@@ -27,6 +27,7 @@<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /><link rel="stylesheet" href="/style.css" /><link rel="stylesheet" href="/features/features.css" />+ <link rel="stylesheet" href="/footer.css" /><linkhref="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500&family=Space+Grotesk:wght@500;600;700&display=swap"rel="stylesheet"@@ -437,22 +438,70 @@</p></li></ul>- <footer class="features-footer">- <p>- three.ws ·- <a href="https://github.com/nirholas/3D" target="_blank" rel="noopener">GitHub</a> ·- <a href="/create">Create</a> ·- <a href="/studio">Studio</a> ·- <a href="/widgets">Widgets</a> ·- <a href="/features">Features</a> ·- <a href="/discover">Discover</a> ·- <a href="/docs/widgets">Docs</a> ·- <a href="https://eips.ethereum.org/EIPS/eip-8004" target="_blank" rel="noopener">ERC-8004</a> ·- <a href="/legal/privacy">Privacy</a> ·- <a href="/legal/tos">Terms</a>- </p>- </footer></section>++ <footer class="h-footer-horizon">+ <div class="h-footer-glow-line" aria-hidden="true"></div>+ <div class="h-footer-floor" aria-hidden="true"></div>+ <div class="h-footer-haze" aria-hidden="true"></div>+ <div class="h-footer-watermark" aria-hidden="true">three.ws</div>+ <div class="h-footer-avatar" aria-hidden="true">+ <model-viewer+ src="/animations/robotexpressive.glb"+ auto-rotate+ auto-rotate-delay="0"+ rotation-per-second="20deg"+ interaction-prompt="none"+ camera-controls="false"+ disable-zoom+ shadow-intensity="0"+ exposure="0.7"+ environment-image="neutral"+ camera-orbit="0deg 80deg 4m"+ field-of-view="35deg"+ loading="lazy"+ ></model-viewer>+ </div>+ <div class="h-footer-inner">+ <div class="h-footer-brand-col">+ <div class="h-footer-brand">+ <span class="wordmark-dot" aria-hidden="true"></span>+ <span>three.ws</span>+ </div>+ <p class="h-footer-tagline">Give your AI a body.</p>+ </div>+ <nav class="h-footer-links" aria-label="Footer">+ <a href="https://github.com/nirholas/3D" target="_blank" rel="noopener">GitHub</a>+ <a href="/create">Create</a>+ <a href="/studio">Studio</a>+ <a href="/widgets">Widgets</a>+ <a href="/features">Features</a>+ <a href="/discover">Discover</a>+ <a href="/showcase">Showcase</a>+ <a href="/docs/widgets">Docs</a>+ <a href="https://eips.ethereum.org/EIPS/eip-8004" target="_blank" rel="noopener">ERC-8004</a>+ <a href="/legal/privacy">Privacy</a>+ <a href="/legal/tos">Terms</a>+ </nav>+ </div>+ <div class="h-footer-bottom">+ <p class="h-footer-legal">© 2026 three.ws — All rights reserved.</p>+ <div class="h-footer-badges">+ <span class="h-footer-badge" aria-label="System status">+ <span class="h-footer-status-dot" aria-hidden="true"></span>+ <span>All systems normal</span>+ </span>+ <span class="h-footer-badge">+ <svg viewBox="0 0 16 16" aria-hidden="true"><path fill="currentColor" d="M8 0a8 8 0 1 0 0 16A8 8 0 0 0 8 0zm0 14.5A6.5 6.5 0 1 1 8 1.5a6.5 6.5 0 0 1 0 13zm-1-9.25a1 1 0 1 1 2 0v3.5a1 1 0 1 1-2 0v-3.5zm1 6.5a1.1 1.1 0 1 1 0-2.2 1.1 1.1 0 0 1 0 2.2z"/></svg>+ <span>Transparent by default</span>+ </span>+ <a class="h-footer-badge" href="https://github.com/nirholas/3D" target="_blank" rel="noopener" aria-label="View source on GitHub">+ <svg viewBox="0 0 16 16" aria-hidden="true"><path fill="currentColor" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z"/></svg>+ <span>Open source</span>+ </a>+ </div>+ </div>+ </footer></main><nav class="act-nav" aria-label="Section navigation">diff --git a/scripts/backfill-erc8004.mjs b/scripts/backfill-erc8004.mjsindex 41da57986..d8e81f195 100644--- a/scripts/backfill-erc8004.mjs+++ b/scripts/backfill-erc8004.mjs@@ -76,31 +76,80 @@ const CHAINS = [{ id: 43113, name: 'Avalanche Fuji', publicRpc: 'https://api.avax-test.network/ext/bc/C/rpc', registry: '0x8004A818BFB912233c491871b3d84c89A494BD9e' },];+// Alchemy free tier limits eth_getLogs to 10 blocks — useless for a backfill.+// Use public RPCs for scanning; Alchemy is better suited for the live cron.function rpcUrl(chain) {- if (ALCHEMY_KEY && ALCHEMY_SLUGS[chain.id]) {- return `https://${ALCHEMY_SLUGS[chain.id]}.g.alchemy.com/v2/${ALCHEMY_KEY}`;- }return chain.publicRpc;}-async function getLogs(chain) {- const url = rpcUrl(chain);+async function jsonRpc(url, method, params) {const res = await fetch(url, {method: 'POST',headers: { 'content-type': 'application/json' },- body: JSON.stringify({- jsonrpc: '2.0', id: 1,- method: 'eth_getLogs',- params: [{ address: chain.registry, topics: [REGISTERED_TOPIC], fromBlock: '0x0', toBlock: 'latest' }],- }),+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),signal: AbortSignal.timeout(30_000),});+ // Always try to parse JSON — some RPCs return a JSON-RPC error body with a non-200 status.+ let body;+ try { body = await res.json(); } catch { throw new Error(`HTTP ${res.status}`); }+ if (body?.error) throw new Error(`RPC ${body.error.code}: ${body.error.message}`);if (!res.ok) throw new Error(`HTTP ${res.status}`);- const body = await res.json();- if (body.error) throw new Error(`RPC ${body.error.code}: ${body.error.message}`);return body.result;}+async function getLogs(chain) {+ const preferred = rpcUrl(chain);+ // If Alchemy fails (network not enabled in app), fall back to public RPC.+ const urls = preferred !== chain.publicRpc ? [preferred, chain.publicRpc] : [chain.publicRpc];+ const url = urls[0];+ const filter = { address: chain.registry, topics: [REGISTERED_TOPIC], fromBlock: '0x0', toBlock: 'latest' };++ for (const endpoint of urls) {+ try {+ return await jsonRpc(endpoint, 'eth_getLogs', [filter]);+ } catch (e) {+ const isHttpErr = /HTTP \d/.test(e.message);+ const isRangeErr = /range|limit/i.test(e.message);++ // HTTP errors (400, 413, 429…) mean this endpoint won't work — try next.+ if (isHttpErr && endpoint !== urls.at(-1)) continue;++ // JSON-RPC range error — chunk with this endpoint.+ if (isRangeErr && !isHttpErr) {+ const match = e.message.match(/([\d,_]+)\s*(?:block|range)/i);+ const chunkSize = match ? parseInt(match[1].replace(/[,_]/g, ''), 10) : 2000;+ const latestHex = await jsonRpc(endpoint, 'eth_blockNumber', []);+ const latest = Number(latestHex);+ const logs = [];+ for (let from = 0; from <= latest; from += chunkSize) {+ const to = Math.min(from + chunkSize - 1, latest);+ let retries = 3;+ while (retries-- > 0) {+ try {+ const chunk = await jsonRpc(endpoint, 'eth_getLogs', [{+ ...filter,+ fromBlock: '0x' + from.toString(16),+ toBlock: '0x' + to.toString(16),+ }]);+ logs.push(...chunk);+ break;+ } catch (re) {+ if (/rate.limit|429/i.test(re.message) && retries > 0) {+ await new Promise(r => setTimeout(r, 1000));+ } else throw re;+ }+ }+ await new Promise(r => setTimeout(r, 80)); // avoid hammering the RPC+ process.stdout.write(`\r chunking ${Math.round(to / latest * 100)}%… `);+ }+ return logs;+ }++ throw e;+ }+ }+}+async function backfillChain(chain) {const logs = await getLogs(chain);let inserted = 0;diff --git a/vercel.json b/vercel.jsonindex 9b689def7..df8b142b6 100644--- a/vercel.json+++ b/vercel.json@@ -150,8 +150,8 @@{ "src": "/api/billing/summary", "dest": "/api/billing/summary" },- { "src": "/my-agents", "dest": "/my-agents/index.html" },- { "src": "/my-agents/", "dest": "/my-agents/index.html" },+ { "src": "/my-agents", "dest": "/public/my-agents/index.html" },+ { "src": "/my-agents/", "dest": "/public/my-agents/index.html" },{ "src": "/my-agents/(.*)", "dest": "/my-agents/$1" },{ "src": "/discover", "dest": "/discover/index.html" },{ "src": "/discover/", "dest": "/discover/index.html" },