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: implement nonce generation and verification for Sign-In with Ethereum (EIP-4361)
nirholasd07c6c9da42c
diff --git a/CLAUDE.md b/CLAUDE.mdindex 259f9c7b5..933031fea 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1,6 +1,8 @@# CLAUDE.md-**Read this first. Then act. Do not ask me questions that this file answers.**+**Read this first. Then act. Do not ask questions this file answers.**++Scoped guidance lives in [api/CLAUDE.md](api/CLAUDE.md), [src/CLAUDE.md](src/CLAUDE.md), and [contracts/CLAUDE.md](contracts/CLAUDE.md) — read whichever applies to where you're editing.---@@ -11,15 +13,15 @@You are allowed to make judgment calls. I hired you to make them. Asking "should I proceed?", "which approach do you prefer?", "do you want me to also…?" before touching a single file is the #1 way you waste my time.**What to do instead of asking:**-- Edit the file, show the diff, and *then* tell me if there was a judgment call worth flagging.-- If you genuinely cannot proceed without an answer, ask **one** specific question — not a menu of options and sub-options. Not "A, B, or C?" — pick the one you'd do and say "going with B unless you say otherwise."-- If you're unsure about a name or placement, take the obvious default and mention it in one line.--**What counts as "I must ask first" — short list, memorize it:**-1. Schema changes to Neon tables (`users`, `avatars`, `widgets`, `agent_identities`, `agent_memories`, `agent_actions`).-2. Renames of public APIs, event bus names, manifest fields, or on-chain ABI.-3. Adding a dependency to [package.json](package.json) (we are zero-dep by principle — exhaust alternatives first).-4. `git push`, `npm run deploy`, publishing, tagging, touching deployed contract addresses.+- Edit the file, show the diff, and *then* flag the one judgment call worth mentioning.+- If you genuinely cannot proceed, ask **one** specific question. Not a menu. Pick the one you'd do and say "going with B unless you say otherwise."+- If unsure about a name or placement, take the obvious default and mention it in one line.++**Must-ask-first — memorize this short list:**+1. Schema changes to Neon tables (see [api/CLAUDE.md](api/CLAUDE.md) for the table list).+2. Renames of public APIs, event-bus action types, manifest fields, or on-chain ABI.+3. Adding a dependency to [package.json](package.json) — zero-dep by principle, exhaust alternatives.+4. `git push`, `npm run deploy`, publishing, tagging, redeploying contracts.5. Deleting files I didn't tell you to delete. Binary assets in [public/avatars/](public/avatars/).Everything else: **do the work.**@@ -28,74 +30,107 @@ Everything else: **do the work.**## What this project is-**3D Agent** — a browser-native 3D viewer that doubles as a runtime for *embodied agents*: 3D avatars with identity, memory, skills, and an emotional presence layer. Started as a glTF/GLB viewer; evolving into a universal frontend that renders agents from other frameworks (MCP, A2A, Claude skills).+**3D Agent** — a browser-native 3D viewer that doubles as a runtime for *embodied agents*: 3D avatars with on-chain identity (ERC-8004), memory, skills, and an emotional presence layer. Started as a glTF/GLB viewer; evolving into a universal frontend that renders agents from other frameworks (MCP, A2A, Claude skills).The viewer is the vehicle. The agent runtime is the product.-**Production domain:** `3dagent.vercel.app` (also `3d.irish`). **Local dev:** `http://localhost:3000` via `npm run dev`.+- **Production:** `3dagent.vercel.app` (also `3d.irish`)+- **Local dev:** `http://localhost:3000` via `npm run dev`+- **MCP endpoint:** `https://3dagent.vercel.app/api/mcp`+- **npm SDK:** [`@nirholas/agent-kit`](sdk/package.json) — separate package, lives in [sdk/](sdk/), not consumed by the main app---## The stack (don't ask, don't change)-| Layer | What | Why I picked it |+| Layer | What | Why ||---|---|---|-| Renderer | three.js + dat.gui | Existing viewer; no replacement needed. |-| Client JSX | **vhtml** (not React) | Zero runtime overhead. See `src/components/*.jsx`. |-| Bundler | Vite 8 | Already configured. `npm run dev` / `npm run build`. |-| Backend | Vercel serverless functions in [api/](api/) | Keep endpoints small; reuse helpers in [api/_lib/](api/_lib/). |-| DB | Neon (Postgres) | Access via `@neondatabase/serverless`. `DATABASE_URL` env var. |-| Object storage | Cloudflare R2 (S3-compatible) | Avatars, assets. Use `@aws-sdk/client-s3`. |-| Auth | JWT via `jose` + `bcryptjs` | Helper lives in [api/_lib/](api/_lib/). **Never hand-roll auth — use `requireAuth()`.** |-| Rate limit | Upstash Redis | `@upstash/ratelimit`. |-| Web3 | `ethers` v6, ERC-8004 identity, Privy wallets | Contracts in [contracts/](contracts/). |-| Validation | `zod` | Use it on every request body. |-| Styling | Plain CSS + tokens in [style.css](style.css) | **No Tailwind. No CSS-in-JS. No new design system.** |+| Renderer | three.js r176 + dat.gui | Existing viewer; no replacement. |+| Client JSX | **vhtml** (not React) | String-based, zero runtime. See `src/components/*.jsx`. |+| Bundler | Vite 8 | `TARGET=lib` splits between `dist/` and `dist-lib/`. |+| Backend | Vercel serverless in [api/](api/) | Small endpoints; reuse helpers in [api/_lib/](api/_lib/). |+| DB | Neon (Postgres) via `@neondatabase/serverless` | Tagged-template `sql` from [api/_lib/db.js](api/_lib/db.js). |+| Object storage | Cloudflare R2 (S3-compatible) | Avatars. Helpers in [api/_lib/r2.js](api/_lib/r2.js). |+| Auth | Session cookies + JWT (HS256) + API keys | Helpers in [api/_lib/auth.js](api/_lib/auth.js). **Never hand-roll.** |+| Rate limit | Upstash Redis via `@upstash/ratelimit` | Presets in [api/_lib/rate-limit.js](api/_lib/rate-limit.js). |+| Web3 | ethers v6 + Privy wallets + ERC-8004 | Contracts in [contracts/](contracts/), ABIs in [src/erc8004/abi.js](src/erc8004/abi.js). |+| Validation | zod | Helpers in [api/_lib/validate.js](api/_lib/validate.js). Every request body. |+| Styling | Plain CSS + tokens in [style.css](style.css) | **No Tailwind. No CSS-in-JS. No design system.** || Modules | ESM only (`"type": "module"`) | No CommonJS in `src/`. |-| Indentation | **Tabs, not spaces** | Match surrounding style. |+| Indentation | **Tabs, 4-wide** | Prettier-enforced. See [.prettierrc.json](.prettierrc.json). |-**Frameworks we do NOT use and will NOT add:** React, Next.js, Tailwind, TypeScript, CSS-in-JS, Redux, SWR, shadcn, any ORM.+**Frameworks we do NOT use and will NOT add:** React, Next.js, Tailwind, TypeScript, CSS-in-JS, Redux, SWR, shadcn, any ORM, any testing framework.----## Where code lives--- [src/viewer.js](src/viewer.js), [src/viewer/](src/viewer/) — three.js renderer, scene, GUI. The original viewer. `Viewer` class has `load()`, `setCamera()`, `setBackgroundColor()`, `setEnvironment()`.-- [src/app.js](src/app.js) — SPA entry: dropzone, URL hash parsing (`#model=`, `#widget=`, `#agent=`), orchestration. This is the integration point for new URL-driven features.-- [src/agent-*.js](src/) — agent runtime modules:- - `agent-protocol.js` — event bus (`EventTarget`-based). **Everything routes through here.**- - `agent-memory.js` — 4-type memory (user / feedback / project / reference). Canonical, don't invent new types.- - `agent-identity.js` — ERC-8004 + wallet.- - `agent-skills.js` — skill execution.- - `agent-avatar.js` — Empathy Layer (emotional presence, gaze, hero text wrap).- - `agent-home.js` — identity card + timeline UI.- - `agent-resolver.js` — resolves agent IDs → manifests.-- [src/runtime/](src/runtime/), [src/skills/](src/skills/), [src/memory/](src/memory/) — composable runtime bits for embedders.-- [src/element.js](src/element.js), [src/manifest.js](src/manifest.js) — `<agent-3d>` web component + manifest loader.-- [src/components/](src/components/) — vhtml JSX components.-- [src/nich-agent.js](src/nich-agent.js) — the reference agent (me).-- [src/account.js](src/account.js) — client for authenticated API calls (avatars). **Mirror this pattern for any new user-scoped resource.**-- [api/](api/) — Vercel serverless. Auth helpers in [api/_lib/](api/_lib/). Mirror `api/avatars/index.js` for new CRUD endpoints.-- [contracts/](contracts/) — Foundry project for ERC-8004 identity contracts.-- [specs/](specs/) — source-of-truth for manifest, skill, memory, embed formats.-- [examples/coach-leo/](examples/coach-leo/) — reference agent (manifest + instructions + skills).-- [prompts/](prompts/) — task prompts for agents (widget-studio, pretext, embed, scalability).-- [public/studio/](public/studio/), [public/dashboard/](public/dashboard/) — native-DOM apps (no framework).-- [dist/](dist/), [dist-lib/](dist-lib/) — build output. **Never edit.**+## Repo map++```+src/ # viewer + agent runtime (see src/CLAUDE.md)+api/ # Vercel serverless (see api/CLAUDE.md)+contracts/ # Foundry / ERC-8004 (see contracts/CLAUDE.md)+public/+ agent/ # /agent/:id unfurl page + /agent/:id/embed iframe target+ dashboard/ # /dashboard authenticated SPA (avatars, keys, MCP, billing)+ studio/ # /studio — DOES NOT EXIST YET; it's the deliverable of prompts/widget-studio/00+sdk/ # @nirholas/agent-kit npm package (separate from main app)+specs/ # source-of-truth formats (manifest/skill/memory/embed v0.1)+examples/coach-leo/ # reference agent (manifest + instructions + skill)+prompts/ # task briefs (embed, pretext, scalability, widget-studio) — see Prompts workflow below+docs/ # authoritative docs: ARCHITECTURE, API, DEPLOYMENT, DEVELOPMENT, MCP, SETUP+scripts/ # animation fetchers + PWA icon generator+dist/, dist-lib/ # build output — never edit+.github/prompts/ # 21 Claude Code feature prompts (not CI)+```++**HTML entry points:** [index.html](index.html) (main app), [embed.html](embed.html) (embed editor), [features.html](features.html) (marketing/ERC-8004 page).++**Config glue you should know:**+- [vite.config.js](vite.config.js) — `TARGET=lib` switches to library build. Multi-entry for the three HTML files. PWA plugin + Workbox.+- [vercel.json](vercel.json) — routes for `/oauth/*`, `/dashboard/*`, `/agent/:id`, `/agent/:id/embed`, `/.well-known/*`. **Fallback `/(.*)` is last — never insert above it.**+- [cors.json](cors.json) — R2 bucket CORS (GET only, localhost + prod origins).+- [.env.example](.env.example) — every env var, grouped below.----## Core conventions+## Environment variables++**Server (no prefix, read via `process.env.X`):**+- `DATABASE_URL` — Neon Postgres+- `R2_ACCOUNT_ID`, `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY`, `R2_BUCKET`, `R2_PUBLIC_BASE`+- `JWT_SECRET`, `JWT_KID` (default `k1`)+- `PASSWORD_ROUNDS` (default `11`)+- `UPSTASH_REDIS_REST_URL`, `UPSTASH_REDIS_REST_TOKEN` (falls back to in-memory for local dev)+- `PUBLIC_APP_ORIGIN` (default `https://3dagent.vercel.app`)+- `BASE_RPC_URL`, `BASE_SEPOLIA_RPC_URL`, `BASESCAN_API_KEY`, `DEPLOYER_PK` (contracts only)++**Client (`VITE_` prefix, read via `import.meta.env.VITE_X`):**+- `VITE_AVATURN_SUBDOMAIN` (avatar creator)+- `VITE_PRIVY_APP_ID` (wallet login)-- **Zero-dep runtime.** Agent modules use `EventTarget`, `localStorage`, `fetch`. Keep it that way. If you think you need a new dep, you probably don't.-- **Event-bus everything.** Actions flow through the protocol bus in [src/agent-protocol.js](src/agent-protocol.js); anything that wants to react (avatar, home, memory) subscribes. **Do not add direct coupling between agent modules.**-- **Auth: reuse the helper.** There is a `requireAuth()` (or equivalent) in [api/_lib/](api/_lib/). Use it. Do not write JWT code in a new endpoint.-- **Validation: always zod.** Every request body, every config blob. Reject unknowns.-- **Neon: use the shared client from [api/_lib/](api/_lib/).** Don't instantiate a new Pool.-- **New CRUD endpoint?** Copy the shape of [api/avatars/index.js](api/avatars/index.js) and [api/avatars/presign.js](api/avatars/presign.js). Same error conventions, same response helpers.-- **Public pages are native DOM.** Follow [public/dashboard/dashboard.js](public/dashboard/dashboard.js). vhtml is fine for templating; no client-side framework.-- **URL hash is the SPA routing layer** for viewer features. `#model=...`, `#widget=...`, `#agent=...`. Parse in [src/app.js](src/app.js).-- **Mobile-first.** Embed iframes run on mobile. Touch must work. Kiosk mode hides controls.+All loaded via [api/_lib/env.js](api/_lib/env.js) server-side — import from there, don't touch `process.env` directly.++---++## Canonical patterns (copy these, don't invent new ones)++### New API endpoint → see [api/CLAUDE.md](api/CLAUDE.md) for the full template.++### New agent skill+1. `src/skills/my-skill/manifest.json` — `{ spec: "skill/0.1", name, version, author, dependencies, provides: { tools } }`+2. `src/skills/my-skill/SKILL.md` — frontmatter (name, description, triggers, cost) + markdown instructions injected into LLM prompt+3. `src/skills/my-skill/tools.json` — Anthropic tool-use schema: `[{ name, description, input_schema }]`+4. `src/skills/my-skill/handlers.js` — `export default { toolName: async (args, ctx) => ({ ok: true, ... }) }` where `ctx` gives you `{ viewer, memory, llm, speak, listen, fetch, loadGLB, loadClip, loadJSON, call }`+5. Reference in the agent's manifest: `skills: [{ uri: "skills/my-skill/", version: "0.1.0" }]`++### New standalone page under `public/`+Follow [public/dashboard/dashboard.js](public/dashboard/dashboard.js). Pattern: one HTML file + one module JS + inline styles on top of global [style.css](style.css). Auth via `credentials: 'include'` + session cookies, never Bearer tokens in browser code. Hash-based tab routing (`#avatars`, `#keys`). vhtml for templating if JSX helps.++### New URL-driven viewer feature+Parse the hash in [src/app.js](src/app.js) — existing keys: `model`, `widget`, `agent`, `kiosk`, `brain`, `proxyURL`, `preset`, `cameraPosition`, `register`. Add your key next to those, don't invent a new routing layer.++### New protocol action+Add to `ACTION_TYPES` in [src/agent-protocol.js](src/agent-protocol.js), emit via `protocol.emit({ type, payload })`, subscribe in avatar/identity/home/memory as needed. **Never add direct module-to-module coupling.** Full event vocabulary in [src/CLAUDE.md](src/CLAUDE.md).---@@ -107,19 +142,17 @@ The viewer is the vehicle. The agent runtime is the product.**"React component or vanilla DOM?"** Vanilla DOM or vhtml JSX. Never React.-**"Should I make this reusable / add abstractions?"** No. Three similar lines beat a premature abstraction. Inline first, refactor only when a third use case shows up.+**"Should I make this reusable / add abstractions?"** No. Three similar lines beat a premature abstraction. Inline first, refactor when a third use case shows up.**"Should I add error handling for [edge case]?"** Only validate at system boundaries (user input, external APIs). Trust internal calls. No defensive `try/catch` around code that can't throw.-**"Tabs or spaces?"** Tabs. Always.--**"Should I add comments?"** Default: no. Only add a comment when the *why* is non-obvious (a hidden constraint, a workaround, a surprising invariant). Never describe *what* the code does.+**"Tabs or spaces?"** Tabs. Always. 4-wide.-**"Should I split this into multiple PRs?"** Do whatever makes the diff easiest to review. One focused PR > three fragmented ones.+**"Should I add comments?"** Default no. Only when *why* is non-obvious (hidden constraint, workaround, surprising invariant). Never describe *what* the code does.-**"Where should I put this new file?"** Look at what it's most similar to and put it next to that. [src/agent-*.js](src/) for agent-runtime concerns. [src/skills/](src/skills/) for skills. [api/](api/) for serverless. [public/<app>/](public/) for a standalone native-DOM page.+**"Where should I put this new file?"** Look at what it's most similar to and put it next to that. `src/agent-*.js` for agent-runtime concerns. `src/skills/` for skills. `api/` for serverless. `public/<app>/` for a standalone native-DOM page.-**"Should I run the build?"** Yes, if you changed runtime code. `npm run build` must pass before you declare done.+**"Should I run the build?"** Yes, if you changed runtime code. `npm run build` must pass before you declare done. There is a pre-existing `@avaturn/sdk` resolution warning — ignore it, it's unrelated.**"Should I commit?"** Only when I explicitly say so. Until then: edit, show diff, stop.@@ -127,7 +160,11 @@ The viewer is the vehicle. The agent runtime is the product.**"Should I rename this for consistency while I'm here?"** No. Scope creep. Do the task I gave you.-**"Which environment variable holds X?"** Grep `.env.example` or `vercel.json`. Then use `process.env.X` server-side, `import.meta.env.VITE_X` client-side.+**"Which env var holds X?"** Grep [.env.example](.env.example) first. Server-side → `process.env.X` (via [api/_lib/env.js](api/_lib/env.js)). Client-side → `import.meta.env.VITE_X`.++**"Should I split this into multiple PRs?"** Do whatever makes the diff easiest to review. One focused PR > three fragmented ones.++**"Does /studio exist?"** No — it's the deliverable of [prompts/widget-studio/00-studio-foundation.md](prompts/widget-studio/00-studio-foundation.md). Don't assume it's there when reading other code.---@@ -137,29 +174,48 @@ The viewer is the vehicle. The agent runtime is the product.|---|---|| `npm run dev` | Vite dev server on :3000 || `npm run build` | Production build → `dist/` |-| `npm run build:lib` | Library build → `dist-lib/` |+| `npm run build:lib` | Library build → `dist-lib/` (ES + UMD, Three.js + ethers bundled) || `npm run build:all` | Both || `npm run clean` | Wipe `dist/`, `dist-lib/` |-| `npm run fetch-animations` | Download Mixamo animation bundle |+| `npm run fetch-animations` | Download Mixamo bundle (calls [scripts/download-animations.mjs](scripts/download-animations.mjs)) |+| `npm run generate-icons` | PWA icons via Sharp from [public/3d.png](public/3d.png) || `npm run deploy` | **Do not run without explicit ask.** |-No test suite. When you change runtime behavior, verify by opening the dev server and exercising the feature. Type-check / build success is not proof the feature works.+No test suite. When you change runtime behavior, verify by running `npm run dev` and exercising the feature in the browser. Build success is not proof the feature works.---## Don't touch without explicit ask-- [dist/](dist/), [dist-lib/](dist-lib/) — regenerated by build.-- [contracts/out/](contracts/out/), [contracts/cache/](contracts/cache/) — Foundry artifacts.-- `.env*` files — secrets.-- [public/avatars/](public/avatars/) binary assets — check before replacing.-- Deployed contract addresses in [contracts/](contracts/).+- [dist/](dist/), [dist-lib/](dist-lib/) — regenerated by build+- [contracts/out/](contracts/out/), [contracts/cache/](contracts/cache/) — Foundry artifacts+- `.env*` files — secrets+- [public/avatars/](public/avatars/) binary assets — check before replacing+- Deployed contract addresses in [src/erc8004/abi.js](src/erc8004/abi.js) — immutable on-chain+- [gitpretty.sh](gitpretty.sh) — destructive history rewrite, never run casually+- The fallback `/(.*)` route at the bottom of [vercel.json](vercel.json) — never insert new routes below it----## Prompts directory+## Prompts workflow++When I hand you a file from [prompts/](prompts/), it is the full brief. Don't second-guess it.++1. Read the subdir's `README.md` first (execution order, ownership guardrails)+2. Parse the prompt: Goal → Prerequisites → "Read these first" (follow the line pointers, don't skip) → "Build this" → **"Do not do this"** (scope-creep guard — respect religiously) → Deliverables → Acceptance → Test plan+3. Read every file listed in "Read these first" before writing anything+4. Implement to the deliverables list exactly — filenames as stated+5. Respect file-ownership guardrails (cross-prompt merge safety depends on it)+6. Verify: `node --check` each JS file, `npx vite build`, manual test plan from the prompt+7. Report in the format the prompt's "Reporting" section asks for++**Subdir scopes at a glance:**+- [prompts/embed/](prompts/embed/) — OG images, oEmbed, agent-id resolver, referrer allowlist+- [prompts/pretext/](prompts/pretext/) — `@chenglou/pretext` text-wrap around avatar on `/features` hero+- [prompts/scalability/](prompts/scalability/) — viewer dispose, render-on-demand, module split, web-component wrap, shared renderer+- [prompts/widget-studio/](prompts/widget-studio/) — `/studio` no-code widget authoring (does not exist yet)-[prompts/](prompts/) contains self-contained task specs (widget-studio, pretext, embed, scalability). If I hand you a file from here, treat it as the full brief — it tells you what to read, what to build, and what not to build. **Follow the "Do not do this" section in each prompt religiously.** Scope creep from those prompts is the second biggest way agents waste my time.+Scope creep from prompts is the second-biggest way agents waste my time. "While I'm here let me also…" — no. Do the task I gave you.---@@ -171,10 +227,10 @@ Short, imperative, conventional-ish: `feat:`, `fix:`, `refactor:`, `chore:`. One## TL;DR-1. Read this file.-2. Read the target files.-3. Make the change.-4. Show me the diff.-5. If something genuinely needed a decision, flag it in one line *after* the work.+1. Read this file + the relevant scoped CLAUDE.md ([api/](api/CLAUDE.md), [src/](src/CLAUDE.md), [contracts/](contracts/CLAUDE.md))+2. Read the target files+3. Make the change+4. Show me the diff+5. If something genuinely needed a decision, flag it in one line *after* the workDon't ask. Don't plan. Don't propose. Just ship.diff --git a/agent-embed.html b/agent-embed.htmlnew file mode 100644index 000000000..1b70ef006--- /dev/null+++ b/agent-embed.html@@ -0,0 +1,140 @@+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8" />+ <title>Agent</title>+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <meta name="description" content="Embedded 3D agent avatar." />+ <meta name="robots" content="noindex" />+ <style>+ html, body { margin: 0; padding: 0; height: 100%; width: 100%; background: transparent; overflow: hidden; font-family: system-ui, sans-serif; }+ #stage { position: absolute; inset: 0; }+ #stage canvas { display: block; width: 100% !important; height: 100% !important; }+ #stage .gui-wrap, #stage .gui-toggle, #stage .annotation-canvas { display: none !important; }+ #stage .model-info { display: none !important; }+ #name-plate {+ position: absolute; left: 12px; bottom: 10px; z-index: 2; pointer-events: none;+ font-size: 11px; color: rgba(255,255,255,0.55); letter-spacing: 0.04em;+ text-shadow: 0 1px 2px rgba(0,0,0,0.6);+ }+ #error {+ position: absolute; inset: 0; display: none; align-items: center; justify-content: center;+ color: rgba(255,255,255,0.4); font-size: 12px; padding: 1rem; text-align: center;+ }+ body.bg-dark { background: #0b0d10; }+ body.bg-light { background: #f5f5f5; }+ </style>+</head>+<body>+ <div id="stage"></div>+ <div id="name-plate"></div>+ <div id="error"></div>++ <script type="module">+ import { Viewer } from './src/viewer.js';+ import { AgentIdentity } from './src/agent-identity.js';+ import { AgentAvatar } from './src/agent-avatar.js';+ import { protocol } from './src/agent-protocol.js';++ const params = new URL(location.href).searchParams;+ const bg = params.get('bg') || 'transparent';+ if (bg === 'dark') document.body.classList.add('bg-dark');+ if (bg === 'light') document.body.classList.add('bg-light');++ const plateOn = params.get('name') !== '0';+ const preview = params.get('preview') === '1';+ const parts = location.pathname.split('/').filter(Boolean);+ const agentId = parts[parts.indexOf('agent') + 1];++ function hostMatches(host, pattern) {+ if (!host || !pattern) return false;+ host = host.toLowerCase();+ pattern = pattern.toLowerCase();+ if (pattern.startsWith('*.')) {+ const suffix = pattern.slice(2);+ return host === suffix || host.endsWith('.' + suffix);+ }+ return host === pattern;+ }++ function embeddingHost() {+ try {+ const anc = window.location.ancestorOrigins;+ if (anc && anc.length) return new URL(anc[0]).hostname;+ } catch {}+ try {+ if (document.referrer) return new URL(document.referrer).hostname;+ } catch {}+ return null;+ }++ async function checkPolicy() {+ if (preview) return true;+ const sameOrigin = !window.parent || window.parent === window+ || (() => { try { return window.parent.location.origin === location.origin; } catch { return false; } })();+ let policy = null;+ try {+ const r = await fetch(`/api/agents/${agentId}/embed-policy`, { credentials: 'omit' });+ if (r.ok) policy = (await r.json()).policy;+ } catch {}+ if (policy === null || policy === undefined) return true;+ if (sameOrigin) return true;+ const host = embeddingHost();+ const hosts = Array.isArray(policy.hosts) ? policy.hosts : [];+ const matched = host ? hosts.some((p) => hostMatches(host, p)) : false;+ if (policy.mode === 'allowlist') return matched;+ if (policy.mode === 'denylist') return !matched;+ return true;+ }++ async function main() {+ if (!(await checkPolicy())) {+ const el = document.getElementById('error');+ el.textContent = 'This agent can only be embedded on approved sites.';+ el.style.display = 'flex';+ parent?.postMessage({ __agent: agentId, type: 'blocked' }, '*');+ return;+ }++ const identity = new AgentIdentity({ agentId, autoLoad: false });+ await identity.load();++ if (plateOn && identity.name) {+ document.getElementById('name-plate').textContent = identity.name;+ }++ if (!identity.avatarId) throw new Error('agent has no avatar body');++ const resp = await fetch(`/api/avatars/${identity.avatarId}`, { credentials: 'include' });+ if (!resp.ok) throw new Error(`avatar ${resp.status}`);+ const { avatar } = await resp.json();+ const glbUrl = avatar?.url;+ if (!glbUrl) throw new Error('no avatar url');++ const stage = document.getElementById('stage');+ const viewer = new Viewer(stage, { kiosk: true });+ if (bg === 'transparent') {+ viewer.renderer?.setClearAlpha(0);+ if (viewer.scene) viewer.scene.background = null;+ }+ await viewer.load(glbUrl, '', new Map());++ const avatarCtl = new AgentAvatar(viewer, protocol, identity);+ avatarCtl.attach();++ window.addEventListener('message', (ev) => {+ const msg = ev.data;+ if (!msg || msg.__agent !== agentId) return;+ if (msg.type === 'action' && msg.action) protocol.emit(msg.action);+ });+ parent?.postMessage({ __agent: agentId, type: 'ready', name: identity.name }, '*');+ }++ main().catch(err => {+ const el = document.getElementById('error');+ el.textContent = err.message || 'Could not load agent';+ el.style.display = 'flex';+ });+ </script>+</body>+</html>diff --git a/agent-home.html b/agent-home.htmlnew file mode 100644index 000000000..7af2b3dbb--- /dev/null+++ b/agent-home.html@@ -0,0 +1,363 @@+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8" />+ <title>Agent Home — 3D Agent</title>+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <meta name="description" content="An embodied 3D AI agent — body, place, identity, memory." />+ <meta name="theme-color" content="#000000" />++ <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 rel="stylesheet" href="/style.css" />+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500&display=swap" rel="stylesheet" />++ <meta property="og:type" content="website" />+ <meta property="og:title" content="Agent" id="og-title" />+ <meta property="og:description" content="An embodied 3D agent." id="og-description" />+ <meta property="og:image" content="" id="og-image" />+ <meta property="og:url" content="" id="og-url" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:title" content="Agent" id="tw-title" />+ <meta name="twitter:description" content="" id="tw-description" />+ <meta name="twitter:image" content="" id="tw-image" />+ <link rel="alternate" type="application/json+oembed" href="" id="oembed-link" title="Agent oEmbed" />++ <style>+ body {+ overflow: auto;+ display: flex;+ flex-direction: column;+ }++ .agent-page-header {+ display: flex;+ align-items: center;+ gap: 1rem;+ padding: 1rem 1.618rem;+ border-bottom: 1px solid rgba(255,255,255,0.06);+ }++ .agent-page-header a {+ color: rgba(255,255,255,0.4);+ text-decoration: none;+ font-size: 0.764rem;+ }++ .agent-page-header a:hover {+ color: rgba(255,255,255,0.8);+ }++ .agent-page-hero {+ max-width: 520px;+ margin: 4rem auto 2rem;+ padding: 0 1rem;+ text-align: center;+ }++ .agent-page-title {+ font-size: 1.618rem;+ font-weight: 300;+ color: #e5e5e5;+ letter-spacing: -0.02em;+ margin: 0 0 0.618rem;+ }++ .agent-page-subtitle {+ font-size: 0.764rem;+ color: rgba(255,255,255,0.35);+ line-height: 1.618;+ }++ .agent-page-card-wrap {+ max-width: 420px;+ margin: 0 auto;+ padding: 0 1rem 4rem;+ }++ .agent-page-card-wrap .agent-home-timeline {+ max-height: 320px;+ }++ .agent-page-card-wrap .agent-home-panel {+ background: rgba(12, 12, 18, 0.98);+ border: 1px solid rgba(255,255,255,0.08);+ border-radius: 12px;+ }++ .agent-embed-hint {+ max-width: 420px;+ margin: 1.618rem auto 0;+ padding: 0 1rem;+ }++ .agent-embed-tabs {+ display: flex;+ gap: 0.382rem;+ margin-bottom: 0.618rem;+ }++ .agent-embed-tab {+ background: transparent;+ border: 1px solid rgba(255,255,255,0.1);+ color: rgba(255,255,255,0.5);+ font-size: 0.618rem;+ padding: 0.236rem 0.618rem;+ border-radius: 999px;+ cursor: pointer;+ font-family: inherit;+ }++ .agent-embed-tab.active {+ background: rgba(255,255,255,0.08);+ color: rgba(255,255,255,0.9);+ border-color: rgba(255,255,255,0.2);+ }++ .agent-embed-code-wrap {+ position: relative;+ }++ .agent-embed-code {+ background: rgba(255,255,255,0.04);+ border: 1px solid rgba(255,255,255,0.08);+ border-radius: 8px;+ padding: 0.618rem 1rem;+ padding-right: 3.8rem;+ font-family: monospace;+ font-size: 0.618rem;+ color: rgba(255,255,255,0.55);+ word-break: break-all;+ line-height: 1.5;+ }++ .agent-embed-copy {+ position: absolute;+ top: 0.382rem;+ right: 0.382rem;+ background: rgba(255,255,255,0.06);+ border: 1px solid rgba(255,255,255,0.1);+ color: rgba(255,255,255,0.6);+ font-size: 0.618rem;+ padding: 0.236rem 0.618rem;+ border-radius: 6px;+ cursor: pointer;+ font-family: inherit;+ }++ .agent-embed-copy:hover { color: rgba(255,255,255,0.9); background: rgba(255,255,255,0.1); }+ .agent-embed-copy.copied { color: #86efac; border-color: rgba(134,239,172,0.3); }++ .agent-embed-label {+ font-size: 0.618rem;+ color: rgba(255,255,255,0.25);+ margin-bottom: 0.382rem;+ }++ .agent-embed-preview-link {+ display: inline-block;+ margin-top: 0.618rem;+ font-size: 0.618rem;+ color: rgba(255,255,255,0.35);+ text-decoration: none;+ }++ .agent-embed-preview-link:hover { color: rgba(255,255,255,0.7); }++ .agent-skills-full {+ max-width: 420px;+ margin: 1.618rem auto 0;+ padding: 0 1rem;+ }++ .agent-skills-title {+ font-size: 0.618rem;+ color: rgba(255,255,255,0.25);+ margin-bottom: 0.618rem;+ text-transform: uppercase;+ letter-spacing: 0.08em;+ }++ .agent-skills-grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));+ gap: 0.618rem;+ }++ .agent-skill-card {+ background: rgba(255,255,255,0.04);+ border: 1px solid rgba(255,255,255,0.07);+ border-radius: 8px;+ padding: 0.618rem;+ }++ .agent-skill-card-name {+ font-size: 0.764rem;+ font-weight: 500;+ color: rgba(255,255,255,0.7);+ margin-bottom: 0.236rem;+ }++ .agent-skill-card-desc {+ font-size: 0.618rem;+ color: rgba(255,255,255,0.3);+ line-height: 1.382;+ }++ .loading-placeholder {+ color: rgba(255,255,255,0.2);+ font-size: 0.764rem;+ text-align: center;+ padding: 2rem;+ }+ </style>+</head>+<body>+ <div class="agent-page-header">+ <a href="/">← 3D Agent</a>+ </div>++ <div class="agent-page-hero">+ <h1 class="agent-page-title" id="page-agent-name">Agent</h1>+ <p class="agent-page-subtitle" id="page-agent-desc">+ Embodied. Present. Persistent.+ </p>+ </div>++ <div class="agent-page-card-wrap">+ <div id="agent-home-container">+ <div class="loading-placeholder">Loading agent…</div>+ </div>+ </div>++ <div class="agent-skills-full" id="agent-skills-section" style="display:none">+ <div class="agent-skills-title">Skills</div>+ <div class="agent-skills-grid" id="agent-skills-grid"></div>+ </div>++ <div class="agent-embed-hint" id="agent-embed-section" style="display:none">+ <div class="agent-embed-label">Share & embed</div>+ <div class="agent-embed-tabs" role="tablist">+ <button class="agent-embed-tab active" data-tab="iframe">iframe</button>+ <button class="agent-embed-tab" data-tab="link">link</button>+ <button class="agent-embed-tab" data-tab="webcomponent"><agent-3d></button>+ </div>+ <div class="agent-embed-code-wrap">+ <div class="agent-embed-code" id="agent-embed-code"></div>+ <button class="agent-embed-copy" id="agent-embed-copy">copy</button>+ </div>+ <a class="agent-embed-preview-link" id="agent-embed-preview" target="_blank" rel="noopener">preview embed →</a>+ <a class="agent-embed-preview-link" id="agent-embed-settings" href="" target="_blank" rel="noopener">embed settings →</a>+ </div>++ <script type="module">+ import { AgentIdentity } from './src/agent-identity.js';+ import { AgentMemory } from './src/agent-memory.js';+ import { AgentSkills } from './src/agent-skills.js';+ import { AgentHome } from './src/agent-home.js';+ import { protocol } from './src/agent-protocol.js';++ const agentId = location.pathname.split('/').filter(Boolean).pop();++ async function main() {+ const identity = new AgentIdentity({ agentId: agentId || undefined, autoLoad: false });+ await identity.load();++ document.getElementById('page-agent-name').textContent = identity.name;+ if (identity.description) {+ document.getElementById('page-agent-desc').textContent = identity.description;+ }++ const container = document.getElementById('agent-home-container');+ container.innerHTML = '';+ const home = new AgentHome(container, identity, protocol, null);+ await home.render();++ if (identity.skills?.length) {+ const skills = new AgentSkills(protocol, identity.memory);+ const section = document.getElementById('agent-skills-section');+ const grid = document.getElementById('agent-skills-grid');+ section.style.display = '';+ skills.list().filter(s => identity.skills.includes(s.name)).forEach(skill => {+ const card = document.createElement('div');+ card.className = 'agent-skill-card';+ card.innerHTML = `+ <div class="agent-skill-card-name">${skill.name}</div>+ <div class="agent-skill-card-desc">${skill.description}</div>+ `;+ grid.appendChild(card);+ });+ }++ const embedSection = document.getElementById('agent-embed-section');+ const embedCode = document.getElementById('agent-embed-code');+ const embedCopy = document.getElementById('agent-embed-copy');+ const embedPreview = document.getElementById('agent-embed-preview');+ const origin = location.origin;+ const embedUrl = `${origin}/agent/${identity.id}/embed`;+ const agentUrl = `${origin}/agent/${identity.id}`;++ const snippets = {+ iframe: `<iframe src="${embedUrl}" width="420" height="520" style="border:0;border-radius:12px" allow="autoplay; xr-spatial-tracking"></iframe>`,+ link: agentUrl,+ webcomponent: `<script type="module" src="${origin}/dist-lib/agent-3d.js"><\/script>\n<agent-3d agent-id="${identity.id}" style="width:420px;height:520px"></agent-3d>`,+ };++ let current = 'iframe';+ const render = () => { embedCode.textContent = snippets[current]; };+ render();+ embedSection.style.display = '';+ embedPreview.href = embedUrl;+ document.getElementById('agent-embed-settings').href = '/dashboard/embed-policy?agent=' + identity.id;++ document.querySelectorAll('.agent-embed-tab').forEach(btn => {+ btn.addEventListener('click', () => {+ current = btn.dataset.tab;+ document.querySelectorAll('.agent-embed-tab').forEach(b => b.classList.toggle('active', b === btn));+ render();+ });+ });++ embedCopy.addEventListener('click', async () => {+ try {+ await navigator.clipboard.writeText(snippets[current]);+ embedCopy.textContent = 'copied';+ embedCopy.classList.add('copied');+ setTimeout(() => { embedCopy.textContent = 'copy'; embedCopy.classList.remove('copied'); }, 1400);+ } catch {}+ });++ populateUnfurlMeta(identity);+ }++ function populateUnfurlMeta(identity) {+ const id = identity?.id;+ if (!id) return;+ const origin = location.origin;+ const name = identity.name || 'Agent';+ const desc = identity.description || 'An embodied 3D agent.';+ const agentUrl = `${origin}/agent/${id}`;+ const img = `${origin}/api/agent/${id}/og`;+ const setAttr = (elId, attr, value) => {+ const el = document.getElementById(elId);+ if (el) el.setAttribute(attr, value);+ };+ setAttr('og-title', 'content', name);+ setAttr('og-description', 'content', desc);+ setAttr('og-image', 'content', img);+ setAttr('og-url', 'content', agentUrl);+ setAttr('tw-title', 'content', name);+ setAttr('tw-description', 'content', desc);+ setAttr('tw-image', 'content', img);+ setAttr('oembed-link', 'href', `${origin}/api/oembed?url=${encodeURIComponent(agentUrl)}`);+ document.title = `${name} — 3D Agent`;+ }++ main().catch(err => {+ document.getElementById('agent-home-container').innerHTML =+ `<div class="loading-placeholder">Could not load agent: ${err.message}</div>`;+ });+ </script>+</body>+</html>diff --git a/api/_lib/schema.sql b/api/_lib/schema.sqlindex 21556c33f..7971e0567 100644--- a/api/_lib/schema.sql+++ b/api/_lib/schema.sql@@ -10,16 +10,21 @@ create extension if not exists "citext";create table if not exists users (id uuid primary key default gen_random_uuid(),email citext not null unique,- password_hash text, -- null = oauth-only account+ password_hash text, -- null = oauth-only or wallet-only accountdisplay_name text,avatar_url text,plan text not null default 'free' check (plan in ('free','pro','team','enterprise')),email_verified boolean not null default false,+ wallet_address text, -- lowercased 0x… for wallet logincreated_at timestamptz not null default now(),updated_at timestamptz not null default now(),deleted_at timestamptz);+-- Additive migration for deployments that pre-date the wallet_address column.+alter table users add column if not exists wallet_address text;+create unique index if not exists users_wallet_unique on users(wallet_address) where wallet_address is not null;+-- ── avatars (GLBs stored in R2) ─────────────────────────────────────────────create table if not exists avatars (id uuid primary key default gen_random_uuid(),diff --git a/api/agents.js b/api/agents.jsindex 7d66a83b9..4e41d3b58 100644--- a/api/agents.js+++ b/api/agents.js@@ -26,15 +26,21 @@ export default wrap(async (req, res) => {// ── List ───────────────────────────────────────────────────────────────────async function handleList(req, res) {- const auth = await resolveAuth(req);- if (!auth) return error(res, 401, 'unauthorized', 'sign in or provide a bearer token');-- // /api/agents/me — get or create the default agent- const url = new URL(req.url, 'http://x');- if (url.pathname.endsWith('/me')) {- return handleGetOrCreateMe(req, res, auth);+ const url = new URL(req.url, 'http://x');+ const isMe = url.pathname.endsWith('/me');+ const auth = await resolveAuth(req);++ // /api/agents/me is the identity bootstrap endpoint — the client calls it+ // on every page load, including for anonymous visitors. Return null instead+ // of 401 so the client can cleanly fall back to a local-only identity+ // without a noisy console error on every unauthenticated page view.+ if (!auth) {+ if (isMe) return json(res, 200, { agent: null });+ return error(res, 401, 'unauthorized', 'sign in or provide a bearer token');}+ if (isMe) return handleGetOrCreateMe(req, res, auth);+const rows = await sql`SELECT * FROM agent_identitiesWHERE user_id = ${auth.userId}@@ -47,23 +53,36 @@ async function handleList(req, res) {// ── Get-or-create default agent ───────────────────────────────────────────async function handleGetOrCreateMe(req, res, auth) {- let [agent] = await sql`- SELECT * FROM agent_identities- WHERE user_id = ${auth.userId}- AND deleted_at IS NULL- ORDER BY created_at ASC- LIMIT 1- `;-- if (!agent) {- [agent] = await sql`- INSERT INTO agent_identities (user_id, name, skills)- VALUES (${auth.userId}, ${'Agent'}, ${['greet', 'present-model', 'validate-model', 'remember', 'think']})- RETURNING *+ try {+ let [agent] = await sql`+ SELECT * FROM agent_identities+ WHERE user_id = ${auth.userId}+ AND deleted_at IS NULL+ ORDER BY created_at ASC+ LIMIT 1`;- }- return json(res, 200, { agent: decorate(agent) });+ if (!agent) {+ [agent] = await sql`+ INSERT INTO agent_identities (user_id, name, skills)+ VALUES (${auth.userId}, ${'Agent'}, ${['greet', 'present-model', 'validate-model', 'remember', 'think']})+ RETURNING *+ `;+ }++ return json(res, 200, { agent: decorate(agent) });+ } catch (err) {+ // Missing table / bad migration shouldn't brick the client — surface a+ // null agent and let the UI fall back to local-only identity.+ const code = err?.code || '';+ const msg = String(err?.message || '');+ const missing = code === '42P01' || /relation.*does not exist/i.test(msg);+ if (missing) {+ console.error('[agents/me] agent_identities table missing — run schema.sql', err);+ return json(res, 200, { agent: null, warning: 'agents_table_missing' });+ }+ throw err;+ }}// ── Create ────────────────────────────────────────────────────────────────diff --git a/api/auth/siwe/nonce.js b/api/auth/siwe/nonce.jsnew file mode 100644index 000000000..98ec84461--- /dev/null+++ b/api/auth/siwe/nonce.js@@ -0,0 +1,32 @@+// Issue a one-time nonce for Sign-In with Ethereum (EIP-4361).+// The client includes this nonce in the message they sign; /verify burns it.++import { sql } from '../../_lib/db.js';+import { cors, json, method, wrap, error } from '../../_lib/http.js';+import { limits, clientIp } from '../../_lib/rate-limit.js';+import { randomToken } from '../../_lib/crypto.js';++const NONCE_TTL_SEC = 5 * 60;++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;++ const ip = clientIp(req);+ const rl = await limits.authIp(ip);+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many nonce requests');++ // EIP-4361 requires ≥8 alphanumeric chars. Strip base64url's - and _.+ let nonce = '';+ while (nonce.length < 16) {+ nonce += randomToken(24).replace(/[^A-Za-z0-9]/g, '');+ }+ nonce = nonce.slice(0, 16);++ await sql`+ insert into siwe_nonces (nonce, expires_at)+ values (${nonce}, now() + ${`${NONCE_TTL_SEC} seconds`}::interval)+ `;++ return json(res, 200, { nonce, ttl: NONCE_TTL_SEC });+});diff --git a/api/auth/siwe/verify.js b/api/auth/siwe/verify.jsnew file mode 100644index 000000000..f35b56434--- /dev/null+++ b/api/auth/siwe/verify.js@@ -0,0 +1,184 @@+// Verify an EIP-4361 (Sign-In with Ethereum) message + signature.+// On success: create or link a user, issue a browser session cookie.++import { verifyMessage, getAddress } from 'ethers';+import { z } from 'zod';+import { sql } from '../../_lib/db.js';+import { createSession, sessionCookie, destroySession } from '../../_lib/auth.js';+import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';+import { limits, clientIp } from '../../_lib/rate-limit.js';+import { env } from '../../_lib/env.js';+import { parse } from '../../_lib/validate.js';++const verifyBody = z.object({+ message: z.string().min(64).max(4000),+ signature: z.string().regex(/^0x[a-fA-F0-9]+$/),+});++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const ip = clientIp(req);+ const rl = await limits.authIp(ip);+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many attempts');++ const body = parse(verifyBody, await readJson(req));++ // 1. Parse SIWE message.+ const fields = parseSiweMessage(body.message);+ if (!fields) return error(res, 400, 'invalid_message', 'malformed SIWE message');++ // 2. Domain + URI must match this deployment. Prevents signature replay from+ // a phishing site using a valid nonce issued here.+ const appOrigin = env.APP_ORIGIN;+ const appHost = new URL(appOrigin).host;+ if (fields.domain !== appHost) {+ return error(res, 400, 'invalid_domain', `domain must be ${appHost}`);+ }+ try {+ const u = new URL(fields.uri);+ if (u.origin !== appOrigin) return error(res, 400, 'invalid_uri', 'uri origin mismatch');+ } catch {+ return error(res, 400, 'invalid_uri', 'uri not a valid URL');+ }++ // 3. Temporal checks.+ const now = Date.now();+ if (fields.expirationTime && Date.parse(fields.expirationTime) < now) {+ return error(res, 400, 'expired', 'message expired');+ }+ if (fields.notBefore && Date.parse(fields.notBefore) > now) {+ return error(res, 400, 'not_yet_valid', 'message not yet valid');+ }++ // 4. Nonce must exist, be unconsumed, and not expired. Burn on success.+ const [nonceRow] = await sql`+ select nonce, expires_at, consumed_at+ from siwe_nonces+ where nonce = ${fields.nonce}+ limit 1+ `;+ if (!nonceRow) return error(res, 400, 'invalid_nonce', 'unknown nonce');+ if (nonceRow.consumed_at) return error(res, 400, 'nonce_reused', 'nonce already used');+ if (new Date(nonceRow.expires_at) < new Date()) {+ return error(res, 400, 'nonce_expired', 'nonce expired');+ }++ // 5. Verify signature recovers the claimed address.+ let recovered;+ try {+ recovered = verifyMessage(body.message, body.signature);+ } catch {+ return error(res, 401, 'invalid_signature', 'signature verification failed');+ }+ let claimed;+ try {+ claimed = getAddress(fields.address);+ } catch {+ return error(res, 400, 'invalid_address', 'address not checksummed correctly');+ }+ if (recovered.toLowerCase() !== claimed.toLowerCase()) {+ return error(res, 401, 'invalid_signature', 'signer does not match address');+ }++ // Burn the nonce (idempotent race-safe: if already consumed, reject).+ const burned = await sql`+ update siwe_nonces+ set consumed_at = now(), address = ${claimed.toLowerCase()}+ where nonce = ${fields.nonce} and consumed_at is null+ returning nonce+ `;+ if (!burned[0]) return error(res, 400, 'nonce_reused', 'nonce already used');++ // 6. Find or create user. Wallet address is the primary key into the user record.+ const addrLower = claimed.toLowerCase();+ const chainId = fields.chainId || null;++ let [wallet] = await sql`+ select user_id from user_wallets where address = ${addrLower} limit 1+ `;+ let userId;++ if (wallet) {+ userId = wallet.user_id;+ await sql`+ update user_wallets+ set last_used_at = now(), chain_id = coalesce(${chainId}, chain_id)+ where address = ${addrLower}+ `;+ } else {+ // Create a new passwordless user. Email is synthesized and placeholder —+ // user can set a real email + password later.+ const placeholderEmail = `wallet-${addrLower}@wallet.local`;+ const [user] = await sql`+ insert into users (email, display_name, wallet_address)+ values (${placeholderEmail}, ${shortAddr(claimed)}, ${addrLower})+ returning id+ `;+ userId = user.id;+ await sql`+ insert into user_wallets (user_id, address, chain_id, is_primary)+ values (${userId}, ${addrLower}, ${chainId}, true)+ `;+ }++ // 7. Issue session.+ await destroySession(req);+ const token = await createSession({+ userId,+ userAgent: req.headers['user-agent'],+ ip,+ });+ res.setHeader('set-cookie', sessionCookie(token));++ const [userRow] = await sql`+ select id, email, display_name, plan, avatar_url, created_at+ from users where id = ${userId} limit 1+ `;++ return json(res, 200, {+ user: userRow,+ wallet: { address: claimed, chain_id: chainId },+ });+});++// ─── EIP-4361 parser ────────────────────────────────────────────────────────+// Minimal hand-rolled parser. We only need the fields we actually verify.+function parseSiweMessage(msg) {+ const lines = msg.split('\n');+ if (lines.length < 6) return null;++ const header = lines[0];+ const m = /^([^\s]+) wants you to sign in with your Ethereum account:$/.exec(header);+ if (!m) return null;+ const domain = m[1];++ const address = (lines[1] || '').trim();+ if (!/^0x[a-fA-F0-9]{40}$/.test(address)) return null;++ const out = { domain, address };+ for (let i = 2; i < lines.length; i++) {+ const line = lines[i];+ const kv = /^([A-Za-z -]+):\s*(.*)$/.exec(line);+ if (!kv) continue;+ const key = kv[1].trim();+ const val = kv[2].trim();+ switch (key) {+ case 'URI': out.uri = val; break;+ case 'Version': out.version = val; break;+ case 'Chain ID': out.chainId = parseInt(val, 10) || null; break;+ case 'Nonce': out.nonce = val; break;+ case 'Issued At': out.issuedAt = val; break;+ case 'Expiration Time': out.expirationTime = val; break;+ case 'Not Before': out.notBefore = val; break;+ case 'Request ID': out.requestId = val; break;+ }+ }+ if (!out.uri || !out.nonce || !out.version) return null;+ return out;+}++function shortAddr(addr) {+ return `${addr.slice(0, 6)}…${addr.slice(-4)}`;+}diff --git a/api/widgets/oembed.js b/api/widgets/oembed.jsnew file mode 100644index 000000000..e5802583d--- /dev/null+++ b/api/widgets/oembed.js@@ -0,0 +1,149 @@+/**+ * oEmbed endpoint for widget URLs+ * -------------------------------+ * GET /api/widgets/oembed?url=<widget-url>[&format=json|xml]+ *+ * Implements https://oembed.com with type=rich. Accepts canonical widget URLs+ * (https://host/w/<id>) and the legacy SPA hash form (https://host/#widget=<id>).+ * The html payload is a sandboxed iframe so consumers (WordPress, Ghost, Notion,+ * Discord, Slack) can render the widget inline.+ */++import { sql } from '../_lib/db.js';+import { env } from '../_lib/env.js';+import { cors, wrap, error } from '../_lib/http.js';++const DEFAULT_W = 600;+const DEFAULT_H = 600;+const THUMB_W = 1200;+const THUMB_H = 630;++const TYPE_DIMENSIONS = {+ 'turntable': { width: 600, height: 600 },+ 'animation-gallery': { width: 720, height: 720 },+ 'talking-agent': { width: 420, height: 600 },+ 'passport': { width: 480, height: 560 },+ 'hotspot-tour': { width: 800, height: 600 },+};++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;++ const url = new URL(req.url, 'http://x');+ const target = url.searchParams.get('url');+ const format = (url.searchParams.get('format') || 'json').toLowerCase();+ const maxW = parseInt(url.searchParams.get('maxwidth') || '0', 10) || null;+ const maxH = parseInt(url.searchParams.get('maxheight') || '0', 10) || null;++ if (!target) return error(res, 400, 'invalid_request', 'url parameter required');++ const widgetId = extractWidgetId(target);+ if (!widgetId) return error(res, 404, 'not_found', 'url is not a recognised widget url');++ const widget = await loadWidget(widgetId);+ if (!widget) return error(res, 404, 'not_found', 'widget not found');++ const origin = env.APP_ORIGIN;+ const embedUrl = `${origin}/#widget=${widget.id}&kiosk=true`;+ const pageUrl = `${origin}/w/${widget.id}`;+ const thumbUrl = `${origin}/api/widgets/${widget.id}/og`;+ const title = widget.name || 'Widget';++ const dims = TYPE_DIMENSIONS[widget.type] || { width: DEFAULT_W, height: DEFAULT_H };+ const width = clamp(maxW || dims.width, 240, 1600);+ const height = clamp(maxH || dims.height, 240, 1600);++ const iframe = `<iframe src="${escapeAttr(embedUrl)}" width="${width}" height="${height}" style="border:0;border-radius:12px;max-width:100%" allow="autoplay; xr-spatial-tracking; clipboard-write" sandbox="allow-scripts allow-same-origin allow-popups allow-forms" loading="lazy"></iframe>`;++ const payload = {+ type: 'rich',+ version: '1.0',+ provider_name: '3D Agent',+ provider_url: origin,+ title,+ author_name: title,+ author_url: pageUrl,+ html: iframe,+ width,+ height,+ thumbnail_url: thumbUrl,+ thumbnail_width: THUMB_W,+ thumbnail_height: THUMB_H,+ };++ res.setHeader('cache-control', 'public, max-age=900');++ if (format === 'xml') {+ res.statusCode = 200;+ res.setHeader('content-type', 'text/xml; charset=utf-8');+ res.end(toXml(payload));+ return;+ }++ res.statusCode = 200;+ res.setHeader('content-type', 'application/json+oembed; charset=utf-8');+ res.end(JSON.stringify(payload));+});++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 extractWidgetId(target) {+ let parsed;+ try { parsed = new URL(target); } catch { return null; }++ const originStr = `${parsed.protocol}//${parsed.host}`;+ const okOrigin = originStr === env.APP_ORIGIN+ || /^https?:\/\/localhost(:\d+)?$/.test(originStr)+ || /^https?:\/\/3d\.irish$/.test(originStr);+ if (!okOrigin) return null;++ const pathMatch = parsed.pathname.match(/^\/w\/([A-Za-z0-9_-]+)\/?$/);+ if (pathMatch) return pathMatch[1];++ if (parsed.hash) {+ const hashMatch = parsed.hash.match(/(?:^|[#&])widget=([A-Za-z0-9_-]+)/);+ if (hashMatch) return hashMatch[1];+ }+ return null;+}++function clamp(n, lo, hi) {+ return Math.max(lo, Math.min(hi, n));+}++function toXml(payload) {+ const lines = Object.entries(payload).map(([k, v]) =>+ ` <${k}>${escapeXml(String(v))}</${k}>`+ );+ return `<?xml version="1.0" encoding="utf-8" standalone="yes"?>\n<oembed>\n${lines.join('\n')}\n</oembed>`;+}++function escapeXml(s) {+ return String(s)+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"')+ .replace(/'/g, ''');+}++function escapeAttr(s) {+ return String(s)+ .replace(/&/g, '&')+ .replace(/"/g, '"')+ .replace(/</g, '<')+ .replace(/>/g, '>');+}diff --git a/api/widgets/og.js b/api/widgets/og.jsnew file mode 100644index 000000000..5fb8470f8--- /dev/null+++ b/api/widgets/og.js@@ -0,0 +1,112 @@+/**+ * Widget OG image endpoint+ * ------------------------+ * GET /api/widgets/:id/og+ *+ * Returns a 1200x630 SVG card (Slack/Discord/X all render image/svg+xml in+ * OG previews, so we avoid pulling in canvas/sharp on the serverless side).+ * If the widget's avatar has a thumbnail, we 302 to that PNG for a richer+ * preview. Falls back to a server-rendered SVG card on miss.+ */++import { sql } from '../_lib/db.js';+import { getAvatar } from '../_lib/avatars.js';+import { cors, wrap } from '../_lib/http.js';++const CACHE_CARD = 'public, max-age=3600, s-maxage=86400';+const CACHE_REDIR = 'public, max-age=3600';++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 sendNotFound(res);++ const widget = await loadWidget(widgetId);+ if (!widget) return sendNotFound(res);++ if (widget.avatar_id) {+ const avatar = await getAvatar({ id: widget.avatar_id });+ if (avatar?.thumbnail_url) {+ res.statusCode = 302;+ res.setHeader('location', avatar.thumbnail_url);+ res.setHeader('cache-control', CACHE_REDIR);+ res.end();+ return;+ }+ }++ sendCardSvg(res, 200, CACHE_CARD, {+ name: widget.name || 'Widget',+ type: TYPE_LABEL[widget.type] || 'Widget',+ });+});++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) {+ // widgets table may not exist yet (prompt 00 owns the migration).+ // Treat as not-found so social crawlers still get a usable card.+ if (/relation .* does not exist/i.test(err?.message || '')) return null;+ throw err;+ }+}++function sendNotFound(res) {+ sendCardSvg(res, 404, 'public, max-age=60', {+ name: 'Widget not found',+ type: '3D Agent',+ });+}++function sendCardSvg(res, status, cacheControl, { name, type }) {+ res.statusCode = status;+ res.setHeader('content-type', 'image/svg+xml; charset=utf-8');+ res.setHeader('cache-control', cacheControl);+ res.end(renderCardSvg({ name, type }));+}++function renderCardSvg({ name, type }) {+ const safeName = escapeXml(truncate(name, 60));+ const safeType = escapeXml(truncate(type, 40));+ return `<?xml version="1.0" encoding="UTF-8"?>+<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630" viewBox="0 0 1200 630" role="img" aria-label="${safeName}">+ <rect width="1200" height="630" fill="#0b0d10"/>+ <rect x="80" y="80" width="180" height="36" rx="18" fill="rgba(139,92,246,0.18)" stroke="rgba(139,92,246,0.6)" stroke-width="1"/>+ <text x="170" y="104" fill="#c4b5fd" font-family="Inter, -apple-system, system-ui, sans-serif" font-size="16" font-weight="500" letter-spacing="2" text-anchor="middle">${safeType.toUpperCase()}</text>+ <text x="80" y="320" fill="#e5e5e5" font-family="Inter, -apple-system, system-ui, sans-serif" font-size="76" font-weight="300" letter-spacing="-2">${safeName}</text>+ <text x="80" y="380" fill="rgba(229,229,229,0.55)" font-family="Inter, -apple-system, system-ui, sans-serif" font-size="24" font-weight="400">Embeddable 3D — no code.</text>+ <text x="80" y="570" fill="rgba(229,229,229,0.3)" font-family="Inter, -apple-system, system-ui, sans-serif" font-size="20" font-weight="400" letter-spacing="4">3D AGENT</text>+</svg>`;+}++function truncate(s, n) {+ s = String(s || '');+ return s.length <= n ? s : s.slice(0, n - 1) + '…';+}++function escapeXml(s) {+ return String(s)+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"')+ .replace(/'/g, ''');+}diff --git a/api/widgets/view.js b/api/widgets/view.jsnew file mode 100644index 000000000..29d5bbc67--- /dev/null+++ b/api/widgets/view.js@@ -0,0 +1,57 @@+/**+ * Widget view event logger+ * ------------------------+ * POST /api/widgets/:id/view+ *+ * Logs an anonymous load event for analytics. No cookies, no IP, no UID.+ * - country: from Vercel edge headers (x-vercel-ip-country), not derived from raw IP+ * - referer_host: hostname only — no path, no query+ *+ * Best-effort: if the underlying widget_views table doesn't exist yet+ * (Prompt 06 owns that migration), we 204 silently so widgets can ship before+ * the dashboard does.+ */++import { sql } from '../_lib/db.js';+import { cors, wrap, error } from '../_lib/http.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;+ if (req.method !== 'POST') return error(res, 405, 'method_not_allowed', 'POST only');++ const url = new URL(req.url, 'http://x');+ const widgetId = url.searchParams.get('id');+ if (!widgetId) return error(res, 400, 'invalid_request', 'id required');++ const country = headerOnce(req, 'x-vercel-ip-country') || null;+ const refererHost = parseRefererHost(req.headers.referer);++ try {+ await sql`+ insert into widget_views (widget_id, country, referer_host, created_at)+ values (${widgetId}, ${country}, ${refererHost}, now())+ `;+ await sql`+ update widgets set view_count = view_count + 1 where id = ${widgetId}+ `;+ } catch (err) {+ if (!/relation .* does not exist/i.test(err?.message || '')) {+ console.warn('[widgets/view] log failed', err?.message);+ }+ }++ res.statusCode = 204;+ res.setHeader('cache-control', 'no-store');+ res.end();+});++function headerOnce(req, name) {+ const v = req.headers[name];+ if (Array.isArray(v)) return v[0] || null;+ return v || null;+}++function parseRefererHost(referer) {+ if (!referer) return null;+ try { return new URL(referer).hostname || null; } catch { return null; }+}diff --git a/features.css b/features.cssindex 39ead192b..033a1467d 100644--- a/features.css+++ b/features.css@@ -758,6 +758,40 @@color: #fff;}+/* ── Pretext overlay ─────────────────────────────────────────────────────── */++/*+ * Absolute overlay rendered by src/features/hero-pretext.js when ?pretext>=2.+ * Typography mirrors .hero-subtitle so the swap is visually continuous.+ * Only activates once .pretext-active lands on .hero — if the layout pass+ * throws before painting, the class is never added and the original subtitle+ * stays visible.+ */+.hero-subtitle-pretext {+ position: absolute;+ font-size: clamp(1.05rem, 1.35vw, 1.25rem);+ color: rgba(255, 255, 255, 0.58);+ font-weight: 300;+ line-height: 1.5;+ pointer-events: none;+ display: none;+}++.pretext-active .hero-subtitle-pretext {+ display: block;+}++.hero-subtitle-pretext-line {+ position: absolute;+ left: 0;+ white-space: pre;+}++/* Reserve the original subtitle's space so the CTA stack doesn't jump. */+.pretext-active .hero-subtitle {+ visibility: hidden;+}+/* ── Responsive ──────────────────────────────────────────────────────────── *//* Tablet — keep two columns but tighten the split */@@ -773,6 +807,13 @@}@media screen and (max-width: 768px) {+ /* Pretext overlay disables itself below this breakpoint; bring the+ original subtitle back in case .pretext-active was set before the+ resize into mobile. */+ .pretext-active .hero-subtitle {+ visibility: visible;+ }+.hero {grid-template-columns: 1fr;gap: var(--space-xl);diff --git a/index.html b/index.htmlindex 8a3dd92ad..8c9357de2 100644--- a/index.html+++ b/index.html@@ -43,6 +43,7 @@<a href="/features">Features</a><a href="/#register">Register Agent</a><a href="/dashboard" class="nav-dashboard">Dashboard</a>+ <a href="/login" class="nav-sign-in" id="nav-sign-in">Sign in</a></nav></header>diff --git a/prompts/widget-studio/07-embed-docs-and-polish.md b/prompts/widget-studio/07-embed-docs-and-polish.mdnew file mode 100644index 000000000..a5a1969fb--- /dev/null+++ b/prompts/widget-studio/07-embed-docs-and-polish.md@@ -0,0 +1,231 @@+# Prompt 07 — Embed Docs, Example Gallery, and Polish++**Branch:** `feat/widget-docs-and-polish`+**Depends on:** Prompts 00–06 all merged.+**Parallel with:** nothing — this is the final pass.++## Goal++Turn the Widget Studio into something people want to use: a public `/widgets` gallery that showcases each widget type with a real embedded demo, a developer-focused `/docs/widgets` page with copy-pasteable snippets, OG/oEmbed support on every widget URL, cross-widget QA, a11y pass, and a homepage nudge pointing visitors to the Studio.++This prompt is where the project stops feeling like a developer tool and starts feeling like a product. Treat it with care.++## Prerequisites++- All five widget prompts (01–05) merged and working.+- Dashboard (Prompt 06) merged.++## Read these first++| File | Why |+|:---|:---|+| All `src/widgets/*.js` files | Confirm every widget mounts cleanly and exposes a consistent `mount(...)` / `destroy()` contract. |+| [features.html](../../features.html) and [style.css](../../style.css) | Reference for the visual system. Match it. |+| [vercel.json](../../vercel.json) | You will add new public routes. |+| [api/agent-oembed.js](../../api/agent-oembed.js) and [api/agent-og.js](../../api/agent-og.js) | Pattern for OG/oEmbed endpoints. |+| [scripts/](../../scripts/) | Existing build-time scripts for icons, animations. If the gallery needs prebuilt poster images, mirror this pattern. |+| [docs/](../../docs/) | Existing developer docs. Follow the tone. |++## Build this++### 1. Example gallery at `/widgets`++Create `public/widgets-gallery/index.html` (route at `/widgets`). A public page with:++- **Hero:** "Embeddable 3D, no code." One-line pitch, CTA: "Create yours in the Studio".+- **Five type sections** — each renders a real, working widget URL in an iframe, shows its config, and provides the snippet to copy. Use a handful of showcase widgets (create them on a demo account and hardcode their widget IDs — store IDs in a small JSON config at `public/widgets-gallery/showcase.json` so they can be updated without code changes).+- **Call-to-action:** "Create yours — it's free" linking to `/studio` (or `/login?return=/studio`).++Layout each section:++```+┌──────────────────────────────────────────────┐+│ Turntable Showcase │+│ Hero banner for sites — auto-rotate, no UI. │+│ │+│ [live iframe demo 600x600] │+│ │+│ <iframe src="..." width="600" height="600"/> │+│ [Copy] [Open in Studio template] │+└──────────────────────────────────────────────┘+```++"Open in Studio template" clones the showcase widget into the user's account (uses Prompt 06's duplicate endpoint if the widget is public to duplicate; otherwise uses a new server-side "template" flag — pick the simpler path).++### 2. Developer docs at `/docs/widgets`++Create `docs/WIDGETS.md` in the repo and link it from the README. Also create a rendered page at `public/docs-widgets.html` with the same content (or rewrite the route to serve the markdown via a minimal renderer — whichever is consistent with how `docs/` is served today).++Sections:++- **Overview** — what widgets are.+- **URL params** — `#widget=<id>` and related.+- **iframe embed** — snippet + size recommendations.+- **Script embed** — `embed.js` snippet + what it does.+- **postMessage API** — parent-to-iframe and iframe-to-parent events the widgets emit:+ - `widget:ready` (iframe → parent)+ - `widget:load` / `widget:load:error`+ - `widget:chat:message` (talking-agent only)+ - `widget:hotspot:open` (hotspot-tour only)+- **CSP / CORS** — what sites need to allow (usually nothing, but document if your embed requires `allow="..."`).+- **Privacy** — visitor data, rate limits, what's logged.+- **FAQ** — why no WordPress plugin, can I self-host, etc.++### 3. OG + oEmbed on every widget++For each widget type, extend the OG/oEmbed endpoints so:++- **OG image** (`/api/widgets/:id/og`) returns a rendered PNG or SVG preview — title + avatar thumbnail + type badge. Use a server-side image library if one is already in deps (`sharp` is in devDependencies — check if it's available at runtime on Vercel; if not, use SVG since Slack/Discord/X will render it). Reasonable output: 1200x630.+- **OG tags** (in the widget page's HTML head when resolving `#widget=`): Open Graph + Twitter card tags. The `index.html` SPA shell needs to set these dynamically — since hash params aren't available server-side, either use a pre-render crawler check (user-agent detection for social bots; redirect them to a server-rendered metadata page) OR move the widget resolution upstream so `/widget/:id` (path, not hash) is the canonical URL.+ - **Recommendation:** add a second canonical URL pattern: `https://host/w/<id>` that's server-rendered with proper meta tags and client-redirects to `#widget=<id>` for regular browsers. Social crawlers see the meta. Regular users hit the SPA. Update Studio's share UI to prefer `/w/<id>`.+- **oEmbed** (`/api/widgets/:id/oembed`): returns the standard oEmbed JSON so WordPress, Ghost, and Notion auto-embed pasted widget URLs. Type = `rich`, `html` = an iframe snippet.++Add `<link rel="alternate" type="application/json+oembed" href="...">` to the widget HTML head.++### 4. Homepage nudge++The main viewer page is currently purely a viewer. After this prompt:++- Add a subtle "Make this a widget" button in the header (visible when a model is loaded). Clicking opens Studio with that model preloaded.+- Add a small "Widgets" link in the nav pointing to `/widgets`.++Do not redesign the homepage. One button, one link.++### 5. Cross-widget QA++Run through each widget type on each browser/device:++| | Chrome desktop | Safari desktop | Firefox desktop | iOS Safari | Android Chrome |+|:---|:-:|:-:|:-:|:-:|:-:|+| Turntable | | | | | |+| Animation Gallery | | | | | |+| Talking Agent | | | | | |+| Passport | | | | | |+| Hotspot Tour | | | | | |++Fix any browser-specific bugs found. Common ones:+- iOS Safari autoplay restrictions on animation clips.+- Safari `speechSynthesis.getVoices()` returning empty until a user gesture.+- Chrome/iOS intersection observer quirks on nested iframes.++### 6. a11y audit++Run `axe` (via `@axe-core/cli` — add as devDep if needed) on:++- `/studio`+- `/widgets` gallery+- Each widget type in public mode+- `/dashboard` widgets tab++Fix every critical and serious violation. Document any known issues in `docs/WIDGETS.md`.++Key checks:+- Color contrast ≥ 4.5:1 for text.+- All interactive elements keyboard-reachable.+- ARIA labels on icon-only buttons.+- `prefers-reduced-motion` respected everywhere.+- Focus visible on all interactive controls.+- Screen reader announces widget state changes (SPEAK, animation changes, hotspot open).++### 7. Performance pass++- Lighthouse performance ≥ 80 on each widget type, mobile emulation.+- First contentful paint < 2s on a cold load with a small GLB.+- Bundle budget: the public widget JS (non-Studio, non-dashboard) should lazy-load only the widget runtime needed for its type. Dynamic imports from Prompt 01 onward should already do this; verify.+- Preload hints for the GLB URL and the HDR env map.++### 8. Error boundaries++Every widget runtime must handle:++- Widget not found (404 from GET) → clear error page, not a crash.+- Avatar deleted / model URL 404 → "Model unavailable" in the widget frame.+- Rate limit exceeded (talking-agent) → polite message.+- RPC failure (passport) → cached data + "last verified" label.+- LLM brain failure (talking-agent) → "Having trouble reaching the brain. Try again in a moment."++### 9. Analytics (respecting privacy)++Add a minimal, first-party analytics log:++- Each widget load: `widget_id`, `type`, country (from Vercel edge headers, not IP), referer host only (not full URL), timestamp.+- Aggregate into `widget_views_daily` table or use `widget_views` from Prompt 06.+- No cookies. No tracking across widgets. No user identifiers.+- Document this in the docs page and in the Studio's "Generate Embed" modal ("By sharing a widget, you agree visitors' anonymous load events will be logged for your analytics.").++### 10. README update++Update the main `README.md` with:++- A new section near the top: "Widget Studio — make any avatar embeddable."+- Link to `/widgets` gallery and `/studio`.+- Update the roadmap section to strike through the shipped items.++## Do not do this++- Do not rewrite the homepage. Two additions only.+- Do not add tracking cookies.+- Do not log chat message content in analytics.+- Do not ship the gallery with broken showcase widgets. Verify each one loads cleanly in incognito before merging.+- Do not add a new design system or rebrand. Match existing styles.+- Do not introduce a documentation SSG. Plain HTML/markdown is fine.++## Deliverables++**New:**+- `public/widgets-gallery/index.html`+- `public/widgets-gallery/gallery.js`+- `public/widgets-gallery/showcase.json`+- `docs/WIDGETS.md`+- `public/docs-widgets.html` (if serving HTML)+- `api/widgets/[id]/og.js` — if not built in Prompt 03, build here.+- `api/widgets/[id]/oembed.js` — same.+- `public/w/[id].html` + route rewrite for server-rendered metadata page.++**Modified:**+- `vercel.json` — new routes (`/widgets`, `/w/:id`, `/docs/widgets`, og/oembed endpoints).+- `README.md` — Widget Studio section + roadmap updates.+- `index.html` — "Make this a widget" button + Widgets nav link.+- Widget runtimes — add error boundaries if missing.+- `src/app.js` — resolve `/w/:id` path to the same widget-load flow as `#widget=`.++## Acceptance criteria++- [ ] `/widgets` gallery renders with 5 working embedded demos.+- [ ] Each demo has a copy-paste iframe snippet that works when pasted in a blank HTML file.+- [ ] `/docs/widgets` page covers all types, URL params, postMessage API, CSP notes.+- [ ] `/w/<id>` server-renders correct OG tags — pasting into Slack shows a rich card.+- [ ] oEmbed auto-embed works in WordPress or Ghost (verify by pasting into a test instance).+- [ ] All five widget types pass a11y audit (no critical/serious violations).+- [ ] Lighthouse performance ≥ 80 on each widget type.+- [ ] All error boundaries trigger correctly when simulated.+- [ ] Homepage has "Make this a widget" button and "Widgets" nav link.+- [ ] README has a prominent Widget Studio section.+- [ ] Analytics logs load events (verify via DB query after loading a widget).+- [ ] No console errors anywhere.+- [ ] `npm run build` succeeds, final bundle reports are reasonable.++## Test plan++1. **Gallery smoke test:** open `/widgets` in incognito. Every section renders. Every embed works. Every "Copy iframe" paste into a blank HTML file renders.+2. **OG test:** share `https://<host>/w/<id>` in Slack and Discord. Rich card with image appears.+3. **oEmbed test:** paste the same URL into WordPress or Ghost. Auto-embeds.+4. **Docs test:** walk through `/docs/widgets`. Every code snippet works when copy-pasted.+5. **Browser matrix:** run through the cross-browser matrix. Any failures — fix or document as known issue with a workaround.+6. **a11y:** run `axe-cli` and Lighthouse a11y on each widget type URL and on Studio/Dashboard. Fix violations.+7. **Perf:** run Lighthouse perf mobile on each widget. Tune preload hints if FCP > 2s.+8. **Error simulation:**+ - Delete an avatar → load its widget → "Model unavailable."+ - Revoke a Talking Agent's brain endpoint → "Can't reach brain."+ - Point a Passport at a non-existent tokenId → "Agent not found."+ - Hit Talking Agent rate limit → polite message.+9. **Analytics:** load 3 widgets, query DB, confirm view rows with correct metadata.+10. **Full flow, fresh user:** sign up → go to viewer → load model → "Make this a widget" → lands in Studio → picks turntable → saves → shares → works in incognito. No friction.++## When you finish++- PR with:+ - Screenshots of `/widgets` gallery and one OG card.+ - Lighthouse scores for each widget type.+ - A short paragraph for the project's social post.+- Then: ship it. Post about it. Send the demo link to 3 real people. Ask what they'd pay for.diff --git a/public/login.html b/public/login.htmlindex 0652eb8ad..f4546eed5 100644--- a/public/login.html+++ b/public/login.html@@ -21,6 +21,11 @@.err { margin-top:14px; padding:10px 12px; background:rgba(255,92,92,.1); border:1px solid rgba(255,92,92,.3); border-radius:8px; color:#ffb3b3; font-size:13px; display:none; }.foot { margin-top:20px; text-align:center; font-size:13px; color:#888; }.brand { font-size:12px; letter-spacing:.1em; text-transform:uppercase; color:var(--accent); margin:0 0 8px; }+ .wallet-btn { background:#1c1c28; border:1px solid #2a2a36; color:#eee; font-weight:500; margin-top:12px; display:flex; align-items:center; justify-content:center; gap:8px; }+ .wallet-btn:hover { background:#22222e; border-color:var(--accent); }+ .divider { display:flex; align-items:center; gap:12px; margin:22px 0 4px; color:#555; font-size:12px; text-transform:uppercase; letter-spacing:.08em; }+ .divider::before, .divider::after { content:''; flex:1; height:1px; background:#2a2a36; }+ .wallet-icon { width:18px; height:18px; }</style></head><body>@@ -33,9 +38,15 @@<label for="password">Password</label><input id="password" type="password" autocomplete="current-password" required minlength="10"><button id="submit" type="submit">Sign in</button>+ <div class="divider">or</div>+ <button id="wallet" type="button" class="wallet-btn">+ <svg class="wallet-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="6" width="20" height="14" rx="2"/><path d="M16 12h2"/></svg>+ Sign in with wallet+ </button><div class="err" id="err"></div><p class="foot">No account? <a href="/register.html">Create one</a></p></form>+<script type="module" src="/wallet-login.js"></script><script>const params = new URLSearchParams(location.search);const next = params.get('next') || '/dashboard/';diff --git a/public/register.html b/public/register.htmlindex 5222f93f4..53473318d 100644--- a/public/register.html+++ b/public/register.html@@ -22,6 +22,11 @@.err { margin-top:14px; padding:10px 12px; background:rgba(255,92,92,.1); border:1px solid rgba(255,92,92,.3); border-radius:8px; color:#ffb3b3; font-size:13px; display:none; }.foot { margin-top:20px; text-align:center; font-size:13px; color:#888; }.brand { font-size:12px; letter-spacing:.1em; text-transform:uppercase; color:var(--accent); margin:0 0 8px; }+ .wallet-btn { background:#1c1c28; border:1px solid #2a2a36; color:#eee; font-weight:500; margin-top:12px; display:flex; align-items:center; justify-content:center; gap:8px; }+ .wallet-btn:hover { background:#22222e; border-color:var(--accent); }+ .divider { display:flex; align-items:center; gap:12px; margin:22px 0 4px; color:#555; font-size:12px; text-transform:uppercase; letter-spacing:.08em; }+ .divider::before, .divider::after { content:''; flex:1; height:1px; background:#2a2a36; }+ .wallet-icon { width:18px; height:18px; }</style></head><body>@@ -37,9 +42,15 @@<input id="password" type="password" autocomplete="new-password" required minlength="10"><div class="hint">At least 10 characters.</div><button id="submit" type="submit">Create account</button>+ <div class="divider">or</div>+ <button id="wallet" type="button" class="wallet-btn">+ <svg class="wallet-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="6" width="20" height="14" rx="2"/><path d="M16 12h2"/></svg>+ Continue with wallet+ </button><div class="err" id="err"></div><p class="foot">Already have one? <a href="/login.html">Sign in</a></p></form>+<script type="module" src="/wallet-login.js"></script><script>const params = new URLSearchParams(location.search);const next = params.get('next') || '/dashboard/';diff --git a/public/wallet-login.js b/public/wallet-login.jsnew file mode 100644index 000000000..283ac3c19--- /dev/null+++ b/public/wallet-login.js@@ -0,0 +1,84 @@+// Client-side Sign-In with Ethereum (EIP-4361).+// Used by /login and /register pages to authenticate without a password.+// Loaded as a module from /public/login.html — ethers is pulled from a CDN+// ESM build so this file works outside the Vite bundler's entry graph.++import { BrowserProvider } from 'https://esm.sh/[email protected]';++const params = new URLSearchParams(location.search);+const next = params.get('next') || '/dashboard/';++async function signInWithWallet() {+ const btn = document.getElementById('wallet');+ const err = document.getElementById('err');+ const setErr = (m) => { if (err) { err.textContent = m; err.style.display = 'block'; } };+ const clearErr = () => { if (err) { err.style.display = 'none'; } };++ if (!window.ethereum) {+ setErr('No wallet detected. Install MetaMask or another Ethereum wallet.');+ return;+ }++ clearErr();+ btn.disabled = true;+ const original = btn.innerHTML;+ btn.textContent = 'Connecting…';++ try {+ const provider = new BrowserProvider(window.ethereum);+ const accounts = await provider.send('eth_requestAccounts', []);+ if (!accounts?.[0]) throw new Error('No accounts returned from wallet');++ const signer = await provider.getSigner();+ const address = await signer.getAddress();+ const network = await provider.getNetwork();+ const chainId = Number(network.chainId);++ btn.textContent = 'Requesting nonce…';+ const nonceRes = await fetch('/api/auth/siwe/nonce', { credentials: 'include' });+ if (!nonceRes.ok) throw new Error('Failed to get nonce');+ const { nonce } = await nonceRes.json();++ const domain = location.host;+ const uri = location.origin;+ const issuedAt = new Date().toISOString();+ const expirationTime = new Date(Date.now() + 5 * 60 * 1000).toISOString();++ const message = [+ `${domain} wants you to sign in with your Ethereum account:`,+ address,+ '',+ 'Sign in to 3D Agent. This does not cost anything and proves wallet ownership.',+ '',+ `URI: ${uri}`,+ 'Version: 1',+ `Chain ID: ${chainId}`,+ `Nonce: ${nonce}`,+ `Issued At: ${issuedAt}`,+ `Expiration Time: ${expirationTime}`,+ ].join('\n');++ btn.textContent = 'Check your wallet…';+ const signature = await signer.signMessage(message);++ btn.textContent = 'Verifying…';+ const verifyRes = await fetch('/api/auth/siwe/verify', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ message, signature }),+ });+ const data = await verifyRes.json();+ if (!verifyRes.ok) throw new Error(data.error_description || 'Verification failed');++ location.href = next;+ } catch (e) {+ const msg = e?.info?.error?.message || e?.message || String(e);+ setErr(msg === 'user rejected action' ? 'Signature cancelled.' : msg);+ btn.disabled = false;+ btn.innerHTML = original;+ }+}++const btn = document.getElementById('wallet');+if (btn) btn.addEventListener('click', signInWithWallet);diff --git a/src/agent-identity.js b/src/agent-identity.jsindex 7872b0793..24a919cff 100644--- a/src/agent-identity.js+++ b/src/agent-identity.js@@ -195,26 +195,30 @@ export class AgentIdentity {if (resp.ok) {const { agent } = await resp.json();- this._record = _normalise(agent);- this._agentId = this._record.id;- this._loaded = true;- this._persist();- if (!this.memory) {- this.memory = new AgentMemory(this._record.id, { backendSync: true });- }- return;- }-- if (resp.status === 404 || resp.status === 401) {- // Not signed in or no agent yet — create a local-only identity- if (!this._record) {- this._record = _makeDefault(this._agentId);+ // Server returns { agent: null } for anonymous /me — treat as+ // "no server identity" and fall through to local-only.+ if (agent) {+ this._record = _normalise(agent);this._agentId = this._record.id;this._loaded = true;this._persist();- this.memory = new AgentMemory(this._agentId, { backendSync: false });+ if (!this.memory) {+ this.memory = new AgentMemory(this._record.id, { backendSync: true });+ }+ return;}}++ // Any non-2xx or a 2xx with null agent → use local record if we have+ // one, otherwise synthesize a local-only identity. Tolerant of 5xx+ // so a backend blip doesn't brick the avatar for the visitor.+ if (!this._record) {+ this._record = _makeDefault(this._agentId);+ this._agentId = this._record.id;+ this._loaded = true;+ this._persist();+ this.memory = new AgentMemory(this._agentId, { backendSync: false });+ }} catch {// Offline — use local record if we have oneif (!this._record) {diff --git a/src/features/hero-pretext.js b/src/features/hero-pretext.jsindex 6cd81f4d2..e707a9f8b 100644--- a/src/features/hero-pretext.js+++ b/src/features/hero-pretext.js@@ -1,7 +1,11 @@// Hero controller for /features — scaffolds submodules behind ?pretext=N flags.//// Respecting prefers-reduced-motion is the responsibility of any submodule that-// animates (gaze, dragon reflow). The scaffold itself is inert.+// animates (gaze, dragon reflow). The scaffold itself is inert. The static wrap+// (flag >= 2) is a one-shot paint per resize, so it has nothing to gate.++const MOBILE_MQ = '(max-width: 768px)';+const RESIZE_DEBOUNCE_MS = 120;export default class PretextHero {constructor(root, options = {}) {@@ -15,7 +19,11 @@ export default class PretextHero {this.flag = String(options.flag ?? '1');this.pretext = null;- this._gaze = null;+ this._gaze = null;+ this._overlay = null;+ this._onResize = null;+ this._resizeT = null;+ this._rafToken = 0;}async init() {@@ -23,6 +31,16 @@ export default class PretextHero {this.pretext = mod;console.log('[pretext-hero] ready');+ const flagNum = Number.parseInt(this.flag, 10);++ if (flagNum >= 2) {+ try {+ this.enableStaticWrap();+ } catch (err) {+ console.warn('[pretext-hero] static wrap failed:', err);+ }+ }+// Flag-gated submodules. 2 and 4 are reserved for text-wrap + dragon mode.if (this.flag === '3' || this.flag === '4') {try {@@ -37,7 +55,168 @@ export default class PretextHero {return this;}+ enableStaticWrap() {+ if (!this.content || !this.subtitle || !this.avatar || !this.pretext) return;++ this._overlay = document.createElement('div');+ this._overlay.className = 'hero-subtitle-pretext';+ this._overlay.setAttribute('aria-hidden', 'true');+ this.content.appendChild(this._overlay);++ const paint = () => {+ try {+ this._paintStaticWrap();+ } catch (err) {+ console.warn('[pretext-hero] paint failed:', err);+ this.root.classList.remove('pretext-active');+ }+ };++ const ready = document.fonts?.ready ?? Promise.resolve();+ ready.then(paint);++ this._onResize = () => {+ if (this._resizeT) clearTimeout(this._resizeT);+ this._resizeT = setTimeout(paint, RESIZE_DEBOUNCE_MS);+ };+ window.addEventListener('resize', this._onResize);+ }++ // One-shot layout pass. Reads geometry, then paints once via rAF — no mid-frame+ // writes, so resize doesn't thrash.+ _paintStaticWrap() {+ if (!this._overlay) return;++ // Mobile: single-column layout, avatar stacks above text. A wrap around+ // a circle that sits above the text would just mean empty short lines+ // for no visual payoff. Fall back to plain subtitle.+ if (window.matchMedia(MOBILE_MQ).matches) {+ this.root.classList.remove('pretext-active');+ this._overlay.replaceChildren();+ this._overlay.style.display = 'none';+ return;+ }+ this._overlay.style.display = '';++ // ── Read phase ───────────────────────────────────────────────────────+ const contentRect = this.content.getBoundingClientRect();+ const subtitleRect = this.subtitle.getBoundingClientRect();+ // The avatar element's rect is what we want — the <model-viewer> canvas+ // includes transparent padding, so its rect would overstate the visual+ // silhouette.+ const avatarRect = this.avatar.getBoundingClientRect();++ const style = getComputedStyle(this.subtitle);+ const font = `${style.fontStyle} ${style.fontWeight} ${style.fontSize} ${style.fontFamily}`;+ const fontSize = Number.parseFloat(style.fontSize);+ const lhRaw = style.lineHeight;+ const lineHeight = lhRaw === 'normal' ? fontSize * 1.5 : Number.parseFloat(lhRaw);++ // Overlay lives inside .hero-content (position: relative). Local origin+ // is the content box's top-left.+ const overlayLeft = subtitleRect.left - contentRect.left;+ const overlayTop = subtitleRect.top - contentRect.top;++ // Extend the layout column past the subtitle's natural right edge,+ // into the gutter and up to just shy of the avatar's right edge, so+ // text visibly flows around the avatar circle. Keep a small breathing+ // margin so the rightmost line doesn't kiss the avatar rect edge.+ const overlayRightPage = Math.max(avatarRect.right - 24, subtitleRect.right);+ const overlayWidth = Math.max(subtitleRect.width, overlayRightPage - subtitleRect.left);++ // Avatar bounding circle, projected into overlay-local coords.+ const circleX = (avatarRect.left + avatarRect.width / 2) - subtitleRect.left;+ const circleY = (avatarRect.top + avatarRect.height / 2) - subtitleRect.top;+ // Slight inset so the wrap hugs the visible silhouette rather than the+ // invisible square of the container.+ const circleR = (Math.min(avatarRect.width, avatarRect.height) / 2) * 0.92;+ const hPad = 14;++ const text = this.subtitle.textContent ?? '';+ const prepared = this.pretext.prepareWithSegments(text, font);++ const lines = [];+ let cursor = { segmentIndex: 0, graphemeIndex: 0 };+ let lineTop = 0;+ const maxLines = 32;++ while (lines.length < maxLines) {+ // Sample the circle at the line's vertical midpoint. A per-band+ // min/max sweep would hug tighter, but for a single circle the+ // midpoint sample is visually indistinguishable and half the work.+ const bandMid = lineTop + lineHeight / 2;+ const dy = bandMid - circleY;+ const effR = circleR + hPad;++ let slotWidth = overlayWidth;+ if (Math.abs(dy) < effR) {+ const dx = Math.sqrt(effR * effR - dy * dy);+ const blockedLeft = circleX - dx;+ // Take the left slot only — the subtitle flows L→R and the+ // avatar sits to its right, so right-of-circle slivers would+ // read as disconnected floating phrases. Left-only is the+ // readable choice.+ if (blockedLeft < overlayWidth) {+ if (blockedLeft > 24) {+ slotWidth = blockedLeft;+ } else {+ // Circle fully covers the left side of this band —+ // skip this row vertically, let text resume below.+ lineTop += lineHeight;+ continue;+ }+ }+ }++ const line = this.pretext.layoutNextLine(prepared, cursor, slotWidth);+ if (line === null) break;++ lines.push({ y: lineTop, text: line.text });++ cursor = line.end;+ lineTop += lineHeight;+ }++ // ── Write phase ─────────────────────────────────────────────────────+ const token = ++this._rafToken;+ requestAnimationFrame(() => {+ if (token !== this._rafToken || !this._overlay) return;++ const overlay = this._overlay;+ overlay.style.left = `${overlayLeft}px`;+ overlay.style.top = `${overlayTop}px`;+ overlay.style.width = `${overlayWidth}px`;+ overlay.style.height = `${Math.max(lineTop, subtitleRect.height)}px`;++ const frag = document.createDocumentFragment();+ for (const { y, text } of lines) {+ const span = document.createElement('span');+ span.className = 'hero-subtitle-pretext-line';+ span.style.top = `${y}px`;+ span.textContent = text;+ frag.appendChild(span);+ }+ overlay.replaceChildren(frag);++ this.root.classList.add('pretext-active');+ });+ }+dispose() {+ if (this._onResize) {+ window.removeEventListener('resize', this._onResize);+ this._onResize = null;+ }+ if (this._resizeT) {+ clearTimeout(this._resizeT);+ this._resizeT = null;+ }+ if (this._overlay) {+ this._overlay.remove();+ this._overlay = null;+ }+ this.root?.classList.remove('pretext-active');+if (this._gaze) {this._gaze.detach();this._gaze = null;diff --git a/style.css b/style.cssindex af0ffa27f..ccebbaf29 100644--- a/style.css+++ b/style.css@@ -276,6 +276,15 @@ header h1 .wordmark-dot {background: linear-gradient(90deg, #a78bfa, #6366f1);}+.nav-sign-in {+ border: 1px solid rgba(255, 255, 255, 0.12);+ border-radius: var(--radius-md);+}++.nav-sign-in.signed-in {+ display: none;+}+.gui-wrap {position: absolute;top: 0;diff --git a/vercel.json b/vercel.jsonindex 9aa6e10b1..520b1d724 100644--- a/vercel.json+++ b/vercel.json@@ -28,9 +28,9 @@{ "src": "/api/agent-memory", "dest": "/api/agent-memory" },{ "src": "/api/agent/([^/]+)/og", "dest": "/api/agent-og?id=$1" },{ "src": "/api/oembed", "dest": "/api/agent-oembed" },- { "src": "/agent/([^/]+)/embed", "dest": "/public/agent/embed.html" },- { "src": "/agent/([^/]+)", "dest": "/public/agent/index.html" },- { "src": "/agent", "dest": "/public/agent/index.html" },+ { "src": "/agent/([^/]+)/embed", "dest": "/agent-embed.html" },+ { "src": "/agent/([^/]+)", "dest": "/agent-home.html" },+ { "src": "/agent", "dest": "/agent-home.html" },{ "src": "/api/(.*)", "dest": "/api/$1" },{diff --git a/vite.config.js b/vite.config.jsindex ceda280d0..87daebe5a 100644--- a/vite.config.js+++ b/vite.config.js@@ -25,6 +25,8 @@ const appConfig = {main: resolve(__dirname, 'index.html'),features: resolve(__dirname, 'features.html'),embed: resolve(__dirname, 'embed.html'),+ 'agent-home': resolve(__dirname, 'agent-home.html'),+ 'agent-embed': resolve(__dirname, 'agent-embed.html'),},},},