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
feat: add widget documentation and gallery
nirholas0c85c0dd7479
diff --git a/.env.example b/.env.exampleindex d5e068430..446548d6f 100644--- a/.env.example+++ b/.env.example@@ -30,6 +30,13 @@ JWT_KID=k1# Password hashing cost (bcryptjs rounds)PASSWORD_ROUNDS=11+# Anthropic API key for /api/chat (agent LLM backend). If unset, chat falls back+# to pattern matching client-side.+ANTHROPIC_API_KEY=+# Optional overrides for chat model + output cap.+CHAT_MODEL=claude-sonnet-4-6+CHAT_MAX_TOKENS=1024+# Avatar creator subdomain (client-side; used by the avatar creator provider)VITE_AVATURN_SUBDOMAIN=diff --git a/README.md b/README.mdindex f66ee0649..2dd5093e6 100644--- a/README.md+++ b/README.md@@ -31,6 +31,26 @@ It's built for **3D artists** previewing exports, **game developers** debugging<br/>+## 🪟 Widget Studio — embeddable 3D, no code++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).++```html+<iframe src="https://3dagent.vercel.app/#widget=wdgt_abc123" width="600" height="600" style="border:0"></iframe>+```++- **[Open the Studio →](https://3dagent.vercel.app/studio)** — pick avatar, pick type, generate embed.+- **[Browse the gallery →](https://3dagent.vercel.app/widgets)** — live demos of every widget type.+- **[Read the docs →](https://3dagent.vercel.app/docs/widgets)** — URL params, postMessage API, oEmbed, privacy.++Widget URLs (`/w/<id>`) get rich Open Graph cards in Slack/Discord/X and auto-embed via oEmbed in WordPress, Ghost, and Notion.++<br/>++---++<br/>+## ✨ Features<br/>diff --git a/api/CLAUDE.md b/api/CLAUDE.mdnew file mode 100644index 000000000..0617a161f--- /dev/null+++ b/api/CLAUDE.md@@ -0,0 +1,175 @@+# api/CLAUDE.md++Scoped guidance for Vercel serverless endpoints. Read [/CLAUDE.md](../CLAUDE.md) first.++---++## Shape of every endpoint++Copy this. Don't hand-roll.++```js+import { sql } from '../_lib/db.js';+import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';+import { cors, json, method, wrap, error } from '../_lib/http.js';+import { parse } from '../_lib/validate.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { z } from 'zod';++const bodySchema = z.object({ name: z.string().trim().min(1).max(100) });++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET', 'POST'])) return;++ // Auth: session OR bearer+ const session = await getSessionUser(req);+ const bearer = session ? null : await authenticateBearer(extractBearer(req));+ if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');+ if (bearer && !hasScope(bearer.scope, 'avatars:read')) return error(res, 403, 'insufficient_scope', '...');+ const userId = session?.id ?? bearer.userId;++ // Rate limit+ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ if (req.method === 'POST') {+ const body = parse(bodySchema, await readJson(req));+ // ... do work+ }++ const rows = await sql`select id, name from avatars where owner_id = ${userId} and deleted_at is null`;+ return json(res, 200, { data: rows });+});+```++Never `res.end(JSON.stringify(...))`. Never read/verify JWTs yourself. Never interpolate user input into SQL.++---++## Helpers in [_lib/](./_lib/)++| File | Exports | Use for |+|---|---|---|+| [_lib/auth.js](_lib/auth.js) | `getSessionUser`, `authenticateBearer`, `extractBearer`, `hasScope`, `createSession`, `sessionCookie`, `destroySession`, `csrfTokenFor`, `verifyCsrfToken`, `isSameSiteOrigin` | All auth. Never roll your own. |+| [_lib/db.js](_lib/db.js) | `sql` | Tagged-template Postgres via `@neondatabase/serverless`. Import; don't instantiate a new Pool. |+| [_lib/http.js](_lib/http.js) | `cors`, `json`, `text`, `redirect`, `error`, `wrap`, `method`, `readJson` | Every response. `wrap()` catches async errors → 500. |+| [_lib/validate.js](_lib/validate.js) | `parse`, `email`, `password`, `displayName`, `slug`, `avatarVisibility`, `avatarContentType`, `registerBody`, `loginBody`, `createAvatarBody`, `presignUploadBody` | zod wrappers. `parse()` throws `{status:400, code:'validation_error'}`. |+| [_lib/rate-limit.js](_lib/rate-limit.js) | `limits.*`, `clientIp` | Preset Upstash limiters. |+| [_lib/r2.js](_lib/r2.js) | `presignUpload`, `presignGet`, `headObject`, `deleteObject`, `publicUrl` | R2 / S3 ops. |+| [_lib/env.js](_lib/env.js) | `env`, `env.ISSUER`, `env.MCP_RESOURCE` | Env vars. Throws if required ones missing. |+| [_lib/avatars.js](_lib/avatars.js) | `stripOwnerFor`, avatar URL resolution | Hides R2 path prefixes from unauthenticated callers. |++---++## Response conventions++- **Success:** `json(res, 200|201|204, { data, ... })` — no-store cache-control set for you.+- **Error:** `error(res, status, code, message, extra?)` → `{ error: code, error_description: message, ...extra }`.+- **Status codes:** 400 validation, 401 unauth, 403 forbidden, 404 not found, 409 conflict, 413 payload too large, 415 unsupported type, 429 rate-limited, 500 internal.+- **Error codes** (OAuth-style strings): `validation_error`, `unauthorized`, `forbidden`, `insufficient_scope`, `not_found`, `conflict`, `rate_limited`, `internal`.++---++## Auth modes++| Mode | Helper | When |+|---|---|---|+| Session cookie | `getSessionUser(req)` | Browser apps in [public/](../public/) — `credentials: 'include'` |+| Bearer JWT (OAuth) | `authenticateBearer(extractBearer(req))` → `{ userId, scope, source: 'oauth', clientId }` | MCP clients, third-party apps |+| Bearer API key | `authenticateBearer(...)` → `{ userId, scope, source: 'apikey', apiKeyId }` | Server-to-server from user scripts |++**Scopes:** `avatars:read`, `avatars:write`, `avatars:delete`, `profile`, `offline_access`. Check via `hasScope(bearer.scope, 'avatars:write')`.++**CSRF:** Only POST endpoints that accept HTML form submissions (OAuth consent, SIWE verify) need `csrfTokenFor` / `verifyCsrfToken`. JSON APIs rely on same-origin + session cookie. Call `destroySession(req)` before `createSession()` to defend against session fixation.++---++## Tables (Neon)++**Must-ask-first before changing any of these.**++- `users` — id, email, password_hash, display_name, plan, avatar_url, deleted_at+- `sessions` — token_hash, user_id, user_agent, ip, expires_at, revoked_at+- `api_keys` — prefix, token_hash, user_id, scope, expires_at, revoked_at+- `agent_identities` — id, user_id, name, description, avatar_id, skills, meta, wallet_address, chain_id, erc8004_agent_id, deleted_at+- `agent_actions` — agent_id, type, payload, source_skill, signature, signer_address, created_at+- `agent_memories` — agent_id, type (user/feedback/project/reference), content, tags, context, salience, expires_at+- `avatars` — owner_id, slug, name, description, storage_key, thumbnail_key, size_bytes, content_type, source, source_meta, visibility (private/unlisted/public), tags, checksum_sha256, version, deleted_at+- `oauth_clients`, `oauth_auth_codes`, `oauth_refresh_tokens` — OAuth 2.1 provider state+- `siwe_nonces` — Sign-In with Ethereum challenges+- `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+- `user_wallets` — user_id, address, chain_id, is_primary++---++## R2 upload flow++Three-step pattern — copy from [avatars/presign.js](avatars/presign.js) and [avatars/index.js](avatars/index.js):++1. Browser `POST /api/avatars/presign` → get signed PUT URL + `storage_key`. Key format: `u/{userId}/{slug}/{timestamp}.glb` (scoped by userId — don't skip this).+2. Browser `PUT` raw bytes to the signed URL.+3. Browser `POST /api/avatars` with `storage_key` to register metadata. Endpoint verifies the object exists via `headObject(key)` and size matches — don't skip this either.++For public/unlisted avatars use `publicUrl(key)` (CDN-cached). For private, `presignGet({ key, expiresIn: 600 })`.++---++## Rate-limit presets++Use the named preset that matches the endpoint. Don't invent new ones inline.++```js+limits.authIp(ip) // 30 / 10 min — login/register+limits.registerIp(ip) // 5 / 1 h+limits.oauthRegisterIp(ip) // 10 / 1 h — dynamic client reg+limits.mcpUser(userId) // 1200 / 1 min+limits.mcpIp(ip) // 600 / 1 min+limits.mcpValidate(key) // 10 / 1 min+limits.mcpInspect(key) // 30 / 1 min+limits.mcpOptimize(key) // 10 / 1 min+limits.oauthToken(clientId)// 120 / 1 min+limits.upload(userId) // 60 / 1 h+```++`clientIp(req)` reads `x-vercel-forwarded-for` → `x-real-ip` → socket.++---++## MCP endpoint — [mcp.js](mcp.js)++MCP 2025-06-18 over HTTP with JSON-RPC 2.0. Tools exposed: `list_my_avatars`, `get_avatar`, `search_public_avatars`, `render_avatar`, `delete_avatar`, `validate_model`, `inspect_model`, `optimize_model`.++Response: `{ content: [{type, text/resource}], structuredContent: {...}, isError? }`. Error codes: -32600 invalid, -32601 unknown method, -32602 bad params, -32603 internal, -32000 server/rate-limited.++When adding a tool: bump rate-limit bucket if heavy, declare scope via `hasScope()`, emit to `usage_events`.++---++## OAuth provider++We *issue* tokens (not consume). Endpoints:++- `/api/oauth/authorize` (GET consent render, POST consent submit) — PKCE S256 mandatory, no implicit/password grants+- `/api/oauth/token` — `authorization_code` + `refresh_token` grants → JWT access + opaque refresh+- `/api/oauth/register` — RFC 7591 dynamic registration, unauthenticated, IP-rate-limited, mints `mcp_*` client IDs+- `/api/oauth/introspect` — RFC 7662+- `/api/oauth/revoke` — RFC 7009+- `/.well-known/oauth-authorization-server` (RFC 8414) and `/.well-known/oauth-protected-resource` (RFC 9728)++Token JWT: `{ sub, client_id, scope, aud, exp, iat, jti, kid: env.JWT_KID }`.++---++## Anti-patterns (don't ship these)++- Hand-rolled JWT / bearer extraction → use `authenticateBearer()`+- Inline SQL concat → always tagged-template `sql\`... ${x} ...\``+- `res.end(JSON.stringify(...))` → `json(res, ...)`+- Instantiating a new `Pool` or `neon()` → import `sql` from [_lib/db.js](_lib/db.js)+- Missing rate-limit on public endpoint+- Hardcoded origins → `env.ISSUER` or `env.APP_ORIGIN`+- Registering a file in `avatars` without `headObject()` size check+- Leaking `owner_id` / R2 path prefix in unauthenticated responses → use `stripOwnerFor()`+- `await` on fire-and-forget logging calls that should use `queueMicrotask()`diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex adf27663f..8b5a937ef 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -69,6 +69,8 @@ export const limits = {mcpOptimize: (key) => getLimiter('mcp:optimize', { limit: 10, window: '1 m' }).limit(key),oauthToken: (clientId) => getLimiter('oauth:token', { limit: 120, window: '1 m' }).limit(clientId),upload: (userId) => getLimiter('upload', { limit: 60, window: '1 h' }).limit(userId),+ chatUser: (userId) => getLimiter('chat:user', { limit: 20, window: '1 m' }).limit(userId),+ chatIp: (ip) => getLimiter('chat:ip', { limit: 40, window: '1 m' }).limit(ip),};// Trust only proxy headers that Vercel itself sets and signs. Naively readingdiff --git a/api/chat.js b/api/chat.jsnew file mode 100644index 000000000..ef2594a8e--- /dev/null+++ b/api/chat.js@@ -0,0 +1,244 @@+// POST /api/chat — AI-powered chat for the 3D Agent.+//+// Takes a user message + viewer context, forwards to Anthropic with a set of+// viewer-control tools exposed as function-calls, and returns:+// { reply: string, actions: [{ type, ...input }] }+// The client executes each action against the live viewer. The model is+// stateless here — callers pass the recent history each turn (sessionStorage).++import { getSessionUser, authenticateBearer, extractBearer } from './_lib/auth.js';+import { cors, json, method, readJson, wrap, error } from './_lib/http.js';+import { parse } from './_lib/validate.js';+import { limits } from './_lib/rate-limit.js';+import { recordEvent } from './_lib/usage.js';+import { z } from 'zod';++const ANTHROPIC_URL = 'https://api.anthropic.com/v1/messages';+const DEFAULT_MODEL = 'claude-sonnet-4-6';+const DEFAULT_MAX_TOKENS = 1024;+const HARD_MAX_TOKENS = 4096;++const contextSchema = z.object({+ modelName: z.string().max(200).optional(),+ vertices: z.number().int().nonnegative().optional(),+ triangles: z.number().int().nonnegative().optional(),+ materials: z.number().int().nonnegative().optional(),+ animations: z.number().int().nonnegative().optional(),+ validationErrors: z.number().int().nonnegative().optional(),+ validationWarnings: z.number().int().nonnegative().optional(),+ currentEnvironment: z.string().max(80).optional(),+ wireframe: z.boolean().optional(),+ skeleton: z.boolean().optional(),+ grid: z.boolean().optional(),+ autoRotate: z.boolean().optional(),+ transparentBg: z.boolean().optional(),+ bgColor: z.string().max(20).optional(),+}).partial().default({});++const chatBody = z.object({+ message: z.string().trim().min(1).max(4000),+ context: contextSchema,+ history: z.array(z.object({+ role: z.enum(['user', 'assistant']),+ content: z.string().min(1).max(4000),+ })).max(20).default([]),+});++const ACTION_TOOLS = [+ {+ name: 'setWireframe',+ description: 'Toggle wireframe mode on the currently loaded model.',+ input_schema: { type: 'object', properties: { value: { type: 'boolean' } }, required: ['value'] },+ },+ {+ name: 'setSkeleton',+ description: 'Toggle the skeleton helper visualization for rigged models.',+ input_schema: { type: 'object', properties: { value: { type: 'boolean' } }, required: ['value'] },+ },+ {+ name: 'setGrid',+ description: 'Toggle the reference grid and axes helper.',+ input_schema: { type: 'object', properties: { value: { type: 'boolean' } }, required: ['value'] },+ },+ {+ name: 'setAutoRotate',+ description: 'Toggle auto-rotation of the camera around the model.',+ input_schema: { type: 'object', properties: { value: { type: 'boolean' } }, required: ['value'] },+ },+ {+ name: 'setBgColor',+ description: 'Set the viewer background color. Accepts a CSS hex like "#001133".',+ input_schema: {+ type: 'object',+ properties: { value: { type: 'string', pattern: '^#[0-9a-fA-F]{3,8}$' } },+ required: ['value'],+ },+ },+ {+ name: 'setTransparentBg',+ description: 'Toggle transparent background (for compositing screenshots).',+ input_schema: { type: 'object', properties: { value: { type: 'boolean' } }, required: ['value'] },+ },+ {+ name: 'setEnvironment',+ description: 'Change the HDRI lighting environment. Known names: "None", "Neutral", "Venice Sunset", "Footprint Court (HDR Labs)".',+ input_schema: { type: 'object', properties: { value: { type: 'string' } }, required: ['value'] },+ },+ {+ name: 'takeScreenshot',+ description: 'Capture a PNG screenshot of the current viewport.',+ input_schema: { type: 'object', properties: {} },+ },+ {+ name: 'loadModel',+ description: 'Load a glTF or GLB model by URL.',+ input_schema: {+ type: 'object',+ properties: { url: { type: 'string', format: 'uri' } },+ required: ['url'],+ },+ },+ {+ name: 'runValidation',+ description: 'Run glTF validation on the currently loaded model and report errors/warnings.',+ input_schema: { type: 'object', properties: {} },+ },+ {+ name: 'showMaterialEditor',+ description: 'Open the material editor panel in the viewer UI.',+ input_schema: { type: 'object', properties: {} },+ },+];++const ACTION_NAMES = new Set(ACTION_TOOLS.map((t) => t.name));++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const apiKey = process.env.ANTHROPIC_API_KEY;+ if (!apiKey) {+ return error(res, 503, 'chat_unavailable', 'chat backend is not configured');+ }++ const auth = await resolveAuth(req);+ if (!auth) return error(res, 401, 'unauthorized', 'sign in to chat with the agent');++ const rl = await limits.chatUser(auth.userId);+ if (!rl.success) {+ const retryAfter = Math.max(1, Math.ceil((rl.reset - Date.now()) / 1000));+ res.setHeader('retry-after', String(retryAfter));+ return error(res, 429, 'rate_limited', 'too many messages — slow down', { retry_after: retryAfter });+ }++ const body = parse(chatBody, await readJson(req));+ const model = process.env.CHAT_MODEL || DEFAULT_MODEL;+ const maxTokens = clampInt(+ parseInt(process.env.CHAT_MAX_TOKENS || '', 10) || DEFAULT_MAX_TOKENS,+ 128,+ HARD_MAX_TOKENS,+ );++ const messages = [+ ...body.history.map((m) => ({ role: m.role, content: m.content })),+ { role: 'user', content: body.message },+ ];++ const started = Date.now();+ let upstream;+ try {+ upstream = await fetch(ANTHROPIC_URL, {+ method: 'POST',+ headers: {+ 'x-api-key': apiKey,+ 'anthropic-version': '2023-06-01',+ 'content-type': 'application/json',+ },+ body: JSON.stringify({+ model,+ max_tokens: maxTokens,+ system: buildSystemPrompt(body.context),+ messages,+ tools: ACTION_TOOLS,+ }),+ });+ } catch (err) {+ console.warn('[chat] upstream fetch failed:', err.message);+ return error(res, 502, 'upstream_unavailable', 'chat backend unreachable');+ }++ if (!upstream.ok) {+ const text = await upstream.text().catch(() => '');+ console.warn('[chat] anthropic', upstream.status, text.slice(0, 400));+ const status = upstream.status === 429 ? 429 : 502;+ return error(res, status, 'upstream_error', `chat backend returned ${upstream.status}`);+ }++ const data = await upstream.json();+ const { reply, actions } = normalize(data);+ const latencyMs = Date.now() - started;++ recordEvent({+ userId: auth.userId,+ apiKeyId: auth.apiKeyId,+ clientId: auth.clientId,+ kind: 'chat',+ tool: model,+ latencyMs,+ meta: {+ input_tokens: data.usage?.input_tokens,+ output_tokens: data.usage?.output_tokens,+ actions: actions.map((a) => a.type),+ has_context: Boolean(body.context?.modelName),+ },+ });++ return json(res, 200, { reply, actions, model });+});++function buildSystemPrompt(ctx = {}) {+ const loaded = ctx.modelName+ ? `A model named "${ctx.modelName}" is loaded. Stats: ${fmt(ctx.vertices)} vertices, ${fmt(ctx.triangles)} triangles, ${fmt(ctx.materials)} materials, ${ctx.animations ?? 0} animations.`+ : 'No model is currently loaded in the viewer.';+ const validation = ctx.validationErrors != null+ ? `Validation has been run: ${ctx.validationErrors} errors, ${ctx.validationWarnings ?? 0} warnings.`+ : 'glTF validation has not been run yet for this model.';+ const settings = `Viewer settings — wireframe:${fmtBool(ctx.wireframe)}, skeleton:${fmtBool(ctx.skeleton)}, grid:${fmtBool(ctx.grid)}, autoRotate:${fmtBool(ctx.autoRotate)}, transparentBg:${fmtBool(ctx.transparentBg)}, bgColor:${ctx.bgColor || '?'}, environment:${ctx.currentEnvironment || '?'}.`;++ return [+ 'You are the 3D Agent — an embodied AI assistant embedded inside a browser-native glTF/GLB viewer at 3dagent.vercel.app.',+ 'Your job is to help the user inspect, understand, and modify the 3D scene. You have deep glTF 2.0, PBR materials, and three.js expertise.',+ 'When the user asks you to change the viewer (e.g. "enable wireframe", "make the background dark blue", "turn on auto rotate"), USE the provided tools to perform the change — do not just describe it.',+ 'When asked about the loaded model, use the context below as ground truth. Do not invent stats.',+ 'Keep replies tight: 1–3 sentences. Plain text, no markdown headers, no emoji.',+ '',+ loaded,+ validation,+ settings,+ ].join('\n');+}++function normalize(data) {+ let reply = '';+ const actions = [];+ for (const block of data.content || []) {+ if (block.type === 'text') {+ reply += block.text;+ } else if (block.type === 'tool_use' && ACTION_NAMES.has(block.name)) {+ actions.push({ type: block.name, ...(block.input || {}) });+ }+ }+ return { reply: reply.trim(), actions };+}++async function resolveAuth(req) {+ const session = await getSessionUser(req);+ if (session) return { userId: session.id, source: 'session' };+ const bearer = await authenticateBearer(extractBearer(req));+ if (bearer) return bearer;+ return null;+}++function fmt(n) { return typeof n === 'number' ? n.toLocaleString('en-US') : '?'; }+function fmtBool(v) { return typeof v === 'boolean' ? (v ? 'on' : 'off') : '?'; }+function clampInt(n, min, max) { return Math.min(max, Math.max(min, n)); }diff --git a/api/widgets/page.js b/api/widgets/page.jsnew file mode 100644index 000000000..fb20f63ef--- /dev/null+++ b/api/widgets/page.js@@ -0,0 +1,160 @@+/**+ * Server-rendered widget metadata page+ * ------------------------------------+ * GET /api/widgets/page?id=<widget-id>+ *+ * Wired to /w/:id via vercel.json. Returns an HTML page with proper Open Graph+ * + Twitter card + oEmbed link tags so social crawlers (Slack, Discord, X,+ * WordPress, Ghost) get a rich preview. Real browsers run the inline script+ * and replace into the SPA viewer at /#widget=<id>.+ */++import { sql } from '../_lib/db.js';+import { env } from '../_lib/env.js';+import { cors, wrap } from '../_lib/http.js';++const TYPE_LABEL = {+ 'turntable': 'Turntable Showcase',+ 'animation-gallery': 'Animation Gallery',+ 'talking-agent': 'Talking Agent',+ 'passport': 'ERC-8004 Passport',+ 'hotspot-tour': 'Hotspot Tour',+};++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;++ const url = new URL(req.url, 'http://x');+ const widgetId = url.searchParams.get('id');+ if (!widgetId) return notFound(res);++ const widget = await loadWidget(widgetId);+ if (!widget) return notFound(res);++ const origin = env.APP_ORIGIN;+ const pageUrl = `${origin}/w/${widget.id}`;+ const embedUrl = `${origin}/#widget=${widget.id}&kiosk=true`;+ const ogUrl = `${origin}/api/widgets/${widget.id}/og`;+ const oembedJs = `${origin}/api/widgets/oembed?url=${encodeURIComponent(pageUrl)}&format=json`;+ const title = widget.name || 'Widget';+ const typeLbl = TYPE_LABEL[widget.type] || 'Widget';+ const desc = `${typeLbl} · embeddable 3D, no code. Powered by 3D Agent.`;++ res.statusCode = 200;+ res.setHeader('content-type', 'text/html; charset=utf-8');+ res.setHeader('cache-control', 'public, max-age=300, s-maxage=900');+ res.end(renderHtml({ title, desc, pageUrl, embedUrl, ogUrl, oembedJs, widgetId: widget.id }));+});++async function loadWidget(id) {+ try {+ const [row] = await sql`+ select id, name, type, avatar_id+ from widgets+ where id = ${id}+ limit 1+ `;+ return row || null;+ } catch (err) {+ if (/relation .* does not exist/i.test(err?.message || '')) return null;+ throw err;+ }+}++function notFound(res) {+ res.statusCode = 404;+ res.setHeader('content-type', 'text/html; charset=utf-8');+ res.setHeader('cache-control', 'public, max-age=60');+ res.end(`<!doctype html><meta charset="utf-8"><title>Widget not found</title>+<style>body{font-family:Inter,system-ui,sans-serif;background:#0a0a0a;color:#e0e0e0;display:grid;place-items:center;min-height:100vh;margin:0}main{text-align:center;padding:2rem}a{color:#8b5cf6}</style>+<main><h1>Widget not found</h1><p>This widget may have been deleted, or the link is wrong.</p><p><a href="/widgets">Browse the gallery</a> · <a href="/">Open viewer</a></p></main>`);+}++function renderHtml({ title, desc, pageUrl, embedUrl, ogUrl, oembedJs, widgetId }) {+ const t = escapeHtml(title);+ const d = escapeHtml(desc);+ return `<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8">+ <meta http-equiv="X-UA-Compatible" content="IE=edge">+ <title>${t} — 3D Agent</title>+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">+ <meta name="description" content="${d}">+ <meta name="theme-color" content="#0a0a0a">++ <meta property="og:type" content="website">+ <meta property="og:site_name" content="3D Agent">+ <meta property="og:title" content="${t}">+ <meta property="og:description" content="${d}">+ <meta property="og:url" content="${escapeAttr(pageUrl)}">+ <meta property="og:image" content="${escapeAttr(ogUrl)}">+ <meta property="og:image:width" content="1200">+ <meta property="og:image:height" content="630">++ <meta name="twitter:card" content="summary_large_image">+ <meta name="twitter:title" content="${t}">+ <meta name="twitter:description" content="${d}">+ <meta name="twitter:image" content="${escapeAttr(ogUrl)}">++ <link rel="canonical" href="${escapeAttr(pageUrl)}">+ <link rel="alternate" type="application/json+oembed" href="${escapeAttr(oembedJs)}" title="${t}">+ <link rel="shortcut icon" href="/favicon.ico">++ <style>+ html,body{margin:0;padding:0;background:#0a0a0a;color:#e0e0e0;font-family:Inter,system-ui,sans-serif;height:100%;overflow:hidden}+ .shell{display:grid;place-items:center;height:100vh;text-align:center;padding:2rem;gap:1rem}+ .shell a{color:#8b5cf6;text-decoration:none}+ .shell a:hover{text-decoration:underline}+ .spinner{width:32px;height:32px;border:2px solid rgba(255,255,255,0.1);border-top-color:#8b5cf6;border-radius:50%;animation:spin 1s linear infinite}+ @keyframes spin{to{transform:rotate(360deg)}}+ @media(prefers-reduced-motion:reduce){.spinner{animation:none}}+ </style>+</head>+<body>+ <noscript>+ <div class="shell">+ <h1>${t}</h1>+ <p>${d}</p>+ <p><a href="${escapeAttr(embedUrl)}">Open viewer</a></p>+ </div>+ </noscript>+ <div class="shell" id="loading" aria-live="polite">+ <div class="spinner" aria-hidden="true"></div>+ <p>Loading ${t}…</p>+ </div>+ <script>+ // Real browsers: replace into the SPA so back-button doesn't loop.+ // Crawlers / bots: ignored, they parse the OG tags above.+ (function () {+ var target = ${JSON.stringify(embedUrl)};+ try {+ var u = new URL(window.location.href);+ if (u.searchParams.get('embed') === '0') return; // escape hatch for debugging+ } catch (e) {}+ window.location.replace(target);+ })();+ </script>+ <script type="application/ld+json">+${escapeJsonLd({+ '@context': 'https://schema.org',+ '@type': 'CreativeWork',+ name: title,+ description: desc,+ url: pageUrl,+ image: ogUrl,+ identifier: widgetId,+ provider: { '@type': 'Organization', name: '3D Agent', url: 'https://3dagent.vercel.app' },+})}+ </script>+</body>+</html>`;+}++function escapeHtml(s) {+ return String(s).replace(/[&<>"']/g, (c) => ({ '&':'&','<':'<','>':'>','"':'"',"'":''' }[c]));+}+function escapeAttr(s) { return escapeHtml(s); }+function escapeJsonLd(obj) {+ return JSON.stringify(obj, null, 2).replace(/</g, '\\u003c');+}diff --git a/contracts/CLAUDE.md b/contracts/CLAUDE.mdnew file mode 100644index 000000000..8911b9de7--- /dev/null+++ b/contracts/CLAUDE.md@@ -0,0 +1,88 @@+# contracts/CLAUDE.md++Scoped guidance for the Foundry project implementing ERC-8004. Read [/CLAUDE.md](../CLAUDE.md) first.++**⚠️ Must-ask-first for any change:** ABI shape, storage layout, deployed address, deploy script. These are on-chain and immutable once deployed.++---++## The three registries++All Solidity 0.8.24, optimizer 200 runs, OpenZeppelin-based.++| Contract | File | Purpose |+|---|---|---|+| **IdentityRegistry** | [src/IdentityRegistry.sol](src/IdentityRegistry.sol) | ERC-721 agents. `register()`, `register(agentURI)`, `register(agentURI, MetadataEntry[])`, `setAgentURI()`, `tokenURI()`, `setAgentWallet()` (EIP-712 delegated), `getAgentWallet()`, `unsetAgentWallet()`, `setMetadata()`, `getMetadata()`, `isAgent()`, `ownerOf()`. |+| **ReputationRegistry** | [src/ReputationRegistry.sol](src/ReputationRegistry.sol) | Signed feedback −100..+100, one review per address per agent. `submitFeedback(agentId, score, uri)`, `getReputation()` → `(avgX100, count)`, `getFeedback()`, `getFeedbackRange()`, `getFeedbackCount()`. |+| **ValidationRegistry** | [src/ValidationRegistry.sol](src/ValidationRegistry.sol) | Allow-listed validators attest off-chain proofs. `recordValidation(agentId, passed, proofHash, proofURI, kind)` (validator-only), `getValidation()`, `getLatestByKind()`, `getValidationRange()`, `addValidator()`, `removeValidator()`, `transferOwnership()`. |++---++## Deployed addresses (immutable — do not change)++Same address on every EVM chain (CREATE2 deterministic). Mirrored in [src/erc8004/abi.js](../src/erc8004/abi.js) `REGISTRY_DEPLOYMENTS`.++### Mainnet (chainIds: 1, 10, 56, 100, 137, 250, 324, 1284, 5000, 8453, 42161, 42220, 43114, 59144, 534352)+- IdentityRegistry: `0x8004A169FB4a3325136EB29fA0ceB6D2e539a432`+- ReputationRegistry: `0x8004BAa17C55a88189AE136b182e5fdA19dE9b63`+- ValidationRegistry: *(not yet deployed on mainnet)*++### Testnet (chainIds: 97, 11155111, 84532, 421614, 11155420, 80002, 43113)+- IdentityRegistry: `0x8004A818BFB912233c491871b3d84c89A494BD9e`+- ReputationRegistry: `0x8004B663056A597Dffe9eCcC1965A193B7388713`+- ValidationRegistry: `0x8004Cb1BF31DAf7788923b405b754f57acEB4272`++**Changing any of these requires:** user approval → redeploy → update `REGISTRY_DEPLOYMENTS` → update `VALIDATION_REGISTRY_DEPLOYMENTS` → migrate any frontend code calling them.++---++## Deploy workflow++```bash+# 1. Env+export BASE_SEPOLIA_RPC_URL=...+export BASE_RPC_URL=...+export BASESCAN_API_KEY=...+export DEPLOYER_PK=0x...++# 2. Build + test+forge build+forge test++# 3. Deploy (dry-run first)+forge script script/Deploy.s.sol --rpc-url base_sepolia+forge script script/Deploy.s.sol --rpc-url base_sepolia --broadcast --verify++# 4. Update frontend ABI/addresses+# Edit: ../src/erc8004/abi.js → REGISTRY_DEPLOYMENTS[<chainId>]+```++Configured RPC aliases (from [foundry.toml](foundry.toml)): `base_sepolia`, `base`. Etherscan verification uses Basescan for both. Remappings: `@openzeppelin/` → `lib/openzeppelin-contracts/`, `forge-std/` → `lib/forge-std/src/`.++**Never run `--broadcast` without my explicit approval.**++---++## ABI bridge to the frontend++ABIs are **hardcoded** in [src/erc8004/abi.js](../src/erc8004/abi.js) as ethers v6 human-readable strings (not JSON):++```js+'function register(string agentURI) external returns (uint256 agentId)'+'function tokenURI(uint256 tokenId) external view returns (string)'+```++No generation step. When you add/change a function signature in Solidity:+1. Change the `.sol`+2. Update the string in `abi.js` to match exactly+3. Update any callers in `src/erc8004/*.js`++---++## Don't touch without ask++- [out/](out/), [cache/](cache/) — Foundry artifacts, regenerated+- [lib/](lib/) — forge submodules (openzeppelin-contracts, forge-std)+- Any deployed address anywhere in the repo+- Storage layout of any deployed contract (appending fields is fine if you know what you're doing, reordering is not)+- EIP-712 domain separator version/name in IdentityRegistry (breaks existing delegated wallet signatures)diff --git a/docs/WIDGETS.md b/docs/WIDGETS.mdnew file mode 100644index 000000000..843192b6f--- /dev/null+++ b/docs/WIDGETS.md@@ -0,0 +1,250 @@+# Widgets++Embeddable 3D — a configured, shareable view of an avatar that any site can drop in with one line of HTML.++A widget is a saved bundle of: an avatar (GLB stored in R2), a widget type (turntable, animation gallery, talking agent, ERC-8004 passport, hotspot tour), and brand config (background, accent, caption, controls, camera). Widgets are created in the [Widget Studio](https://3dagent.vercel.app/studio) and shared via short URLs.++---++## Table of Contents++- [Quick start](#quick-start)+- [Widget types](#widget-types)+- [URLs](#urls)+- [Embedding](#embedding)+- [postMessage API](#postmessage-api)+- [OG / oEmbed](#og--oembed)+- [CSP / CORS](#csp--cors)+- [Privacy & analytics](#privacy--analytics)+- [FAQ](#faq)++---++## Quick start++1. Sign in at [3dagent.vercel.app](https://3dagent.vercel.app).+2. Open the [Studio](https://3dagent.vercel.app/studio).+3. Pick an avatar, pick a widget type, tweak brand colors and controls, click **Generate Embed**.+4. Copy the iframe snippet into any HTML page, blog post, Notion doc, or CMS.++---++## Widget types++| Type | Best for | Default size |+|---|---|---|+| `turntable` | Hero banners, product showcases. Auto-rotate, no UI. | 600 × 600 |+| `animation-gallery` | Showcasing a rigged avatar's animation library. | 720 × 720 |+| `talking-agent` | Embodied chat — your agent on your site. | 420 × 600 |+| `passport` | On-chain identity card backed by ERC-8004. | 480 × 560 |+| `hotspot-tour` | Annotated 3D scenes with clickable POIs. | 800 × 600 |++---++## URLs++Every widget has three canonical URLs.++| URL | Use it for |+|---|---|+| `https://3dagent.vercel.app/w/<id>` | Sharing in Slack/Discord/X — server-rendered with rich OG card. |+| `https://3dagent.vercel.app/#widget=<id>` | The SPA viewer with the widget config applied. |+| `https://3dagent.vercel.app/api/widgets/<id>/og` | The 1200×630 preview image. |++`/w/<id>` is the recommended share URL — bots get an OG preview, browsers fall through to the SPA.++### Hash parameters++The viewer supports the following hash params (combine with `&`):++| Param | Type | Description |+|---|---|---|+| `widget` | `string` | Loads a saved widget by id. |+| `model` | `string` | Loads a raw GLB by URL (mutually exclusive with `widget`). |+| `kiosk` | `boolean` | Hides the header chrome for clean iframe embeds. |+| `cameraPosition` | `x,y,z` | Comma-separated camera position override. |+| `preset` | `string` | HDR environment preset name. |++---++## Embedding++### iframe (recommended)++```html+<iframe+ src="https://3dagent.vercel.app/#widget=wdgt_abc123def456&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>+```++**Size guidance:**+- Turntable / hotspot-tour: 1:1 or 4:3 — let the user breathe.+- Talking-agent: 7:10 portrait — chat needs vertical space.+- Passport: anything ≥ 360 × 480.++### Script embed++```html+<script async src="https://3dagent.vercel.app/embed.js" data-widget="wdgt_abc123def456"></script>+```++The script injects a sandboxed iframe at the script tag's location and forwards size/postMessage events to the parent. Use this when you want auto-resize behavior; use a raw iframe when you want full control.++### oEmbed (WordPress, Ghost, Notion)++Most CMSes auto-detect oEmbed. Paste a `https://3dagent.vercel.app/w/<id>` URL on its own line and the editor should turn it into a live embed automatically. If not, use the iframe snippet above.++---++## postMessage API++Widgets communicate with the parent page via `window.postMessage`. **Always check `event.origin === 'https://3dagent.vercel.app'` (or your custom domain) before trusting any message.**++### iframe → parent++| Event | Payload | When |+|---|---|---|+| `widget:ready` | `{ id, type }` | Widget runtime has booted. |+| `widget:load` | `{ id, model_url }` | Underlying GLB loaded successfully. |+| `widget:load:error` | `{ id, error }` | GLB or config failed to load. |+| `widget:chat:message` | `{ role, content }` | Talking-agent only — a new chat turn. |+| `widget:hotspot:open` | `{ id, label }` | Hotspot-tour only — visitor opened a POI. |+| `widget:resize` | `{ width, height }` | Widget reports its preferred size. |++```js+window.addEventListener('message', (e) => {+ if (e.origin !== 'https://3dagent.vercel.app') return;+ if (e.data?.type === 'widget:ready') {+ console.log('Widget mounted:', e.data.id);+ }+});+```++### parent → iframe++| Event | Payload | Effect |+|---|---|---|+| `widget:config` | `{ background, accent, autoRotate, ... }` | Live-update brand config (used by the Studio preview). |+| `widget:command` | `{ command, args }` | Trigger a runtime action (e.g. `play_clip`, `wave`). |++```js+const iframe = document.querySelector('iframe');+iframe.contentWindow.postMessage(+ { type: 'widget:config', config: { background: '#ff00aa' } },+ 'https://3dagent.vercel.app'+);+```++---++## OG / oEmbed++Every widget URL serves rich-preview metadata.++### Open Graph++`/w/<id>` returns a server-rendered HTML page with:++```html+<meta property="og:title" content="…">+<meta property="og:description" content="…">+<meta property="og:image" content="https://3dagent.vercel.app/api/widgets/<id>/og">+<meta name="twitter:card" content="summary_large_image">+<link rel="alternate" type="application/json+oembed" href="https://3dagent.vercel.app/api/widgets/oembed?url=…">+```++### oEmbed endpoint++```+GET /api/widgets/oembed?url=<widget-url>&format=json+```++Returns standard [oEmbed v1.0](https://oembed.com) JSON, type `rich`.++```json+{+ "type": "rich",+ "version": "1.0",+ "provider_name": "3D Agent",+ "provider_url": "https://3dagent.vercel.app",+ "title": "…",+ "html": "<iframe …></iframe>",+ "width": 600,+ "height": 600,+ "thumbnail_url": "…",+ "thumbnail_width": 1200,+ "thumbnail_height": 630+}+```++Accepts both `https://host/w/<id>` and `https://host/#widget=<id>` forms. Optional `maxwidth` / `maxheight` clamp the returned iframe dimensions.++---++## CSP / CORS++Widgets run in a sandboxed iframe with these `allow` flags:++- `autoplay` — needed for ambient animations.+- `xr-spatial-tracking` — for future WebXR support.+- `clipboard-write` — passport widget copies its address.++If your site uses a strict Content Security Policy, allow:++```+frame-src https://3dagent.vercel.app;+img-src https://3dagent.vercel.app data:;+```++The widget iframe makes outbound requests to `3dagent.vercel.app` and (for some widgets) to public RPC endpoints / R2 storage CDNs. None of these require parent-side CORS configuration.++---++## Privacy & analytics++We log a minimal first-party event per widget load:++| Field | Source |+|---|---|+| `widget_id` | the widget being loaded |+| `type` | the widget type |+| `country` | Vercel edge header (`x-vercel-ip-country`) |+| `referer_host` | hostname of the embedding page (no path, no query) |+| `created_at` | timestamp |++We **do not** log:+- IP addresses+- User agent strings+- Cookies (we don't set any on the embed)+- Chat message content (talking-agent transcripts stay between visitor and agent brain)+- Full URLs (only the host)++The widget owner can see aggregated counts in their [Dashboard](https://3dagent.vercel.app/dashboard). No cross-widget tracking.++---++## FAQ++**Can I self-host?** The runtime is open source. The Studio + saved-widgets API depends on Neon + R2; you'd need to wire those yourself. See [DEPLOYMENT.md](./DEPLOYMENT.md).++**Why no WordPress plugin?** The oEmbed endpoint already does what a plugin would. Paste a `/w/<id>` URL into a Gutenberg paragraph block — done.++**How big is the bundle?** The widget runtime lazy-loads only the code needed for its type. Cold load with a small GLB lands ~400KB JS + the GLB itself. Use `loading="lazy"` on the iframe to defer until scroll.++**Mobile?** Yes — every widget type works on iOS Safari and Android Chrome. Touch controls are first-class. `kiosk=true` is enabled by default in embed mode.++**Can I customize per-page?** Use `postMessage` to send live `widget:config` events from the parent page (e.g. tie the widget background to your site theme).++**What about offline?** The viewer registers a service worker for repeat-visit caching. First load is online-only.++---++## Known issues++- iOS Safari may require a user gesture before `speechSynthesis.getVoices()` returns voices for the talking-agent widget.+- Some browser extensions (uBlock + strict mode) will block the analytics POST. The widget itself still works.+- Embedding inside a parent iframe that's *also* sandboxed can break WebGL initialization. Add `allow-scripts allow-same-origin` to the parent sandbox.diff --git a/index.html b/index.htmlindex 8c9357de2..6a435561f 100644--- a/index.html+++ b/index.html@@ -41,7 +41,12 @@<nav class="features-nav"><a href="/" class="active">Viewer</a><a href="/features">Features</a>+ <a href="/widgets">Widgets</a><a href="/#register">Register Agent</a>+ <a class="make-widget-btn" id="make-widget-btn" href="/studio" hidden title="Save the current model as an embeddable widget">+ <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/></svg>+ <span>Make this a widget</span>+ </a><a href="/dashboard" class="nav-dashboard">Dashboard</a><a href="/login" class="nav-sign-in" id="nav-sign-in">Sign in</a></nav>diff --git a/public/dashboard/dashboard.js b/public/dashboard/dashboard.jsindex e6ed49544..772fa2d36 100644--- a/public/dashboard/dashboard.js+++ b/public/dashboard/dashboard.js@@ -36,16 +36,21 @@ export function signOut() {}export function navigate(tab) {- document.querySelectorAll('aside a').forEach((a) => a.classList.toggle('active', a.dataset.tab === tab));+ // Support #edit/<id> sub-routes for per-avatar edit screens.+ const [base, ...rest] = (tab || 'avatars').split('/');+ document.querySelectorAll('aside a').forEach((a) => a.classList.toggle('active', a.dataset.tab === base));const main = document.getElementById('main');main.innerHTML = '';- const renderer = tabs[tab] || tabs.avatars;- renderer(main);+ const renderer = tabs[base] || tabs.avatars;+ renderer(main, rest);}const tabs = {avatars: renderAvatars,+ create: renderCreate,+ edit: renderEdit,upload: renderUpload,+ embed: renderEmbed,keys: renderKeys,mcp: renderMcp,billing: renderBilling,@@ -59,7 +64,7 @@ async function renderAvatars(root) {try {const { avatars } = await api.listAvatars();if (!avatars.length) {- list.innerHTML = `<div class="empty">No avatars yet. <a href="#upload">Upload one</a> or create via the viewer.</div>`;+ list.innerHTML = `<div class="empty">No avatars yet. <a href="#create">Take a selfie</a> or <a href="#upload">upload a .glb</a>.</div>`;return;}list.innerHTML = '';@@ -82,7 +87,10 @@ function avatarCard(a) {<div class="row" style="gap:6px; margin-bottom:10px">${a.tags.map((t) => `<span class="tag">${esc(t)}</span>`).join('')}</div><div class="row" style="justify-content:space-between"><select data-vis>${['private','unlisted','public'].map((v) => `<option ${v===a.visibility?'selected':''} value="${v}">${v}</option>`).join('')}</select>- <button class="btn sec" data-del>Delete</button>+ <div class="row" style="gap:6px">+ <a class="btn sec" href="#edit/${encodeURIComponent(a.id)}">Edit</a>+ <button class="btn sec" data-del>Delete</button>+ </div></div>`;el.querySelector('[data-vis]').addEventListener('change', async (e) => {@@ -168,6 +176,261 @@ function uploadToR2(url, file, onProgress) {});}+// ── Create from selfie ──────────────────────────────────────────────────────+// Embeds the Ready Player Me hosted creator (free, no API key). RPM handles+// camera capture, selfie-to-mesh, and returns a GLB URL via postMessage.+// We fetch that GLB and run it through the same R2 upload path as manual uploads.+const RPM_SUBDOMAIN = 'demo'; // any public RPM subdomain works for self-serve+const RPM_ORIGIN = `https://${RPM_SUBDOMAIN}.readyplayer.me`;+const RPM_SRC = `${RPM_ORIGIN}/avatar?frameApi&bodyType=fullbody&clearCache=true`;++function renderCreate(root) {+ root.innerHTML = `+ <div class="toolbar">+ <div>+ <h1>Create from a selfie</h1>+ <p class="sub">Take a photo. We turn it into a 3D avatar and save it to your account.</p>+ </div>+ <button class="btn sec" id="rpm-restart" type="button" style="display:none">Start over</button>+ </div>+ <div id="rpm-stage" class="card" style="padding:0; overflow:hidden; min-height:640px; position:relative">+ <div id="rpm-intro" style="padding:32px; text-align:center">+ <div style="font-size:42px; line-height:1; margin-bottom:12px">📸</div>+ <p style="margin:0 0 18px; color:#ccc">+ Next screen: allow camera access, take a selfie, pick body type.+ Your avatar auto-saves here when you hit "Next" in the last step.+ </p>+ <button class="btn" id="rpm-launch" type="button">Open camera</button>+ </div>+ <iframe id="rpm-iframe" title="Avatar creator" allow="camera *; microphone *" style="display:none; width:100%; height:640px; border:0; background:#0f0f17"></iframe>+ <div id="rpm-progress" class="muted" style="padding:16px 20px; border-top:1px solid var(--border); display:none"></div>+ </div>+ `;++ const launchBtn = root.querySelector('#rpm-launch');+ const restartBtn = root.querySelector('#rpm-restart');+ const intro = root.querySelector('#rpm-intro');+ const iframe = root.querySelector('#rpm-iframe');+ const progress = root.querySelector('#rpm-progress');++ const say = (msg, isError = false) => {+ progress.style.display = 'block';+ progress.style.color = isError ? '#ffb3b3' : '#888';+ progress.textContent = msg;+ };++ let onMsg = null;++ const start = () => {+ intro.style.display = 'none';+ iframe.style.display = 'block';+ iframe.src = RPM_SRC;+ restartBtn.style.display = 'inline-block';+ progress.style.display = 'none';++ onMsg = async (event) => {+ if (event.origin !== RPM_ORIGIN) return;+ const data = parseRpmMessage(event.data);+ if (!data?.eventName) return;++ // Ready Player Me → subscribe to all events once its frame is ready.+ if (data.eventName === 'v1.frame.ready') {+ iframe.contentWindow?.postMessage(+ JSON.stringify({ target: 'readyplayerme', type: 'subscribe', eventName: 'v1.**' }),+ RPM_ORIGIN,+ );+ return;+ }++ if (data.eventName === 'v1.avatar.exported') {+ const glbUrl = data.data?.url;+ if (!glbUrl) { say('No avatar URL returned', true); return; }+ say('Fetching avatar…');+ try {+ const avatar = await saveRpmAvatar(glbUrl);+ say(`Saved "${avatar.name}". Redirecting…`);+ setTimeout(() => { location.hash = 'avatars'; }, 600);+ } catch (err) {+ say(err.message || 'Failed to save avatar', true);+ }+ }+ };+ window.addEventListener('message', onMsg);+ };++ const stop = () => {+ if (onMsg) window.removeEventListener('message', onMsg);+ onMsg = null;+ iframe.src = 'about:blank';+ iframe.style.display = 'none';+ intro.style.display = 'block';+ restartBtn.style.display = 'none';+ progress.style.display = 'none';+ };++ launchBtn.addEventListener('click', start);+ restartBtn.addEventListener('click', stop);+}++function parseRpmMessage(raw) {+ if (!raw) return null;+ if (typeof raw === 'object') return raw;+ try { return JSON.parse(raw); } catch { return null; }+}++async function saveRpmAvatar(sourceUrl) {+ const res = await fetch(sourceUrl);+ if (!res.ok) throw new Error(`Fetch avatar failed: ${res.status}`);+ const blob = await res.blob();+ const contentType = 'model/gltf-binary';+ const size = blob.size;+ const checksum = await sha256Hex(blob);++ const { upload_url, storage_key } = await api.presign({+ size_bytes: size,+ content_type: contentType,+ checksum_sha256: checksum,+ });++ await new Promise((resolve, reject) => {+ const xhr = new XMLHttpRequest();+ xhr.open('PUT', upload_url);+ xhr.setRequestHeader('content-type', contentType);+ xhr.onload = () => (xhr.status >= 200 && xhr.status < 300 ? resolve() : reject(new Error(`Upload failed (${xhr.status})`)));+ xhr.onerror = () => reject(new Error('Network error during upload'));+ xhr.send(blob);+ });++ const { avatar } = await api.createAvatar({+ storage_key,+ size_bytes: size,+ content_type: contentType,+ checksum_sha256: checksum,+ name: `Selfie avatar ${new Date().toLocaleDateString()}`,+ visibility: 'private',+ tags: ['selfie'],+ source: 'import',+ source_meta: { provider: 'readyplayerme', source_url: sourceUrl, selfie_based: true },+ });++ // Wire the new avatar straight into the caller's default agent identity so+ // the selfie immediately becomes the agent's body across the site.+ await attachAvatarToDefaultAgent(avatar.id).catch((e) => console.warn('attach to agent skipped:', e.message));+ return avatar;+}++async function attachAvatarToDefaultAgent(avatarId) {+ const meRes = await fetch('/api/agents/me', { credentials: 'include' });+ if (!meRes.ok) return;+ const { agent } = await meRes.json();+ if (!agent) return;+ await fetch(`/api/agents/${agent.id}`, {+ method: 'PUT',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ avatar_id: avatarId }),+ });+}++// ── Edit avatar ─────────────────────────────────────────────────────────────+async function renderEdit(root, params = []) {+ const id = params[0];+ if (!id) { location.hash = 'avatars'; return; }++ root.innerHTML = `+ <div class="toolbar">+ <div>+ <h1>Edit avatar</h1>+ <p class="sub">Update the details that appear in MCP results and the public gallery.</p>+ </div>+ <a class="btn sec" href="#avatars">Back</a>+ </div>+ <div id="edit-body">+ <div class="muted">Loading…</div>+ </div>+ `;++ const body = root.querySelector('#edit-body');+ let avatar;+ try {+ const res = await fetch(`/api/avatars/${encodeURIComponent(id)}`, { credentials: 'include' });+ if (!res.ok) throw new Error((await res.json()).error_description || res.statusText);+ avatar = (await res.json()).avatar;+ } catch (err) {+ body.innerHTML = `<div class="err">${esc(err.message)}</div>`;+ return;+ }++ const previewUrl = avatar.url || avatar.model_url;+ body.innerHTML = `+ <div style="display:grid; grid-template-columns:minmax(260px,1fr) minmax(260px,2fr); gap:20px; align-items:start">+ <div class="card" style="padding:10px">+ <div class="preview" style="aspect-ratio:1/1; margin:0; background:#0f0f17; border-radius:10px; overflow:hidden">+ ${previewUrl+ ? `<model-viewer src="${attr(previewUrl)}" camera-controls auto-rotate shadow-intensity="1" exposure="1" tone-mapping="aces" style="width:100%;height:100%"></model-viewer>`+ : `<div style="display:grid;place-items:center;height:100%;color:#555;font-size:12px">Preview unavailable</div>`}+ </div>+ <p class="muted" style="margin:10px 4px 0">${fmtSize(avatar.size_bytes || 0)} · ${esc(avatar.source || 'upload')}</p>+ </div>+ <form id="ef" class="card" style="max-width:560px">+ <label style="display:block">Name<input id="ename" value="${attr(avatar.name || '')}" maxlength="120" style="width:100%"></label>+ <label style="display:block;margin-top:12px">Description<textarea id="edesc" rows="3" style="width:100%">${esc(avatar.description || '')}</textarea></label>+ <label style="display:block;margin-top:12px">Visibility+ <select id="evis" style="width:100%">+ ${['private','unlisted','public'].map((v) => `<option ${v===avatar.visibility?'selected':''} value="${v}">${v}</option>`).join('')}+ </select>+ </label>+ <label style="display:block;margin-top:12px">Tags (comma separated)<input id="etags" value="${attr((avatar.tags || []).join(', '))}" style="width:100%"></label>+ <div id="emsg" class="muted" style="margin-top:12px"></div>+ <div class="row" style="gap:8px; margin-top:16px">+ <button class="btn" type="submit">Save changes</button>+ <button class="btn sec" id="euse" type="button">Use as my agent's body</button>+ </div>+ </form>+ </div>+ `;++ const msg = body.querySelector('#emsg');+ body.querySelector('#ef').addEventListener('submit', async (e) => {+ e.preventDefault();+ msg.style.color = '#888';+ msg.textContent = 'Saving…';+ try {+ const tags = (body.querySelector('#etags').value || '').split(',').map((s) => s.trim()).filter(Boolean);+ await api.patchAvatar(id, {+ name: body.querySelector('#ename').value.trim(),+ description: body.querySelector('#edesc').value.trim() || undefined,+ visibility: body.querySelector('#evis').value,+ tags,+ });+ msg.style.color = '#9a8cff';+ msg.textContent = 'Saved.';+ } catch (err) {+ msg.style.color = '#ffb3b3';+ msg.textContent = err.message;+ }+ });++ body.querySelector('#euse').addEventListener('click', async () => {+ msg.style.color = '#888';+ msg.textContent = 'Linking to your agent…';+ try {+ await attachAvatarToDefaultAgent(id);+ msg.style.color = '#9a8cff';+ msg.textContent = 'Your agent will now render with this avatar.';+ } catch (err) {+ msg.style.color = '#ffb3b3';+ msg.textContent = err.message || 'Failed to link avatar to agent';+ }+ });+}++async function sha256Hex(blob) {+ const buf = await blob.arrayBuffer();+ const hash = await crypto.subtle.digest('SHA-256', buf);+ return Array.from(new Uint8Array(hash), (b) => b.toString(16).padStart(2, '0')).join('');+}+// ── API keys ────────────────────────────────────────────────────────────────async function renderKeys(root) {root.innerHTML = `@@ -258,6 +521,135 @@ function renderMcp(root) {`;}+// ── Embed ───────────────────────────────────────────────────────────────────+// Shows copy-paste snippets for dropping the agent into Lobehub, Claude,+// an iframe on any site, and a postMessage example for piping chat into the+// avatar so it reacts (speaks / emotes) to host-app events.+async function renderEmbed(root) {+ root.innerHTML = `+ <h1>Embed your agent</h1>+ <p class="sub">Drop your agent into Lobehub, Claude Artifacts, your site, or anywhere that can render an iframe. The agent reacts to chat messages via a postMessage bridge.</p>+ <div id="embed-body"><div class="muted">Loading your agent…</div></div>+ `;+ const body = root.querySelector('#embed-body');++ let agent;+ try {+ const res = await fetch('/api/agents/me', { credentials: 'include' });+ if (res.ok) agent = (await res.json()).agent;+ } catch {}++ if (!agent) {+ body.innerHTML = `+ <div class="empty">+ You don't have an agent yet. <a href="#create">Create one from a selfie</a> first.+ </div>+ `;+ return;+ }++ const origin = location.origin;+ const embedUrl = `${origin}/agent/${encodeURIComponent(agent.id)}/embed`;+ const homeUrl = `${origin}/agent/${encodeURIComponent(agent.id)}`;+ const iframeSnippet = `<iframe src="${embedUrl}" allow="camera; microphone" style="width:320px;height:420px;border:0;border-radius:16px;overflow:hidden" title="${esc(agent.name || 'Agent')}"></iframe>`;+ const lobehubSnippet = [+ "// Drop into a Lobehub fork — renders the agent alongside the chat panel",+ "// and forwards assistant messages to it so the avatar speaks/emotes.",+ "import { useEffect, useRef } from 'react';",+ "",+ "export function AgentSidecar({ latestAssistantMessage }) {",+ ` const AGENT_ID = ${JSON.stringify(agent.id)};`,+ ` const EMBED_URL = ${JSON.stringify(embedUrl)};`,+ " const ref = useRef(null);",+ "",+ " useEffect(() => {",+ " if (!ref.current || !latestAssistantMessage) return;",+ " ref.current.contentWindow?.postMessage({",+ " __agent: AGENT_ID,",+ " type: 'action',",+ " action: { type: 'speak', payload: { text: latestAssistantMessage.text } },",+ " }, '*');",+ " }, [latestAssistantMessage]);",+ "",+ " return <iframe ref={ref} src={EMBED_URL} allow=\"camera; microphone\"",+ " style={{ width: 320, height: 420, border: 0, borderRadius: 16 }} />;",+ "}",+ ].join('\n');+ const claudeSnippet = [+ "<!-- Paste into Claude as an HTML Artifact. The avatar renders live. -->",+ `<iframe src="${embedUrl}"`,+ " style=\"width:100%;height:480px;border:0;border-radius:16px\"",+ " allow=\"camera; microphone\"></iframe>",+ ].join('\n');+ const postMessageSnippet = [+ "// From any host page, make the avatar speak + emote:",+ "const frame = document.querySelector('iframe');",+ "frame.contentWindow.postMessage({",+ ` __agent: ${JSON.stringify(agent.id)},`,+ " type: 'action',",+ " action: { type: 'speak', payload: { text: 'Hello from the host app' } },",+ "}, '*');",+ "",+ "// Listen for agent readiness:",+ "window.addEventListener('message', (e) => {",+ ` if (e.data?.__agent === ${JSON.stringify(agent.id)} && e.data.type === 'ready') {`,+ " console.log('agent online:', e.data.name);",+ " }",+ "});",+ ].join('\n');++ body.innerHTML = `+ <div style="display:grid; grid-template-columns:minmax(260px,1fr) minmax(320px,1.4fr); gap:20px; align-items:start">+ <div class="card" style="padding:8px">+ <iframe src="${attr(embedUrl + '?preview=1')}" style="width:100%;aspect-ratio:3/4;border:0;border-radius:10px;background:#0f0f17" title="Preview"></iframe>+ <div class="row" style="justify-content:space-between; padding:10px 6px 4px">+ <strong>${esc(agent.name || 'My Agent')}</strong>+ <a href="${attr(homeUrl)}" target="_blank" class="muted">Home page →</a>+ </div>+ <p class="muted" style="padding:0 6px">Agent ID <code>${esc(agent.id)}</code></p>+ </div>+ <div>+ ${snippetBlock('Universal iframe (any site)', iframeSnippet, 'html')}+ ${snippetBlock('Lobehub React sidecar', lobehubSnippet, 'tsx')}+ ${snippetBlock('Claude Artifact', claudeSnippet, 'html')}+ ${snippetBlock('postMessage bridge (speak + listen)', postMessageSnippet, 'js')}+ <div class="card" style="margin-top:14px">+ <h3 style="margin:0 0 6px">Who can embed?</h3>+ <p class="muted" style="margin:0 0 10px">By default anyone. Lock it down to specific hosts (your Lobehub deploy, your Substack…) on the <a href="/dashboard/embed-policy?agent=${encodeURIComponent(agent.id)}">embed-policy page</a>.</p>+ </div>+ </div>+ </div>+ `;++ for (const btn of body.querySelectorAll('[data-copy]')) {+ btn.addEventListener('click', async () => {+ const target = body.querySelector(btn.dataset.copy);+ if (!target) return;+ try {+ await navigator.clipboard.writeText(target.textContent);+ const original = btn.textContent;+ btn.textContent = 'Copied';+ setTimeout(() => { btn.textContent = original; }, 1200);+ } catch {+ btn.textContent = 'Copy failed';+ }+ });+ }+}++function snippetBlock(title, code, _lang) {+ const id = 'snip-' + Math.random().toString(36).slice(2, 8);+ return `+ <div class="card" style="margin-bottom:14px">+ <div class="row" style="justify-content:space-between; margin-bottom:8px">+ <strong>${esc(title)}</strong>+ <button class="btn sec" data-copy="#${id}" type="button">Copy</button>+ </div>+ <pre id="${id}" style="margin:0; max-height:260px">${esc(code)}</pre>+ </div>+ `;+}+// ── Billing placeholder ─────────────────────────────────────────────────────function renderBilling(root) {root.innerHTML = `<h1>Plan & usage</h1><p class="sub">You're on the <b>${esc(state.user.plan)}</b> plan.</p><div class="card muted">Detailed usage analytics coming soon.</div>`;diff --git a/public/dashboard/index.html b/public/dashboard/index.htmlindex 574da0341..1ff14ba21 100644--- a/public/dashboard/index.html+++ b/public/dashboard/index.html@@ -56,7 +56,9 @@<div class="layout"><aside><a href="#avatars" class="active" data-tab="avatars">Avatars</a>+ <a href="#create" data-tab="create">Create from selfie</a><a href="#upload" data-tab="upload">Upload</a>+ <a href="#embed" data-tab="embed">Embed</a><a href="#keys" data-tab="keys">API keys</a><a href="#mcp" data-tab="mcp">MCP</a><a href="#billing" data-tab="billing">Plan & usage</a>diff --git a/public/docs-widgets.html b/public/docs-widgets.htmlnew file mode 100644index 000000000..103458f3b--- /dev/null+++ b/public/docs-widgets.html@@ -0,0 +1,248 @@+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8">+ <meta http-equiv="X-UA-Compatible" content="IE=edge">+ <title>Widget Docs — 3D Agent</title>+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">+ <meta name="description" content="Embed 3D widgets on any site. URL params, iframe + script embeds, postMessage API, oEmbed, privacy.">+ <meta name="theme-color" content="#0a0a0a">++ <meta property="og:type" content="article">+ <meta property="og:title" content="3D Agent — Widget Docs">+ <meta property="og:description" content="Embed 3D widgets on any site. URL params, postMessage API, oEmbed, privacy.">+ <meta property="og:url" content="https://3dagent.vercel.app/docs/widgets">++ <link rel="canonical" href="https://3dagent.vercel.app/docs/widgets">+ <link rel="shortcut icon" href="/favicon.ico">+ <link rel="preconnect" href="https://fonts.googleapis.com">+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Space+Grotesk:wght@500;600;700&display=swap" rel="stylesheet">+ <link rel="stylesheet" href="/style.css">+ <link rel="stylesheet" href="/widgets-gallery/gallery.css">+ <style>+ .docs-main {+ max-width: 760px;+ margin: 0 auto;+ padding: var(--space-2xl) var(--space-lg);+ line-height: var(--leading-normal);+ }+ .docs-main h1 {+ font-family: var(--font-display);+ font-weight: 300;+ font-size: var(--text-2xl);+ letter-spacing: -1px;+ margin: 0 0 var(--space-md);+ }+ .docs-main h2 {+ font-family: var(--font-display);+ font-weight: 400;+ font-size: var(--text-xl);+ margin: var(--space-2xl) 0 var(--space-sm);+ padding-bottom: var(--space-xs);+ border-bottom: 1px solid rgba(255,255,255,0.08);+ }+ .docs-main h3 {+ font-weight: 500;+ font-size: var(--text-lg);+ margin: var(--space-xl) 0 var(--space-sm);+ }+ .docs-main p, .docs-main li { color: rgba(229,229,229,0.85); }+ .docs-main ul, .docs-main ol { padding-left: var(--space-lg); }+ .docs-main code {+ font-family: var(--font-mono);+ font-size: 0.92em;+ background: rgba(255,255,255,0.06);+ padding: 1px 5px;+ border-radius: 3px;+ color: #e5e5e5;+ }+ .docs-main pre {+ background: #0a0a0a;+ border: 1px solid rgba(255,255,255,0.08);+ border-radius: var(--radius-md);+ padding: var(--space-md);+ overflow-x: auto;+ line-height: 1.5;+ font-family: var(--font-mono);+ font-size: var(--text-sm);+ }+ .docs-main pre code {+ background: transparent;+ padding: 0;+ }+ .docs-main table {+ width: 100%;+ border-collapse: collapse;+ margin: var(--space-md) 0;+ font-size: var(--text-sm);+ }+ .docs-main th, .docs-main td {+ text-align: left;+ padding: var(--space-xs) var(--space-sm);+ border-bottom: 1px solid rgba(255,255,255,0.06);+ }+ .docs-main th { color: rgba(229,229,229,0.6); font-weight: 500; }+ .docs-main a { color: var(--accent); }+ .docs-main hr { border: 0; border-top: 1px solid rgba(255,255,255,0.08); margin: var(--space-xl) 0; }+ .docs-toc {+ padding: var(--space-md);+ background: rgba(255,255,255,0.025);+ border: 1px solid rgba(255,255,255,0.06);+ border-radius: var(--radius-md);+ margin-bottom: var(--space-xl);+ }+ .docs-toc ul { margin: var(--space-xs) 0; padding-left: var(--space-md); }+ </style>+</head>+<body class="gallery-body">+ <header class="gallery-header">+ <h1><a href="/"><span class="wordmark-dot" aria-hidden="true"></span>3D Agent</a></h1>+ <nav class="features-nav">+ <a href="/">Viewer</a>+ <a href="/features">Features</a>+ <a href="/widgets">Widgets</a>+ <a href="/docs/widgets" class="active" aria-current="page">Docs</a>+ <a href="/dashboard" class="nav-dashboard">Dashboard</a>+ </nav>+ </header>++ <main class="docs-main">+ <h1>Widgets</h1>+ <p>Embeddable 3D — a configured, shareable view of an avatar that any site can drop in with one line of HTML.</p>+ <p>A widget is a saved bundle of: an avatar (GLB stored in R2), a widget type (turntable, animation gallery, talking agent, ERC-8004 passport, hotspot tour), and brand config (background, accent, caption, controls, camera). Widgets are created in the <a href="/studio">Widget Studio</a> and shared via short URLs.</p>++ <div class="docs-toc">+ <strong>On this page:</strong>+ <ul>+ <li><a href="#quick-start">Quick start</a></li>+ <li><a href="#widget-types">Widget types</a></li>+ <li><a href="#urls">URLs</a></li>+ <li><a href="#embedding">Embedding</a></li>+ <li><a href="#postmessage-api">postMessage API</a></li>+ <li><a href="#og-oembed">OG / oEmbed</a></li>+ <li><a href="#csp-cors">CSP / CORS</a></li>+ <li><a href="#privacy">Privacy & analytics</a></li>+ <li><a href="#faq">FAQ</a></li>+ </ul>+ </div>++ <h2 id="quick-start">Quick start</h2>+ <ol>+ <li>Sign in at <a href="/">3dagent.vercel.app</a>.</li>+ <li>Open the <a href="/studio">Studio</a>.</li>+ <li>Pick an avatar, pick a widget type, tweak brand colors and controls, click <strong>Generate Embed</strong>.</li>+ <li>Copy the iframe snippet into any HTML page, blog post, Notion doc, or CMS.</li>+ </ol>++ <h2 id="widget-types">Widget types</h2>+ <table>+ <thead><tr><th>Type</th><th>Best for</th><th>Default size</th></tr></thead>+ <tbody>+ <tr><td><code>turntable</code></td><td>Hero banners, product showcases. Auto-rotate, no UI.</td><td>600 × 600</td></tr>+ <tr><td><code>animation-gallery</code></td><td>Showcasing a rigged avatar's animation library.</td><td>720 × 720</td></tr>+ <tr><td><code>talking-agent</code></td><td>Embodied chat — your agent on your site.</td><td>420 × 600</td></tr>+ <tr><td><code>passport</code></td><td>On-chain identity card backed by ERC-8004.</td><td>480 × 560</td></tr>+ <tr><td><code>hotspot-tour</code></td><td>Annotated 3D scenes with clickable POIs.</td><td>800 × 600</td></tr>+ </tbody>+ </table>++ <h2 id="urls">URLs</h2>+ <p>Every widget has three canonical URLs.</p>+ <table>+ <thead><tr><th>URL</th><th>Use it for</th></tr></thead>+ <tbody>+ <tr><td><code>/w/<id></code></td><td>Sharing in Slack/Discord/X — server-rendered with rich OG card.</td></tr>+ <tr><td><code>/#widget=<id></code></td><td>The SPA viewer with the widget config applied.</td></tr>+ <tr><td><code>/api/widgets/<id>/og</code></td><td>The 1200×630 preview image.</td></tr>+ </tbody>+ </table>++ <h3>Hash parameters</h3>+ <table>+ <thead><tr><th>Param</th><th>Type</th><th>Description</th></tr></thead>+ <tbody>+ <tr><td><code>widget</code></td><td>string</td><td>Loads a saved widget by id.</td></tr>+ <tr><td><code>model</code></td><td>string</td><td>Loads a raw GLB by URL (mutually exclusive with <code>widget</code>).</td></tr>+ <tr><td><code>kiosk</code></td><td>boolean</td><td>Hides the header chrome for clean iframe embeds.</td></tr>+ <tr><td><code>cameraPosition</code></td><td>x,y,z</td><td>Comma-separated camera position override.</td></tr>+ <tr><td><code>preset</code></td><td>string</td><td>HDR environment preset name.</td></tr>+ </tbody>+ </table>++ <h2 id="embedding">Embedding</h2>+ <h3>iframe (recommended)</h3>+<pre><code><iframe+ src="https://3dagent.vercel.app/#widget=wdgt_abc123def456&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></code></pre>++ <h3>Script embed</h3>+<pre><code><script async src="https://3dagent.vercel.app/embed.js" data-widget="wdgt_abc123def456"></script></code></pre>++ <h3>oEmbed (WordPress, Ghost, Notion)</h3>+ <p>Most CMSes auto-detect oEmbed. Paste a <code>/w/<id></code> URL on its own line and the editor should turn it into a live embed automatically.</p>++ <h2 id="postmessage-api">postMessage API</h2>+ <p>Widgets communicate with the parent page via <code>window.postMessage</code>. <strong>Always check <code>event.origin</code> before trusting any message.</strong></p>++ <h3>iframe → parent</h3>+ <table>+ <thead><tr><th>Event</th><th>Payload</th><th>When</th></tr></thead>+ <tbody>+ <tr><td><code>widget:ready</code></td><td><code>{ id, type }</code></td><td>Widget runtime has booted.</td></tr>+ <tr><td><code>widget:load</code></td><td><code>{ id, model_url }</code></td><td>Underlying GLB loaded successfully.</td></tr>+ <tr><td><code>widget:load:error</code></td><td><code>{ id, error }</code></td><td>GLB or config failed to load.</td></tr>+ <tr><td><code>widget:chat:message</code></td><td><code>{ role, content }</code></td><td>Talking-agent only.</td></tr>+ <tr><td><code>widget:hotspot:open</code></td><td><code>{ id, label }</code></td><td>Hotspot-tour only.</td></tr>+ <tr><td><code>widget:resize</code></td><td><code>{ width, height }</code></td><td>Widget reports preferred size.</td></tr>+ </tbody>+ </table>++<pre><code>window.addEventListener('message', (e) => {+ if (e.origin !== 'https://3dagent.vercel.app') return;+ if (e.data?.type === 'widget:ready') {+ console.log('Widget mounted:', e.data.id);+ }+});</code></pre>++ <h3>parent → iframe</h3>+ <table>+ <thead><tr><th>Event</th><th>Payload</th><th>Effect</th></tr></thead>+ <tbody>+ <tr><td><code>widget:config</code></td><td><code>{ background, accent, autoRotate, … }</code></td><td>Live-update brand config.</td></tr>+ <tr><td><code>widget:command</code></td><td><code>{ command, args }</code></td><td>Trigger a runtime action.</td></tr>+ </tbody>+ </table>++ <h2 id="og-oembed">OG / oEmbed</h2>+ <p>Every widget URL serves rich-preview metadata. <code>/w/<id></code> is server-rendered with Open Graph + Twitter card tags and a <code><link rel="alternate" type="application/json+oembed"></code> pointer.</p>+<pre><code>GET /api/widgets/oembed?url=<widget-url>&format=json</code></pre>+ <p>Returns standard <a href="https://oembed.com">oEmbed v1.0</a> JSON, type <code>rich</code>. Accepts both <code>/w/<id></code> and <code>/#widget=<id></code> forms.</p>++ <h2 id="csp-cors">CSP / CORS</h2>+ <p>Widgets run in a sandboxed iframe with these <code>allow</code> flags: <code>autoplay</code>, <code>xr-spatial-tracking</code>, <code>clipboard-write</code>. If your site uses strict CSP, allow:</p>+<pre><code>frame-src https://3dagent.vercel.app;+img-src https://3dagent.vercel.app data:;</code></pre>++ <h2 id="privacy">Privacy & analytics</h2>+ <p>We log a minimal first-party event per widget load: <code>widget_id</code>, <code>type</code>, <code>country</code> (Vercel edge header), <code>referer_host</code> (hostname only), <code>created_at</code>. No IPs. No cookies. No user agents. No chat content. No cross-widget tracking.</p>++ <h2 id="faq">FAQ</h2>+ <p><strong>Can I self-host?</strong> The runtime is open source. The Studio + saved-widgets API depends on Neon + R2; you'd need to wire those yourself. See <a href="/docs/deployment">deployment guide</a>.</p>+ <p><strong>Why no WordPress plugin?</strong> The oEmbed endpoint already does what a plugin would.</p>+ <p><strong>How big is the bundle?</strong> Cold load ~400KB JS + the GLB itself.</p>+ <p><strong>Mobile?</strong> Yes — every widget type works on iOS Safari and Android Chrome.</p>++ <hr>+ <p><a href="/widgets">← Back to gallery</a> · <a href="/studio">Open the Studio →</a></p>+ </main>++ <footer class="gallery-footer">+ <p>3D Agent · <a href="/">Viewer</a> · <a href="/widgets">Widgets</a> · <a href="/docs/widgets">Docs</a> · <a href="https://github.com/nirholas/3D">GitHub</a></p>+ </footer>+</body>+</html>diff --git a/public/widgets-gallery/gallery.css b/public/widgets-gallery/gallery.cssnew file mode 100644index 000000000..de85b4c84--- /dev/null+++ b/public/widgets-gallery/gallery.css@@ -0,0 +1,285 @@+/* Widget gallery — matches root style.css tokens. No new design system. */++html, body.gallery-body {+ overflow: auto;+ height: auto;+ min-height: 100vh;+}++.gallery-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: var(--space-md) var(--space-lg);+ border-bottom: 1px solid rgba(255,255,255,0.06);+ background: rgba(0,0,0,0.5);+ 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;+ display: inline-flex;+ 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;+ padding: var(--space-xs) var(--space-sm);+ border-radius: var(--radius-md);+ transition: 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);+}++.gallery-main {+ max-width: 1080px;+ margin: 0 auto;+ padding: var(--space-2xl) var(--space-lg);+ display: flex;+ flex-direction: column;+ gap: var(--space-2xl);+}++.gallery-hero {+ text-align: center;+ display: flex;+ flex-direction: column;+ gap: var(--space-md);+ align-items: center;+}+.gallery-hero .eyebrow {+ margin: 0;+ font-size: var(--text-sm);+ letter-spacing: 4px;+ text-transform: uppercase;+ color: var(--accent);+ font-weight: 600;+}+.gallery-hero h2 {+ margin: 0;+ font-family: var(--font-display);+ font-size: var(--text-2xl);+ font-weight: 300;+ letter-spacing: -1px;+ line-height: 1.1;+}+.gallery-hero .lede {+ max-width: 60ch;+ margin: 0;+ font-size: var(--text-lg);+ color: rgba(229,229,229,0.7);+ line-height: var(--leading-normal);+}+.cta-row {+ display: flex;+ gap: var(--space-sm);+ flex-wrap: wrap;+ justify-content: center;+ margin-top: var(--space-sm);+}++.btn {+ display: inline-flex;+ align-items: center;+ gap: var(--space-xs);+ padding: var(--space-sm) var(--space-lg);+ border-radius: 999px;+ font-family: var(--font-body);+ font-size: var(--text-base);+ font-weight: 500;+ text-decoration: none;+ border: 1px solid transparent;+ cursor: pointer;+ transition: transform 0.15s, 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); }++.gallery-grid {+ display: flex;+ flex-direction: column;+ gap: var(--space-2xl);+}+.gallery-grid .loading {+ color: rgba(229,229,229,0.55);+ text-align: center;+}++.showcase {+ display: grid;+ grid-template-columns: minmax(0, 1fr) minmax(280px, 380px);+ 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);+}+@media (max-width: 820px) {+ .showcase { grid-template-columns: 1fr; }+}++.showcase-frame {+ position: relative;+ border-radius: var(--radius-md);+ overflow: hidden;+ background: #050505;+ aspect-ratio: 1 / 1;+}+.showcase-frame iframe {+ position: absolute;+ inset: 0;+ width: 100%;+ height: 100%;+ border: 0;+ display: block;+}++.showcase-meta {+ display: flex;+ flex-direction: column;+ gap: var(--space-md);+}+.showcase-meta .type-tag {+ display: inline-block;+ font-size: var(--text-xs);+ letter-spacing: 3px;+ text-transform: uppercase;+ color: var(--accent);+ font-weight: 600;+}+.showcase-meta h3 {+ margin: 0;+ font-family: var(--font-display);+ font-size: var(--text-xl);+ font-weight: 400;+ letter-spacing: -0.5px;+}+.showcase-meta p {+ margin: 0;+ color: rgba(229,229,229,0.7);+ line-height: var(--leading-normal);+}++.snippet {+ position: relative;+ background: #0a0a0a;+ border: 1px solid rgba(255,255,255,0.08);+ border-radius: var(--radius-md);+ padding: var(--space-sm);+ font-family: var(--font-mono);+ font-size: var(--text-sm);+ color: rgba(229,229,229,0.85);+ white-space: pre-wrap;+ word-break: break-all;+ overflow-x: auto;+}+.snippet code { display: block; }+.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;+ padding: var(--space-xs) var(--space-sm);+ font-size: var(--text-sm);+ background: rgba(255,255,255,0.05);+ border: 1px solid rgba(255,255,255,0.1);+ color: #e5e5e5;+ border-radius: var(--radius-md);+ cursor: pointer;+ text-align: center;+ text-decoration: none;+ font-family: var(--font-body);+ transition: background 0.15s;+}+.snippet-row button:hover,+.snippet-row a:hover { background: rgba(255,255,255,0.1); }+.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); }++.error-state {+ padding: var(--space-md);+ 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);+}++.gallery-cta {+ text-align: center;+ padding: var(--space-2xl) var(--space-lg);+ background: rgba(139,92,246,0.06);+ border: 1px solid rgba(139,92,246,0.15);+ border-radius: var(--radius-lg);+ display: flex;+ flex-direction: column;+ 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); }++.gallery-footer {+ padding: var(--space-lg);+ text-align: center;+ color: rgba(229,229,229,0.5);+ 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; }++@media (prefers-reduced-motion: reduce) {+ .btn, .snippet-row button, .snippet-row a { transition: none; }+ .btn-primary:hover { transform: none; }+}diff --git a/public/widgets-gallery/gallery.js b/public/widgets-gallery/gallery.jsnew file mode 100644index 000000000..8b376d46d--- /dev/null+++ b/public/widgets-gallery/gallery.js@@ -0,0 +1,133 @@+// 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.++const GRID_EL = document.getElementById('gallery-grid');++const ORIGIN = location.origin;++(async function init() {+ let showcase;+ try {+ const res = await fetch('/widgets-gallery/showcase.json', { cache: 'no-cache' });+ if (!res.ok) throw new Error(`showcase.json ${res.status}`);+ showcase = await res.json();+ } catch (err) {+ GRID_EL.innerHTML = '';+ GRID_EL.appendChild(errorEl('Could not load showcase config.', err.message));+ GRID_EL.removeAttribute('aria-busy');+ return;+ }++ GRID_EL.innerHTML = '';+ for (const w of showcase.widgets || []) {+ GRID_EL.appendChild(renderShowcase(w));+ }+ GRID_EL.removeAttribute('aria-busy');+})();++function renderShowcase(w) {+ const root = document.createElement('article');+ root.className = 'showcase';+ root.setAttribute('aria-labelledby', `sc-${w.id}-title`);++ const widgetUrl = `${ORIGIN}/#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>`;++ 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 meta = document.createElement('div');+ meta.className = 'showcase-meta';++ const tag = document.createElement('span');+ tag.className = 'type-tag';+ tag.textContent = w.type;+ meta.appendChild(tag);++ const h = document.createElement('h3');+ h.id = `sc-${w.id}-title`;+ h.textContent = w.label;+ meta.appendChild(h);++ const desc = document.createElement('p');+ desc.textContent = w.tagline;+ meta.appendChild(desc);++ const code = document.createElement('pre');+ code.className = 'snippet';+ code.setAttribute('aria-label', 'Embed snippet');+ const codeInner = document.createElement('code');+ codeInner.textContent = snippet;+ code.appendChild(codeInner);+ meta.appendChild(code);++ 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}`);+ 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}`);+ 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`);+ row.appendChild(studio);++ meta.appendChild(row);++ root.appendChild(frame);+ root.appendChild(meta);+ return root;+}++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';+ document.body.appendChild(ta);+ ta.select();+ try { document.execCommand('copy'); } catch {}+ ta.remove();+ }+ const orig = btn.textContent;+ btn.classList.add('copied');+ btn.textContent = 'Copied!';+ setTimeout(() => {+ btn.textContent = orig;+ btn.classList.remove('copied');+ }, 1400);+}++function errorEl(msg, detail) {+ const e = document.createElement('div');+ e.className = 'error-state';+ e.textContent = detail ? `${msg} (${detail})` : msg;+ return e;+}diff --git a/public/widgets-gallery/index.html b/public/widgets-gallery/index.htmlnew file mode 100644index 000000000..9e494d317--- /dev/null+++ b/public/widgets-gallery/index.html@@ -0,0 +1,65 @@+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8">+ <meta http-equiv="X-UA-Compatible" content="IE=edge">+ <title>Widgets — 3D Agent</title>+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">+ <meta name="description" content="Embeddable 3D, no code. Drop a widget into any site, blog, or Notion doc.">+ <meta name="theme-color" content="#0a0a0a">++ <meta property="og:type" content="website">+ <meta property="og:site_name" content="3D Agent">+ <meta property="og:title" content="3D Agent — Widgets">+ <meta property="og:description" content="Embeddable 3D, no code. Drop a widget into any site, blog, or Notion doc.">+ <meta property="og:url" content="https://3dagent.vercel.app/widgets">++ <link rel="canonical" href="https://3dagent.vercel.app/widgets">+ <link rel="shortcut icon" href="/favicon.ico">+ <link rel="preconnect" href="https://fonts.googleapis.com">+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Space+Grotesk:wght@500;600;700&display=swap" rel="stylesheet">+ <link rel="stylesheet" href="/style.css">+ <link rel="stylesheet" href="/widgets-gallery/gallery.css">+</head>+<body class="gallery-body">+ <header class="gallery-header">+ <h1><a href="/"><span class="wordmark-dot" aria-hidden="true"></span>3D Agent</a></h1>+ <nav class="features-nav">+ <a href="/">Viewer</a>+ <a href="/features">Features</a>+ <a href="/widgets" class="active" aria-current="page">Widgets</a>+ <a href="/docs/widgets">Docs</a>+ <a href="/dashboard" class="nav-dashboard">Dashboard</a>+ </nav>+ </header>++ <main class="gallery-main" id="gallery-main">+ <section class="gallery-hero">+ <p class="eyebrow">Widget Studio</p>+ <h2>Embeddable 3D, no code.</h2>+ <p class="lede">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="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>+ </div>+ </section>++ <section class="gallery-grid" id="gallery-grid" aria-busy="true">+ <p class="loading">Loading showcase widgets…</p>+ </section>++ <section class="gallery-cta">+ <h3>Make your own.</h3>+ <p>Pick an avatar, pick a widget type, paste the snippet. Free for personal use.</p>+ <a class="btn btn-primary" href="/studio">Open the Studio</a>+ </section>+ </main>++ <footer class="gallery-footer">+ <p>3D Agent · <a href="/">Viewer</a> · <a href="/widgets">Widgets</a> · <a href="/docs/widgets">Docs</a> · <a href="https://github.com/nirholas/3D">GitHub</a></p>+ </footer>++ <script type="module" src="/widgets-gallery/gallery.js"></script>+</body>+</html>diff --git a/public/widgets-gallery/showcase.json b/public/widgets-gallery/showcase.jsonnew file mode 100644index 000000000..d99143ace--- /dev/null+++ b/public/widgets-gallery/showcase.json@@ -0,0 +1,45 @@+{+ "_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.",+ "widgets": [+ {+ "type": "turntable",+ "label": "Turntable Showcase",+ "tagline": "Hero banner for sites — auto-rotate, no UI.",+ "id": "wdgt_demo_turntab",+ "width": 600,+ "height": 600+ },+ {+ "type": "animation-gallery",+ "label": "Animation Gallery",+ "tagline": "Click through every clip on a rigged avatar.",+ "id": "wdgt_demo_animgal",+ "width": 720,+ "height": 720+ },+ {+ "type": "talking-agent",+ "label": "Talking Agent",+ "tagline": "Embodied chat — your agent, your site, your tone.",+ "id": "wdgt_demo_talking",+ "width": 420,+ "height": 600+ },+ {+ "type": "passport",+ "label": "ERC-8004 Passport",+ "tagline": "On-chain identity card for any agent.",+ "id": "wdgt_demo_passprt",+ "width": 480,+ "height": 560+ },+ {+ "type": "hotspot-tour",+ "label": "Hotspot Tour",+ "tagline": "Explorable 3D scenes with annotated points of interest.",+ "id": "wdgt_demo_hotspot",+ "width": 800,+ "height": 600+ }+ ]+}diff --git a/src/CLAUDE.md b/src/CLAUDE.mdnew file mode 100644index 000000000..c98b5d5c1--- /dev/null+++ b/src/CLAUDE.md@@ -0,0 +1,165 @@+# src/CLAUDE.md++Scoped guidance for the viewer + agent runtime. Read [/CLAUDE.md](../CLAUDE.md) first.++---++## The two halves++- **Viewer half** — [viewer.js](viewer.js), [viewer/](viewer/), [environments.js](environments.js), [validator.js](validator.js), [animation-manager.js](animation-manager.js), [model-info.js](model-info.js), [annotations.js](annotations.js), [editor/](editor/). Pure three.js. Loads GLB, renders, manages animations, validates.+- **Agent half** — [agent-*.js](./), [runtime/](runtime/), [skills/](skills/), [memory/](memory/), [erc8004/](erc8004/), [manifest.js](manifest.js), [element.js](element.js). Adds persona, memory, skills, identity, emotional presence.++The viewer doesn't know about agents. The agent layer wraps the viewer through [runtime/scene.js](runtime/scene.js) (SceneController).++---++## Module map++### Agent primitives (singleton-ish, per element instance)+- [agent-protocol.js](agent-protocol.js) — **the bus.** Everything communicates through `protocol.emit()` / `protocol.on()`. Don't add direct module-to-module coupling.+- [agent-identity.js](agent-identity.js) — passport + diary. localStorage + `/api/agents/:id`. Wallet linking, signed action history.+- [agent-memory.js](agent-memory.js) — in-memory 4-type store (see also [memory/index.js](memory/index.js) for the file-based variant).+- [agent-skills.js](agent-skills.js) — built-in skills (greet, present-model, validate-model, remember, think, sign-action, help).+- [agent-avatar.js](agent-avatar.js) — **the Empathy Layer.** Emotion blend, morph targets, gaze, one-shot gestures.+- [agent-home.js](agent-home.js) — identity card + action timeline + emotion presence UI.+- [agent-resolver.js](agent-resolver.js) — resolves `agent-id="..."` attributes to manifests via `/api/agents/:id`.++### Runtime (LLM brain)+- [runtime/index.js](runtime/index.js) — tool loop. `MAX_TOOL_ITERATIONS = 8`.+- [runtime/providers.js](runtime/providers.js) — `AnthropicProvider`, `NullProvider`.+- [runtime/scene.js](runtime/scene.js) — SceneController wraps Viewer with agent-facing API (`playClipByName`, `lookAt`, `setExpression`, `loadGLB`).+- [runtime/tools.js](runtime/tools.js) — `BUILTIN_TOOLS` + handlers (wave, lookAt, play_clip, setExpression, speak, remember).+- [runtime/speech.js](runtime/speech.js) — TTS/STT via browser Web Speech API.++### Format loaders+- [manifest.js](manifest.js) — `agent-manifest/0.1`. Loads from `agent://chain/id`, `ipfs://`, `ar://`, `https://`. `normalize()` adapts ERC-8004 registration JSON.+- [skills/index.js](skills/index.js) — SkillRegistry. `.install(spec, { bundleBase })`, trust modes (`any`, `owned-only`, `whitelist`), recursive deps.+- [memory/index.js](memory/index.js) — file-based (frontmatter `.md` files + auto-generated MEMORY.md index + append-only timeline). Modes: `local`, `ipfs`, `encrypted-ipfs`, `none`.+- [ipfs.js](ipfs.js) — IPFS/Arweave → HTTPS gateway with fallback (ipfs.io → dweb.link → nft.storage).++### Web component boundary+- [element.js](element.js) — `<agent-3d>` custom element. IntersectionObserver lazy boot unless `eager`. See attribute list in [specs/EMBED_SPEC.md](../specs/EMBED_SPEC.md).+- [lib.js](lib.js) — CDN library export surface.+- [app.js](app.js) — main SPA entry. **URL hash routing lives here** — keys: `model`, `widget`, `agent`, `kiosk`, `brain`, `proxyURL`, `preset`, `cameraPosition`, `register`.++### Blockchain+- [erc8004/abi.js](erc8004/abi.js) — IdentityRegistry / ReputationRegistry / ValidationRegistry ABIs + `REGISTRY_DEPLOYMENTS` (mainnet + testnet addresses, keyed by chainId).+- [erc8004/agent-registry.js](erc8004/) — `connectWallet()`, `registerAgent()`, `buildRegistrationJSON()`, `pinToIPFS()`.+- [erc8004/privy.js](erc8004/) — Privy OAuth hooks.+- [erc8004/reputation.js](erc8004/) — `submitFeedback()`, `getReputation()`, `getRecentReviews()`.+- [erc8004/validation-recorder.js](erc8004/) — `recordValidation()`, `hashReport()`.++---++## The protocol bus — event vocabulary++All events are `CustomEvent` with `detail = { type, payload, timestamp, agentId, sourceSkill }`. Emitters fire on `protocol`, consumers subscribe via `protocol.on(type, handler)`.++| Type | Payload | Emitted by | Consumed by |+|---|---|---|---|+| `speak` | `{ text, sentiment }` (-1..1) | runtime, skills | avatar (emotion), home (timeline), nich-agent (chat UI) |+| `think` | `{ thought }` | runtime | home, avatar |+| `gesture` | `{ name, duration }` | skills, avatar | avatar (one-shot clip) |+| `emote` | `{ trigger, weight }` (0..1) | skills, avatar internals | avatar (emotion blend) |+| `look-at` | `{ target: 'model'\|'user'\|'camera' }` | skills | scene-ctrl |+| `perform-skill` | `{ skill, args, animationHint }` | runtime | skills registry |+| `skill-done` | `{ skill, result: { success, output, sentiment, data } }` | skill handlers | avatar, identity |+| `skill-error` | `{ skill, error }` | skill handlers | avatar (concern + empathy), identity |+| `remember` | `{ type, content, ... }` | skills, runtime | memory, identity |+| `sign` | `{ message, address }` | skills | identity |+| `load-start` | `{ uri }` | viewer | avatar (patience + curiosity) |+| `load-end` | `{ uri, error? }` | viewer | avatar (concern or celebration) |+| `validate` | `{ errors, warnings }` | validator | avatar, identity |+| `presence` | `{ state }` | element | home |++**Identity records these to the backend:** `speak`, `remember`, `sign`, `skill-done`, `validate`, `load-end`. Fire-and-forget via `POST /api/agent-actions`.++**Debug:** `window.VIEWER.agent_protocol.history.slice(-10)` or `protocol.on('*', console.log)`.++---++## The Empathy Layer — how it actually works++### State+Continuous weighted blend of `{ neutral, concern, celebration, patience, curiosity, empathy }`. All blend simultaneously. `neutral = 1 - sum(others)`.++### Decay (per second)+| Emotion | Rate | Half-life |+|---|---|---|+| concern | 0.08 | ~9s |+| celebration | 0.18 | ~4s |+| patience | 0.035 | ~20s |+| curiosity | 0.12 | ~6s |+| empathy | 0.055 | ~13s |++### Stimulus rules (protocol → emotion)+- `speak`: valence > 0.3 → celebration; < -0.2 → concern; arousal > 0.5 → curiosity+- `skill-done`: `result.sentiment` > 0.3 → celebration; < -0.2 → concern+- `skill-error`: concern + empathy (scaled by error streak × 0.25)+- `load-start`: patience + curiosity+- `load-end`: error → concern; success → celebration + curiosity+- `validate`: errors → concern; warnings → concern; clean → celebration + nod++### Morph target mapping (per frame, lerp speed ~4.0)+- celebration → mouthSmile 0.85, mouthOpen 0.2, cheekPuff 0.2+- concern → mouthFrown 0.55, browInnerUp 0.6, noseSneer 0.15+- empathy → eyeSquint 0.4, browInnerUp 0.5+- curiosity → browOuterUp 0.7/0.5+- patience → eyesClosed 0.15 (subtle)++### Head transform+Z-rotation = `(curiosity*12 + empathy*9 + concern*4)` degrees. X-rotation (lean) = `curiosity*0.03 - patience*0.02`. Finds `Head` or `Neck` bone in skeleton.++**Don't add a discrete emotion FSM.** The whole point is the continuous blend.++---++## Conventions++- **ESM only.** No CommonJS.+- **Tabs, 4-wide.** Prettier-enforced.+- **JSDoc for public APIs.** No TypeScript.+- **Classes over factories** where there's state. EventTarget for buses.+- **Naming:** CamelCase classes, camelCase methods, UPPER_CASE constants, `_underscore` for private methods/fields.+- **vhtml JSX** in `*.jsx` components — string-based, no virtual DOM. See [components/](components/).+- **Tool result shape:** `{ ok: true, ... }` or `{ ok: false, error: 'msg' }`.+- **Skill handler context:** `(args, ctx)` where `ctx = { viewer, memory, llm, speak, listen, fetch, loadGLB, loadClip, loadJSON, call }`.++---++## Gotchas++- **`window.VIEWER`** is a debug global exposing `.editor, .agent, .agent_protocol, .agent_avatar, .agent_skills, .runtime, .scene_ctrl`. Never rely on it in production code — use closure / DI.+- **Manifest `_baseURI`** must end with `/` for relative resolution of `body.uri`, `SKILL.md`, `tools.json`, `handlers.js`.+- **Viewer._afterAnimateHooks** — avatar hooks its `_tickEmotion` here for per-frame decay. Fragile coupling; don't rearrange.+- **SpeechRecognition** silently noops if unavailable. Check `window.SpeechRecognition || window.webkitSpeechRecognition` before relying.+- **Morph traversal** iterates every mesh every frame. Cheap on Mixamo avatars, expensive on scene-scale models — don't add per-vertex work.+- **Skill `owned-only` trust** compares `manifest.author` with `ownerAddress` from element attr or backend. Mismatch → skill load throws.+- **`viewer.js` is large (~11k lines).** [prompts/scalability/03-module-split.md](../prompts/scalability/03-module-split.md) is the planned refactor. Don't start it ad-hoc.+- **`memory.recall()` is substring search.** No embeddings yet.+- **No rate limit on `protocol.emit()`.** A runaway skill loop will cascade.++---++## What's half-built (don't assume working)++- [features/hero-pretext.js](features/) — flag-gated, not core+- [editor/](editor/) — GLB export + material editor exist, agent-system integration minimal+- ERC-8004 reputation/validation — hooked but no UI+- Memory `encrypted-ipfs` mode — stub+- Runtime `thinking: 'auto'` — limited UX wiring+- Privy integration — functions exist, no full auth flow in element.js+- Avatar Creator save-to-account — may not persist in all flows+- `@avaturn/sdk` resolution warning at build time — **pre-existing, ignore**++---++## Adding things++**New action type:** add to `ACTION_TYPES` in [agent-protocol.js](agent-protocol.js), emit at source, subscribe in consumers. Update the event vocabulary table above.++**New built-in tool:** add to `BUILTIN_TOOLS` array + `BUILTIN_HANDLERS` in [runtime/tools.js](runtime/tools.js). Handler signature: `async (args, ctx) => ({ ok: true, ... })`.++**New skill:** bundle under [skills/](skills/). See /CLAUDE.md "Canonical patterns → New agent skill" for the 5-step recipe.++**New URL hash param:** parse in [app.js](app.js) next to existing keys. Don't invent a new routing layer.diff --git a/src/app.js b/src/app.jsindex 82b76075d..02153b248 100644--- a/src/app.js+++ b/src/app.js@@ -8,7 +8,7 @@ import { Footer } from './components/footer';import { NichAgent } from './nich-agent.js';import { AvatarCreator } from './avatar-creator.js';import { resolveURI, isDecentralizedURI } from './ipfs.js';-import { saveRemoteGlbToAccount } from './account.js';+import { saveRemoteGlbToAccount, getMe } from './account.js';import queryString from 'query-string';// Agent system — the new primitive layer@@ -47,6 +47,7 @@ class App {cameraPosition: hash.cameraPosition ? hash.cameraPosition.split(',').map(Number) : null,brain: hash.brain || 'none',proxyURL: hash.proxyURL || '',+ agent: hash.agent || '',};this.el = el;@@ -75,6 +76,7 @@ class App {this.createDropzone();this.setupAvatarCreator();this.hideSpinner();+ this._updateSignInLink();const options = this.options;@@ -89,6 +91,12 @@ class App {return;}+ // Load a specific agent by ID: /#agent=<uuid>+ if (options.agent) {+ this._loadAgent(options.agent);+ return;+ }+// Load specified model or default CZ avatarconst model = options.model || '/avatars/cz.glb';const resolvedModel = isDecentralizedURI(model) ? resolveURI(model) : model;@@ -191,6 +199,43 @@ class App {}}+ async _updateSignInLink() {+ const link = document.getElementById('nav-sign-in');+ if (!link) return;+ try {+ const user = await getMe();+ if (user) link.classList.add('signed-in');+ } catch { /* leave sign-in visible */ }+ }++ _refreshMakeWidgetButton() {+ const btn = document.getElementById('make-widget-btn');+ if (!btn) return;+ const url = this._currentModelUrl;+ if (!url) { btn.hidden = true; return; }+ btn.href = `/studio?model=${encodeURIComponent(url)}`;+ btn.hidden = false;+ }++ async _loadAgent(agentId) {+ this.identity = new AgentIdentity({ agentId, autoLoad: false });+ await this.identity.load();++ let glbUrl = '/avatars/cz.glb';+ if (this.identity.avatarId) {+ try {+ const resp = await fetch(`/api/avatars/${this.identity.avatarId}`, { credentials: 'include' });+ if (resp.ok) {+ const { avatar } = await resp.json();+ if (avatar?.url) glbUrl = avatar.url;+ }+ } catch { /* fall through to default */ }+ }++ this.view(glbUrl, '', new Map());+ this._initAgentSystem();+ }+_initNichAgent() {const agent = new NichAgent(document.body, protocol, this.skills, this.identity, this.runtime);window.VIEWER.agent = agent;@@ -277,6 +322,9 @@ class App {const viewer = this.viewer || this.createViewer();const fileURL = typeof rootFile === 'string' ? rootFile : URL.createObjectURL(rootFile);+ this._currentModelUrl = typeof rootFile === 'string' ? rootFile : null;+ this._refreshMakeWidgetButton();+// Emit load startprotocol.emit({type: ACTION_TYPES.LOAD_START,diff --git a/src/nich-agent.js b/src/nich-agent.jsindex 88e95200f..aa7d07b83 100644--- a/src/nich-agent.js+++ b/src/nich-agent.js@@ -34,6 +34,9 @@ export class NichAgent {this.messages = [];this.onFirstOpen = null;this._hasOpened = false;+ this._apiDisabled = false;+ this._storageKey = `nich-agent:history:${this.identity?.id || 'default'}`;+ this._loadHistory();this._buildUI();this._initSpeechRecognition();@@ -55,6 +58,9 @@ export class NichAgent {this._addMessage('agent', `[performing: ${skill}]`, 'status');}});++ // Clear chat history on model change so context stays relevant+ this.protocol.on(ACTION_TYPES.LOAD_START, () => this._resetHistory());}}@@ -181,14 +187,26 @@ export class NichAgent {}}- // Try Runtime LLM when a real provider is configured (not NullProvider)+ // Preferred path: call the /api/chat LLM endpoint with viewer context.+ if (!this._apiDisabled) {+ const apiResult = await this._callChatAPI(text);+ if (apiResult.ok) {+ await this._applyApiReply(apiResult);+ return;+ }+ if (apiResult.disable) this._apiDisabled = true;+ }++ // Secondary: the client-side Runtime (only meaningful if a provider+ // was configured via #brain=anthropic&proxyURL=... — NullProvider returns '').if (this.runtime) {try {const { text: reply } = await this.runtime.send(text);if (reply) {this._addMessage('agent', reply);this._speak(reply);- // Runtime events are bridged to protocol in app.js — no double emit+ this._pushHistory('user', text);+ this._pushHistory('assistant', reply);return;}} catch (err) {@@ -196,7 +214,7 @@ export class NichAgent {}}- // Fallback: pattern-match response (no LLM needed)+ // Final fallback: offline pattern match so the agent still responds.const response = this._generateResponse(text);this._addMessage('agent', response);this._speak(response);@@ -210,6 +228,199 @@ export class NichAgent {}}+ // ── Chat API ─────────────────────────────────────────────────────────────++ async _callChatAPI(message) {+ const typing = this._startTyping();+ try {+ const res = await fetch('/api/chat', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ message,+ context: this._buildContext(),+ history: this._history.slice(-10),+ }),+ });++ if (res.status === 401) return { ok: false, disable: true, reason: 'unauthorized' };+ if (res.status === 503) return { ok: false, disable: true, reason: 'unconfigured' };+ if (res.status === 429) {+ const data = await res.json().catch(() => ({}));+ return { ok: false, rateLimited: true, retryAfter: data.retry_after };+ }+ if (!res.ok) return { ok: false, reason: `http_${res.status}` };++ const data = await res.json();+ return { ok: true, message, reply: (data.reply || '').trim(), actions: data.actions || [] };+ } catch (err) {+ console.warn('[NichAgent] /api/chat failed:', err.message);+ return { ok: false, reason: 'network' };+ } finally {+ typing();+ }+ }++ async _applyApiReply({ message, reply, actions }) {+ this._pushHistory('user', message);++ if (reply) {+ this._addMessage('agent', reply);+ this._speak(reply);+ this._pushHistory('assistant', reply);+ if (this.protocol) {+ this.protocol.emit({+ type: ACTION_TYPES.SPEAK,+ payload: { text: reply, sentiment: 0 },+ agentId: this.identity?.id || 'default',+ });+ }+ }++ for (const action of actions || []) {+ try {+ await this._executeAction(action);+ } catch (err) {+ console.warn('[NichAgent] action failed:', action?.type, err.message);+ }+ }+ }++ _buildContext() {+ const viewer = window.VIEWER?.app?.viewer;+ const validator = window.VIEWER?.app?.validator;+ const state = viewer?.state || {};+ const ctx = {+ wireframe: !!state.wireframe,+ skeleton: !!state.skeleton,+ grid: !!state.grid,+ autoRotate: !!state.autoRotate,+ transparentBg: !!state.transparentBg,+ bgColor: state.bgColor,+ currentEnvironment: state.environment,+ };+ if (viewer?.content) {+ if (viewer.content.name) ctx.modelName = viewer.content.name;+ const stats = this._countStats(viewer.content);+ ctx.vertices = stats.vertices;+ ctx.triangles = stats.triangles;+ ctx.materials = stats.materials;+ ctx.animations = viewer.clips?.length || 0;+ }+ if (validator?.report) {+ ctx.validationErrors = validator.report.errors?.length || 0;+ ctx.validationWarnings = validator.report.warnings?.length || 0;+ }+ return ctx;+ }++ _countStats(root) {+ let vertices = 0, triangles = 0;+ const materials = new Set();+ root.traverse((node) => {+ if (node.isMesh || node.isPoints || node.isLine) {+ const geo = node.geometry;+ if (geo) {+ if (geo.index) triangles += geo.index.count / 3;+ else if (geo.attributes.position) triangles += geo.attributes.position.count / 3;+ if (geo.attributes.position) vertices += geo.attributes.position.count;+ }+ const mats = Array.isArray(node.material) ? node.material : [node.material];+ for (const m of mats) if (m) materials.add(m.uuid);+ }+ });+ return { vertices, triangles: Math.round(triangles), materials: materials.size };+ }++ async _executeAction(action) {+ const viewer = window.VIEWER?.app?.viewer;+ const app = window.VIEWER?.app;+ if (!action || typeof action.type !== 'string') return;++ switch (action.type) {+ case 'setWireframe':+ if (viewer) { viewer.state.wireframe = !!action.value; viewer.updateDisplay(); }+ break;+ case 'setSkeleton':+ if (viewer) { viewer.state.skeleton = !!action.value; viewer.updateDisplay(); }+ break;+ case 'setGrid':+ if (viewer) { viewer.state.grid = !!action.value; viewer.updateDisplay(); }+ break;+ case 'setAutoRotate':+ if (viewer) { viewer.state.autoRotate = !!action.value; viewer.updateDisplay(); }+ break;+ case 'setBgColor':+ if (viewer && typeof action.value === 'string') {+ viewer.state.bgColor = action.value;+ viewer.updateBackground();+ }+ break;+ case 'setTransparentBg':+ if (viewer) { viewer.state.transparentBg = !!action.value; viewer.updateBackground(); }+ break;+ case 'setEnvironment':+ if (viewer && typeof action.value === 'string') {+ viewer.state.environment = action.value;+ viewer.updateEnvironment();+ }+ break;+ case 'takeScreenshot':+ viewer?.takeScreenshot?.();+ break;+ case 'loadModel':+ if (typeof action.url === 'string' && app?.view) {+ app.view(action.url, '', new Map());+ }+ break;+ case 'runValidation':+ // Open/focus the validation report panel so the user sees current results.+ document.querySelector('.validator-toggle')?.click?.();+ break;+ case 'showMaterialEditor':+ app?.editor?.sceneExplorer?.toggle?.();+ break;+ default:+ console.warn('[NichAgent] unknown action:', action.type);+ }+ }++ // ── Typing indicator ─────────────────────────────────────────────────────++ _startTyping() {+ const messagesEl = this.panel.querySelector('#agent-messages');+ const el = document.createElement('div');+ el.className = 'nich-message agent typing';+ el.textContent = '…';+ messagesEl.appendChild(el);+ messagesEl.scrollTop = messagesEl.scrollHeight;+ return () => el.remove();+ }++ // ── Conversation history (sessionStorage) ────────────────────────────────++ _loadHistory() {+ this._history = [];+ try {+ const raw = sessionStorage.getItem(this._storageKey);+ if (raw) this._history = JSON.parse(raw).slice(-20);+ } catch {+ this._history = [];+ }+ }++ _pushHistory(role, content) {+ this._history.push({ role, content });+ if (this._history.length > 20) this._history = this._history.slice(-20);+ try { sessionStorage.setItem(this._storageKey, JSON.stringify(this._history)); } catch {}+ }++ _resetHistory() {+ this._history = [];+ try { sessionStorage.removeItem(this._storageKey); } catch {}+ }+/*** Map user input to a skill name.* Returns null if no skill matches.diff --git a/style.css b/style.cssindex ccebbaf29..4a0531ecb 100644--- a/style.css+++ b/style.css@@ -1307,6 +1307,42 @@ footer .separator {}}+/******************************************************************************+ * Make this a widget — appears once a model is loaded+ */+.make-widget-btn {+ display: inline-flex;+ align-items: center;+ gap: var(--space-xs);+ padding: var(--space-sm) var(--space-lg);+ background: rgba(0, 229, 160, 0.1);+ border: 1px solid rgba(0, 229, 160, 0.3);+ border-radius: var(--radius-lg);+ color: rgba(255, 255, 255, 0.85);+ font-family: inherit;+ font-size: var(--text-sm);+ font-weight: 500;+ text-decoration: none;+ cursor: pointer;+ transition: all 0.25s ease;+ letter-spacing: 0.02em;+}+.make-widget-btn:hover {+ background: rgba(0, 229, 160, 0.22);+ color: #fff;+ border-color: rgba(0, 229, 160, 0.55);+}+.make-widget-btn:focus-visible {+ outline: 2px solid rgba(0, 229, 160, 0.7);+ outline-offset: 2px;+}+.make-widget-btn[hidden] { display: none; }+.make-widget-btn svg { width: 1em; height: 1em; }+@media screen and (max-width: 700px) {+ .make-widget-btn span { display: none; }+ .make-widget-btn { padding: var(--space-xs) var(--space-sm); }+}+/******************************************************************************* Avatar Creator Modal*/@@ -1849,6 +1885,17 @@ footer .separator {padding: 2px var(--space-xs);}+.nich-message.typing {+ color: rgba(255,255,255,0.4);+ letter-spacing: 2px;+ animation: nich-typing 1.1s ease-in-out infinite;+}++@keyframes nich-typing {+ 0%, 100% { opacity: 0.35; }+ 50% { opacity: 0.85; }+}+.nich-mic-hint {font-size: var(--text-xs);color: rgba(255,255,255,0.25);diff --git a/vercel.json b/vercel.jsonindex 520b1d724..d417e7c73 100644--- a/vercel.json+++ b/vercel.json@@ -31,6 +31,17 @@{ "src": "/agent/([^/]+)/embed", "dest": "/agent-embed.html" },{ "src": "/agent/([^/]+)", "dest": "/agent-home.html" },{ "src": "/agent", "dest": "/agent-home.html" },++ { "src": "/api/widgets/oembed", "dest": "/api/widgets/oembed" },+ { "src": "/api/widgets/page", "dest": "/api/widgets/page" },+ { "src": "/api/widgets/([A-Za-z0-9_-]+)/og", "dest": "/api/widgets/og?id=$1" },+ { "src": "/api/widgets/([A-Za-z0-9_-]+)/view", "dest": "/api/widgets/view?id=$1" },+ { "src": "/w/([A-Za-z0-9_-]+)", "dest": "/api/widgets/page?id=$1" },+ { "src": "/widgets", "dest": "/public/widgets-gallery/index.html" },+ { "src": "/widgets/", "dest": "/public/widgets-gallery/index.html" },+ { "src": "/widgets/(.*)", "dest": "/public/widgets-gallery/$1" },+ { "src": "/docs/widgets", "dest": "/public/docs-widgets.html" },+{ "src": "/api/(.*)", "dest": "/api/$1" },{