Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat: enhance wallet handling to support ERC-8004 agent ID updates

nirholas3c7f6265e0d0
diff --git a/.github/prompts/stack-01-siwe-wallet-login.md b/.github/prompts/stack-01-siwe-wallet-login.md
new file mode 100644
index 000000000..05d6b86ee
--- /dev/null
+++ b/.github/prompts/stack-01-siwe-wallet-login.md
@@ -0,0 +1,63 @@
+---
+mode: agent
+description: "Complete SIWE wallet login end-to-end — nonce, verify, session, error states"
+---
+
+# Stack Layer 1: SIWE Wallet Login End-to-End
+
+## Problem
+
+Sign-In With Ethereum (SIWE) endpoints exist at [api/auth/siwe/nonce.js](api/auth/siwe/nonce.js) and [api/auth/siwe/verify.js](api/auth/siwe/verify.js) but the full flow is not yet wired up on the client. [public/login.html](public/login.html) and [public/wallet-login.js](public/wallet-login.js) exist but the happy path from "click Connect" → authenticated session is not reliably working end-to-end.
+
+This is priority stack layer 1 (wallet auth 100%). Nothing else on the stack can ship without this working.
+
+## Implementation
+
+### Server (already partially exists — verify + harden)
+
+1. `POST /api/auth/siwe/nonce` returns `{ nonce, issuedAt, expiresAt }`.
+ - Store nonce in a short-TTL key (Upstash Redis, 5 min) bound to client IP + user agent.
+ - Reject if called more than 10×/min per IP.
+2. `POST /api/auth/siwe/verify` accepts `{ message, signature }`:
+ - Parse SIWE message, extract nonce, verify nonce is live and not yet consumed.
+ - Verify signature recovers to `message.address` using `ethers.verifyMessage`.
+ - Consume nonce (delete from Redis).
+ - Upsert row in `users` keyed by `wallet_address` (lowercase).
+ - Issue JWT via the existing helper in [api/_lib/](api/_lib/). Set `auth` cookie (HttpOnly, Secure, SameSite=Lax, 30d).
+ - Return `{ user: { id, wallet_address, handle } }`.
+
+### Client ([public/wallet-login.js](public/wallet-login.js))
+
+1. Detect injected wallet (`window.ethereum`) OR fall back to WalletConnect via `@walletconnect/ethereum-provider` (already a dep? check [package.json](package.json) — if not, use Privy which is already integrated).
+2. On "Connect" click:
+ - Request accounts.
+ - Fetch `/api/auth/siwe/nonce`.
+ - Build SIWE message: domain, address, statement, URI, version=1, chainId, nonce, issuedAt.
+ - Request signature via `personal_sign`.
+ - POST `{ message, signature }` to `/api/auth/siwe/verify`.
+ - On success: redirect to `/dashboard/`.
+3. Surface every failure with a concrete message ("Wallet rejected", "Nonce expired, retry", "Signature invalid").
+
+### Database
+
+`users` table must have: `id`, `wallet_address` (unique, lowercase), `handle`, `created_at`, `email` (nullable), `privy_did` (nullable for Privy flow). Add migration if missing.
+
+### Session
+
+Reuse `requireAuth()` from [api/_lib/](api/_lib/) — no new JWT code. Verify it accepts wallet-authed users (no email required).
+
+## Validation
+
+- Open [/login.html](public/login.html) in an incognito window with MetaMask.
+- Click Connect → approve account → sign message → land on `/dashboard/` with a live session.
+- Refresh `/dashboard/` — still authenticated.
+- Hit `/api/auth/me` → returns `{ id, wallet_address, handle }`.
+- Replay the same nonce → verify returns 400.
+- Wait 6 minutes after fetching nonce → verify returns 400 ("nonce expired").
+- `npm run build` passes.
+
+## Do not do this
+
+- Do NOT add a new auth library. Reuse `jose` + existing helper.
+- Do NOT store the signature server-side beyond verification.
+- Do NOT create a new `users` table — extend the existing one.
diff --git a/.github/prompts/stack-02-privy-unified-auth.md b/.github/prompts/stack-02-privy-unified-auth.md
new file mode 100644
index 000000000..acd762f97
--- /dev/null
+++ b/.github/prompts/stack-02-privy-unified-auth.md
@@ -0,0 +1,59 @@
+---
+mode: agent
+description: "Unify Privy + SIWE so one user row handles both email+wallet auth paths"
+---
+
+# Stack Layer 1: Unified Privy + SIWE Auth
+
+## Problem
+
+Privy is integrated (per recent commit `e4bc161`) and SIWE is being added. Without a single source of truth, we'll end up with two parallel user tables / session mechanisms and a mess of bugs at the boundary. Users who sign in via Privy (email + embedded wallet) and users who sign in via external wallet (MetaMask SIWE) must resolve to the **same** user row keyed by wallet address.
+
+## Implementation
+
+### Schema reconciliation
+
+`users` table should have:
+- `id` (primary key, uuid or serial)
+- `wallet_address` (unique, lowercase, nullable only during transitional migration)
+- `privy_did` (nullable, unique when set)
+- `email` (nullable)
+- `handle` (nullable)
+- `created_at`, `updated_at`
+
+### Server resolution logic ([api/_lib/](api/_lib/))
+
+Add `resolveUser({ walletAddress, privyDid, email })` helper:
+1. If `privyDid` is provided: look up by `privy_did`. If found, return.
+2. If `walletAddress` is provided: look up by `wallet_address`. If found, link `privy_did` if not set, return.
+3. Else create a new row with whatever identifiers are present.
+4. Never create two rows for the same wallet.
+
+### Privy callback
+
+When Privy auth completes, server-side verify the Privy token, extract `did` + wallet address (if embedded wallet), call `resolveUser`, issue the same JWT as SIWE path.
+
+### SIWE callback
+
+After SIWE verify succeeds, call `resolveUser({ walletAddress })`, issue JWT.
+
+### Client
+
+`/login.html` shows two options: "Sign in with Wallet" (SIWE, MetaMask/WalletConnect) and "Sign in with Email" (Privy). Both land at the same `/dashboard/` and produce the same `/api/auth/me` response shape.
+
+### Migration
+
+If there are existing user rows with only `email`, backfill `wallet_address` from Privy embedded wallet on next login.
+
+## Validation
+
+- Sign in via MetaMask (SIWE). Note user id. Sign out.
+- Sign in via Privy email with the same wallet as the embedded wallet → same user id.
+- Sign in via Privy email only (no embedded wallet), then later link a wallet → merges into same row, no duplicate.
+- `/api/auth/me` returns consistent shape regardless of auth path.
+- `npm run build` passes.
+
+## Do not do this
+
+- Do NOT create `privy_users` or `wallet_users` side tables. One table.
+- Do NOT trust Privy's client-side token — always verify server-side via the Privy SDK.
diff --git a/.github/prompts/stack-03-auth-session-recovery.md b/.github/prompts/stack-03-auth-session-recovery.md
new file mode 100644
index 000000000..14aeaf2a0
--- /dev/null
+++ b/.github/prompts/stack-03-auth-session-recovery.md
@@ -0,0 +1,54 @@
+---
+mode: agent
+description: "Make auth sessions survive refresh, new tab, wallet disconnect, token near-expiry"
+---
+
+# Stack Layer 1: Session Recovery & Refresh
+
+## Problem
+
+Wallet auth must *stay* authenticated across page refresh, new tabs, wallet disconnect, and token near-expiry. Today the session cookie works on refresh but we have no:
+- Silent refresh before token expiry
+- Cross-tab auth state sync
+- Graceful handling when wallet disconnects but session is still valid (session should persist — wallet is not session)
+
+## Implementation
+
+### Refresh endpoint
+
+`POST /api/auth/refresh`:
+- Reads existing `auth` cookie.
+- If token is valid and within the last 7 days of its 30d TTL, issue a new cookie with fresh 30d TTL.
+- If expired, return 401.
+- Rate-limit 1/min per user.
+
+### Client refresh scheduler ([src/account.js](src/account.js))
+
+- On app boot, decode JWT `exp` client-side (non-trusting, just for scheduling).
+- `setTimeout` to call `/api/auth/refresh` when the token is 7 days from expiry.
+- Exponential backoff on failure.
+
+### Cross-tab sync
+
+- On successful login/logout, `localStorage.setItem('auth-change', Date.now())`.
+- Listen for `storage` events → re-fetch `/api/auth/me` and update UI.
+
+### Wallet-vs-session separation
+
+- A disconnected wallet does NOT log the user out. The server cookie is the source of truth.
+- Show a "Wallet disconnected — reconnect to sign actions" banner, but keep the session alive.
+- Only `/api/auth/logout` (which clears the cookie) ends the session.
+
+### Error boundary
+
+- If any authenticated API call returns 401, redirect to `/login.html?next=<current>`.
+- Preserve query params on the `next` redirect.
+
+## Validation
+
+- Sign in, refresh page 10× → still authenticated, no re-sign needed.
+- Sign in in tab A, open tab B → tab B is authenticated without page reload.
+- Sign out in tab A → tab B shows logged-out state within 2s.
+- Disconnect wallet in MetaMask → session still valid, banner shows.
+- Manually set cookie expiry to 7 days from now → next API call triggers refresh, new 30d cookie issued.
+- `npm run build` passes.
diff --git a/.github/prompts/stack-04-auth-error-ux.md b/.github/prompts/stack-04-auth-error-ux.md
new file mode 100644
index 000000000..b39fb8e7c
--- /dev/null
+++ b/.github/prompts/stack-04-auth-error-ux.md
@@ -0,0 +1,54 @@
+---
+mode: agent
+description: "Turn every auth failure into a clear, recoverable user-facing message"
+---
+
+# Stack Layer 1: Auth Error UX
+
+## Problem
+
+Today auth errors bubble up as generic "Login failed" with no indication of cause. Users silently fail and bounce. This layer is not shippable without a clear error UX.
+
+## Implementation
+
+### Catalog every auth error path
+
+For each endpoint under [api/auth/](api/auth/), enumerate failure modes and map to an error code string:
+- `WALLET_REJECTED` — user rejected signature
+- `NONCE_EXPIRED` — SIWE nonce older than 5 min
+- `NONCE_INVALID` — nonce not found / already consumed
+- `SIGNATURE_INVALID` — recovered address does not match
+- `CHAIN_MISMATCH` — client chainId doesn't match expected
+- `RATE_LIMITED` — too many attempts
+- `PRIVY_TOKEN_INVALID`
+- `USER_BANNED` (future-proof)
+- `NETWORK_ERROR` (client-side catch-all)
+
+Server returns `{ error: { code, message } }` with HTTP status 400/401/429.
+
+### Client error renderer
+
+In [public/wallet-login.js](public/wallet-login.js) and [public/login.html](public/login.html), map each code to:
+- A human message.
+- A **recovery action** (button): "Retry", "Connect different wallet", "Switch network", "Sign in with email instead".
+
+### Logging
+
+Log every auth failure server-side with `user_id` (if known), `error.code`, and a request id. Expose via an internal endpoint `/api/_admin/auth-errors` (gated by an admin JWT claim) so we can see patterns.
+
+### Analytics hook
+
+Fire a `auth.failed` event with the code to whatever analytics sink is wired up (if any — check [src/app.js](src/app.js) for an existing event pattern; if none, skip — no new dep).
+
+## Validation
+
+- Reject signature in MetaMask → "Signature rejected. Retry?" with a button that restarts the flow.
+- Set system clock 10 min forward during nonce exchange → "Nonce expired. Retry?" with a Retry button.
+- Hammer the endpoint 20× in 10s → "Too many attempts. Wait 60s."
+- Disconnect network during signature → "Network error. Check your connection."
+- `npm run build` passes.
+
+## Do not do this
+
+- Do NOT use `alert()`. Inline the error in the login UI.
+- Do NOT leak signature bytes, nonces, or stack traces to the client.
diff --git a/.github/prompts/stack-05-selfie-capture.md b/.github/prompts/stack-05-selfie-capture.md
new file mode 100644
index 000000000..0a97d8fed
--- /dev/null
+++ b/.github/prompts/stack-05-selfie-capture.md
@@ -0,0 +1,62 @@
+---
+mode: agent
+description: "Camera + upload UI that captures a selfie and hands it to the avatar pipeline"
+---
+
+# Stack Layer 2: Selfie Capture UI
+
+## Problem
+
+The magic moment of the product is "photo becomes your agent." We need the capture surface: a page where a logged-in user takes a selfie (or uploads one), previews it, confirms, and submits it to the avatar creation pipeline.
+
+## Implementation
+
+### Page
+
+`public/create/index.html` — a standalone native-DOM page (follow [public/dashboard/dashboard.js](public/dashboard/dashboard.js) style, no framework).
+
+### Flow
+
+1. **Auth gate** — if no session, redirect to `/login.html?next=/create/`.
+2. **Method picker** — two buttons: "Use Camera" and "Upload Photo".
+3. **Camera path** — `navigator.mediaDevices.getUserMedia({ video: { facingMode: 'user', width: 1024, height: 1024 } })`.
+ - Live `<video>` preview.
+ - Circle/square crop overlay for framing guidance.
+ - Capture button → draw frame to `<canvas>` at native resolution → `canvas.toBlob('image/jpeg', 0.9)`.
+4. **Upload path** — `<input type="file" accept="image/jpeg,image/png,image/webp">`.
+ - Validate: max 10MB, min 512px shortest side.
+5. **Preview + confirm** — show captured/uploaded image, "Retake" and "Use this photo" buttons.
+6. **Submit** — presigned upload to R2 (see [api/avatars/presign.js](api/avatars/presign.js) for pattern), then POST to the pipeline kickoff endpoint (`/api/avatars/create-from-photo` — see prompt stack-06).
+
+### Camera handling
+
+- Request permission explicitly with a button click (not on page load).
+- Handle denial: show "We need camera access to take a selfie. Or upload a photo instead."
+- Handle no-camera environment (desktop without webcam): fall back to upload only.
+- Release the stream (`track.stop()`) when leaving the page or switching to upload.
+
+### Mobile
+
+- Prefer `facingMode: 'user'` (front camera).
+- Full-screen camera view on mobile.
+- Big touch targets (min 48px).
+
+### Accessibility
+
+- Alt text / aria-labels on all controls.
+- Keyboard-navigable.
+
+## Validation
+
+- Desktop Chrome + webcam: flow completes, JPEG submitted.
+- Mobile Safari: front camera opens, capture works.
+- Deny camera permission → upload path still works.
+- Upload 15MB file → friendly error.
+- No session → redirected to login.
+- `npm run build` passes.
+
+## Do not do this
+
+- Do NOT add a React component. Native DOM only.
+- Do NOT resize/compress client-side before submit — backend does that.
+- Do NOT auto-start the camera on page load; wait for user gesture (iOS requires it).
diff --git a/.github/prompts/stack-06-face-to-avatar-backend.md b/.github/prompts/stack-06-face-to-avatar-backend.md
new file mode 100644
index 000000000..3f37a3ba0
--- /dev/null
+++ b/.github/prompts/stack-06-face-to-avatar-backend.md
@@ -0,0 +1,73 @@
+---
+mode: agent
+description: "Backend pipeline that turns an uploaded selfie into a riggable GLB avatar"
+---
+
+# Stack Layer 2: Selfie → GLB Avatar Pipeline
+
+## Problem
+
+We need a server endpoint that accepts a selfie and returns a GLB avatar (riggable, with facial morphs) saved to the user's account. This is the technical heart of the "magic moment."
+
+## Implementation
+
+### Endpoint
+
+`POST /api/avatars/create-from-photo`
+
+Body:
+```json
+{ "photoKey": "uploads/<userId>/<uuid>.jpg", "name": "optional display name" }
+```
+
+Response (202 Accepted):
+```json
+{ "avatarId": "...", "status": "processing", "statusUrl": "/api/avatars/<id>/status" }
+```
+
+### Provider selection
+
+Pick ONE provider to start (don't implement all):
+
+| Provider | Pros | Cons |
+|---|---|---|
+| Ready Player Me | Mature, has avatar-from-photo API, GLB output with standard rig + ARKit blendshapes | Requires partner key; avatars are stylized, not photoreal |
+| Meshy / Tripo AI | Photoreal head meshes | No standard rig — would need rigging pass |
+| In-house (MediaPipe + blendshape fitting) | Zero vendor lock-in | Weeks of work |
+
+**Recommend Ready Player Me** for v1 — it gives us a production-ready rigged GLB with ARKit blendshapes that our Empathy Layer can drive. Use the partner API (ask user for the API key env var — do NOT check one in).
+
+### Pipeline steps
+
+1. Validate photo from R2 (size, content-type, contains a face — use a simple face-detection heuristic or provider validation).
+2. POST to RPM avatar-from-photo endpoint (async job).
+3. Poll provider status; on completion, download the GLB.
+4. Store GLB to R2 at `avatars/<userId>/<avatarId>.glb`.
+5. Insert row in `avatars` table: `{ id, user_id, name, glb_url, source: 'selfie', photo_key, status: 'ready', created_at }`.
+6. Optionally run Draco compression via `gltf-transform` CLI or library before storing.
+
+### Status endpoint
+
+`GET /api/avatars/:id/status` returns `{ status: 'processing' | 'ready' | 'failed', progress?: 0-100, error?: string }`.
+
+### Webhook support
+
+If provider supports webhooks, set one at `/api/webhooks/rpm` with HMAC verification. Otherwise poll every 5s from a Vercel cron for up to 2 minutes; then fail.
+
+### Environment variables
+
+`RPM_API_KEY`, `RPM_SUBDOMAIN` (or equivalent for chosen provider). Add to [.env.example](.env.example).
+
+## Validation
+
+- Upload a front-facing selfie → 30s later, a rigged GLB exists at `avatars/<userId>/<id>.glb`.
+- GLB loads in the viewer with 52 ARKit morph targets visible.
+- Bad photo (no face) → status `failed`, useful error.
+- Provider outage → status `failed`, user can retry without re-upload.
+- `npm run build` passes.
+
+## Do not do this
+
+- Do NOT store the raw photo forever — delete from R2 once avatar is ready (GDPR).
+- Do NOT return the GLB URL until the job is fully done.
+- Do NOT skip face detection — users will upload random images.
diff --git a/.github/prompts/stack-07-avatar-creation-progress.md b/.github/prompts/stack-07-avatar-creation-progress.md
new file mode 100644
index 000000000..786bee451
--- /dev/null
+++ b/.github/prompts/stack-07-avatar-creation-progress.md
@@ -0,0 +1,56 @@
+---
+mode: agent
+description: "Progress UI for the 30-90s avatar generation — live status, cancel, preview"
+---
+
+# Stack Layer 2: Avatar Creation Progress UI
+
+## Problem
+
+Avatar generation takes 30–90s. Users won't sit through a blank spinner. Need a live progress surface that makes the wait feel intentional and shows the result the moment it lands.
+
+## Implementation
+
+### Page
+
+After `/create/` submits, redirect to `/create/status/?id=<avatarId>`.
+
+### UI
+
+- Large status card: photo thumbnail (from upload), avatar name placeholder, status text, progress bar.
+- Progress bar stages: `Uploaded → Detecting face → Generating mesh → Rigging → Ready`.
+- Fun micro-copy per stage (avoid generic "Processing...").
+- Cancel button (only active until ~`Rigging` stage).
+- On `ready`: swap in a live 3D preview of the avatar (use [src/viewer.js](src/viewer.js)) + "View agent" + "Edit avatar" buttons.
+
+### Polling / SSE
+
+- Poll `GET /api/avatars/:id/status` every 2s via `setInterval`.
+- OR (preferred) use SSE: `GET /api/avatars/:id/status/stream` → server-sent events with progress deltas. Implement whichever is simpler given the Vercel runtime (polling is fine for v1).
+- Stop polling on `ready` or `failed`.
+- Auto-redirect to `/agent/:slug` on `ready` after a 2s "celebrate" pause, OR let user click View.
+
+### Failure state
+
+- Show the error.
+- "Try again with a different photo" → returns to `/create/`.
+- "Report issue" → opens mailto or Linear form.
+
+### Cancel
+
+- `POST /api/avatars/:id/cancel` marks row as cancelled. Frontend navigates back to `/create/`.
+- Provider call continues server-side (we eat the cost) but the avatar row is marked cancelled.
+
+## Validation
+
+- Submit photo → progress page shows live stage transitions.
+- On ready, live 3D preview renders within 3s.
+- Cancel mid-flight → returned to `/create/`, row marked cancelled.
+- Refresh the status page → resumes from current state.
+- Provider failure → friendly error, retry path.
+- `npm run build` passes.
+
+## Do not do this
+
+- Do NOT use a modal over the previous page — dedicated page is easier to refresh/share.
+- Do NOT pretend the progress — each stage should reflect real server state.
diff --git a/.github/prompts/stack-08-avatar-save-and-slug.md b/.github/prompts/stack-08-avatar-save-and-slug.md
new file mode 100644
index 000000000..e7f0c18ac
--- /dev/null
+++ b/.github/prompts/stack-08-avatar-save-and-slug.md
@@ -0,0 +1,64 @@
+---
+mode: agent
+description: "Persist created avatars with a user-chosen slug and route /agent/:slug to the viewer"
+---
+
+# Stack Layer 2: Avatar Persistence + Slug Routing
+
+## Problem
+
+Once an avatar is generated we need: (1) a stable, shareable URL, (2) a slug chosen by the user, (3) a DB row that the rest of the app treats as canonical.
+
+## Implementation
+
+### Slug picker
+
+On the status page when status hits `ready`, prompt the user for a slug (prefilled with something like `agent-<short>`). Validate client-side: `[a-z0-9-]{3,32}`, no leading/trailing dash.
+
+Call `PATCH /api/avatars/:id`:
+```json
+{ "slug": "satoshi", "name": "Satoshi", "bio": "optional one-liner" }
+```
+
+Server returns 409 if slug is taken, 400 if invalid, 200 with the updated row on success.
+
+### Routing
+
+`/agent/:slug` should route to the viewer with the avatar loaded. Update [src/app.js](src/app.js) URL parser to handle `#agent=<slug>` and also handle path-based `/agent/:slug` via Vercel rewrite (add to [vercel.json](vercel.json)):
+
+```json
+{ "source": "/agent/:slug", "destination": "/index.html?agent=:slug" }
+```
+
+[src/app.js](src/app.js) reads `agent` from query or hash, fetches `/api/avatars/by-slug/:slug`, and loads the GLB.
+
+### Lookup endpoint
+
+`GET /api/avatars/by-slug/:slug` returns the public view of the avatar (no owner PII):
+```json
+{ "id", "slug", "name", "bio", "glb_url", "owner": { "handle" }, "created_at" }
+```
+
+404 if not found.
+
+### Default slug
+
+If user skips the slug picker, assign `agent-<shortId>` automatically — never leave an avatar sluggless.
+
+### DB migration
+
+`avatars` table: add `slug` (unique, nullable), `bio` (text, nullable). Index on slug.
+
+## Validation
+
+- Create avatar, set slug to `satoshi` → `/agent/satoshi` loads the viewer with the GLB.
+- Try to reuse `satoshi` for a second avatar → 409.
+- Invalid slug (`SATOSHI!`) → 400 with useful message.
+- Skip slug picker → auto-slug assigned, URL still works.
+- `/api/avatars/by-slug/nonexistent` → 404.
+- `npm run build` passes.
+
+## Do not do this
+
+- Do NOT expose owner wallet or email on the public lookup.
+- Do NOT mutate the slug after set without also keeping the old slug as a redirect (out of scope for v1 — disallow slug changes for now).
diff --git a/.github/prompts/stack-09-avatar-editor-shell.md b/.github/prompts/stack-09-avatar-editor-shell.md
new file mode 100644
index 000000000..bc93c81e4
--- /dev/null
+++ b/.github/prompts/stack-09-avatar-editor-shell.md
@@ -0,0 +1,62 @@
+---
+mode: agent
+description: "Edit-avatar page shell — auth-gated, tabbed, lives at /edit/:slug"
+---
+
+# Stack Layer 3: Avatar Editor Shell
+
+## Problem
+
+Users need a page to edit an avatar after creation. Today there is no edit surface. This prompt creates the page shell — tabs, routing, auth — so subsequent prompts can fill in each tab.
+
+## Implementation
+
+### Route
+
+`/edit/:slug` — Vercel rewrite → `/edit/index.html?slug=:slug` (add to [vercel.json](vercel.json)).
+
+### Auth + ownership
+
+- Require session. Redirect to `/login.html?next=/edit/<slug>` if not.
+- Fetch `/api/avatars/by-slug/:slug` client-side.
+- Fetch `/api/auth/me` — if `user.id !== avatar.user_id`, show "Not your avatar" and link to the public view.
+
+### Page
+
+`public/edit/index.html` — native DOM, plain CSS.
+
+Layout:
+- Left (40%): live 3D preview via [src/viewer.js](src/viewer.js), auto-rotating.
+- Right (60%): tabbed editor.
+
+Tabs (each filled by a separate prompt):
+1. **Identity** — name, bio, slug lock, delete (stack-10)
+2. **Skills** — attach/detach (stack-11)
+3. **Memory** — seed initial facts (stack-12)
+4. **Animation** — default idle, swap rig (stack-13)
+5. **Mesh** — replace underlying GLB (stack-14)
+
+### Tab state
+
+Hash-based: `/edit/satoshi#skills`. Clicking a tab updates the hash, back/forward works.
+
+### Save flow
+
+Each tab has its own Save button → its own `PATCH /api/avatars/:id` endpoint slice. Unsaved changes banner if the user clicks away.
+
+### Bridge to viewer
+
+Use the existing event bus in [src/agent-protocol.js](src/agent-protocol.js) to push edits to the preview pane live (e.g., identity name change → avatar home updates in preview).
+
+## Validation
+
+- Visit `/edit/satoshi` while logged out → redirected to login.
+- Log in as someone else → "Not your avatar".
+- Log in as owner → all 5 tabs render, preview loads the avatar.
+- Tab hash routing works across refresh + back button.
+- `npm run build` passes.
+
+## Do not do this
+
+- Do NOT build the tab internals here — each is a separate prompt. Just stub them with a placeholder + save button.
+- Do NOT duplicate the viewer — reuse [src/viewer.js](src/viewer.js) in a smaller canvas.
diff --git a/.github/prompts/stack-10-avatar-identity-tab.md b/.github/prompts/stack-10-avatar-identity-tab.md
new file mode 100644
index 000000000..ea48dca2d
--- /dev/null
+++ b/.github/prompts/stack-10-avatar-identity-tab.md
@@ -0,0 +1,59 @@
+---
+mode: agent
+description: "Identity tab of avatar editor — edit name, bio, visibility; delete avatar"
+---
+
+# Stack Layer 3: Identity Tab
+
+## Problem
+
+Users need to edit an avatar's public identity after creation: name, bio, visibility (public/unlisted), and delete it entirely.
+
+## Implementation
+
+### Form fields
+
+- `name` — required, 2–64 chars.
+- `bio` — optional, max 280 chars, live count.
+- `visibility` — radio: `public`, `unlisted`. (No `private` — all avatars are at least unlisted.)
+- `slug` — read-only for v1, with a note "Slug is permanent."
+
+### Save
+
+`PATCH /api/avatars/:id`:
+```json
+{ "name": "...", "bio": "...", "visibility": "public" }
+```
+
+Use `zod` to validate on the server. Reject unknowns. Only owner can edit.
+
+### Delete
+
+"Delete avatar" button with a confirm-text input ("type the slug to confirm").
+
+`DELETE /api/avatars/:id`:
+- Soft-delete first: mark `deleted_at`. Keep the row 30 days for recovery.
+- Remove from public lookups (`GET /api/avatars/by-slug/:slug` returns 404 for soft-deleted).
+- Remove GLB from R2 only after 30d via a cron.
+
+### Visibility semantics
+
+- `public`: listed in `/api/avatars/public`, OG-scraped, etc.
+- `unlisted`: direct URL works, not in public listings, no search indexing (`noindex` robots meta on `/agent/:slug`).
+
+### DB changes
+
+`avatars` table: add `visibility` (enum: 'public', 'unlisted', default 'unlisted'), `deleted_at` (nullable timestamp).
+
+## Validation
+
+- Edit name and bio → Save → refresh → persists.
+- Change visibility to unlisted → removed from `/api/avatars/public`, direct URL still works.
+- Delete with correct slug confirmation → soft-deleted, 404 on public lookup.
+- Attempt to edit someone else's avatar via API → 403.
+- `npm run build` passes.
+
+## Do not do this
+
+- Do NOT hard-delete on first click. Soft-delete.
+- Do NOT allow slug changes in v1.
diff --git a/.github/prompts/stack-11-avatar-skills-tab.md b/.github/prompts/stack-11-avatar-skills-tab.md
new file mode 100644
index 000000000..38cae2e03
--- /dev/null
+++ b/.github/prompts/stack-11-avatar-skills-tab.md
@@ -0,0 +1,66 @@
+---
+mode: agent
+description: "Skills tab — attach/detach skills to an avatar from a catalog"
+---
+
+# Stack Layer 3: Skills Tab
+
+## Problem
+
+An avatar's capabilities are defined by which skills are attached. Today skills are hard-coded per agent in [src/nich-agent.js](src/nich-agent.js). We need a UI to attach/detach skills from a catalog per avatar, persisted to the DB.
+
+## Implementation
+
+### Catalog source
+
+Skills live in [src/skills/](src/skills/). Add a manifest at [specs/schema/skills.json](specs/schema/skills.json) (or read the directory) that exposes:
+```json
+[
+ { "id": "greet", "name": "Greet", "description": "Say hello with presence", "tags": ["default"] },
+ { "id": "validate-model", "name": "Validate glTF", "tags": ["3d"] }
+]
+```
+
+Expose via `GET /api/skills/catalog` (public, cached).
+
+### DB
+
+`avatar_skills` table: `avatar_id` (fk), `skill_id` (text), `config` (jsonb, nullable), `enabled` (bool, default true), `created_at`. Unique on (avatar_id, skill_id).
+
+### UI
+
+Two columns:
+- **Attached** (left): skills currently on this avatar. Each row has a toggle (enable/disable), a config button (if skill has settings), and a remove.
+- **Available** (right): catalog minus attached. "Attach" button per row.
+
+Drag-and-drop optional; start with buttons.
+
+### API
+
+- `GET /api/avatars/:id/skills`
+- `POST /api/avatars/:id/skills` body `{ skillId, config? }`
+- `PATCH /api/avatars/:id/skills/:skillId` body `{ enabled?, config? }`
+- `DELETE /api/avatars/:id/skills/:skillId`
+
+All owner-only.
+
+### Config schemas
+
+Each skill in the catalog can declare a `configSchema` (zod-like JSON schema). Render a simple form from it (text fields and booleans only for v1).
+
+### Live update
+
+On save, emit a `skills.updated` event on the agent protocol so the preview pane re-hydrates its skill set.
+
+## Validation
+
+- Attach `validate-model` → preview pane can now trigger glTF validation.
+- Detach `greet` → preview agent no longer greets.
+- Edit skill config (e.g., greeting text) → persists and reflects live.
+- Reordering (if implemented) persists.
+- `npm run build` passes.
+
+## Do not do this
+
+- Do NOT invent new skills here — catalog is a mirror of [src/skills/](src/skills/).
+- Do NOT allow attaching skills not in the catalog (server must validate).
diff --git a/.github/prompts/stack-12-avatar-memory-seed.md b/.github/prompts/stack-12-avatar-memory-seed.md
new file mode 100644
index 000000000..27745f9d1
--- /dev/null
+++ b/.github/prompts/stack-12-avatar-memory-seed.md
@@ -0,0 +1,67 @@
+---
+mode: agent
+description: "Memory tab — seed initial facts/feedback/references into an avatar's memory store"
+---
+
+# Stack Layer 3: Memory Tab
+
+## Problem
+
+Per [specs/MEMORY_SPEC.md](specs/MEMORY_SPEC.md) and [src/agent-memory.js](src/agent-memory.js), agent memory has four canonical types: `user`, `feedback`, `project`, `reference`. Today memories are only written by the agent at runtime. We need a UI to *seed* memories during avatar setup so the agent boots with meaningful context.
+
+## Implementation
+
+### Existing backend
+
+[api/agent-memory.js](api/agent-memory.js) likely already handles read/write. Verify the endpoints match:
+- `GET /api/agents/:id/memories?type=...`
+- `POST /api/agents/:id/memories` body `{ type, name, description, body }`
+- `DELETE /api/agents/:id/memories/:memoryId`
+
+Note: memory is keyed to *agent* not *avatar* — confirm agent_identity ↔ avatar relationship in [api/agents/](api/agents/). If an avatar doesn't yet have an agent_identity row, create one on first memory write.
+
+### UI
+
+Four subsections, one per memory type, in collapsible cards:
+1. **User** — "Who is this agent for?"
+2. **Feedback** — "How should it behave?"
+3. **Project** — "What is it working on?"
+4. **Reference** — "External resources it should know about"
+
+Each subsection:
+- List of existing memories (name + one-line description).
+- "Add memory" → modal with `name`, `description`, `body` textarea.
+- Edit / delete per row.
+
+### Import from template
+
+"Import starter pack" button — loads a preset bundle (e.g., "Customer support agent starter" with 5 pre-written memories of each type). Templates live at [specs/schema/memory-templates/](specs/schema/memory-templates/) as JSON files.
+
+### Validation
+
+Server-side zod schema:
+```js
+{
+ type: z.enum(['user', 'feedback', 'project', 'reference']),
+ name: z.string().min(2).max(100),
+ description: z.string().max(200),
+ body: z.string().min(1).max(10000)
+}
+```
+
+### Live preview
+
+On memory add/edit, emit a `memory.updated` event on the agent protocol. The avatar preview can log "memory updated" in its timeline ([src/agent-home.js](src/agent-home.js)).
+
+## Validation
+
+- Add a memory of each of the 4 types → persists and reloads.
+- Delete a memory → gone.
+- Try to create a 5th type → rejected.
+- Import starter pack → ~5 memories added in one shot.
+- `npm run build` passes.
+
+## Do not do this
+
+- Do NOT invent new memory types. Four canonical types only.
+- Do NOT expose another user's memories on `/agent/:slug`. Memory reads for the public page must strip private content (see [specs/MEMORY_SPEC.md](specs/MEMORY_SPEC.md)).
diff --git a/.github/prompts/stack-13-avatar-animation-tab.md b/.github/prompts/stack-13-avatar-animation-tab.md
new file mode 100644
index 000000000..3bad8731e
--- /dev/null
+++ b/.github/prompts/stack-13-avatar-animation-tab.md
@@ -0,0 +1,70 @@
+---
+mode: agent
+description: "Animation tab — pick idle + gesture animations from Mixamo bundle"
+---
+
+# Stack Layer 3: Animation Tab
+
+## Problem
+
+Avatars ship with a skeleton but no default animations. We need a UI to pick: (1) idle animation, (2) greeting animation, (3) thinking animation, (4) celebration animation. Bundled via `npm run fetch-animations` (Mixamo).
+
+## Implementation
+
+### Animation inventory
+
+[src/animation-manager.js](src/animation-manager.js) already handles loading/blending. List available clips via `GET /api/animations/catalog` — reads from wherever fetch-animations puts them (`public/animations/` or similar).
+
+Catalog response:
+```json
+[
+ { "id": "idle-breathing", "name": "Breathing Idle", "tags": ["idle"], "durationMs": 3200, "previewGif": "/previews/idle-breathing.gif" },
+ ...
+]
+```
+
+### UI
+
+Four slots:
+| Slot | Purpose |
+|---|---|
+| Idle | Plays when agent is passive (default loop) |
+| Greet | Plays on `greet` skill or avatar home load |
+| Think | Plays during async actions (sign, fetch, compute) |
+| Celebrate | Plays on `celebration` emotion peak |
+
+Each slot shows current selection, "Change" button opens a picker modal with previews.
+
+### Preview
+
+Picker shows animation name + a looping preview. If GIF previews don't exist, render a tiny canvas that plays the clip on the user's current avatar rig (more work but nicer).
+
+### Persistence
+
+`avatars.animations` jsonb column:
+```json
+{ "idle": "idle-breathing", "greet": "waving", "think": "thinking-scratch", "celebrate": "fist-pump" }
+```
+
+`PATCH /api/avatars/:id/animations` endpoint.
+
+### Retarget compatibility
+
+Not all Mixamo clips retarget cleanly to every rig. If a selected clip fails to retarget at runtime ([src/animation-manager.js](src/animation-manager.js)), fall back to the default idle and log a warning — don't crash the viewer.
+
+### Live bridge
+
+On change, emit `animation.set` event on agent protocol → preview pane swaps immediately.
+
+## Validation
+
+- Change idle → preview loops the new idle within 1s.
+- Change greet → hitting greet skill plays the new animation.
+- Pick an incompatible clip → warning, falls back to default, preview still works.
+- Persists across refresh.
+- `npm run build` passes.
+
+## Do not do this
+
+- Do NOT upload arbitrary user-provided FBX/GLB animations in v1 — catalog only.
+- Do NOT regenerate preview GIFs client-side — ship them with the animation bundle.
diff --git a/.github/prompts/stack-14-avatar-mesh-replace.md b/.github/prompts/stack-14-avatar-mesh-replace.md
new file mode 100644
index 000000000..b24a019fb
--- /dev/null
+++ b/.github/prompts/stack-14-avatar-mesh-replace.md
@@ -0,0 +1,57 @@
+---
+mode: agent
+description: "Mesh tab — replace underlying GLB (rerun selfie, upload GLB, or pick preset)"
+---
+
+# Stack Layer 3: Mesh Replacement Tab
+
+## Problem
+
+Users may want to change the underlying 3D mesh of an existing avatar while keeping identity, skills, and memory intact. Three paths: (1) retake selfie, (2) upload a GLB directly, (3) pick a preset avatar.
+
+## Implementation
+
+### Three methods
+
+1. **Retake selfie** — reuse the selfie flow from stack-05/06. On completion, update `avatars.glb_url` on the existing row (do NOT create a new avatar).
+2. **Upload GLB** — `<input type="file" accept=".glb,.gltf">`. Validate client-side (<50MB). Presign → upload → PATCH avatar.
+3. **Preset picker** — small catalog at `GET /api/avatars/presets` (e.g., "Shiba", "Robot", "Ghost"). Click to apply.
+
+### Validation (server)
+
+On any mesh replacement, run the existing [src/validator.js](src/validator.js) server-side (or a lightweight version) against the new GLB:
+- Must be valid glTF 2.0.
+- Must have a skinned mesh with a rig (warn if not — some presets are static).
+- File size < 100MB.
+
+Reject with a descriptive error if invalid.
+
+### Morph target compatibility
+
+If the new mesh lacks ARKit blendshapes, the Empathy Layer falls back to head-bone-only expression. Detect this and surface a non-blocking warning in the UI: "This mesh doesn't support facial expressions."
+
+### Keep-alive
+
+Identity, skills, memory, animations — all preserved. Only `glb_url`, `source`, and `updated_at` change on the avatar row.
+
+### Preview
+
+After replacement, re-render the preview pane with the new GLB. The agent home timeline ([src/agent-home.js](src/agent-home.js)) logs a `mesh.replaced` action.
+
+### Old mesh retention
+
+Keep the old GLB in R2 for 30 days (versioning). Add `avatar_mesh_history` table: `{ avatar_id, glb_url, replaced_at }`. "Revert to previous" button if within 30 days.
+
+## Validation
+
+- Replace via GLB upload → preview shows new mesh, all skills/memory intact.
+- Replace via preset → same.
+- Upload an invalid file → rejected with helpful error.
+- Upload a rigless mesh → warning shown, still accepted.
+- Revert to previous → previous GLB restored.
+- `npm run build` passes.
+
+## Do not do this
+
+- Do NOT create a new avatar row on mesh replace. Mutate in place.
+- Do NOT delete the old GLB immediately.
diff --git a/.github/prompts/stack-15-agent-public-page.md b/.github/prompts/stack-15-agent-public-page.md
new file mode 100644
index 000000000..66deaded7
--- /dev/null
+++ b/.github/prompts/stack-15-agent-public-page.md
@@ -0,0 +1,63 @@
+---
+mode: agent
+description: "Polish the public /agent/:slug page — hero, identity card, presence, CTAs"
+---
+
+# Stack Layer 4: Public Agent Page
+
+## Problem
+
+`/agent/:slug` currently loads the viewer with the GLB but lacks a complete public presentation: identity card, bio, owner info, embed CTA, share buttons. This is the page that onlookers see when someone shares a link.
+
+## Implementation
+
+### Layout (desktop)
+
+- **Hero** — full-viewport 3D viewer with the avatar auto-rotating and breathing.
+- **Identity card** (top-left overlay) — name, handle, bio, verified badge if ERC-8004 registered.
+- **Action dock** (bottom-center) — buttons for skills the agent exposes (e.g., "Greet", "Introduce yourself", "Show model").
+- **Presence strip** (top-right) — current emotional blend ([src/agent-avatar.js](src/agent-avatar.js) Empathy Layer), shown as weighted pills ("60% curious, 30% neutral").
+- **Share + embed** (bottom-right) — copy link, copy embed, social share.
+
+### Layout (mobile)
+
+- Hero viewer, full-screen.
+- Identity as a collapsible sheet from the bottom.
+- Action dock docked above the sheet.
+
+### Data load
+
+Single fetch: `GET /api/agents/by-slug/:slug/public` returns `{ avatar, identity, skills, publicMemories, onchain }`. Avoid N+1.
+
+### OG + oembed
+
+Delegate to existing [api/agent-og.js](api/agent-og.js) and [api/agent-oembed.js](api/agent-oembed.js). Add `<meta>` tags on the page for Twitter/LinkedIn scraping.
+
+### Verified badge
+
+If `identity.onchain.registered === true` (ERC-8004), show a small badge that links to the chain record.
+
+### Empty states
+
+- No skills → hide action dock.
+- No bio → hide bio line.
+- No public memories → hide the memories section (don't render an empty panel).
+
+### Kiosk mode
+
+Respect `?kiosk=1` query: hide everything but the viewer + presence strip. Used by embed (see stack-17).
+
+## Validation
+
+- `/agent/satoshi` shows full page with identity, skills, embed CTA.
+- Clicking a skill triggers it visibly (avatar animates, emotion shifts).
+- Share link copied to clipboard.
+- OG tags verified with `curl` + unfurl checker.
+- Mobile layout works in responsive devtools.
+- `?kiosk=1` strips to just viewer + presence.
+- `npm run build` passes.
+
+## Do not do this
+
+- Do NOT load any owner-private data (wallet, email, private memories) on this page.
+- Do NOT add comments/social features — that's a later concern.
diff --git a/.github/prompts/stack-16-embed-code-generator.md b/.github/prompts/stack-16-embed-code-generator.md
new file mode 100644
index 000000000..1eafa78c6
--- /dev/null
+++ b/.github/prompts/stack-16-embed-code-generator.md
@@ -0,0 +1,72 @@
+---
+mode: agent
+description: "Embed code generator — copy-paste snippets for iframe, web component, React"
+---
+
+# Stack Layer 4: Embed Code Generator
+
+## Problem
+
+For the agent to appear in third-party sites, the owner needs one-click copy-paste embed snippets. Today no generator UI exists. Must produce iframe, web-component, and React snippets from a single settings form.
+
+## Implementation
+
+### Page
+
+`/embed/:slug` — dedicated page, linked from the agent public page's share CTA.
+
+### Settings form
+
+- **Size** — preset (400×600, 600×600, full-width responsive) or custom W×H.
+- **Mode** — `presence` (full interactive), `kiosk` (no UI), `snapshot` (static image).
+- **Theme** — light, dark, auto.
+- **Actions visible** — checkboxes for which skills appear in the action dock.
+- **Auto-rotate** — on/off.
+- **Background** — transparent, solid color picker, environment preset.
+
+### Generated snippets
+
+Live-update three snippets in tabs as settings change:
+
+**iframe**:
+```html
+<iframe src="https://3dagent.vercel.app/agent/satoshi?kiosk=1&theme=dark"
+ width="600" height="600" style="border:0"
+ allow="camera; microphone; xr-spatial-tracking"></iframe>
+```
+
+**Web component** (using [src/element.js](src/element.js)):
+```html
+<script src="https://3dagent.vercel.app/dist-lib/agent-3d.js"></script>
+<agent-3d slug="satoshi" theme="dark" mode="kiosk"></agent-3d>
+```
+
+**React** (thin wrapper note — the lib is framework-agnostic):
+```jsx
+<iframe src="https://3dagent.vercel.app/agent/satoshi?kiosk=1" width={600} height={600} />
+```
+
+### Copy button
+
+Each snippet has a "Copy" button. Track copy events (`embed.copied` telemetry) so we can see adoption.
+
+### Live preview
+
+Right side of the page renders the actual embedded agent with the chosen settings, reflecting changes in real time.
+
+### Referrer allowlist link
+
+"Restrict which sites can embed this agent" link → takes owner to [prompts/embed/03-embed-allowlist.md](prompts/embed/03-embed-allowlist.md) settings (already specced).
+
+## Validation
+
+- Change size → live preview resizes, snippet updates.
+- Copy each of the three snippets → paste into a test HTML file → all three render the agent.
+- Transparent background + solid page color → agent floats on page.
+- Web component snippet works offline if `dist-lib/agent-3d.js` is served (not 404).
+- `npm run build` passes.
+
+## Do not do this
+
+- Do NOT generate server-side React components. Reference the iframe/web-component path.
+- Do NOT hardcode the domain — read from `window.location.origin` so preview works on localhost.
diff --git a/.github/prompts/stack-17-kiosk-mode-polish.md b/.github/prompts/stack-17-kiosk-mode-polish.md
new file mode 100644
index 000000000..e940f03a5
--- /dev/null
+++ b/.github/prompts/stack-17-kiosk-mode-polish.md
@@ -0,0 +1,69 @@
+---
+mode: agent
+description: "Kiosk mode polish — minimal chrome, responsive to parent sizing, fast first paint"
+---
+
+# Stack Layer 4: Kiosk Mode Polish
+
+## Problem
+
+`?kiosk=1` is the embed-optimized view. Today it likely only hides some chrome. Needs to be rock-solid: minimal UI, fast first paint, responsive to parent iframe sizing, touch-first, no scroll bleed.
+
+## Implementation
+
+### Visible elements in kiosk
+
+- Viewer (full iframe).
+- Presence strip (small, corner, semi-transparent).
+- Optional: minimal action dock (only if parent passes `?actions=1`).
+- Nothing else. No login, no nav, no footer.
+
+### Responsive sizing
+
+- Listen to `resize` and `window.matchMedia`. Viewer re-renders on container resize.
+- Use `ResizeObserver` on the canvas parent.
+- Respect `devicePixelRatio`, capped at 2 for mobile performance.
+
+### First paint < 2s
+
+- Preload the GLB via `<link rel="preload" as="fetch" crossorigin>` injected after `/api/avatars/by-slug` returns.
+- Inline critical CSS (hero background, loading state).
+- Defer non-critical JS (analytics, Privy, anything not needed to render the GLB).
+- Show a placeholder silhouette while GLB loads.
+
+### Touch
+
+- Single-finger rotate, two-finger pan/zoom (already in OrbitControls but verify on mobile).
+- No conflicting page scroll — `touch-action: none` on the canvas.
+- `<html>` and `<body>` must be `overflow: hidden` in kiosk.
+
+### Parent-child messaging
+
+Accept `postMessage` from the parent:
+- `{ type: 'agent.setSkill', id: 'greet' }` → triggers a skill.
+- `{ type: 'agent.setEmotion', blend: { curious: 0.8 } }` → overrides emotional state temporarily.
+- `{ type: 'agent.reload' }` → re-fetch and re-render.
+
+Post back to parent:
+- `{ type: 'agent.ready', avatarId }` on first render.
+- `{ type: 'agent.skillResult', id, result }` on skill completion.
+
+Only accept messages from origins in the referrer allowlist ([prompts/embed/03-embed-allowlist.md](prompts/embed/03-embed-allowlist.md)). Post back via `event.source.postMessage`.
+
+### Theme
+
+`?theme=light|dark|auto` — auto uses `prefers-color-scheme`. Affects presence strip + any chrome, not the 3D scene lighting (that's `?env=...`).
+
+## Validation
+
+- Embed the iframe in a test page with resize handles → smooth resize, no blank frames.
+- Lighthouse FCP on mobile < 2s (check with throttled 3G).
+- Touch rotate works on iOS Safari without page scroll.
+- `postMessage({type:'agent.setSkill',id:'greet'})` from parent → avatar greets.
+- Non-allowlisted parent sends postMessage → ignored.
+- `npm run build` passes.
+
+## Do not do this
+
+- Do NOT ship login UI into kiosk.
+- Do NOT accept postMessage from `*` — always check origin.
diff --git a/.github/prompts/stack-18-embed-telemetry.md b/.github/prompts/stack-18-embed-telemetry.md
new file mode 100644
index 000000000..bd70cbed7
--- /dev/null
+++ b/.github/prompts/stack-18-embed-telemetry.md
@@ -0,0 +1,65 @@
+---
+mode: agent
+description: "Track embed views, skill invocations, and session duration — without tracking users"
+---
+
+# Stack Layer 4: Embed Telemetry
+
+## Problem
+
+We need to know which agents are being embedded, where, how often they're interacted with, and which skills get used. Without tracking individual users (privacy-first).
+
+## Implementation
+
+### Events
+
+POST to `/api/telemetry` (batched, fire-and-forget from client):
+- `embed.view` — iframe loaded. Fields: `{ avatarId, parentOrigin, kiosk, theme, ua }`
+- `embed.skill.invoked` — `{ avatarId, skillId, parentOrigin }`
+- `embed.session.duration` — on pagehide: `{ avatarId, parentOrigin, ms, interactions }`
+
+### Privacy
+
+- Do NOT send: user id, wallet, IP (server drops it), cookies, referrer path (only origin).
+- Hash the parent origin with a daily-rotating salt if you want aggregate origin counts without storing the raw value long-term. Start without hashing for v1.
+- Respect `Do-Not-Track` header.
+
+### Storage
+
+`agent_telemetry` table in Neon:
+```sql
+avatar_id, event, parent_origin, kiosk bool, theme, ua_bucket, occurred_at
+```
+
+Keep raw events 30 days, then aggregate into `agent_telemetry_daily` rollups.
+
+### Dashboard
+
+Owner-only page `/dashboard/agents/:slug/stats`:
+- 7-day / 30-day views.
+- Top parent origins.
+- Top skills invoked.
+- Avg session duration.
+- Sparkline of daily views.
+
+### Rate limit
+
+Drop events exceeding 100/min per avatar from a single IP. Use Upstash Redis.
+
+### Batch + throttle
+
+Client buffers events up to 10 or 5 seconds, then POSTs. Flush on `pagehide`.
+
+## Validation
+
+- Embed an agent in a test page → `embed.view` logged within 5s.
+- Trigger 3 skills → 3 `embed.skill.invoked` events.
+- Close the tab → `embed.session.duration` event captured.
+- Stats dashboard shows the events.
+- DNT header set → no events sent.
+- `npm run build` passes.
+
+## Do not do this
+
+- Do NOT use Google Analytics / third-party tracker — build it in.
+- Do NOT log IP or UA to the DB raw — bucket the UA (mobile/desktop/bot).
diff --git a/.github/prompts/stack-19-artifacts-single-file.md b/.github/prompts/stack-19-artifacts-single-file.md
new file mode 100644
index 000000000..9a4c84dbb
--- /dev/null
+++ b/.github/prompts/stack-19-artifacts-single-file.md
@@ -0,0 +1,71 @@
+---
+mode: agent
+description: "Self-contained HTML build for Claude.ai Artifacts — one file, no external fetches"
+---
+
+# Stack Layer 5: Claude Artifacts Single-File Embed
+
+## Problem
+
+Claude.ai Artifacts run user-supplied HTML in a sandboxed iframe with restricted network access. To make an agent appear inside a Claude conversation, we need a single self-contained HTML file that renders the agent — no external CDN calls for JS, no cross-origin fetches that would be blocked.
+
+## Implementation
+
+### Build target
+
+Add a new Vite build output: `npm run build:artifact` → produces `dist-artifact/agent.html` — a single HTML file with:
+- Inline JS (three.js, viewer, agent runtime, all in one `<script type="module">`).
+- Inline CSS.
+- Inline base64-encoded or HTTP-fetched GLB (see hydration below).
+
+Vite config: new entry `src/artifact-entry.js`, `viteStaticCopy` or `rollup-plugin-html-literals` to inline everything. Target < 2MB gzipped (three.js alone is ~600KB gzipped — monitor).
+
+### Hydration modes
+
+The single HTML accepts an agent spec via URL hash OR inlined JSON:
+
+Mode A (hash-injected by the host):
+```
+agent.html#agent={"slug":"satoshi","glb":"data:...","skills":[...]}
+```
+
+Mode B (inline, for static Artifacts):
+```html
+<script type="application/json" id="agent-spec">{...full spec...}</script>
+```
+
+On load, read spec, boot viewer + agent runtime, render.
+
+### GLB handling
+
+Claude Artifacts block many cross-origin fetches. Three options:
+1. **Inline base64** — GLB embedded in the HTML (bloats the file; only for demo avatars).
+2. **Use Claude's allowed origins** — if R2 public URL is on an allowed list, fetch normally.
+3. **Host-proxied** — Claude's environment might proxy fetches; document the constraint and test.
+
+For v1: support inline base64 AND allow a passthrough URL. Document which works in Artifacts.
+
+### No auth / no writes
+
+Artifact mode is read-only:
+- No login UI.
+- No memory writes.
+- Skills that need the network are disabled (grayed out).
+- Only rendering + local-only skills (animation, emotion) work.
+
+### MCP tool that emits this
+
+Add an MCP tool `render_agent_artifact` to [api/mcp.js](api/mcp.js): given a slug, returns an `artifact` payload with the single HTML pre-filled for that agent. Claude picks it up and emits the Artifact.
+
+## Validation
+
+- `npm run build:artifact` produces `dist-artifact/agent.html` under 2MB.
+- Open the file directly in a browser → avatar renders, animates.
+- Paste into Claude.ai as an Artifact with an agent hash → renders embedded in the chat.
+- No external fetches in devtools Network tab (all inline).
+- `npm run build` passes.
+
+## Do not do this
+
+- Do NOT ship write-capable skills into the artifact.
+- Do NOT inline megabyte-scale GLBs by default — that's a demo mode, not production.
diff --git a/.github/prompts/stack-20-lobehub-plugin.md b/.github/prompts/stack-20-lobehub-plugin.md
new file mode 100644
index 000000000..5f2feae70
--- /dev/null
+++ b/.github/prompts/stack-20-lobehub-plugin.md
@@ -0,0 +1,93 @@
+---
+mode: agent
+description: "Lobehub plugin manifest + renderer so agents embody in the user's LobeHub fork"
+---
+
+# Stack Layer 5: LobeHub Plugin Integration
+
+## Problem
+
+User maintains a LobeHub fork. Per priority stack, an agent from 3dagent.vercel.app must appear as an embodied 3D presence inside LobeHub chats — not a JSON blob. LobeHub plugins are the right extension point.
+
+## Implementation
+
+### Plugin manifest
+
+Host at `https://3dagent.vercel.app/.well-known/lobehub-plugin.json`:
+```json
+{
+ "identifier": "3d-agent",
+ "version": "1.0.0",
+ "meta": {
+ "title": "3D Agent",
+ "description": "Embodied 3D agents — identity, memory, skills, emotional presence",
+ "avatar": "https://3dagent.vercel.app/icon.png",
+ "tags": ["3d", "agent", "avatar"]
+ },
+ "api": [
+ {
+ "name": "renderAgent",
+ "description": "Render an embodied agent by slug or agent card URL",
+ "url": "https://3dagent.vercel.app/api/lobehub/render-agent",
+ "parameters": { "type": "object", "properties": { "slug": { "type": "string" } }, "required": ["slug"] }
+ },
+ {
+ "name": "summonAgent",
+ "description": "Ask the 3D agent to perform a skill and return the result + rendering",
+ "url": "https://3dagent.vercel.app/api/lobehub/summon-agent",
+ "parameters": { "type": "object", "properties": { "slug": { "type": "string" }, "skill": { "type": "string" }, "input": { "type": "string" } }, "required": ["slug", "skill"] }
+ }
+ ],
+ "ui": [
+ {
+ "name": "agent-embed",
+ "url": "https://3dagent.vercel.app/lobehub/embed.html"
+ }
+ ]
+}
+```
+
+### Plugin endpoints
+
+`POST /api/lobehub/render-agent` — returns a payload the plugin chrome renders:
+```json
+{
+ "type": "embed",
+ "url": "https://3dagent.vercel.app/agent/satoshi?kiosk=1&theme=auto",
+ "width": 480,
+ "height": 480,
+ "fallbackText": "3D Agent: Satoshi — open in browser to interact"
+}
+```
+
+`POST /api/lobehub/summon-agent` — triggers a skill server-side (or via headless agent) and returns both text + an embed URL that shows the animated response.
+
+### UI plugin
+
+`/lobehub/embed.html` — near-identical to `?kiosk=1` but:
+- Reads the LobeHub plugin context (agent spec, theme from host).
+- Posts lifecycle events via `postMessage` to the LobeHub parent.
+- Respects LobeHub's theme tokens (read from `postMessage` at mount).
+
+### Install flow
+
+Document in repo: how the user installs the plugin in their fork. Either:
+- Official LobeHub plugin marketplace submission (later), OR
+- Direct manifest URL install (immediate).
+
+### Auth
+
+Plugin does NOT require auth to render public avatars. If the LobeHub user wants their *own* agents listed, they pass a 3D Agent API key (see [api/keys/](api/keys/)) in a settings field.
+
+## Validation
+
+- User installs the plugin in their LobeHub fork via manifest URL.
+- Types "summon satoshi" or calls the tool → agent renders embedded in the chat.
+- Emotion/animation responds to the conversation context (basic v1: just renders).
+- Mobile LobeHub: embed resizes and touch works.
+- `npm run build` passes.
+
+## Do not do this
+
+- Do NOT fork LobeHub code — integrate only via the plugin API.
+- Do NOT require a 3D Agent login to view public agents.
diff --git a/api/_lib/agent-wallet.js b/api/_lib/agent-wallet.js
new file mode 100644
index 000000000..bb49311cc
--- /dev/null
+++ b/api/_lib/agent-wallet.js
@@ -0,0 +1,77 @@
+// Agent wallet generation and management.
+// Generates a random Ethereum wallet per agent and encrypts the private key
+// at rest using AES-256-GCM with the server JWT_SECRET as the key material.
+
+import { webcrypto } from 'node:crypto';
+import { env } from './env.js';
+
+const subtle = (globalThis.crypto?.subtle) || webcrypto.subtle;
+const randomBytes = (n) => {
+ const b = new Uint8Array(n);
+ (globalThis.crypto || webcrypto).getRandomValues(b);
+ return b;
+};
+
+// ── Key derivation ──────────────────────────────────────────────────────────
+// Derive a stable AES-256 key from JWT_SECRET for encrypting agent private keys.
+async function deriveKey() {
+ const raw = new TextEncoder().encode(env.JWT_SECRET);
+ const base = await subtle.importKey('raw', raw, 'HKDF', false, ['deriveKey']);
+ return subtle.deriveKey(
+ { name: 'HKDF', hash: 'SHA-256', salt: new TextEncoder().encode('agent-wallet-v1'), info: new Uint8Array(0) },
+ base,
+ { name: 'AES-GCM', length: 256 },
+ false,
+ ['encrypt', 'decrypt'],
+ );
+}
+
+// ── Encrypt / decrypt ───────────────────────────────────────────────────────
+
+async function encrypt(plaintext) {
+ const key = await deriveKey();
+ const iv = randomBytes(12);
+ const data = new TextEncoder().encode(plaintext);
+ const ct = await subtle.encrypt({ name: 'AES-GCM', iv }, key, data);
+ const buf = new Uint8Array(iv.length + ct.byteLength);
+ buf.set(iv, 0);
+ buf.set(new Uint8Array(ct), iv.length);
+ return Buffer.from(buf).toString('base64');
+}
+
+async function decrypt(ciphertext) {
+ const key = await deriveKey();
+ const raw = Buffer.from(ciphertext, 'base64');
+ const iv = raw.subarray(0, 12);
+ const ct = raw.subarray(12);
+ const plain = await subtle.decrypt({ name: 'AES-GCM', iv }, key, ct);
+ return new TextDecoder().decode(plain);
+}
+
+// ── Wallet generation ───────────────────────────────────────────────────────
+
+/**
+ * Generate a new Ethereum wallet for an agent.
+ * Returns { address, encrypted_key } where encrypted_key is the AES-GCM
+ * encrypted private key (base64). Store encrypted_key in agent meta.
+ */
+export async function generateAgentWallet() {
+ // Generate 32 random bytes for a private key
+ const pk = randomBytes(32);
+ const pkHex = '0x' + Array.from(pk, (b) => b.toString(16).padStart(2, '0')).join('');
+
+ // Compute address from private key using ethers
+ const { computeAddress } = await import('ethers');
+ const address = computeAddress(pkHex);
+
+ const encrypted_key = await encrypt(pkHex);
+ return { address, encrypted_key };
+}
+
+/**
+ * Recover an agent wallet's private key from its encrypted form.
+ * Only call this when the agent needs to sign a transaction.
+ */
+export async function recoverAgentKey(encryptedKey) {
+ return decrypt(encryptedKey);
+}
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index 8b5a937ef..ad9db836d 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -71,6 +71,8 @@ export const limits = {
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),
+ widgetWrite: (userId) => getLimiter('widget:write', { limit: 60, window: '1 m' }).limit(userId),
+ widgetRead: (ip) => getLimiter('widget:read', { limit: 600, window: '1 m' }).limit(ip),
};
// Trust only proxy headers that Vercel itself sets and signs. Naively reading
diff --git a/api/_lib/schema.sql b/api/_lib/schema.sql
index 7971e0567..cb7301487 100644
--- a/api/_lib/schema.sql
+++ b/api/_lib/schema.sql
@@ -295,3 +295,41 @@ do $$ begin
create trigger agent_identities_set_updated_at before update on agent_identities
for each row execute function set_updated_at();
exception when duplicate_object then null; end $$;
+
+-- ── widgets — saved configurations of avatars rendered in a widget runtime ──
+create table if not exists widgets (
+ id text primary key, -- 'wdgt_' + 12 base64url chars
+ user_id uuid not null references users(id) on delete cascade,
+ avatar_id uuid references avatars(id) on delete set null,
+ type text not null check (type in ('turntable','animation-gallery','talking-agent','passport','hotspot-tour')),
+ name text not null,
+ config jsonb not null default '{}'::jsonb,
+ is_public boolean not null default true,
+ view_count bigint not null default 0,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ deleted_at timestamptz
+);
+
+create index if not exists widgets_user_idx
+ on widgets(user_id) where deleted_at is null;
+create index if not exists widgets_type_idx
+ on widgets(type) where deleted_at is null;
+
+do $$ begin
+ create trigger widgets_set_updated_at before update on widgets
+ for each row execute function set_updated_at();
+exception when duplicate_object then null; end $$;
+
+-- ── widget_views — anonymous load events for widget owner analytics ─────────
+-- No IPs, no UAs, no cookies. country from x-vercel-ip-country edge header.
+create table if not exists widget_views (
+ id bigserial primary key,
+ widget_id text not null references widgets(id) on delete cascade,
+ country text,
+ referer_host text,
+ created_at timestamptz not null default now()
+);
+
+create index if not exists widget_views_widget_time
+ on widget_views(widget_id, created_at desc);
diff --git a/api/agents.js b/api/agents.js
index 4e41d3b58..e0b430f55 100644
--- a/api/agents.js
+++ b/api/agents.js
@@ -14,6 +14,7 @@
import { getSessionUser, authenticateBearer, extractBearer } from './_lib/auth.js';
import { sql } from './_lib/db.js';
import { cors, json, method, readJson, wrap, error } from './_lib/http.js';
+import { generateAgentWallet } from './_lib/agent-wallet.js';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
@@ -63,9 +64,16 @@ async function handleGetOrCreateMe(req, res, auth) {
`;
if (!agent) {
+ const wallet = await generateAgentWallet();
[agent] = await sql`
- INSERT INTO agent_identities (user_id, name, skills)
- VALUES (${auth.userId}, ${'Agent'}, ${['greet', 'present-model', 'validate-model', 'remember', 'think']})
+ INSERT INTO agent_identities (user_id, name, skills, wallet_address, meta)
+ VALUES (
+ ${auth.userId},
+ ${'Agent'},
+ ${['greet', 'present-model', 'validate-model', 'remember', 'think']},
+ ${wallet.address},
+ ${sql.json({ encrypted_wallet_key: wallet.encrypted_key })}
+ )
RETURNING *
`;
}
@@ -96,14 +104,18 @@ async function handleCreate(req, res) {
if (!name) return error(res, 400, 'validation_error', 'name is required');
+ const wallet = await generateAgentWallet();
+ const meta = { ...(body.meta || {}), encrypted_wallet_key: wallet.encrypted_key };
+
const [agent] = await sql`
- INSERT INTO agent_identities (user_id, name, description, skills, meta)
+ INSERT INTO agent_identities (user_id, name, description, skills, wallet_address, meta)
VALUES (
${auth.userId},
${name},
${body.description ? String(body.description).slice(0, 500) : null},
${body.skills || ['greet', 'present-model', 'validate-model', 'remember', 'think']},
- ${body.meta || {}}
+ ${wallet.address},
+ ${sql.json(meta)}
)
RETURNING *
`;
@@ -194,7 +206,11 @@ export async function handleWallet(req, res, id) {
if (existing.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');
if (req.method === 'DELETE') {
- await sql`UPDATE agent_identities SET wallet_address = null, chain_id = null WHERE id = ${id}`;
+ await sql`
+ UPDATE agent_identities
+ SET wallet_address = null, chain_id = null, erc8004_agent_id = null
+ WHERE id = ${id}
+ `;
return json(res, 200, { ok: true });
}
@@ -202,11 +218,15 @@ export async function handleWallet(req, res, id) {
const body = await readJson(req);
const address = String(body.wallet_address || '').trim();
const chainId = Number(body.chain_id) || null;
+ // Optional: post-mint, the client can patch in the minted ERC-8004 agent id.
+ const erc8004 = body.erc8004_agent_id != null ? BigInt(body.erc8004_agent_id).toString() : null;
if (!address) return error(res, 400, 'validation_error', 'wallet_address required');
const [updated] = await sql`
UPDATE agent_identities
- SET wallet_address = ${address}, chain_id = ${chainId}
+ SET wallet_address = ${address},
+ chain_id = ${chainId},
+ erc8004_agent_id = COALESCE(${erc8004}::bigint, erc8004_agent_id)
WHERE id = ${id}
RETURNING *
`;
@@ -224,6 +244,10 @@ async function resolveAuth(req) {
}
function decorate(row, isOwner = true) {
+ // Strip encrypted_wallet_key from meta — never expose to the client.
+ const meta = { ...(row.meta || {}) };
+ delete meta.encrypted_wallet_key;
+
const base = {
id: row.id,
name: row.name,
@@ -231,7 +255,7 @@ function decorate(row, isOwner = true) {
avatar_id: row.avatar_id,
home_url: row.home_url || `/agent/${row.id}`,
skills: row.skills || [],
- meta: row.meta || {},
+ meta,
is_registered: Boolean(row.erc8004_agent_id),
created_at: row.created_at,
};
diff --git a/api/agents/[id]/sign.js b/api/agents/[id]/sign.js
new file mode 100644
index 000000000..8dc016ef6
--- /dev/null
+++ b/api/agents/[id]/sign.js
@@ -0,0 +1,71 @@
+// POST /api/agents/:id/sign — owner-only; signs an arbitrary message with the
+// agent's server-held wallet. The key is encrypted at rest with JWT_SECRET-
+// derived AES-GCM and decrypted in-memory just long enough to sign.
+//
+// Request: { message: string, kind?: 'personal'|'eip191' (default personal) }
+// Response: { address, signature }
+
+import { z } from 'zod';
+import { Wallet } from 'ethers';
+import { sql } from '../../_lib/db.js';
+import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';
+import { recoverAgentKey } from '../../_lib/agent-wallet.js';
+import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
+import { limits, clientIp } from '../../_lib/rate-limit.js';
+import { parse } from '../../_lib/validate.js';
+
+const signBody = z.object({
+ // EIP-191 personal messages — what wallets sign today. Keep the upper bound
+ // generous for signed action JSON / SIWE-like payloads the agent emits.
+ message: z.string().min(1).max(8192),
+ kind: z.enum(['personal']).default('personal'),
+});
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const id = req.query?.id || new URL(req.url, 'http://x').pathname.split('/').filter(Boolean)[2];
+ if (!id) return error(res, 400, 'invalid_request', 'agent id required');
+
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+
+ // Rate limit — signing decrypts a private key; keep the budget tight.
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many sign requests');
+
+ const [row] = await sql`
+ SELECT id, user_id, wallet_address, meta
+ FROM agent_identities
+ WHERE id = ${id} AND deleted_at IS NULL
+ LIMIT 1
+ `;
+ if (!row) return error(res, 404, 'not_found', 'agent not found');
+ if (row.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');
+
+ const encryptedKey = row.meta?.encrypted_wallet_key;
+ if (!encryptedKey) return error(res, 409, 'no_wallet', 'agent has no server wallet');
+
+ const body = parse(signBody, await readJson(req));
+
+ let signature;
+ try {
+ const pkHex = await recoverAgentKey(encryptedKey);
+ const wallet = new Wallet(pkHex);
+ signature = await wallet.signMessage(body.message);
+ } catch (e) {
+ console.error('[agents/sign] signing failed', e);
+ return error(res, 500, 'sign_failed', 'could not sign message');
+ }
+
+ return json(res, 200, { address: row.wallet_address, signature });
+});
+
+async function resolveAuth(req) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return { userId: bearer.userId };
+ return null;
+}
diff --git a/api/widgets/[id].js b/api/widgets/[id].js
new file mode 100644
index 000000000..8bb099d26
--- /dev/null
+++ b/api/widgets/[id].js
@@ -0,0 +1,125 @@
+/**
+ * Widget by id — GET (public/private), PATCH (owner), DELETE (owner)
+ * -------------------------------------------------------------------
+ * GET /api/widgets/:id — public if is_public, else owner-only.
+ * Joins avatar so caller has model_url + thumbnail
+ * in a single round-trip (Studio + dashboard).
+ * PATCH /api/widgets/:id — owner-only. Updates name/config/is_public/avatar_id.
+ * DELETE /api/widgets/:id — owner-only. Soft-delete via deleted_at.
+ *
+ * View counter: GET increments view_count when the caller is unauthenticated
+ * OR not the owner. Owner previews shouldn't pollute their own analytics.
+ */
+
+import { z } from 'zod';
+
+import { sql } from '../_lib/db.js';
+import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
+import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
+import { parse } from '../_lib/validate.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { decorate } from './index.js';
+
+const WIDGET_TYPES = ['turntable', 'animation-gallery', 'talking-agent', 'passport', 'hotspot-tour'];
+
+const patchSchema = z.object({
+ name: z.string().trim().min(1).max(120).optional(),
+ config: z.record(z.any()).optional(),
+ is_public: z.boolean().optional(),
+ avatar_id: z.string().uuid().nullable().optional(),
+ type: z.enum(WIDGET_TYPES).optional(),
+});
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,PATCH,DELETE,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'PATCH', 'DELETE'])) return;
+
+ const id = idFromReq(req);
+ if (!id) return error(res, 400, 'invalid_request', 'id required');
+
+ const auth = await resolveAuth(req);
+
+ if (req.method === 'GET') {
+ const rl = await limits.widgetRead(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const rows = await sql`
+ select w.id, w.user_id, w.avatar_id, w.type, w.name, w.config, w.is_public,
+ w.view_count, w.created_at, w.updated_at,
+ a.name as avatar_name, a.thumbnail_key as avatar_thumbnail_key,
+ a.storage_key as avatar_storage_key, a.visibility as avatar_visibility
+ from widgets w
+ left join avatars a on a.id = w.avatar_id and a.deleted_at is null
+ where w.id = ${id} and w.deleted_at is null
+ limit 1
+ `;
+ const row = rows[0];
+ if (!row) return error(res, 404, 'not_found', 'widget not found');
+
+ const isOwner = !!auth?.userId && auth.userId === row.user_id;
+ if (!row.is_public && !isOwner) return error(res, 404, 'not_found', 'widget not found');
+
+ // Owner viewing in dashboard/studio shouldn't bump counts.
+ if (!isOwner) {
+ sql`update widgets set view_count = view_count + 1 where id = ${id}`.catch(() => {});
+ }
+
+ return json(res, 200, { widget: decorate(row) });
+ }
+
+ if (!auth?.userId) return error(res, 401, 'unauthorized', 'authentication required');
+ if (auth.source === 'oauth' || auth.source === 'apikey') {
+ const need = req.method === 'DELETE' ? 'avatars:delete' : 'avatars:write';
+ if (!hasScope(auth.scope, need)) return error(res, 403, 'insufficient_scope', `${need} required`);
+ }
+
+ const rl = await limits.widgetWrite(auth.userId);
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ if (req.method === 'PATCH') {
+ const patch = parse(patchSchema, await readJson(req));
+
+ if (patch.avatar_id) {
+ const owns = await sql`
+ select 1 from avatars where id = ${patch.avatar_id} and owner_id = ${auth.userId} and deleted_at is null limit 1
+ `;
+ if (!owns[0]) return error(res, 400, 'invalid_avatar', 'avatar_id not found or not owned by caller');
+ }
+
+ const [row] = await sql`
+ update widgets set
+ name = coalesce(${patch.name ?? null}, name),
+ config = coalesce(${patch.config ? JSON.stringify(patch.config) : null}::jsonb, config),
+ is_public = coalesce(${patch.is_public ?? null}::boolean, is_public),
+ avatar_id = case when ${patch.avatar_id !== undefined} then ${patch.avatar_id ?? null}::uuid else avatar_id end,
+ type = coalesce(${patch.type ?? null}, type)
+ where id = ${id} and user_id = ${auth.userId} and deleted_at is null
+ returning id, user_id, avatar_id, type, name, config, is_public, view_count, created_at, updated_at
+ `;
+ if (!row) return error(res, 404, 'not_found', 'widget not found or not yours');
+ return json(res, 200, { widget: decorate(row) });
+ }
+
+ // DELETE — soft delete so existing embeds get a clean 404 rather than orphan rows.
+ const rows = await sql`
+ update widgets set deleted_at = now()
+ where id = ${id} and user_id = ${auth.userId} and deleted_at is null
+ returning id
+ `;
+ if (!rows[0]) return error(res, 404, 'not_found', 'widget not found or not yours');
+ return json(res, 200, { ok: true });
+});
+
+function idFromReq(req) {
+ const fromQuery = req.query?.id;
+ if (typeof fromQuery === 'string' && fromQuery) return fromQuery;
+ const path = new URL(req.url, 'http://x').pathname;
+ const m = path.match(/\/api\/widgets\/([^/]+)/);
+ return m ? decodeURIComponent(m[1]) : null;
+}
+
+async function resolveAuth(req) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id, source: 'session', scope: 'avatars:read avatars:write avatars:delete' };
+ return await authenticateBearer(extractBearer(req));
+}
diff --git a/api/widgets/[id]/duplicate.js b/api/widgets/[id]/duplicate.js
new file mode 100644
index 000000000..2f8957d0b
--- /dev/null
+++ b/api/widgets/[id]/duplicate.js
@@ -0,0 +1,70 @@
+/**
+ * POST /api/widgets/:id/duplicate
+ * -------------------------------
+ * Owner-only. Clones a widget (config, type, avatar_id, is_public) under a new
+ * id with name "<original> (copy)". Returns the new widget so the dashboard
+ * can prepend it to the grid without re-fetching.
+ */
+
+import crypto from 'node:crypto';
+
+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 { limits } from '../../_lib/rate-limit.js';
+import { decorate } from '../index.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const id = idFromReq(req);
+ if (!id) return error(res, 400, 'invalid_request', 'id required');
+
+ const auth = await resolveAuth(req);
+ if (!auth?.userId) return error(res, 401, 'unauthorized', 'authentication required');
+ if (auth.source === 'oauth' || auth.source === 'apikey') {
+ if (!hasScope(auth.scope, 'avatars:write')) return error(res, 403, 'insufficient_scope', 'avatars:write required');
+ }
+
+ const rl = await limits.widgetWrite(auth.userId);
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const [src] = await sql`
+ select id, type, name, config, avatar_id, is_public
+ from widgets
+ where id = ${id} and user_id = ${auth.userId} and deleted_at is null
+ limit 1
+ `;
+ if (!src) return error(res, 404, 'not_found', 'widget not found or not yours');
+
+ const newId = 'wdgt_' + crypto.randomBytes(9).toString('base64url');
+ const newName = trim(`${src.name} (copy)`, 120);
+
+ const [row] = await sql`
+ insert into widgets (id, user_id, avatar_id, type, name, config, is_public)
+ values (${newId}, ${auth.userId}, ${src.avatar_id}, ${src.type}, ${newName},
+ ${JSON.stringify(src.config || {})}::jsonb, ${src.is_public})
+ returning id, user_id, avatar_id, type, name, config, is_public, view_count, created_at, updated_at
+ `;
+
+ return json(res, 201, { widget: decorate(row) });
+});
+
+function trim(s, max) {
+ return s.length <= max ? s : s.slice(0, max);
+}
+
+function idFromReq(req) {
+ const fromQuery = req.query?.id;
+ if (typeof fromQuery === 'string' && fromQuery) return fromQuery;
+ const path = new URL(req.url, 'http://x').pathname;
+ const m = path.match(/\/api\/widgets\/([^/]+)\/duplicate/);
+ return m ? decodeURIComponent(m[1]) : null;
+}
+
+async function resolveAuth(req) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id, source: 'session', scope: 'avatars:read avatars:write' };
+ return await authenticateBearer(extractBearer(req));
+}
diff --git a/api/widgets/[id]/stats.js b/api/widgets/[id]/stats.js
new file mode 100644
index 000000000..c218a8ff5
--- /dev/null
+++ b/api/widgets/[id]/stats.js
@@ -0,0 +1,143 @@
+/**
+ * GET /api/widgets/:id/stats
+ * --------------------------
+ * Owner-only. Returns aggregate analytics for the widget:
+ * {
+ * view_count: <bigint cumulative>,
+ * last_viewed_at: <iso|null>,
+ * recent_views_7d:[ { day, count }, … 8 entries ascending — UTC ],
+ * top_referers: [ { host, count }, … up to 5 ],
+ * top_countries: [ { country, count }, … up to 5 ],
+ * chat_count: <int|null> // best-effort, null when unsupported
+ * }
+ *
+ * Best-effort throughout: missing widget_views or chat tables don't 500 — they
+ * return zero/empty arrays so the dashboard's sparkline can still render an
+ * "all-zero" state without special casing.
+ */
+
+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';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const id = idFromReq(req);
+ if (!id) return error(res, 400, 'invalid_request', 'id required');
+
+ const auth = await resolveAuth(req);
+ if (!auth?.userId) return error(res, 401, 'unauthorized', 'authentication required');
+ if (auth.source === 'oauth' || auth.source === 'apikey') {
+ if (!hasScope(auth.scope, 'avatars:read')) return error(res, 403, 'insufficient_scope', 'avatars:read required');
+ }
+
+ // Ownership check — never 404 vs 403 leak: collapse to 404 either way.
+ const [w] = await sql`
+ select id, type, view_count
+ from widgets
+ where id = ${id} and user_id = ${auth.userId} and deleted_at is null
+ limit 1
+ `;
+ if (!w) return error(res, 404, 'not_found', 'widget not found or not yours');
+
+ const [recentViews, topReferers, topCountries, lastViewed, chatCount] = await Promise.all([
+ recentViewsByDay(id),
+ topAggregates(id, 'referer_host'),
+ topAggregates(id, 'country'),
+ lastViewedAt(id),
+ chatCountFor(id, w.type),
+ ]);
+
+ res.setHeader('cache-control', 'private, max-age=30');
+ return json(res, 200, {
+ stats: {
+ view_count: Number(w.view_count || 0),
+ last_viewed_at: lastViewed,
+ recent_views_7d: recentViews,
+ top_referers: topReferers,
+ top_countries: topCountries,
+ chat_count: chatCount,
+ },
+ });
+});
+
+async function recentViewsByDay(id) {
+ // Always return 8 days (today + previous 7) so the sparkline doesn't have
+ // to reason about gaps. 0-fill missing days from the actual rows.
+ const days = [];
+ const today = startOfUtcDay(new Date());
+ for (let i = 7; i >= 0; i--) {
+ const d = new Date(today.getTime() - i * 86400_000);
+ days.push({ day: d.toISOString().slice(0, 10), count: 0 });
+ }
+ try {
+ const rows = await sql`
+ select date_trunc('day', created_at)::date::text as day, count(*)::bigint as count
+ from widget_views
+ where widget_id = ${id} and created_at >= ${days[0].day}::date
+ group by 1 order by 1
+ `;
+ const idx = new Map(days.map((d, i) => [d.day, i]));
+ for (const r of rows) {
+ const i = idx.get(r.day);
+ if (i !== undefined) days[i].count = Number(r.count);
+ }
+ } catch (err) {
+ if (!/relation .* does not exist/i.test(err?.message || '')) throw err;
+ }
+ return days;
+}
+
+async function topAggregates(id, column) {
+ try {
+ const rows = await sql.query(
+ `select coalesce(${column}, '') as key, count(*)::bigint as count
+ from widget_views
+ where widget_id = $1 and ${column} is not null
+ group by 1 order by count desc limit 5`,
+ [id],
+ );
+ return rows.map((r) => ({ [column === 'referer_host' ? 'host' : 'country']: r.key, count: Number(r.count) }));
+ } catch (err) {
+ if (/relation .* does not exist/i.test(err?.message || '')) return [];
+ throw err;
+ }
+}
+
+async function lastViewedAt(id) {
+ try {
+ const rows = await sql`select max(created_at) as t from widget_views where widget_id = ${id}`;
+ return rows[0]?.t || null;
+ } catch (err) {
+ if (/relation .* does not exist/i.test(err?.message || '')) return null;
+ throw err;
+ }
+}
+
+// Talking-agent widget chats live in agent_actions (Prompt 03 will wire this).
+// Until that table-or-source is finalized, return null so the UI knows to hide
+// the chat stat line for non-talking-agent types and for un-instrumented ones.
+async function chatCountFor(_id, type) {
+ if (type !== 'talking-agent') return null;
+ return null;
+}
+
+function startOfUtcDay(d) {
+ return new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()));
+}
+
+function idFromReq(req) {
+ const fromQuery = req.query?.id;
+ if (typeof fromQuery === 'string' && fromQuery) return fromQuery;
+ const path = new URL(req.url, 'http://x').pathname;
+ const m = path.match(/\/api\/widgets\/([^/]+)\/stats/);
+ return m ? decodeURIComponent(m[1]) : null;
+}
+
+async function resolveAuth(req) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id, source: 'session', scope: 'avatars:read avatars:write' };
+ return await authenticateBearer(extractBearer(req));
+}
diff --git a/api/widgets/index.js b/api/widgets/index.js
new file mode 100644
index 000000000..ca847d9e1
--- /dev/null
+++ b/api/widgets/index.js
@@ -0,0 +1,121 @@
+/**
+ * Widget CRUD — list + create
+ * ---------------------------
+ * GET /api/widgets — list current user's widgets
+ * POST /api/widgets — create a new widget for current user
+ *
+ * Auth: session cookie or bearer (avatars:read for list, avatars:write for create).
+ * Widget IDs: 'wdgt_' + 12 url-safe random chars (crypto.randomBytes(9).base64url).
+ */
+
+import crypto from 'node:crypto';
+import { z } from 'zod';
+
+import { sql } from '../_lib/db.js';
+import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
+import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
+import { parse } from '../_lib/validate.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { publicUrl } from '../_lib/r2.js';
+
+const WIDGET_TYPES = ['turntable', 'animation-gallery', 'talking-agent', 'passport', 'hotspot-tour'];
+
+const createBody = z.object({
+ type: z.enum(WIDGET_TYPES),
+ name: z.string().trim().min(1).max(120),
+ avatar_id: z.string().uuid().nullable().optional(),
+ config: z.record(z.any()).default({}),
+ is_public: z.boolean().default(true),
+});
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ const auth = await resolveAuth(req, req.method === 'POST' ? 'avatars:write' : 'avatars:read');
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in or provide a valid bearer token');
+
+ if (req.method === 'GET') {
+ const rl = await limits.widgetRead(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const rows = await sql`
+ select w.id, w.user_id, w.avatar_id, w.type, w.name, w.config, w.is_public,
+ w.view_count, w.created_at, w.updated_at,
+ a.name as avatar_name, a.thumbnail_key as avatar_thumbnail_key,
+ a.storage_key as avatar_storage_key, a.visibility as avatar_visibility
+ from widgets w
+ left join avatars a on a.id = w.avatar_id and a.deleted_at is null
+ where w.user_id = ${auth.userId} and w.deleted_at is null
+ order by w.updated_at desc
+ limit 500
+ `;
+ return json(res, 200, { widgets: rows.map(decorate) });
+ }
+
+ // POST
+ const rl = await limits.widgetWrite(auth.userId);
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const body = parse(createBody, await readJson(req));
+
+ if (body.avatar_id) {
+ const owns = await sql`
+ select 1 from avatars where id = ${body.avatar_id} and owner_id = ${auth.userId} and deleted_at is null limit 1
+ `;
+ if (!owns[0]) return error(res, 400, 'invalid_avatar', 'avatar_id not found or not owned by caller');
+ }
+
+ const id = newWidgetId();
+ const [row] = await sql`
+ insert into widgets (id, user_id, avatar_id, type, name, config, is_public)
+ values (${id}, ${auth.userId}, ${body.avatar_id ?? null}, ${body.type}, ${body.name},
+ ${JSON.stringify(body.config)}::jsonb, ${body.is_public})
+ returning id, user_id, avatar_id, type, name, config, is_public, view_count, created_at, updated_at
+ `;
+ return json(res, 201, { widget: decorate(row) });
+});
+
+async function resolveAuth(req, requiredScope) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id, source: 'session' };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (!bearer) return null;
+ if (!hasScope(bearer.scope, requiredScope)) return null;
+ return bearer;
+}
+
+function newWidgetId() {
+ return 'wdgt_' + crypto.randomBytes(9).toString('base64url');
+}
+
+export function decorate(row) {
+ const out = {
+ id: row.id,
+ user_id: row.user_id,
+ avatar_id: row.avatar_id,
+ type: row.type,
+ name: row.name,
+ config: row.config || {},
+ is_public: row.is_public,
+ view_count: Number(row.view_count || 0),
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ };
+ if (row.avatar_name !== undefined) {
+ out.avatar = row.avatar_id ? {
+ id: row.avatar_id,
+ name: row.avatar_name,
+ thumbnail_url: safePublicUrl(row.avatar_thumbnail_key),
+ model_url: (row.avatar_visibility === 'public' || row.avatar_visibility === 'unlisted')
+ ? safePublicUrl(row.avatar_storage_key) : null,
+ visibility: row.avatar_visibility,
+ } : null;
+ }
+ return out;
+}
+
+function safePublicUrl(key) {
+ if (!key) return null;
+ try { return publicUrl(key); } catch { return null; }
+}
diff --git a/features.css b/features.css
index 033a1467d..1b2352bb4 100644
--- a/features.css
+++ b/features.css
@@ -792,6 +792,47 @@
visibility: hidden;
}
+/* ── Dragon mode (?pretext=4) ────────────────────────────────────────────── */
+
+/*
+ * Activated by src/features/hero-dragon.js. The avatar detaches from its grid
+ * column and is positioned absolutely within .hero so it can chase the cursor
+ * via transform. The content column expands to full hero width so Pretext has
+ * more room to reflow the subtitle around the moving silhouette.
+ */
+.hero--dragon {
+ position: relative;
+}
+
+.hero--dragon .hero-content {
+ grid-column: 1 / -1;
+ max-width: none;
+ z-index: 2;
+}
+
+.hero--dragon .hero-subtitle-pretext {
+ max-width: none;
+}
+
+.hero--dragon .hero-avatar {
+ position: absolute;
+ top: 0;
+ right: 0;
+ z-index: 3;
+ justify-self: auto;
+ transform: translate3d(0, 0, 0);
+ transition: none;
+}
+
+/* The ring/pulse/tag decorations read as static UI chrome — hide them while
+ * the avatar roams so the silhouette reads as the hero of the composition. */
+.hero--dragon .hero-avatar-ring,
+.hero--dragon .hero-avatar-pulse,
+.hero--dragon .hero-avatar-tag {
+ opacity: 0;
+ transition: opacity 0.4s ease;
+}
+
/* ── Responsive ──────────────────────────────────────────────────────────── */
/* Tablet — keep two columns but tighten the split */
diff --git a/prompts/INDEX.md b/prompts/INDEX.md
new file mode 100644
index 000000000..294e27150
--- /dev/null
+++ b/prompts/INDEX.md
@@ -0,0 +1,51 @@
+# Priority Stack — Dispatch Index
+
+The **only** goal. Six bands, in order. Everything else is secondary until these ship.
+
+1. **Wallet auth, 100%** — SIWE end-to-end. A user can sign in with MetaMask / Privy / WalletConnect and stay signed in. No email required.
+2. **Selfie → agent** — User takes a photo in-browser; we return a rigged 3D avatar bound to their identity.
+3. **Edit avatars** — Material/texture/scene editing on an existing avatar (partially shipped), plus regenerate-from-photo and variants.
+4. **View + embed** — Public viewer and embeddable snippet (partially shipped); polish, share flow, and per-agent settings.
+5. **Portable embed (Claude.ai + LobeHub)** — The agent shows up *inside* a chat surface looking embodied, not as JSON.
+6. **On-chain deployment** — Agent identity lives on-chain; any host (LobeHub, Claude) can summon the same avatar from the address alone.
+
+## Dispatch order
+
+Each band is a folder. Prompts inside a band can run in parallel unless they touch the same file.
+
+- [wallet-auth/](./wallet-auth/) — band 1
+- [selfie-onboarding/](./selfie-onboarding/) — band 2
+- [avatar-editing/](./avatar-editing/) — band 3
+- [portable-embed/](./portable-embed/) — band 4 (view + embed polish)
+- [claude-lobehub/](./claude-lobehub/) — band 5 (chat-surface integration)
+- [onchain/](./onchain/) — band 6
+
+Don't skip bands. Band 2 depends on band 1 (we need to know *who* owns the agent before generating one). Band 5 depends on band 4 (embed must work on a regular page before it works inside Claude). Band 6 depends on band 1 (wallet = onchain identity).
+
+## House rules for every prompt
+
+- One deliverable per prompt, one PR per prompt.
+- No scope creep. If something outside the prompt needs fixing, note it in the reporting section — do not fix it.
+- Cite exact file paths and line numbers. Don't invent APIs; read the existing code.
+- Prefer editing existing files to creating new ones.
+- Test path: `node --check` the new JS, `npx vite build`, then manual smoke.
+- Output a reporting block at the end: what shipped, what was skipped, what broke, unrelated bugs noticed.
+
+## What's already shipped (don't redo)
+
+- `src/editor/*` — material editor, scene explorer, texture inspector (see `.github/prompts/material-editor.md`, `scene-graph-explorer.md`, `texture-inspector.md`)
+- `api/mcp.js` — MCP tools including `validate_model`, `inspect_model`, `optimize_model`
+- `api/_lib/fetch-model.js` — SSRF-hardened URL fetcher
+- `public/.well-known/agent-card.json` — A2A discovery with 8 skills
+- `src/erc8004/agent-registry.js` — wallet connect via Privy / injected provider (used for ERC-8004 registration, *not yet* for user auth)
+- `src/agent-identity.js`, `src/agent-memory.js`, `src/agent-protocol.js`, `src/agent-avatar.js`, `src/agent-home.js` — the agent runtime (Empathy Layer etc.)
+
+## What we are NOT prioritizing right now
+
+- Pretext rebrand (`prompts/pretext/`) — shipped / shelved
+- Widget studio (`prompts/widget-studio/`) — secondary
+- Scalability (`prompts/scalability/`) — revisit when traffic shape is known
+- Embed referrer allowlist (`prompts/embed/03-embed-allowlist.md`) — nice-to-have, not core
+- CLI tool, AR quick-look, side-by-side diff, screenshot export — all secondary
+
+Agents should not start those without explicit user direction.
diff --git a/prompts/README.md b/prompts/README.md
new file mode 100644
index 000000000..1d9b97fc1
--- /dev/null
+++ b/prompts/README.md
@@ -0,0 +1,40 @@
+# Build prompts — priority stack
+
+Self-contained task prompts for building the 3D Agent platform toward the **CZ demo**: a user (starting with CZ) signs in with their wallet, sees their own embodied avatar agent, can embed it into LobeHub / Claude, and its identity lives onchain.
+
+Each file is designed to be dropped into a fresh Claude Code agent without extra context.
+
+## The priority stack (build in this order)
+
+| Layer | Directory | Ship state |
+|---|---|---|
+| 1. Wallet auth 100% | [wallet-auth/](./wallet-auth/) | Foundation. SIWE login + link-to-user + fix `/api/agents/me` 500. |
+| 2. Selfie → agent | [selfie-agent/](./selfie-agent/) | The magic moment — photo capture becomes a personal avatar. |
+| 3. Edit avatar | [avatar-edit/](./avatar-edit/) | Post-creation morph / outfit / accessory editing. |
+| 4. View + embed | existing `/agent/:id` + [embed/](./embed/) | Mostly working. Polish prompts exist in `embed/`. |
+| 5. Claude / LobeHub embed | [lobehub-embed/](./lobehub-embed/), [claude-artifact/](./claude-artifact/) | Agent renders embodied inside host chats. Primary integration target. |
+| 6. Onchain | [onchain/](./onchain/) | Deploy ERC-8004 contracts, register, hydrate agent from chain. |
+| 🎯 CZ demo | [cz-demo/](./cz-demo/) | Bespoke landing + pre-registered cz.glb onchain + scripted first interaction. |
+
+## Side lanes (not blockers for CZ demo)
+
+Do not open these while anything in the priority stack above is broken:
+
+- [pretext/](./pretext/) — hero text / dragon / gaze-follow polish
+- [scalability/](./scalability/) — dispose / render-on-demand / module-split
+- [widget-studio/](./widget-studio/) — turntable, animation gallery, passport, hotspot tour
+- [embed/03-embed-allowlist.md](./embed/03-embed-allowlist.md) — referrer allowlist
+
+## Rules that apply to every task
+
+- No new runtime dependencies unless the task file explicitly allows them.
+- No new docs (README.md, CLAUDE.md) unless the task says so.
+- `node --check` every modified JS file before reporting done.
+- `npx vite build` and report the result. The pre-existing `@avaturn/sdk` resolution warning is unrelated — ignore.
+- Respect `Files off-limits` sections — other tasks may be editing them.
+- If you discover an unrelated bug, note it in your report. Do not fix it in the same change.
+- Stay on one task end-to-end. Do not silently hop to adjacent concerns.
+
+## Reporting
+
+Each task ends with a short report: files created, files edited (which sections), commands run and their output, manual verification URLs, any surprises.
diff --git a/prompts/agent-3d/01-openai-provider.md b/prompts/agent-3d/01-openai-provider.md
new file mode 100644
index 000000000..c3e9e01ba
--- /dev/null
+++ b/prompts/agent-3d/01-openai-provider.md
@@ -0,0 +1,63 @@
+# Task 01 — OpenAI brain provider
+
+## Context
+
+The runtime currently ships with an Anthropic provider at [src/runtime/providers.js](../../src/runtime/providers.js) and a no-op `NullProvider`. The `createProvider()` factory throws for any other provider string. We want parity for OpenAI so developers can pick their model provider in a manifest or via the `brain` attribute on `<agent-3d>`.
+
+OpenAI's tool-use shape differs from Anthropic's. The runtime's `_loop()` in [src/runtime/index.js](../../src/runtime/index.js) consumes a normalized result `{ text, toolCalls: [{ id, name, input }], thinking, stopReason }` and hands back `provider.formatAssistantWithToolCalls(...)` and `provider.formatToolResults(...)` — the provider encapsulates both directions of the API shape.
+
+## Goal
+
+Add `OpenAIProvider` to [src/runtime/providers.js](../../src/runtime/providers.js) with full tool-use parity and identical normalized output, so the runtime is provider-agnostic and `manifest.brain.provider: "openai"` just works.
+
+## Deliverable
+
+1. **`OpenAIProvider` class** in [src/runtime/providers.js](../../src/runtime/providers.js):
+ - Constructor accepts `{ model, proxyURL, apiKey, temperature, maxTokens }`. Default model: `gpt-4o-2024-11-20`.
+ - `async complete({ system, messages, tools })` — POST to `${proxyURL}/v1/chat/completions` (or `https://api.openai.com/v1/chat/completions` if `apiKey` passed directly). Respect the `key-proxy` pattern from [specs/EMBED_SPEC.md](../../specs/EMBED_SPEC.md) — never send raw API keys to the browser unless explicitly provided.
+ - Convert Anthropic-shaped `messages` (already flowing through the runtime) into OpenAI's chat format:
+ - `role: "assistant"` messages with `content: [{ type: "tool_use", id, name, input }]` → OpenAI's `tool_calls: [{ id, type: "function", function: { name, arguments: JSON.stringify(input) } }]`.
+ - `role: "user"` messages with `content: [{ type: "tool_result", tool_use_id, content }]` → OpenAI's `role: "tool", tool_call_id, content`.
+ - Convert tool schemas: Anthropic's `{ name, description, input_schema }` → OpenAI's `{ type: "function", function: { name, description, parameters } }`.
+ - Normalize response to `{ text, toolCalls, thinking: "", stopReason }`.
+ - `formatAssistantWithToolCalls(text, toolCalls)` must round-trip through the runtime untouched — meaning the Anthropic-shape message objects the runtime stores are OK; the conversion happens inside `complete()` on the way out.
+2. **Register in `createProvider()`** — extend the factory to dispatch `provider === "openai"`.
+3. **Update [specs/AGENT_MANIFEST.md](../../specs/AGENT_MANIFEST.md)** — add `openai` to the `brain.provider` enum line and list representative model ids.
+
+## Audit checklist
+
+- [ ] `OpenAIProvider.complete()` returns the same normalized shape as `AnthropicProvider.complete()` — including empty `thinking` string.
+- [ ] Tool calls flow end-to-end: a skill declares a tool, runtime calls it, response is consumed by OpenAI, runtime dispatches, result message is built, OpenAI receives it on the next turn.
+- [ ] `messages` array format the runtime maintains does NOT diverge between providers — conversion is provider-local.
+- [ ] Multiple tool calls in one assistant turn are supported (OpenAI returns them as an array).
+- [ ] `system` is passed as a prepended `{ role: "system" }` message since OpenAI doesn't have a dedicated `system` top-level field.
+- [ ] Errors surface with provider + status in the message (`OpenAI 429: ...`).
+- [ ] No API key leaks to the DOM even when `api-key` attribute is set (stay behind fetch — don't log the request body).
+- [ ] Works with `brain="gpt-4o-mini"` on `<agent-3d>` as a shortcut (element already passes `brain` → `manifest.brain.model`).
+
+## Constraints
+
+- No new npm dependencies. Use `fetch`.
+- Do not introduce streaming in this task — a follow-up can add SSE.
+- Do not touch [src/runtime/index.js](../../src/runtime/index.js) except to add OpenAI to an allowlist comment if one exists. The provider must conform to the existing `Runtime._loop()` contract.
+- Do not read any existing OpenAI SDK — we stay vanilla fetch for bundle-size reasons.
+
+## Verification
+
+1. `node --check src/runtime/providers.js`.
+2. `npm run build:lib` passes.
+3. Write a tiny local harness in `scratch/openai-smoke.js` (gitignored or deleted after): instantiate `OpenAIProvider` with a real key, send a prompt that forces a tool call with a fake tool schema, confirm the normalized response shape. Delete the harness after confirming.
+4. In a browser, set `<agent-3d manifest="..." brain="gpt-4o-mini" key-proxy="http://localhost:8787/openai">` with a local proxy that forwards to OpenAI, confirm the agent replies.
+
+## Scope boundaries — do NOT do these
+
+- Do not implement streaming / SSE / partial token handling.
+- Do not add OpenAI-specific features (o1 reasoning, assistants API, vision) — those are separate tasks.
+- Do not invent a new normalized shape. Match Anthropic's exactly.
+- Do not change the manifest schema beyond adding `openai` to the enum line.
+
+## Reporting
+
+- Confirm the tool-use round-trip worked end-to-end (include a copy-paste of the request + response logs from your smoke test, redacted).
+- Flag any behavior difference between providers that leaked into the runtime (there should be zero).
+- Note token usage differences observed (OpenAI prices differently; operators may want to see this in future telemetry).
diff --git a/prompts/agent-3d/02-elevenlabs-tts.md b/prompts/agent-3d/02-elevenlabs-tts.md
new file mode 100644
index 000000000..f335974d5
--- /dev/null
+++ b/prompts/agent-3d/02-elevenlabs-tts.md
@@ -0,0 +1,62 @@
+# Task 02 — ElevenLabs TTS provider
+
+## Context
+
+TTS is currently browser-only (`BrowserTTS` in [src/runtime/speech.js](../../src/runtime/speech.js)) — good for ubiquity, bad for character. An agent with a distinct, crafted voice needs higher-quality synthesis. ElevenLabs is the common choice for real-time voice synthesis with recognizable timbre and low latency.
+
+The factory `createTTS({ provider })` dispatches on `provider` and currently throws for anything other than `"browser"` or `"none"`.
+
+## Goal
+
+Add `ElevenLabsTTS` to [src/runtime/speech.js](../../src/runtime/speech.js) that ships a proxy-friendly, streaming-audio-aware implementation behind the same `speak(text)` / `cancel()` / `speaking` interface, so switching providers is a manifest field.
+
+## Deliverable
+
+1. **`ElevenLabsTTS` class** in [src/runtime/speech.js](../../src/runtime/speech.js):
+ - Constructor: `{ voiceId, modelId = "eleven_turbo_v2_5", apiKey, proxyURL, rate = 1, pitch = 1, lang = "en-US" }`.
+ - `async speak(text, { onStart, onEnd })` — POST to ElevenLabs `text-to-speech/{voiceId}/stream` endpoint (via `proxyURL` if set, else direct with `apiKey`). Stream the audio response via `MediaSource` or fall back to buffered `<audio>` playback if the browser doesn't support MSE for `audio/mpeg`.
+ - `cancel()` aborts the fetch and stops playback. Set `this._speaking = false`.
+ - Respect `rate` and `pitch` by mapping to ElevenLabs' `voice_settings` (`stability`, `similarity_boost`, `style`, `use_speaker_boost`) where reasonable. Document mapping choice in a code comment.
+ - Same public surface as `BrowserTTS`: `speak`, `cancel`, `speaking` getter.
+2. **Register in `createTTS()`** — dispatch `provider === "elevenlabs"`.
+3. **Update [specs/AGENT_MANIFEST.md](../../specs/AGENT_MANIFEST.md)** — extend the `voice.tts.provider` enum to include `"elevenlabs"` with a note about `voiceId` and `modelId` fields.
+4. **Update [specs/EMBED_SPEC.md](../../specs/EMBED_SPEC.md)** — document that `tts="elevenlabs:{voiceId}"` on the element is shorthand. Parser lives in [src/element.js](../../src/element.js).
+
+## Audit checklist
+
+- [ ] Streaming playback starts within ~500ms on a fast connection — first audio chunk plays before the full response is received.
+- [ ] `cancel()` interrupts mid-utterance immediately; the next `speak()` begins cleanly.
+- [ ] `speaking` transitions true → false only when audio fully ends (or is canceled).
+- [ ] `onStart` fires on first audible frame, `onEnd` on final frame or abort.
+- [ ] Fallback to buffered playback works in Safari for `audio/mpeg` (MediaSource limitations).
+- [ ] No API key appears in DevTools Network tab when `proxyURL` is used.
+- [ ] Works with the runtime's voice event dispatch — `voice:speech-start` / `voice:speech-end` fire correctly.
+- [ ] `prefers-reduced-motion: reduce` does NOT affect TTS (it's motion-only) — do not gate on it.
+
+## Constraints
+
+- No new npm dependencies. Use `fetch` + `MediaSource` + `AudioContext` as needed.
+- Do not introduce Web Audio graph routing, EQ, or per-word timing — keep to play/stop.
+- Browser-side only; the proxy is outside this task's scope (but document its expected request/response shape).
+- Do not touch [src/runtime/index.js](../../src/runtime/index.js).
+
+## Verification
+
+1. `node --check src/runtime/speech.js`.
+2. `npm run build:lib` passes.
+3. Manual: configure an agent with `voice.tts.provider = "elevenlabs"` and a test voice id; confirm audible speech and cancel behavior in Chrome + Safari + Firefox.
+4. Network panel: confirm no raw api key when `proxyURL` is configured.
+
+## Scope boundaries — do NOT do these
+
+- Do not add voice cloning, voice selection UI, or custom pronunciation dictionaries.
+- Do not attempt to sync mouth shapes / visemes to phonemes — that's a separate task (lipsync).
+- Do not wire an ElevenLabs agent (their "conversational AI" product) — we're using TTS only.
+- Do not add billing/quota tracking.
+
+## Reporting
+
+- Note the chosen `voice_settings` mapping for `rate`/`pitch` and whether it felt natural.
+- Report startup latency observed (first byte → first audible frame).
+- Document the proxy request shape you assumed (for the follow-up backend task).
+- Flag any browser where streaming audio did not work and what fallback kicked in.
diff --git a/prompts/agent-3d/03-whisper-stt.md b/prompts/agent-3d/03-whisper-stt.md
new file mode 100644
index 000000000..5170c004a
--- /dev/null
+++ b/prompts/agent-3d/03-whisper-stt.md
@@ -0,0 +1,66 @@
+# Task 03 — Whisper STT provider
+
+## Context
+
+Browser-native `SpeechRecognition` (`BrowserSTT` in [src/runtime/speech.js](../../src/runtime/speech.js)) is unreliable: Chromium-only on desktop, varying quality, cloud-dependent anyway. Whisper via the OpenAI API (or a self-hosted whisper.cpp endpoint) produces consistent transcriptions across browsers and languages.
+
+The factory `createSTT({ provider })` throws for anything other than `"browser"` or `"none"`.
+
+## Goal
+
+Add `WhisperSTT` to [src/runtime/speech.js](../../src/runtime/speech.js) that records mic audio, sends it to a Whisper endpoint, and returns transcripts — with the same `listen({ onInterim, onFinal })` surface as the browser variant.
+
+## Deliverable
+
+1. **`WhisperSTT` class** in [src/runtime/speech.js](../../src/runtime/speech.js):
+ - Constructor: `{ endpoint, apiKey, language = "en", model = "whisper-1", chunkDurationMs = 3000 }`.
+ - `endpoint` defaults to `https://api.openai.com/v1/audio/transcriptions`. Operators can point to their own whisper.cpp server by swapping.
+ - `async listen({ onInterim, onFinal })`:
+ - Request mic permission via `navigator.mediaDevices.getUserMedia({ audio: true })`.
+ - Record with `MediaRecorder` (`audio/webm;codecs=opus`).
+ - Option A (simpler): stop recording on VAD silence (see below) or when `stop()` is called, upload the full blob, emit one `onFinal(text)`.
+ - Option B (preferred): chunk recording every `chunkDurationMs`, upload each chunk, emit `onInterim(text)` per chunk, emit `onFinal(text)` on stop. Chunks are independent transcriptions; concatenate on the client.
+ - Emit VAD-based silence detection using `AudioContext` + `AnalyserNode` RMS threshold — stop recording after ~1.2s of silence unless in `continuous` mode.
+ - `stop()` — halt recording, await any in-flight transcription, resolve the `listen()` promise with accumulated text.
+ - `listening` getter.
+2. **Register in `createSTT()`**.
+3. **Update [specs/AGENT_MANIFEST.md](../../specs/AGENT_MANIFEST.md)** — add `whisper` to the `voice.stt.provider` enum, document `endpoint` and `language` fields.
+
+## Audit checklist
+
+- [ ] Mic permission is requested exactly once per session; revoked permission raises a typed error.
+- [ ] Transcription works in Chrome, Firefox, Safari (16+) — all support `MediaRecorder` with Opus.
+- [ ] VAD silence detection does not cut off the user mid-sentence (test with a 4-second pause in the middle of speaking).
+- [ ] `onInterim` fires incrementally in chunked mode; `onFinal` fires exactly once on stop.
+- [ ] Uploaded blobs are ≤ 25 MB (Whisper API limit) — chunk if longer.
+- [ ] Works behind a proxy: if `endpoint` is a relative path or non-OpenAI origin, do not send `Authorization` unless `apiKey` is explicitly passed.
+- [ ] Cleanup on `stop()`: all `MediaStreamTrack`s are stopped, `AudioContext` closed, pending fetches aborted.
+- [ ] Browser shows the mic indicator only while actively recording.
+
+## Constraints
+
+- No new npm dependencies.
+- Do not introduce WebSocket streaming (OpenAI's realtime API is a future task).
+- Do not block on missing `MediaRecorder` — raise a typed error so the runtime can fall back.
+- Do not persist audio blobs — hold them in memory for the duration of the upload, then release.
+
+## Verification
+
+1. `node --check src/runtime/speech.js`.
+2. `npm run build:lib` passes.
+3. Manual test in three browsers: speak a few sentences, confirm accurate transcription; stop mid-sentence, confirm clean abort.
+4. DevTools Memory: after 10 `listen()` sessions, no MediaRecorder or AudioContext leaks.
+
+## Scope boundaries — do NOT do these
+
+- Do not add lipsync / phoneme timing output.
+- Do not add language detection or translation — pass-through the `language` param.
+- Do not attempt offline Whisper (WASM whisper.cpp) — that's a separate task.
+- Do not change the runtime's `Runtime.listen()` method.
+
+## Reporting
+
+- Which mode (A or B) you implemented and why.
+- VAD silence threshold chosen (RMS value + window size) and how it felt.
+- Transcription latency observed (speech end → final text).
+- Any browser-specific quirks (Safari's MediaRecorder issues are known).
diff --git a/prompts/agent-3d/04-encrypted-memory.md b/prompts/agent-3d/04-encrypted-memory.md
new file mode 100644
index 000000000..7e50fdf35
--- /dev/null
+++ b/prompts/agent-3d/04-encrypted-memory.md
@@ -0,0 +1,68 @@
+# Task 04 — Encrypted IPFS memory mode
+
+## Context
+
+[src/memory/index.js](../../src/memory/index.js) currently supports `mode: "local"` and stubs `ipfs` / `encrypted-ipfs` (the spec describes them; the loader only implements local + a read-only IPFS variant).
+
+When an agent's memory carries real user PII — preferences, confessions to a coach, references to personal goals — the memory bundle MUST be encrypted to the owner wallet. Only the owner can decrypt. Other devices (same wallet) can decrypt too, which is how the agent "follows" the user across devices. See [specs/MEMORY_SPEC.md](../../specs/MEMORY_SPEC.md) § Storage modes.
+
+## Goal
+
+Implement `encrypted-ipfs` memory mode: writes are encrypted to the agent's owner wallet pubkey via an ECIES / libsodium-sealed-box equivalent, pinned to IPFS, and only the owner can read them back.
+
+## Deliverable
+
+1. **Key derivation** in `src/memory/crypto.js` (new file):
+ - Export `deriveEncryptionKey(signer)` — signs a canonical message with the wallet (via `ethers`) and HKDFs a 32-byte key. Use `ethers.hashMessage` + `signer.signMessage` patterns already used in [src/erc8004/agent-registry.js](../../src/erc8004/agent-registry.js).
+ - Export `encryptBlob(plaintext: Uint8Array, key: Uint8Array)` → `{ nonce, ciphertext }` using `crypto.subtle` (`AES-GCM`, 12-byte nonce, authenticated).
+ - Export `decryptBlob({ nonce, ciphertext }, key)` → `Uint8Array` or throws on tamper.
+2. **Extend `Memory` class** in [src/memory/index.js](../../src/memory/index.js):
+ - New static `Memory._loadEncryptedIPFS({ namespace, manifestURI, signer, pinner })` — fetch the encrypted blob from IPFS, decrypt with the derived key, parse JSON, hydrate state.
+ - New `_persistEncrypted()` method that serializes memory to JSON, encrypts, uploads via the provided `pinner`, and updates the stored CID (in localStorage for fast recovery AND optionally in `manifest.id.memoryCID` if a signer + registry write is authorized).
+ - Batch persistence: do NOT pin on every write — debounce by ~3s or a manual `flush()` call.
+3. **Pinner abstraction** — accept `pinner: (blob) => Promise<{ cid }>` so this task does not bind to a specific pinning service (see [08-ipfs-pinning-service.md](./08-ipfs-pinning-service.md)).
+4. **Element integration** — in [src/element.js](../../src/element.js)'s `_boot()`, when `manifest.memory.mode === "encrypted-ipfs"`:
+ - Require a connected signer (if none, surface `agent:error` with `{ phase: "memory", reason: "wallet-required" }`).
+ - Wire the pinner from whichever pinning service is configured (default to `window.__agent3dPinner` if present; otherwise no-op with a console warning).
+
+## Audit checklist
+
+- [ ] Encryption uses an AEAD (AES-GCM or equivalent) — no unauthenticated ciphertext.
+- [ ] Key derivation is deterministic for the same wallet so memory follows the user across devices.
+- [ ] The canonical signed message is versioned (`agent-3d:memory:v1:{agentId}`) — bump on breaking crypto changes.
+- [ ] Tamper detection: modifying the ciphertext by one byte fails decryption with a clear error, not silent corruption.
+- [ ] Debounce prevents thrashing pinning service on rapid writes.
+- [ ] Offline writes buffer in localStorage and flush when the pinner comes back online.
+- [ ] No plaintext memory ever leaves the browser — verify with a network-panel capture.
+- [ ] Loading without a signer gracefully falls back to read-only cached state (or surfaces the wallet-required error cleanly).
+- [ ] `flush()` resolves only after the CID is recorded — callers can await a durable save.
+
+## Constraints
+
+- Use `crypto.subtle` — no `node-crypto`, no polyfills, no bundle bloat.
+- No new npm dependencies (ethers is already a dep).
+- Do not commit changes to `manifest.id.memoryCID` on-chain unless the manifest explicitly opts in (`memory.onChainPointer: true`). Chain writes cost money.
+- Do not touch [src/runtime/index.js](../../src/runtime/index.js) — the Memory API surface stays the same.
+
+## Verification
+
+1. `node --check src/memory/crypto.js src/memory/index.js`.
+2. `npm run build:lib` passes.
+3. Integration smoke test in a dev page with a local wallet (hardhat, or signed MetaMask on a testnet):
+ - Write memories, refresh, confirm they load and decrypt.
+ - Use a different wallet — decryption must fail with a clear error.
+ - Flush to IPFS, fetch the CID manually, confirm content is unreadable without the key.
+
+## Scope boundaries — do NOT do these
+
+- Do not introduce multi-signer / shared memory (two wallets unlocking the same bundle). That's a future feature.
+- Do not attempt on-chain key registration — key derivation stays purely off-chain + deterministic from signatures.
+- Do not re-encrypt every write with a new nonce *and* re-pin the whole bundle if the write is a single-line append — use an append-only blob format OR debounce aggressively (pick one and document).
+- Do not mask or rotate nonces per entry — per-bundle nonce is fine given AEAD semantics.
+
+## Reporting
+
+- Chosen debounce interval + whether append-only vs full-rewrite was used.
+- Measured round-trip (write → pin → fetch → decrypt) time on a test CID.
+- Any UX friction where the user had to re-sign repeatedly; if yes, propose caching the derived key in-memory for the tab lifetime.
+- Threat model notes: what this protects against (gateway snoopers, account compromise on other devices) and what it does NOT (compromise of the wallet itself).
diff --git a/prompts/agent-3d/README.md b/prompts/agent-3d/README.md
new file mode 100644
index 000000000..6bd29f036
--- /dev/null
+++ b/prompts/agent-3d/README.md
@@ -0,0 +1,80 @@
+# agent-3d framework build-out
+
+Delegate-ready prompts for turning the current `<agent-3d>` scaffold ([src/element.js](../../src/element.js), [specs/](../../specs/)) into a production-grade embodied-agent framework. Each file is a self-contained task — no shared state between tasks unless explicitly noted in "Depends on".
+
+## Reference reading before starting any task
+
+- [specs/AGENT_MANIFEST.md](../../specs/AGENT_MANIFEST.md)
+- [specs/SKILL_SPEC.md](../../specs/SKILL_SPEC.md)
+- [specs/MEMORY_SPEC.md](../../specs/MEMORY_SPEC.md)
+- [specs/EMBED_SPEC.md](../../specs/EMBED_SPEC.md)
+- Existing series that interact with this work: [prompts/embed/](../embed/README.md), [prompts/widget-studio/](../widget-studio/README.md), [prompts/scalability/](../scalability/README.md)
+
+## Rules that apply to all tasks
+
+- Do not modify [src/viewer.js](../../src/viewer.js) unless the task explicitly asks. All agent-specific control lives in [src/runtime/scene.js](../../src/runtime/scene.js).
+- No changes to the spec files under [specs/](../../specs/) without bumping the version in the frontmatter of that file.
+- `node --check` every new JS file. `npm run build:all` must pass before claiming done.
+- Zero new build-time dependencies unless the task authorizes it. Runtime-only deps are fine.
+- Respect the kiosk/debug/editor attribute semantics already defined in [specs/EMBED_SPEC.md](../../specs/EMBED_SPEC.md).
+- The custom element tag is currently `agent-3d` — if the final tag name changes, only touch the registration sites, never spread hardcoded tag strings into runtime code (use `Agent3DElement` class references).
+- If Anthropic API access is not configured in the dev environment, use `brain="none"` or mock the provider — never block on network credentials.
+- If you discover an unrelated bug, note it in "Reporting". Do not fix it in the same change.
+
+## Recommended execution order
+
+Tasks are grouped by readiness and dependency. Within a group they are independent.
+
+### Group A — provider surface (independent, parallelizable)
+
+1. [01-openai-provider.md](./01-openai-provider.md) — OpenAI brain provider.
+2. [02-elevenlabs-tts.md](./02-elevenlabs-tts.md) — ElevenLabs TTS provider.
+3. [03-whisper-stt.md](./03-whisper-stt.md) — Whisper STT provider.
+
+### Group B — persistence & trust
+
+4. [04-encrypted-memory.md](./04-encrypted-memory.md) — `encrypted-ipfs` memory mode.
+5. [05-skill-sandbox.md](./05-skill-sandbox.md) — worker-isolated skill handler execution.
+6. [20-memory-embeddings-retrieval.md](./20-memory-embeddings-retrieval.md) — embedding-based memory recall.
+7. [24-skill-signature-verification.md](./24-skill-signature-verification.md) — signed skill bundle verification.
+
+### Group C — scene & embodiment
+
+8. [06-multi-agent-scene.md](./06-multi-agent-scene.md) — multiple `<agent-3d>` instances sharing a scene.
+9. [11-ar-webxr.md](./11-ar-webxr.md) — WebXR / Quick Look / Scene Viewer.
+10. [12-vrm-support.md](./12-vrm-support.md) — VRM rig support alongside Mixamo.
+11. [13-animation-retargeting.md](./13-animation-retargeting.md) — Mixamo→Mixamo clip retargeting.
+
+### Group D — distribution & editor
+
+12. [10-responsive-presets.md](./10-responsive-presets.md) — mobile/desktop clamp() preset generator.
+13. [18-editor-polish.md](./18-editor-polish.md) — touch, magnetic snap, device preview, undo.
+14. [21-agent-home-page.md](./21-agent-home-page.md) — wire `agent-home.html` / `agent-embed.html` to the new editor.
+15. [07-manifest-builder-ui.md](./07-manifest-builder-ui.md) — form-based manifest authoring.
+16. [15-conversation-persistence.md](./15-conversation-persistence.md) — save/restore chat history per agent.
+17. [25-error-ux.md](./25-error-ux.md) — loading + error states worthy of shipping.
+18. [28-accessibility-audit.md](./28-accessibility-audit.md) — a11y pass on shadow DOM chrome.
+19. [29-onboarding-walkthrough.md](./29-onboarding-walkthrough.md) — first-run tour.
+
+### Group E — platform & infrastructure
+
+20. [08-ipfs-pinning-service.md](./08-ipfs-pinning-service.md) — pluggable pinning (web3.storage, Filebase, Pinata, local IPFS).
+21. [09-validator-attestations.md](./09-validator-attestations.md) — signed glTF validator attestations.
+22. [16-bundle-optimization.md](./16-bundle-optimization.md) — code-split Three.js loaders behind dynamic imports.
+23. [17-cdn-deployment.md](./17-cdn-deployment.md) — versioned CDN release pipeline with SRI.
+24. [19-skill-marketplace.md](./19-skill-marketplace.md) — skill discovery index + optional on-chain registry.
+25. [22-privy-auth.md](./22-privy-auth.md) — Privy-backed agent ownership / signing.
+
+### Group F — ecosystem adapters
+
+26. [17-react-wrapper.md](./17-react-wrapper.md) — `@3d-agent/react` typed wrapper.
+27. [30-framework-wrappers-svelte.md](./30-framework-wrappers-svelte.md) — Vue 3 + Svelte wrappers.
+28. [26-typescript-declarations.md](./26-typescript-declarations.md) — published `.d.ts` for the element + public API.
+
+### Group G — quality gates
+
+29. [27-e2e-test-harness.md](./27-e2e-test-harness.md) — Playwright harness.
+
+## Tag naming note
+
+When the framework tag is finalized (currently `agent-3d`), a one-pass `sed` migration is sufficient across specs, element registration, lib entry, editor, and examples. Individual tasks should not introduce hardcoded tag strings into runtime code — reference the element class instead.
diff --git a/prompts/avatar-edit/01-edit-appearance-flow.md b/prompts/avatar-edit/01-edit-appearance-flow.md
new file mode 100644
index 000000000..42cc30fb3
--- /dev/null
+++ b/prompts/avatar-edit/01-edit-appearance-flow.md
@@ -0,0 +1,81 @@
+# Task: Re-enter Avaturn with the current avatar and save the edit as a new version
+
+## Context
+
+Repo: `/workspaces/3D`. The user creates an avatar via [src/avatar-creator.js](../../src/avatar-creator.js) which embeds the Avaturn SDK in a modal and fires `onExport(glbUrl)`. Today that is **one-shot**: there is no way to re-enter Avaturn with the existing avatar preloaded and tweak it.
+
+The avatar bytes are stored in R2 at `u/{userId}/{slug}/{timestamp}.glb` and registered in the `avatars` table (see [api/CLAUDE.md](../../api/CLAUDE.md)). The `agent_identities.avatar_id` column points at the current avatar row. Every agent has exactly one current avatar; the rest is history.
+
+The Avaturn SDK supports continuing from an existing session URL — our [api/avatars/[id].js](../../api/avatars/[id].js) does not yet create or return one. The dashboard at [public/dashboard/](../../public/dashboard/) is where the "Edit appearance" button lives.
+
+## Goal
+
+Wire a flow where the user clicks "Edit appearance" on their avatar in the dashboard → Avaturn opens prefilled with the existing avatar → on export, a **new** `avatars` row is created, linked as a new version of the existing avatar, and `agent_identities.avatar_id` is updated to point at it. The previous row is retained as a history entry.
+
+AgentId does not change. Wallet link does not change.
+
+## Deliverable
+
+1. **Backend**
+ - New endpoint: `POST /api/avatars/:id/session` — creates an Avaturn edit session for the given avatar the caller owns. Returns `{ sessionUrl }`. Rate-limit via `limits.upload(userId)`.
+ - New column (or reuse a JSON `meta` field on `avatars`): `parent_avatar_id uuid null references avatars(id)` so history is queryable. If adding a column requires a migration, document the SQL in the reporting section — do not silently change schema.
+ - New endpoint: `GET /api/avatars/:id/versions` — returns ordered list of `{ id, created_at, storage_key, is_current }` for an avatar and its ancestors.
+ - Update [api/avatars/index.js](../../api/avatars/index.js) (the POST handler) to accept an optional `parent_avatar_id` in the body and persist it; when set, the newly registered avatar is treated as a version of that parent and `agent_identities.avatar_id` is updated in the same transaction.
+
+2. **Frontend — src/avatar-creator.js**
+ - Extend `AvatarCreator.open(sessionUrl, { existingAvatarUrl } = {})` so the caller can pass a preload URL. Pass it through to `AvaturnSDK.init` as whatever option the SDK exposes for "continue from this avatar" (check the SDK's current options — if no such option exists, document what would be needed and fall back to opening fresh with a warning banner in the modal).
+ - Extend `onExport` signature so callers get the same `glbUrl` they do today — no breaking change.
+
+3. **Frontend — dashboard**
+ - Add an "Edit appearance" button on each avatar card in [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js).
+ - Clicking it: `POST /api/avatars/:id/session` → open `AvatarCreator` with the returned sessionUrl and the current GLB URL → on export, run the upload flow from [api/avatars/presign.js](../../api/avatars/presign.js) + `POST /api/avatars` with `parent_avatar_id` set to the row being edited.
+ - Show a small "version N of M" chip on the card, clickable to reveal the version list (from `GET /api/avatars/:id/versions`). Clicking a prior version calls `PATCH /api/agents/:agentId { avatar_id }` to revert.
+
+## Audit checklist
+
+- The avatarId on `agent_identities` changes; the agentId does **not**.
+- Wallet link (`agent_identities.wallet_address`, `user_wallets`) is untouched by the flow.
+- ERC-8004 record (`agent_identities.erc8004_agent_id`) is untouched. If present, surface a small warning in the UI: "Editing appearance does not update your on-chain registration. [Re-register?]". Do not auto-re-register.
+- Old avatar rows are **not** deleted. Soft-delete is fine only when the user explicitly asks to prune history; this task does not add that UI.
+- The parent chain is walkable — you can traverse `parent_avatar_id` back to the original selfie.
+- Previewing a prior version in the dashboard does not mutate the database until the user clicks "restore".
+- Deleting a user (cascade) still works — no orphaned version chains.
+
+## Constraints
+
+- No new runtime dependencies. Use the existing `@avaturn/sdk`.
+- If Avaturn's SDK does not expose a "preload existing avatar" option in our pinned version, **do not upgrade** — document it and ship the button flow with a placeholder (fresh session) plus a `console.info` breadcrumb.
+- Use the existing R2 presign flow from [api/avatars/presign.js](../../api/avatars/presign.js) + [api/avatars/index.js](../../api/avatars/index.js). Do not add a second upload path.
+- Use `sql` from [_lib/db.js](../../api/_lib/db.js) tagged templates — no ORM, no raw concat.
+- Use `getSessionUser` + `authenticateBearer` from [_lib/auth.js](../../api/_lib/auth.js) — same auth surface as [api/avatars/[id].js](../../api/avatars/[id].js).
+- Any version-switch write must go through `PATCH /api/agents/:agentId` or a dedicated endpoint — never update `agent_identities` from client-side JS directly.
+
+## Verification
+
+1. `node --check` every JS file you modified.
+2. `npx vite build` — expect success (ignore the pre-existing `@avaturn/sdk` resolution warning).
+3. Manual:
+ - Sign in, create a selfie avatar.
+ - Note `agent_identities.id` and `avatar_id` in the DB.
+ - Click "Edit appearance", export from Avaturn.
+ - Confirm `agent_identities.id` is unchanged.
+ - Confirm `agent_identities.avatar_id` points at a new `avatars` row whose `parent_avatar_id` is the original.
+ - Click "version 1" chip → restore → confirm `avatar_id` is back on the original.
+ - Confirm the agent's action history (`agent_actions` rows) is untouched across the full flow.
+4. Sign out, sign back in with a different user, call `GET /api/avatars/:id/session` on someone else's avatar → expect 404 (`not_found`), not 403 — mirror the pattern in [api/avatars/[id].js](../../api/avatars/[id].js).
+
+## Scope boundaries — do NOT do these
+
+- Do not build a diff visualizer showing before/after morph targets.
+- Do not implement auto-pruning of history.
+- Do not touch the ERC-8004 registration flow. Re-registration is layer 6.
+- Do not change the shape of `onExport(glbUrl)` callers rely on.
+- Do not build in-place morph-slider editing in the dashboard — that is [05-outfits-and-accessories.md](./05-outfits-and-accessories.md) scope.
+
+## Reporting
+
+- Files created / edited (include which function or section).
+- SQL migration needed (if any) — copy-pasteable.
+- Whether Avaturn SDK supported the preload option in the pinned version; if not, what the stub looks like.
+- `npx vite build` output (abbreviated).
+- Any version-chain edge case you hit (circular parents, deleted middle versions, etc.).
diff --git a/prompts/avatar-edit/02-replace-glb-upload.md b/prompts/avatar-edit/02-replace-glb-upload.md
new file mode 100644
index 000000000..29b1a76e1
--- /dev/null
+++ b/prompts/avatar-edit/02-replace-glb-upload.md
@@ -0,0 +1,88 @@
+# Task: Direct GLB upload to replace an avatar without going through Avaturn
+
+## Context
+
+Repo: `/workspaces/3D`. Today the only path to set an avatar's bytes is through the Avaturn modal ([src/avatar-creator.js](../../src/avatar-creator.js)). Advanced users — people bringing their own rigged GLB, studio artists, or power users swapping to a custom model — have no way to upload directly.
+
+The R2 upload primitives already exist:
+- [api/avatars/presign.js](../../api/avatars/presign.js) returns a signed PUT URL given `{ content_type, size_bytes, slug? }`.
+- [api/avatars/index.js](../../api/avatars/index.js) registers an uploaded object after the browser PUTs raw bytes. It verifies via `headObject()` that the object exists and size matches.
+
+The agent's stable identity lives on `agent_identities` (id = agentId). The avatar bytes live in `avatars` (linked via `agent_identities.avatar_id`). The wallet linkage lives on `user_wallets` and/or `agent_identities.wallet_address`. None of these should change when the user uploads a replacement GLB.
+
+## Goal
+
+Ship a "Replace GLB" button on the dashboard avatar card. Clicking it opens a file picker, accepts `.glb` (reject `.gltf`, reject anything else), uploads direct-to-R2 via presign, and re-points the existing agent at the new avatar row. The same agentId keeps the same wallet link and action history.
+
+## Deliverable
+
+1. **Frontend — dashboard**
+ - In [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js), add a "Replace GLB" action next to "Edit appearance" (from [01-edit-appearance-flow.md](./01-edit-appearance-flow.md)).
+ - Use a hidden `<input type="file" accept=".glb,model/gltf-binary">`. Validate client-side:
+ - Extension is `.glb`.
+ - MIME type is `model/gltf-binary` or `application/octet-stream` (browsers sometimes send the latter).
+ - File size ≤ the user's plan quota from `plan_quotas.max_bytes_per_avatar` (fetch once at dashboard mount via existing `/api/auth/me` or a new small endpoint if not surfaced).
+ - On select: read first 4 bytes to verify the magic number `glTF` (`0x67 0x6c 0x54 0x46`). If the magic does not match, reject with an inline error — do not upload.
+ - Call presign, PUT to the signed URL, then `POST /api/avatars` with `parent_avatar_id` = current avatar id, `source: 'direct-upload'`.
+ - Surface an "this bypasses Avaturn — your avatar may not animate correctly if it's not rigged to the Mixamo skeleton" warning before upload. One-click confirm.
+
+2. **Backend**
+ - Extend the `createAvatarBody` schema in [_lib/validate.js](../../api/_lib/validate.js) to accept `source: 'direct-upload'` (existing values likely include `'avaturn'`, `'selfie'`, etc. — preserve them).
+ - Confirm that [api/avatars/index.js](../../api/avatars/index.js)'s registration handler still calls `headObject()` + size check. No regression.
+ - Add optional server-side sanity check on the registered GLB: read the first 12 bytes via a signed GET (or defer until first render). If you add it, keep it behind a feature flag so this task stays small. If skipping, note it in the report.
+ - Ensure `agent_identities.avatar_id` update happens in the same SQL transaction as the `avatars` insert. Reuse the transactional helper from task 01 if that task shipped first; otherwise add it here.
+
+3. **Compatibility check on the new GLB**
+ - In [src/animation-manager.js](../../src/animation-manager.js), the `_buildBoneNameMap` already attempts retargeting. After a replace-GLB upload, trigger a client-side check: load the new GLB into the existing viewer, count bones, compute how many match the project's expected Mixamo-ish names. If under 50%, show a non-blocking warning: "Animations may not play — skeleton mismatch." Do not block the upload.
+ - Do not modify `_buildBoneNameMap`. Re-use its logic read-only for the check, or call it directly.
+
+## Audit checklist
+
+- agentId (`agent_identities.id`) unchanged across the replace.
+- Wallet fields (`agent_identities.wallet_address`, `chain_id`) unchanged.
+- `agent_identities.erc8004_agent_id` unchanged. Show the same "on-chain registration will drift" warning as task 01. No auto-re-register.
+- The old avatar row is **not** deleted. `parent_avatar_id` chain stays intact so the user can revert.
+- Content-type is verified server-side via `headObject()` — already done by registration endpoint; do not regress it.
+- `.gltf` + accompanying `.bin` is rejected (single-file GLB only for this task).
+- GLB magic number is checked client-side before upload.
+- Upload is scoped to the authenticated user — presign uses `userId` in the key. Do not accept a `userId` from client input.
+- Rate-limited via `limits.upload(userId)`.
+- Quota (`plan_quotas.max_bytes_per_avatar`, `max_total_bytes`) is enforced. Existing presign handler should already; verify and note if it doesn't.
+
+## Constraints
+
+- No new runtime dependencies. No GLB parser library — magic number byte check is enough client-side.
+- No changes to R2 bucket config, CORS, or presign helpers in [_lib/r2.js](../../api/_lib/r2.js).
+- Do not add a "drop zone" with drag-and-drop unless it's trivially cheap — the file picker is the minimum viable target.
+- No server-side GLB validation beyond magic-number / header in this task. Mesh-level validation exists separately in [src/validator.js](../../src/validator.js) and MCP `validate_model` — do not wire those in here.
+- Dashboard stays native-DOM — no framework.
+
+## Verification
+
+1. `node --check` every modified JS file.
+2. `npx vite build`.
+3. Manual:
+ - Sign in, have an existing avatar.
+ - Click "Replace GLB", pick a valid Mixamo-rigged `.glb` (find one under `public/models/` or re-export from Blender). Confirm upload succeeds, `agent_identities.avatar_id` points at the new row, `agentId` unchanged.
+ - Try uploading a `.txt` renamed to `.glb` — client-side magic-number check rejects it.
+ - Try uploading an oversize file — quota rejects it.
+ - Try uploading a non-Mixamo rigged GLB — confirm the "skeleton mismatch" warning surfaces.
+ - Revert to the prior version via the version chip (from task 01) — confirm it works.
+ - Sign in as user B, try to POST to `/api/avatars` with `parent_avatar_id` pointing at user A's avatar — expect 404 `not_found`.
+
+## Scope boundaries — do NOT do these
+
+- Do not build a GLB viewer preview modal before confirm-upload. The existing viewer post-upload is enough.
+- Do not add `.gltf` + separate asset support. Single-file `.glb` only.
+- Do not add thumbnail generation. A later task will handle that.
+- Do not touch the Avaturn modal.
+- Do not re-validate on-chain records.
+
+## Reporting
+
+- Files created / edited.
+- SQL migration (if any) — copy-pasteable.
+- Whether `plan_quotas.max_bytes_per_avatar` was already enforced by presign; if not, where you added the check.
+- Whether the skeleton-mismatch warning triggers on your test GLBs.
+- `npx vite build` output.
+- Any unexpected behavior from `headObject()` against newly PUT objects (eventual consistency issues, etc.).
diff --git a/prompts/avatar-edit/README.md b/prompts/avatar-edit/README.md
new file mode 100644
index 000000000..3297a143f
--- /dev/null
+++ b/prompts/avatar-edit/README.md
@@ -0,0 +1,58 @@
+# Edit avatar (layer 3)
+
+Post-creation avatar editing. Without this, selfie-creation feels one-shot: a user can only change their agent's face by deleting and starting over. This layer lets them swap appearance, rename, attach animations, and try outfits without losing their agentId, wallet link, or action history.
+
+## State going in
+
+- Layer 1 (wallet auth) is shipped — sessions exist, `/api/agents/me` works.
+- Layer 2 (selfie-agent) is shipped — the user has a persistent `agent_identities` row with `avatar_id` pointing at an R2 object, wallet linkage is in place.
+- [src/avatar-creator.js](../../src/avatar-creator.js) embeds the Avaturn SDK modal.
+- [src/animation-manager.js](../../src/animation-manager.js) handles clip loading + crossfade.
+- [api/avatars/[id].js](../../api/avatars/[id].js) supports GET / PATCH / DELETE. There is no "replace GLB bytes" endpoint yet — some tasks add one.
+- [src/editor/](../../src/editor/) already ships scene-explorer, material-editor, texture-inspector, glb-export — reuse these for any mesh/material operation. Do not fork.
+- Dashboard lives at [public/dashboard/](../../public/dashboard/) (`dashboard.js` + `index.html`). It is native-DOM, no framework. All edit UIs land here under `#edit/<id>` sub-routes.
+
+## The non-negotiable invariant
+
+**Every edit preserves stable agent identity.** Same `agent_identities.id` (agentId), same wallet link (`user_wallets`, `wallet_address` on the agent row), same ERC-8004 registration if present, same action history. Edits produce a new `avatars` row (or a new GLB version tagged against the existing one) — they never mint a new agent.
+
+If a task would orphan or duplicate the agentId, stop and report. This is the whole point of the layer.
+
+## Tasks
+
+| # | File | Ships |
+|---|---|---|
+| 01 | [01-edit-appearance-flow.md](./01-edit-appearance-flow.md) | Re-enter Avaturn with current avatar loaded → save diff as new GLB version, keep prior as history |
+| 02 | [02-replace-glb-upload.md](./02-replace-glb-upload.md) | Direct GLB upload replaces avatar bytes without going through Avaturn |
+| 03 | [03-edit-identity-metadata.md](./03-edit-identity-metadata.md) | Edit name / bio / skills / service endpoints with debounced autosave + uniqueness checks |
+| 04 | [04-animation-library.md](./04-animation-library.md) | List / attach / detach animation clips on an avatar, preview in dashboard |
+| 05 | [05-outfits-and-accessories.md](./05-outfits-and-accessories.md) | Preset pack (hats, glasses, 2-3 outfits) swapped via morph / bone overlays in the same GLB |
+
+## Sequencing
+
+- 03 can ship first — pure metadata, lowest risk, immediate user value. No new storage flow.
+- 01 and 02 are parallel tracks; 02 is smaller and can land first as an escape hatch while Avaturn re-entry is being figured out.
+- 04 depends on a stable avatar record but is otherwise independent.
+- 05 depends on 04's attach/detach plumbing for accessory loading.
+
+## Dependencies on other series
+
+- [selfie-agent/](../selfie-agent/) — all five tasks assume an avatar already exists. If a user lands on edit without an avatar, redirect to the selfie flow.
+- [wallet-auth/](../wallet-auth/) — tasks 01/02/04/05 write to R2 and mutate `agent_identities`; require an authenticated session.
+
+## Out of scope for the whole layer
+
+- Multiplayer try-on, shared outfit inventories.
+- Marketplace / purchasable cosmetics.
+- Procedural body generation (height, weight sliders outside Avaturn's own controls).
+- Voice cloning / speech editing — separate layer.
+- On-chain metadata rewrites (layer 6, onchain).
+
+## Rules that apply to every task
+
+- No new runtime dependencies unless the task file explicitly allows them.
+- `node --check` every modified JS file before reporting done.
+- `npx vite build` and report the result. The pre-existing `@avaturn/sdk` resolution warning is unrelated — ignore.
+- Preserve agentId, wallet link, and ERC-8004 record on every write path.
+- Reuse [src/editor/](../../src/editor/) utilities for mesh/material/export. Do not build parallel implementations.
+- Keep dashboard native-DOM — no React / Vue / Svelte.
diff --git a/prompts/avatar-editing/00-README.md b/prompts/avatar-editing/00-README.md
new file mode 100644
index 000000000..b166ab393
--- /dev/null
+++ b/prompts/avatar-editing/00-README.md
@@ -0,0 +1,40 @@
+# Band 3 — Edit Avatars
+
+## The end state
+
+An owner opens `/agent/:slug/edit` (or the equivalent panel) on an avatar they already have and can:
+
+- Tweak materials, textures, and scene graph — **already shipped** (see `src/editor/*`).
+- Retake the selfie and regenerate the avatar, keeping the same agent identity, slug, and action history.
+- Switch outfits, accessories, or style presets without losing their identity.
+- Roll back to a previous version.
+- Save and publish — the new GLB replaces (or is versioned alongside) the old one at the same URL so every existing embed keeps working.
+
+## Current state
+
+- Material editor, scene explorer, texture inspector all shipped — `src/editor/index.js`, `src/editor/material-editor.js`, `src/editor/scene-explorer.js`, `src/editor/texture-inspector.js`, exposed on `window.VIEWER.editor`.
+- Edits can be exported as a new GLB via `src/editor/glb-export.js` but there is no "save back to the server" path yet.
+- Avatar records are stored in the `avatars` table. We have a `model_url`, but no concept of versions.
+- Selfie → avatar pipeline (band 2) is the prerequisite for regenerate-from-photo.
+
+## Prompts in this band
+
+| # | File | Depends on |
+|---|---|---|
+| 01 | [save-edits-to-server.md](./01-save-edits-to-server.md) | — |
+| 02 | [regenerate-from-photo.md](./02-regenerate-from-photo.md) | band 2 done |
+| 03 | [outfit-variants.md](./03-outfit-variants.md) | 01 |
+| 04 | [version-history.md](./04-version-history.md) | 01 |
+
+## Done = merged when
+
+- Owner on `/agent/:slug/edit` can make a material change, click **Save**, and the change persists — reloading the page or viewing the public URL shows the new look.
+- Retake-selfie flow produces a new GLB bound to the same agent id; old versions are retained.
+- Owner can roll back to version N — the public `model_url` serves version N's bytes.
+- Every existing embed continues to render (no broken URLs after a version bump).
+
+## Off-limits for this band
+
+- Do not rewrite the editor (band 3 of earlier work shipped it — trust it).
+- Do not introduce a new storage service. R2 is the blob store; Postgres is the source of truth for version pointers.
+- Do not require a second GLB upload path — reuse `api/avatars` with a `version` query param or similar.
diff --git a/prompts/avatar-platform/01-strip-avaturn.md b/prompts/avatar-platform/01-strip-avaturn.md
new file mode 100644
index 000000000..26904e5c0
--- /dev/null
+++ b/prompts/avatar-platform/01-strip-avaturn.md
@@ -0,0 +1,77 @@
+# Task: Remove Avaturn dependencies and rename the chat agent
+
+## Context
+
+Repo: `/workspaces/3D`. Two Avaturn packages are in [package.json:45-46](../../package.json#L45-L46):
+
+- `@avaturn/sdk` — used by [src/avatar-creator.js:1](../../src/avatar-creator.js#L1) to embed Avaturn's hosted editor iframe (`preview.avaturn.dev/editor`).
+- `@avaturn-live/web-sdk` — declared but **not imported anywhere** in `src/`. Dead weight; it's their realtime talking-head streaming product and not useful here.
+
+[src/avaturn-agent.js](../../src/avaturn-agent.js) defines a class called `AvaturnAgent` but is 100% our own code — a plain chat/voice panel with no Avaturn integration. The name, CSS prefix (`avaturn-*`), and file path all falsely suggest vendor affiliation.
+
+We are replacing Avaturn with an owned, self-hosted stack (see this directory's [README.md](./README.md)). This task yanks the deps and strips the misleading branding so downstream tasks have a clean slate.
+
+## Goal
+
+After this task:
+
+1. Neither `@avaturn/sdk` nor `@avaturn-live/web-sdk` appear in `package.json` or the lockfile.
+2. [src/avatar-creator.js](../../src/avatar-creator.js) is **deleted** (replacement comes in tasks 03, 16, 17).
+3. [src/avaturn-agent.js](../../src/avaturn-agent.js) is renamed to `src/agent-panel.js`, class renamed to `AgentPanel`, CSS prefix changed from `avaturn-` to `agent-`. Behavior unchanged.
+4. Any imports/callers updated.
+5. CSS selectors updated in [style.css](../../style.css) (search for `.avaturn-`).
+6. The app boots and the chat panel works exactly as before — just with new names.
+
+## Deliverable
+
+1. **Package surgery** — `npm uninstall @avaturn/sdk @avaturn-live/web-sdk`. Confirm [package.json](../../package.json) and lockfile diff is exactly the two removals.
+2. **Delete** [src/avatar-creator.js](../../src/avatar-creator.js). Search for any imports (`import .* from .*avatar-creator`) and remove them — update callers to no-op the creator-open path with a `console.warn('[creator] not yet wired — see avatar-platform task 03+')`. Don't leave dead buttons; comment them out with a TODO pointing at task 16.
+3. **Rename** [src/avaturn-agent.js](../../src/avaturn-agent.js) → `src/agent-panel.js`. Inside:
+ - Class `AvaturnAgent` → `AgentPanel`.
+ - All CSS classes `avaturn-*` → `agent-*` (keep the suffix: `avaturn-panel` → `agent-panel`, `avaturn-mic` → `agent-mic`, etc.).
+ - The header title `SperaxOS` stays (it's a valid brand label).
+4. **Update [src/app.js](../../src/app.js)** — import path and class name. No behavioral changes.
+5. **Update [style.css](../../style.css)** — replace every `.avaturn-*` selector with `.agent-*`. Verify none are missed.
+6. **Update [src/avaturn-agent.js](../../src/avaturn-agent.js) callers** if any exist outside app.js (there shouldn't be).
+
+## Audit checklist
+
+- [ ] `grep -r "avaturn" src/` returns **zero** matches (case-insensitive).
+- [ ] `grep -r "avaturn" package.json package-lock.json` returns zero matches.
+- [ ] `grep -r "AvaturnAgent\|AvaturnSDK" .` returns zero matches outside `node_modules/` and this prompts folder.
+- [ ] `.avaturn-` does not appear in [style.css](../../style.css).
+- [ ] The toggle button opens the chat panel, messages send, mic works — same as before.
+- [ ] `npx vite build` completes with no new errors.
+- [ ] `node --check src/agent-panel.js` parses.
+
+## Constraints
+
+- Do **not** implement the new creator, editor, or VRM loading in this task. Those are tasks 02, 03, 16.
+- Do **not** change chat/voice behavior. This is a pure rename + deletion pass.
+- Do **not** touch [src/viewer.js](../../src/viewer.js) or any rendering code.
+- Keep git history clean: one commit for the npm uninstall + deletion, one for the rename. Or a single coherent commit if you prefer — document the choice in reporting.
+
+## Verification
+
+1. `npm uninstall @avaturn/sdk @avaturn-live/web-sdk` — watch the lockfile diff.
+2. `npx vite build` passes.
+3. `npm run dev`, open the app:
+ - Agent panel toggle works.
+ - Typing + pressing Enter echoes a reply.
+ - Mic button still toggles active state.
+4. Open DevTools, inspect panel DOM — classes are all `agent-*`, no `avaturn-*`.
+5. Drag-drop a `.glb` into the viewer — it still loads (confirms nothing accidental in viewer path).
+
+## Scope boundaries — do NOT do these
+
+- Do not start vendoring CharacterStudio, three-vrm, TalkingHead, or any of the replacement stack. That's tasks 02+.
+- Do not remove the agent panel's response logic. The rule-based replies stay until task 14.
+- Do not rename `SperaxOS` in the header string; that's brand copy, not vendor label.
+- Do not touch the `src/` files listed under `features/` — the pretext experiments are independent.
+
+## Reporting
+
+- Confirm the exact lines removed from package.json and any transitive deps that fell out of the lockfile.
+- List every file touched by the rename, with old → new identifier mapping.
+- Any usages of `@avaturn-live/web-sdk` you found that the initial grep missed.
+- Screenshot-or-describe the chat panel before/after to confirm visual parity.
diff --git a/prompts/avatar-platform/02-vrm-runtime.md b/prompts/avatar-platform/02-vrm-runtime.md
new file mode 100644
index 000000000..fbc4bcf47
--- /dev/null
+++ b/prompts/avatar-platform/02-vrm-runtime.md
@@ -0,0 +1,74 @@
+# Task: Adopt VRM as the avatar format and wire @pixiv/three-vrm into the viewer
+
+## Context
+
+Repo: `/workspaces/3D`. The viewer in [src/viewer.js](../../src/viewer.js) uses three.js with `GLTFLoader` and accepts `.gltf` / `.glb`. Downstream tasks need **VRM** (a glTF extension with standardized humanoid bones, expressions, and spring-bone physics) so that TalkingHead (09), Kalidokit mirror mode (12), and CharacterStudio (03) all compose cleanly.
+
+VRM files are valid GLB. The viewer already loads them geometrically. What's missing is the VRM-specific runtime: expressions (`aa`, `ih`, `blink`, `happy`...), humanoid bone API, and optional MToon shader. `@pixiv/three-vrm` is the MIT-licensed standard from VRoid.
+
+## Goal
+
+After this task:
+
+1. `@pixiv/three-vrm` is installed and the viewer loads `.vrm` files (and any `.glb` that happens to carry the VRM extension) with the VRM runtime attached.
+2. `window.VIEWER.activeVRM` exposes the loaded `VRM` instance (or `null`), for downstream modules to introspect.
+3. A simple smoke test — loading a known VRM and firing a single expression (`aa`) through the console — works.
+4. Loading a plain non-VRM GLB still works exactly as before.
+
+## Deliverable
+
+1. **Install** — `npm install @pixiv/three-vrm`. Pin to the latest 3.x (check the upstream for the current major). Update lockfile.
+2. **New file** `src/vrm-runtime.js`:
+ - Exports `createVRMLoaderPlugin(gltfLoader)` that registers the VRM plugin on the provided `GLTFLoader`.
+ - Exports `async loadVRM(gltfLoader, url)` returning `{ scene, vrm }` where `vrm` is the `VRM` instance or `null` if the file is plain GLB.
+ - Exports `updateVRM(vrm, deltaSeconds)` calling `vrm.update(dt)` — used by the render loop.
+ - Exports `disposeVRM(vrm)` — cleans up spring bones and detaches.
+3. **Modify [src/viewer.js](../../src/viewer.js)** — in the GLTFLoader setup, install the VRM plugin. In the scene-setup path that runs after a model loads, detect `gltf.userData.vrm` (set by the plugin). If present:
+ - Store it as `this.activeVRM`.
+ - In the render/update loop, call `updateVRM(this.activeVRM, delta)` every frame.
+ - On model replacement/dispose, call `disposeVRM(previous)`.
+4. **Expose** — `window.VIEWER.activeVRM` reads from `app.viewer.activeVRM`.
+5. **Accept `.vrm` in the file picker / dropzone** — search [src/app.js](../../src/app.js) and the dropzone config for the `.glb, .gltf` accept list; add `.vrm`.
+6. **Smoke-test asset** — download a public CC0 VRM (e.g., one of the AvatarSample set from VRoid Hub, or a file from the asset-library task later) into [public/avatars/](../../public/avatars/) as `sample.vrm`. License info goes into a `public/avatars/NOTICES.md` (create it).
+
+## Audit checklist
+
+- [ ] `npm ls @pixiv/three-vrm` prints a single resolved version, no duplicates.
+- [ ] Dropping `sample.vrm` onto the viewer loads the character; dropping a known-good GLB still works.
+- [ ] In DevTools console: `VIEWER.app.viewer.activeVRM.expressionManager.setValue('aa', 1); VIEWER.app.viewer.activeVRM.update(0)` — the mouth opens.
+- [ ] Loading a non-VRM GLB → `VIEWER.app.viewer.activeVRM === null`.
+- [ ] The render loop calls `updateVRM` exactly once per frame when a VRM is loaded (profile in Performance tab).
+- [ ] Spring bones (hair / skirt) settle and move under gravity when you orbit the camera quickly.
+- [ ] Disposing and reloading does not leak — no duplicate spring-bone listeners after three reloads (check via a heap snapshot or manual counter).
+
+## Constraints
+
+- **No changes to the non-VRM GLB code path.** Plain GLBs render the same as before.
+- Use `@pixiv/three-vrm` via npm, not vendored — this one is infrastructural, and the README.md carves out the exception.
+- Do not import anything from `@pixiv/three-vrm-springbone`, `-animation`, etc. separately — the umbrella package re-exports what's needed.
+- Do not add React, r3f, or any framework. Stay in vanilla JS + three.js.
+- Do not commit a VRM file larger than 10 MB. If `sample.vrm` is bigger, use [git-lfs](https://git-lfs.com/) via the existing `.gitattributes` — or pick a smaller sample.
+
+## Verification
+
+1. `node --check src/vrm-runtime.js`.
+2. `npx vite build` passes; bundle size delta is reported in the summary.
+3. Dev server, load `sample.vrm` → character renders with correct material (MToon or standard).
+4. Console smoke test from audit checklist passes.
+5. Load plain `.glb` → renders, `activeVRM === null`, no errors.
+6. Reload-and-dispose loop (3×) → no leaked listeners.
+
+## Scope boundaries — do NOT do these
+
+- Do not build the editor UI or expression panel. That's task 16.
+- Do not add lipsync, TTS, or any audio wiring. Tasks 09–10.
+- Do not add automatic `lookAt` / gaze tracking — that's either the existing pretext task 03 (for `model-viewer` only) or deferred.
+- Do not swap three.js versions.
+
+## Reporting
+
+- Version of `@pixiv/three-vrm` installed and its peer-dep compatibility with `three@^0.176`.
+- Bundle size before vs after.
+- Any console warnings from the VRM plugin on the sample file.
+- The sample VRM's source URL and license, copied into `public/avatars/NOTICES.md`.
+- Render-loop deltaTime measurement (mean + p95) with a VRM loaded, before any animation features land.
\ No newline at end of file
diff --git a/prompts/avatar-platform/03-vendor-character-studio.md b/prompts/avatar-platform/03-vendor-character-studio.md
new file mode 100644
index 000000000..986c6dee3
--- /dev/null
+++ b/prompts/avatar-platform/03-vendor-character-studio.md
@@ -0,0 +1,86 @@
+# Task: Vendor CharacterStudio's CharacterManager into src/character/
+
+## Context
+
+Repo: `/workspaces/3D`. Task 02 established VRM as the avatar format via `@pixiv/three-vrm`. We now need an asset-driven customization runtime: hair, clothes, body, skin tone, morph presets. [M3-org/CharacterStudio](https://github.com/M3-org/CharacterStudio) is MIT-licensed, uses `@pixiv/three-vrm`, and recently refactored so that its core logic lives in a standalone `CharacterManager` class (no React dependency).
+
+We are **vendoring** (copying source + attribution), not installing via npm — per this directory's [README.md](./README.md).
+
+This task imports only the runtime. The UI (side-panel editor) is task 16.
+
+## Goal
+
+After this task:
+
+1. `src/vendor/character-studio/` contains the upstream `CharacterManager` and its direct dependencies, trimmed to what we actually need (no React, no the CharacterStudio Next.js app shell).
+2. A thin adapter `src/character/character-manager.js` exposes a stable API the rest of the app can depend on, hiding upstream changes.
+3. A smoke test: instantiating `CharacterManager`, loading a manifest, attaching the resulting `scene` to our viewer — works.
+4. Attribution is in `src/vendor/character-studio/NOTICE` (MIT text + upstream URL + commit SHA we vendored from).
+
+## Deliverable
+
+1. **Fetch upstream** — `git clone https://github.com/M3-org/CharacterStudio /tmp/character-studio` (shallow clone fine). Note the commit SHA; record it in `NOTICE`.
+2. **Identify the core** — in upstream, locate `CharacterManager` and the modules it directly imports. Typically: character loading, asset swapping, VRM manipulation, export-to-GLB helpers. Do NOT pull in:
+ - React components
+ - Next.js routing
+ - UI styling
+ - Anything under `src/components/` that imports JSX
+3. **Copy the minimal set** into `src/vendor/character-studio/`. Preserve the original relative import paths within that tree; adjust only the entry point.
+4. **Adapter** `src/character/character-manager.js` — exports a class `CharacterManager` (our name, wraps the upstream one) with:
+ - `async loadManifest(url)` — loads an asset manifest JSON.
+ - `async loadTrait(traitGroup, traitId)` — e.g., `loadTrait('hair', 'hair-03')`.
+ - `async removeTrait(traitGroup)`.
+ - `getScene()` — returns a `THREE.Object3D` to add to the scene.
+ - `async exportVRM()` / `async exportGLB()` — returns a `Blob`.
+ - `dispose()`.
+5. **Manifest bootstrap** — create `public/character-manifest.example.json` showing the schema. Task 17 replaces this with a real asset library.
+6. **Viewer hook** — when a `CharacterManager` instance is created and `getScene()` is called, the consumer (future editor UI) decides when to add it. No automatic wiring in the viewer — keep the runtime pluggable.
+7. **License handling** — copy upstream `LICENSE` verbatim to `src/vendor/character-studio/NOTICE` with a prepended line: `Vendored from https://github.com/M3-org/CharacterStudio @ <SHA>`.
+
+## Audit checklist
+
+- [ ] Upstream license is MIT (confirm — if it's not, stop and ask before proceeding).
+- [ ] No React, JSX, Next.js, or Tailwind references in `src/vendor/character-studio/`.
+- [ ] `grep -r "react" src/vendor/character-studio/` returns zero matches in code (descriptions in comments ok but note them).
+- [ ] The adapter surface in `src/character/character-manager.js` does not leak upstream internals (consumers should not need to import anything from `src/vendor/`).
+- [ ] `NOTICE` file includes upstream URL, commit SHA, and full MIT license text.
+- [ ] `node --check src/character/character-manager.js` parses.
+- [ ] `npx vite build` completes.
+
+## Constraints
+
+- Vendor only. No npm install of CharacterStudio or its UI deps.
+- Do not modify upstream source beyond the minimum required to make imports resolve in our tree. If you must patch, wrap the change in a `// PATCH:` comment explaining why.
+- If the upstream depends on a non-MIT package, either use the npm version of that sub-dep or stop and flag it.
+- Don't wire up the side-panel UI, hotbar, or any controls. That's task 16.
+- Don't modify [src/viewer.js](../../src/viewer.js).
+
+## Verification
+
+1. `node --check` each new JS file.
+2. `npx vite build` passes.
+3. Smoke test in DevTools console:
+ ```js
+ const { CharacterManager } = await import('/src/character/character-manager.js');
+ const mgr = new CharacterManager({ renderer: VIEWER.app.viewer.renderer });
+ await mgr.loadManifest('/character-manifest.example.json');
+ VIEWER.app.viewer.scene.add(mgr.getScene());
+ ```
+ Avatar appears. No console errors.
+4. `mgr.dispose()` removes the character and frees GPU resources (verify via `renderer.info.memory`).
+
+## Scope boundaries — do NOT do these
+
+- No editor UI (task 16).
+- No asset library (task 17).
+- No photo-to-avatar (tasks 07, 08).
+- Do not couple `CharacterManager` to the viewer's camera, lights, or controls — keep it scene-graph-only.
+
+## Reporting
+
+- Upstream commit SHA vendored.
+- Total bytes of vendored code (`du -sh src/vendor/character-studio`).
+- List of files copied (or a `tree` output).
+- Any patches applied, with a one-line reason each.
+- Any upstream deps that remain as npm installs vs were vendored inline (with rationale).
+- Confirmation that the smoke test avatar rendered correctly.
diff --git a/prompts/avatar-platform/04-desktop-photo-capture.md b/prompts/avatar-platform/04-desktop-photo-capture.md
new file mode 100644
index 000000000..0373ee7dc
--- /dev/null
+++ b/prompts/avatar-platform/04-desktop-photo-capture.md
@@ -0,0 +1,87 @@
+# Task: Desktop three-shot webcam photo capture
+
+## Context
+
+Repo: `/workspaces/3D`. We're building an Avaturn-style photo-to-avatar flow. This task handles the **desktop capture surface**: a modal that requests webcam permission, guides the user through three captures (left profile, center, right profile), and hands off a `{ left, center, right }` triple of `Blob`s to a callback.
+
+This task does not generate the avatar — that's tasks 07 (fast, MediaPipe) and 08 (HD, NextFace backend). It also does not handle mobile capture — that's task 06. It just captures.
+
+## Goal
+
+After this task:
+
+1. A new `PhotoCapture` module can be opened from anywhere in the app, prompts camera permission, and walks the user through three framed captures with clear visual guidance.
+2. On completion, it resolves with `{ left: Blob, center: Blob, right: Blob }`.
+3. On cancel / permission denied / error, it rejects with a typed error.
+4. Reduced-motion and keyboard navigation are fully supported.
+
+## Deliverable
+
+1. **New module** `src/capture/photo-capture.js` exporting default class `PhotoCapture`:
+ - `constructor(container, options)` — `options: { jpegQuality = 0.92, targetSize = { w: 1024, h: 1024 } }`.
+ - `async open() -> Promise<{ left: Blob, center: Blob, right: Blob }>` — opens modal, resolves on success, rejects on cancel.
+ - `dispose()` — stops tracks, removes DOM.
+2. **Modal UX**:
+ - Title: "Take three photos to build your avatar"
+ - Live `<video>` preview with a face-oriented overlay guide (SVG circle + rule-of-thirds hints).
+ - Current step indicator (1/3, 2/3, 3/3) + labeled step: "Left profile" / "Face forward" / "Right profile".
+ - Primary button: "Capture" (`space` or `enter` to trigger).
+ - Retake button on each thumbnail after capture.
+ - Cancel button (`escape`).
+3. **Capture pipeline**:
+ - `getUserMedia({ video: { width: { ideal: 1280 }, height: { ideal: 720 }, facingMode: 'user' } })`.
+ - Draw current frame to an offscreen `<canvas>`, resize to `targetSize`, encode as JPEG at `jpegQuality` via `canvas.toBlob()`.
+ - Show thumbnail for each captured step.
+4. **Error handling** — rejections:
+ - `PhotoCaptureError('permission_denied')` if `NotAllowedError`.
+ - `PhotoCaptureError('no_camera')` if `NotFoundError`.
+ - `PhotoCaptureError('cancelled')` on user cancel.
+ - `PhotoCaptureError('unsupported')` if `navigator.mediaDevices` is missing.
+5. **Styling** — add a block to [style.css](../../style.css) using the `capture-*` class prefix. Dark theme, matches the existing agent panel aesthetic.
+6. **Accessibility**:
+ - Focus trap in modal.
+ - `aria-live` region announces step changes.
+ - Buttons have `aria-label`.
+ - `prefers-reduced-motion: reduce` disables modal entry/exit animation.
+
+## Audit checklist
+
+- [ ] `node --check src/capture/photo-capture.js`.
+- [ ] Permission denial rejects with `PhotoCaptureError('permission_denied')`, not a generic `Error`.
+- [ ] Escape key cancels; resolve/reject is exclusive (cancel after two captures does not leak a third).
+- [ ] Camera tracks are stopped in all exit paths (success, cancel, error, `dispose()`).
+- [ ] Thumbnails render immediately after capture — no flicker.
+- [ ] Retake replaces the blob cleanly (no accumulated memory — verify by re-taking 10× and watching heap).
+- [ ] On a device with no camera, the "unsupported" / "no_camera" branch shows a clear message and rejects.
+- [ ] Tab key cycles inside modal only.
+
+## Constraints
+
+- No external deps. Pure `MediaDevices` + canvas.
+- No TypeScript.
+- Do not send images anywhere. This task stops at producing blobs — network is tasks 05, 08.
+- Do not integrate with the viewer yet. The opener and consumer belong to a later task (07 wires the fast path).
+- Do not add analytics, telemetry, or third-party pixels.
+
+## Verification
+
+1. Dev server, from DevTools console: `const pc = new (await import('/src/capture/photo-capture.js')).default(document.body); const triple = await pc.open();` — walks through the flow, returns three blobs.
+2. Deny permission at prompt → rejects with `permission_denied`.
+3. Escape during capture → rejects with `cancelled`, tracks stopped (check `pc` has no live tracks).
+4. Take photos, retake the center one, finalize → the center blob reflects the retake.
+5. `prefers-reduced-motion: reduce` → modal appears instantly, no slide/fade.
+
+## Scope boundaries — do NOT do these
+
+- No avatar generation. Blobs in, blobs out.
+- No mobile browser UI (different constraints, handled in task 06).
+- No upload logic.
+- No file-picker fallback — webcam only. (File upload is a future addition behind a different flag.)
+- Do not auto-open the capture modal on page load.
+
+## Reporting
+
+- Observed video resolution on your dev machine (`track.getSettings()`).
+- Blob sizes for the three captures at default quality.
+- Any Safari/iOS-specific quirks discovered (autoplay, `playsinline`, `getUserMedia` gating).
+- Whether the rule-of-thirds overlay actually helps framing in practice, or should be removed.
diff --git a/prompts/avatar-platform/05-session-bridge.md b/prompts/avatar-platform/05-session-bridge.md
new file mode 100644
index 000000000..d6936ab3b
--- /dev/null
+++ b/prompts/avatar-platform/05-session-bridge.md
@@ -0,0 +1,87 @@
+# Task: Session bridge — ephemeral channel for desktop↔mobile handoff
+
+## Context
+
+Repo: `/workspaces/3D`. To replicate Avaturn's QR-to-phone flow (desktop opens QR → phone captures photos → result appears back on desktop), we need a short-lived relay that pairs two clients by a session ID without requiring a user account.
+
+This task ships the **transport only** — a backend endpoint (or serverless function) plus a browser client. The phone UI is task 06, desktop QR UI is task 06. The capture flow is task 04. This task is the pipe between them.
+
+## Goal
+
+After this task:
+
+1. A desktop client can `createSession()` and receive a short `sessionId` + a `sessionUrl` pointing at the mobile route.
+2. The desktop subscribes to the session and receives events pushed from the mobile side (photos, status).
+3. The mobile client can `attachSession(sessionId)` and post events.
+4. Sessions auto-expire after 10 minutes.
+5. All session data is ephemeral: no persistence to a DB, no logging of image contents.
+
+## Deliverable
+
+1. **Backend choice** — decide between:
+ - A. **Vercel Edge Function + Upstash Redis** (matches existing [vercel.json](../../vercel.json) hint in [package.json:41](../../package.json#L41)). Document the env vars needed.
+ - B. **Standalone Node/Bun server** under `server/session/` with in-memory map + SSE.
+ - Default to A if the project already deploys to Vercel; else B. **Document the decision** in the reporting section.
+2. **Endpoints** (names are fixed regardless of backend choice):
+ - `POST /api/session/new` → `{ sessionId, sessionUrl, expiresAt }`. `sessionUrl` is `https://<host>/m/<sessionId>`.
+ - `GET /api/session/:id/stream` — Server-Sent Events stream pushing `{ type, data }` events to the subscriber (desktop).
+ - `POST /api/session/:id/events` — mobile posts `{ type, data }` events (JSON body, multipart for images).
+ - `GET /api/session/:id` → metadata only (`{ status, lastEventAt }`), no event payloads.
+3. **Client module** `src/capture/session-client.js`:
+ - `async createSession() -> { sessionId, sessionUrl, stream }` — `stream` is an `AsyncIterable<Event>`.
+ - `async attachSession(sessionId) -> { post(type, data) }`.
+ - Auto-reconnects SSE on drop (with backoff).
+4. **Security**:
+ - Session IDs are 128-bit random, URL-safe base64 (~22 chars).
+ - Rate-limit: max 5 `/api/session/new` per IP per minute; max 20 events per session; max 10 MB total payload per session.
+ - No CORS wildcard — allow the deployed origin + `localhost`.
+ - Images never written to disk; streamed through memory and discarded after dispatch.
+5. **Expiry** — sessions self-destruct after 10 min from `createdAt`, or 2 min after `terminated` event, whichever comes first.
+6. **Observability** — a minimal counter log line per session (`[session] new <id>`, `[session] end <id> reason=<expiry|done|error>`). **Never** log event payloads.
+
+## Audit checklist
+
+- [ ] Session IDs are unguessable (128 bits of entropy).
+- [ ] Expired sessions return 410 Gone; unknown IDs return 404.
+- [ ] SSE stream closes cleanly on `terminated`.
+- [ ] Rate limits are enforced and return 429 with `Retry-After`.
+- [ ] No image data in logs (grep a full-flow log for common bytes / base64 fragments).
+- [ ] Disabling Upstash env vars makes the backend fail loudly at startup (A only), not silently.
+- [ ] CORS policy blocks other origins.
+- [ ] `node --check` the new JS files.
+- [ ] Dev server + endpoints work locally without Upstash (A: document a `LOCAL_DEV=1` fallback to in-memory; B: no fallback needed).
+
+## Constraints
+
+- No auth / user accounts. This is intentionally an ephemeral pairing channel.
+- No DB of images; payloads live in memory or Redis with TTL only.
+- No WebRTC — the blobs need a server-mediated path so the desktop doesn't need to be reachable.
+- No WebSockets unless SSE is genuinely insufficient (it isn't here — one-way stream desktop←mobile plus REST mobile→desktop).
+- Do not ship this behind the existing Avaturn flow — it's independent infrastructure.
+- Do not add tracing/APM SDKs.
+
+## Verification
+
+1. `npm run dev` (and any backend start command for option B).
+2. `curl -X POST http://localhost:3000/api/session/new` → returns session triple.
+3. Open `curl -N http://localhost:3000/api/session/<id>/stream` in one terminal; `curl -X POST .../events -d '{"type":"hello","data":{}}'` in another — event appears on the SSE stream.
+4. Post 11 events in rapid succession → 11th returns 429.
+5. Wait 10 min → session returns 410.
+6. Post 11 MB → rejected.
+7. Two concurrent sessions stay isolated (no cross-delivery).
+
+## Scope boundaries — do NOT do these
+
+- No QR rendering (task 06).
+- No photo capture (tasks 04, 06).
+- No avatar generation (tasks 07, 08).
+- No admin UI to list sessions.
+- No session resumption after browser refresh on the desktop — keep it simple; desktop reload = new session.
+
+## Reporting
+
+- Backend choice (A or B) with one sentence on why.
+- Env vars required to deploy.
+- Measured median and p95 latency for a 2 MB image event (mobile post → desktop SSE receipt) on local dev.
+- Any unavoidable pitfalls with SSE through Vercel's edge runtime (if applicable).
+- Recommended monitoring dashboard once this ships (descriptive only, don't implement).
diff --git a/prompts/avatar-platform/06-mobile-capture-route.md b/prompts/avatar-platform/06-mobile-capture-route.md
new file mode 100644
index 000000000..7986431a6
--- /dev/null
+++ b/prompts/avatar-platform/06-mobile-capture-route.md
@@ -0,0 +1,80 @@
+# Task: Mobile capture route and desktop QR handoff
+
+## Context
+
+Repo: `/workspaces/3D`. Task 04 built desktop webcam capture. Task 05 built the session bridge. This task stitches them for the **phone-scan-QR-to-capture** flow: the desktop shows a QR; the phone opens it; phone captures three photos; they stream back to the desktop; the desktop proceeds.
+
+Depends on tasks 04 and 05.
+
+## Goal
+
+1. A new page `m.html` (plus its entry module) is the landing for `/m/:sessionId` URLs — a mobile-first photo capture UI that uses the `MediaDevices` rear-facing `user` camera.
+2. The desktop has a module that renders a QR code for a session URL and listens on the SSE stream for captured photos.
+3. The end-to-end flow works: desktop scan-with-phone → three photos on phone → blobs arrive on desktop → resolves identical shape to task 04 (`{ left, center, right }`).
+4. Works offline on the phone side after the initial HTML load (enable via the existing [vite-plugin-pwa](../../package.json#L60) config — scope the cache to `m.html` and its assets).
+
+## Deliverable
+
+1. **Mobile route entry** `m.html` at the repo root + [vite.config.mjs](../../vite.config.mjs) tweak to register it as an additional input. Page content:
+ - Detects `window.location.pathname` → extracts `sessionId`.
+ - Loads `src/capture/mobile-capture.js`.
+ - Renders full-screen camera preview + capture UI optimized for portrait phone form factor.
+2. **New module** `src/capture/mobile-capture.js`:
+ - `init(sessionId)` — attaches to the session via `attachSession()` from task 05.
+ - Three-shot capture flow (left, center, right), mirrored from desktop task 04 but redesigned for touch + portrait + single-hand use.
+ - On each capture, POST the blob to `/api/session/:id/events` with `type: 'photo'`, `step: 'left'|'center'|'right'`.
+ - After the third capture, POST `type: 'done'` and show "Photos sent — check your desktop".
+ - Front-camera only (`facingMode: 'user'`).
+ - Fallback: if `getUserMedia` fails, show a file-picker accepting three images with `capture="user"` hint.
+3. **Desktop QR handoff module** `src/capture/qr-handoff.js`:
+ - `async open(container): Promise<{ left, center, right }>` — same return shape as `PhotoCapture` from task 04.
+ - Creates a session via `createSession()`, renders the `sessionUrl` as a QR code (use the `qrcode` npm package — add it, it's ~7 KB gzipped).
+ - Shows a waiting state with spinner + "Scan to continue on your phone".
+ - Subscribes to the SSE stream; collects three `photo` events, resolves when `done` arrives.
+ - Has a "Use webcam instead" button that disposes the QR flow and opens `PhotoCapture` from task 04.
+4. **Styling** — `capture-mobile-*` prefix for the mobile-only CSS. Keep the mobile route CSS in a separate stylesheet loaded only by `m.html` to avoid bloat on the main app.
+5. **PWA config** — update `vite-plugin-pwa` options so `m.html` and its module chunk are precached. The main app's existing PWA behavior must not regress.
+
+## Audit checklist
+
+- [ ] Visiting `/m/<valid-session-id>` on a phone opens the camera and shows the left/center/right walkthrough.
+- [ ] Visiting `/m/<expired-or-unknown>` shows a friendly "session expired or not found" page with a link to the main app.
+- [ ] QR on desktop renders correctly and is large enough to scan at arm's length (≥ 240px on a 1080p display).
+- [ ] Three photos taken on phone → three blobs appear on desktop → resolution matches `{ left, center, right }` shape.
+- [ ] Kill the phone mid-capture → desktop shows "session abandoned" after the 10-min expiry (task 05's TTL).
+- [ ] "Use webcam instead" fallback resolves with the same shape.
+- [ ] The desktop flow works on localhost with HTTPS via `vite --https` or an HTTPS tunnel (document how — `mkcert`, `cloudflared`, or Vite's self-signed mode).
+- [ ] `npx vite build` produces the extra `m.html` entry.
+
+## Constraints
+
+- Mobile page must be independently cacheable — offline reload must still render the capture UI. Network only needed for `/api/session/...`.
+- Do not share CSS bundles between `m.html` and the main app — mobile bundle stays lean.
+- Keep the total JS for the mobile route under 50 KB gzipped (excluding images). MediaPipe is NOT loaded here — this page only captures. Server does the heavy lifting in tasks 07/08.
+- Do not require login.
+- `qrcode` dependency is the only new npm add.
+
+## Verification
+
+1. Dev server with HTTPS (required for `getUserMedia` on mobile).
+2. Desktop: open QR flow → phone scans → captures → desktop resolves.
+3. Open `/m/<random-invalid-id>` → graceful error page, no JS crash.
+4. Test on at least one real Android + one iOS device. Document which and any quirks.
+5. Airplane-mode test: load `m.html` once on the phone, toggle airplane mode, reload → PWA renders the UI shell. Turn airplane off → a retry button recovers the session if still valid.
+6. Lighthouse score on `m.html` → Performance ≥ 90 on mobile emulation.
+
+## Scope boundaries — do NOT do these
+
+- Do not generate the avatar. Just move blobs across the bridge.
+- Do not persist captured photos beyond the session TTL (already enforced by task 05).
+- Do not implement end-to-end encryption between phone and desktop — noted as future work.
+- Do not add user accounts or cross-device linking beyond this session pairing.
+- Do not change the main app shell.
+
+## Reporting
+
+- Real devices tested + OS/browser versions.
+- Measured session-creation → blob-arrival latency over WiFi and 4G.
+- The `qrcode` package version and its gzipped size impact on the desktop bundle.
+- Any iOS `getUserMedia` quirks (playsinline, autoplay, permission persistence).
+- Screenshots or a short screencap of the full desktop-phone-desktop flow.
diff --git a/prompts/avatar-platform/07-photo-to-avatar-fast.md b/prompts/avatar-platform/07-photo-to-avatar-fast.md
new file mode 100644
index 000000000..7b21f15c6
--- /dev/null
+++ b/prompts/avatar-platform/07-photo-to-avatar-fast.md
@@ -0,0 +1,84 @@
+# Task: Browser-side photo-to-avatar (MediaPipe fast path)
+
+## Context
+
+Repo: `/workspaces/3D`. Tasks 04/06 deliver `{ left, center, right }` photo blobs. This task converts that triple into a **first-pass avatar** entirely client-side, in seconds, using Google's MediaPipe Face Landmarker (Apache-2.0) to detect 478 3D landmarks + 52 blendshapes.
+
+The output is recognizable, not photoreal. It's the "instant gratification" result that shows the user something immediately while the HD path (task 08) runs in the background.
+
+Depends on tasks 02 and 04 (or 06).
+
+## Goal
+
+1. Given `{ center: Blob }` (left/right are ignored in v1 — they'll feed task 08), produce a VRM file (or a patched VRM from a base template) that resembles the user.
+2. The template is a neutral base VRM bundled in [public/avatars/](../../public/avatars/).
+3. Customization applied:
+ - Head shape morphed toward the detected face via landmark-driven morph targets or a blendshape approximation.
+ - Face texture projected from the center photo.
+ - Skin tone sampled from the face and applied to exposed skin slots.
+ - Hair kept from the template (editor UI in task 16 lets the user swap).
+4. Total time from blob in to avatar rendered < 5 seconds on a mid-range laptop.
+
+## Deliverable
+
+1. **Base template** — `public/avatars/template-neutral.vrm`. A rigged, expression-ready VRM with a neutral face. Source with CC0/MIT license only. Record in `public/avatars/NOTICES.md`.
+2. **MediaPipe integration** `src/capture/face-landmarks.js`:
+ - Loads MediaPipe Face Landmarker WASM + model from a CDN or vendored at `public/vendor/mediapipe/`.
+ - Exports `detectFace(blob) -> { landmarks: Float32Array[478*3], blendshapes: Record<string, number>, matrix: Float32Array[16] }`.
+ - Model is loaded lazily on first call, cached for subsequent calls.
+3. **Avatar generator** `src/capture/fast-avatar.js`:
+ - `async generate({ center, left?, right? }) -> Blob` — a VRM Blob.
+ - Loads the template VRM, applies morphs/textures, exports with `VRMExporter` (from `@pixiv/three-vrm-core` or implement via `GLTFExporter` + manual VRM extension patching).
+4. **Head-shape approximation** — use a small set of morph-target drivers:
+ - Face width → `faceWidth` morph (if template has it) or a scale on jaw bones.
+ - Face length → scale Y on cranium bone.
+ - Nose prominence → nose morph or localized mesh displacement.
+ - Document exactly which drivers the template exposes in `public/avatars/template-neutral.vrm.meta.json`.
+5. **Texture projection** — crop the center photo to the face region detected by MediaPipe, warp to the template's UV head region using the 478-landmark topology. Use a small offscreen canvas + perspective warp. This is the biggest quality lever; budget it explicitly.
+6. **Skin-tone sampling** — average pixels inside the face mesh polygon (excluding eyes/mouth), convert to linear sRGB, find nearest slot and apply to all skin-mapped materials.
+7. **Fallback** — if MediaPipe fails to detect a face, resolve with the plain template and emit a `photo_quality_low` warning; the caller can surface a "retake" option.
+
+## Audit checklist
+
+- [ ] `generate({ center })` on a test photo completes in < 5s on a dev machine (document the machine).
+- [ ] Output is a valid VRM that loads in the viewer (task 02 path).
+- [ ] Skin tone of the output visibly matches the input photo within a reasonable delta (no pink Caucasian default for a darker-skinned input).
+- [ ] Three very different faces produce three visibly different avatars.
+- [ ] A photo with no face rejects or returns a flagged template — doesn't silently produce garbage.
+- [ ] MediaPipe model is loaded once per page session, not per call.
+- [ ] No PII persisted: after `generate` resolves, no image bytes remain in module state.
+- [ ] `node --check` the new JS.
+- [ ] Bundle impact: MediaPipe loader code ≤ 20 KB; the WASM + model are lazy-loaded and cached by the browser / service worker.
+
+## Constraints
+
+- Client-only. No network calls beyond the MediaPipe model fetch (CDN or self-hosted).
+- No ML model training or fine-tuning in-browser. MediaPipe's stock model only.
+- Do not attempt photoreal texture stitching from all three photos — that's task 08's job (server-side, NextFace).
+- The template VRM must be CC0/MIT; flag and stop if nothing fits.
+- Use `@pixiv/three-vrm` for load/save; don't reinvent the VRM parsing.
+
+## Verification
+
+1. `node --check` new files.
+2. Run the full flow: task 04's `PhotoCapture.open()` → pass blobs to `generate()` → add resulting scene to viewer.
+3. Five test images (diverse lighting, skin tones, angles, one with glasses, one low-quality) → each produces a sensible avatar or a clear reject.
+4. Time the pipeline with `performance.now()` — include mean, p95, max.
+5. Close and reopen the tab; re-run → MediaPipe loads from cache on second run.
+
+## Scope boundaries — do NOT do these
+
+- No HD face reconstruction — that's task 08.
+- No voice/speech wiring.
+- No saving to a backend — the returned VRM Blob is handed to the caller.
+- No editor UI — the user can only see the avatar after generation; customization comes in task 16.
+- Do not attempt to generate hair from the photo. Too fragile; keep template hair.
+
+## Reporting
+
+- MediaPipe Face Landmarker version used and model URL.
+- Template VRM source + license + a note on which morph targets it exposes.
+- Median/p95/max generation time + dev machine specs.
+- A short qualitative assessment: "for these N test faces, this path is {recognizable / uncanny / unusable}".
+- Known failure modes (e.g., side-lit photos, non-frontal angles, heavy makeup) and which ones warrant a retake prompt in task 20's onboarding.
+- Flag any texture-projection artifacts that suggest we need a different warping approach.
diff --git a/prompts/avatar-platform/08-photo-to-avatar-hd.md b/prompts/avatar-platform/08-photo-to-avatar-hd.md
new file mode 100644
index 000000000..75382dcbf
--- /dev/null
+++ b/prompts/avatar-platform/08-photo-to-avatar-hd.md
@@ -0,0 +1,87 @@
+# Task: HD photo-to-avatar backend (NextFace)
+
+## Context
+
+Repo: `/workspaces/3D`. Task 07 ships a fast, in-browser avatar. This task adds the **high-fidelity path**: a GPU backend running [abdallahdib/NextFace](https://github.com/abdallahdib/NextFace) (MIT) that accepts three photos and returns a photoreal head mesh + textures, which we re-topologize onto our VRM template.
+
+This is the "Avaturn quality" tier. It runs async in the background: task 07's result shows immediately; task 08's result replaces it a minute later when ready.
+
+Depends on task 07 (to have a result to replace).
+
+## Goal
+
+1. A containerized NextFace service with a REST endpoint: `POST /api/reconstruct` accepting three images, returning a mesh + albedo + normal map archive.
+2. A client-side module that posts to that endpoint and, on completion, patches the VRM from task 07 with the higher-fidelity head geometry and textures.
+3. Sensible fallback: if the service is down or slow, the fast-path avatar simply remains in place.
+
+## Deliverable
+
+1. **Backend service** under `services/nextface/`:
+ - `Dockerfile` starting from a PyTorch CUDA base image.
+ - `requirements.txt` with NextFace's pins (pull from upstream).
+ - `server.py` — a minimal FastAPI or Flask app exposing:
+ - `POST /api/reconstruct` — multipart with `center`, `left`, `right` image fields → returns a `application/zip` of `{ mesh.obj, albedo.png, normal.png, meta.json }`.
+ - `GET /health` — GPU status, queue depth, model warm/cold.
+ - Concurrency: one job at a time per GPU; additional requests queue.
+ - Timeouts: 120s hard cap, 60s soft target.
+2. **Deployment docs** in `services/nextface/DEPLOY.md`:
+ - Supported hardware (minimum: 8 GB VRAM, CUDA 11.8+).
+ - One-liner to run locally: `docker build && docker run --gpus all -p 8080:8080 ...`.
+ - One production target choice: Modal, Replicate, RunPod, Baseten, or self-hosted. **Pick one and document it**. Don't spread across all.
+3. **Client module** `src/capture/hd-avatar.js`:
+ - `async requestHD(blobs, baseVRMBlob, { endpoint, timeoutMs = 90000 })` → Promise<`Blob` (upgraded VRM)> or rejects.
+ - Posts multipart, streams progress events if the backend supports them (optional, nice-to-have).
+ - Applies the returned mesh + textures onto the VRM from task 07:
+ - Replaces head mesh geometry (keeping bone weights re-projected via closest-point mapping).
+ - Replaces face texture.
+ - Normal map applied to the head material if the VRM supports it.
+4. **Orchestration** `src/capture/avatar-pipeline.js`:
+ - Combines 07 + 08. `async runPipeline(blobs, { onFast, onHD, onError })`:
+ - Resolves `onFast` with the fast-path VRM.
+ - In parallel, kicks off `requestHD`; on resolve, calls `onHD` with the upgraded VRM.
+ - On HD failure, calls `onError({ stage: 'hd' })` but does not discard the fast-path result.
+5. **Config** — `VITE_HD_ENDPOINT` env var for the client; `NEXTFACE_MODEL_DIR` for the backend.
+
+## Audit checklist
+
+- [ ] NextFace license is MIT (confirm upstream before starting).
+- [ ] End-to-end latency (three 1MP photos → HD VRM) is < 90s p95 on the chosen production target.
+- [ ] If the backend is unreachable, the pipeline emits `onError({ stage: 'hd' })` without discarding the fast-path avatar.
+- [ ] The re-topologized mesh keeps the VRM humanoid rig intact — expressions still work after the HD patch.
+- [ ] Skin tone on the HD result matches the photos more closely than task 07's result (visual check on 3 test faces).
+- [ ] No photos persist on the backend beyond the request lifecycle (confirm via filesystem audit in the Dockerfile's tmpfs usage).
+- [ ] Backend has auth: a bearer token or signed session token (reuse task 05's session IDs if that's easiest).
+- [ ] Client respects a global "opt out of HD" setting (env or runtime flag) for privacy-sensitive deploys.
+
+## Constraints
+
+- Do not ship the NextFace model weights in the main frontend bundle.
+- Do not commit GPU-specific binaries to git. Weights download on container start or at build time.
+- Pay cost matters: design so idle cost is ~$0 (scale-to-zero).
+- Do not proxy images through the main app server; the client posts directly to the HD endpoint (with a pre-signed token from task 05 if needed).
+- Do not train, fine-tune, or upload photos to a third-party ML service.
+
+## Verification
+
+1. Build and run the Docker image locally on a machine with a GPU (or a cloud dev env). Hit `/health` → 200.
+2. `curl -F [email protected] -F [email protected] -F [email protected] http://localhost:8080/api/reconstruct` → returns a zip.
+3. Run the full pipeline via `avatar-pipeline.js` in the browser → `onFast` fires in < 5s, `onHD` fires in < 90s with a noticeably better avatar.
+4. Kill the backend mid-flight → `onError` fires, fast-path result remains displayed.
+5. Budget check: confirm your chosen platform can handle 100 concurrent jobs at the queued-throughput target, and estimate the cost per avatar.
+
+## Scope boundaries — do NOT do these
+
+- No additional face-reconstruction models beyond NextFace. We can swap later if quality is wrong, but one model per task.
+- No hair/body reconstruction — face only. Body comes from the template + editor.
+- No video input — stills only.
+- Do not store reconstructed avatars on the backend; return once, discard.
+
+## Reporting
+
+- Chosen deployment target + a one-sentence rationale.
+- Upstream NextFace commit SHA used.
+- Latency numbers (mean, p95, max) on the chosen hardware.
+- Per-avatar GPU cost estimate.
+- Qualitative quality delta vs task 07 on the same 5 test faces.
+- Known failure modes of NextFace itself (e.g., occluded faces, extreme expressions) and how the client surfaces them.
+- Privacy posture: exactly what leaves the browser, what the backend sees, what persists where, for how long.
diff --git a/prompts/avatar-platform/09-talking-head.md b/prompts/avatar-platform/09-talking-head.md
new file mode 100644
index 000000000..225c3e9a1
--- /dev/null
+++ b/prompts/avatar-platform/09-talking-head.md
@@ -0,0 +1,71 @@
+# Task: Vendor met4citizen/TalkingHead and wire it to the active VRM
+
+## Context
+
+Repo: `/workspaces/3D`. [met4citizen/TalkingHead](https://github.com/met4citizen/TalkingHead) (MIT) is a production-quality real-time lipsync + body-animation engine for full-body 3D avatars. It speaks Oculus visemes, supports Mixamo FBX animations, and has built-in idle behaviors.
+
+Task 02 loads VRMs. This task makes them talk, blink, fidget, and gesture.
+
+Depends on task 02.
+
+## Goal
+
+1. `src/vendor/talking-head/` contains the upstream engine, vendored with attribution.
+2. A thin adapter `src/agent/talking-head.js` exposes a stable API the agent brain (task 14) can call: `speak(text)`, `setMood(emotion)`, `playGesture(name)`.
+3. The adapter binds to `VIEWER.app.viewer.activeVRM` from task 02; when a new VRM loads, the engine re-attaches automatically.
+4. Idle behaviors (subtle head sway, eye darts, blinks) run at all times when a VRM is loaded.
+
+## Deliverable
+
+1. **Vendor** — clone upstream, record SHA + MIT license in `src/vendor/talking-head/NOTICE`. Copy only the engine module(s); skip demo HTML/CSS.
+2. **Dependencies** — TalkingHead expects three.js (we have it) and, for its TTS path, browser APIs. It has optional ties to ElevenLabs / Azure; **do not vendor those paths** — task 10 provides our own TTS with visemes.
+3. **Adapter** `src/agent/talking-head.js`:
+ - `class TalkingHead { attach(vrm): void; detach(): void; async speak(text, { visemes?, audio? }); setMood(name, strength); playGesture(name); idleOn(); idleOff(); dispose(); }`
+ - If `visemes` + `audio` are supplied (from task 10), use them directly. If only `text` is supplied, emit a warning — task 10 is the expected provider.
+4. **Render-loop integration** — the adapter registers a `tick(delta)` callback that the existing render loop already calls (see how [src/viewer.js](../../src/viewer.js) drives animation). Don't start a second RAF loop.
+5. **Auto-attach** — observe `activeVRM` changes. When a new VRM loads (task 02 swap), detach from the old one (if any) and attach to the new. When `activeVRM` is null, idle is paused.
+6. **Animation library** — optional: if upstream bundles or expects Mixamo FBX idle loops, put them in [public/animations/](../../public/animations/) with per-file license notes. Keep the set minimal (1 idle, 1 wave, 1 nod).
+
+## Audit checklist
+
+- [ ] Upstream license is MIT (confirm).
+- [ ] `node --check` new JS files.
+- [ ] Console smoke test: `await VIEWER.app.talkingHead.speak('hello world')` — the avatar mouths the syllables. Without task 10 ready, this emits the warning and does text-only animation (jaw open/close approximation).
+- [ ] Loading a new VRM mid-session → idle resumes on the new avatar, old one's listeners are gone.
+- [ ] Disposing the viewer (see task 19) cleanly removes all TalkingHead listeners.
+- [ ] Idle does not pin CPU — FPS on a mid-range laptop with idle active stays ≥ 55 fps on a blank background.
+- [ ] `prefers-reduced-motion: reduce` → idle is dampened (no sway, slow blinks only).
+
+## Constraints
+
+- Vendor, do not npm. TalkingHead is a single class; don't take its peripheral demo code.
+- Do not depend on any TTS service in this task. Task 10 supplies audio+visemes.
+- Do not couple to Ready Player Me — we use VRM (RPM avatars are GLB; TalkingHead supports both, but we commit to VRM). Strip RPM-specific code paths.
+- Do not modify the engine internals beyond the minimum needed for the VRM path. Wrap changes in `// PATCH:` comments.
+- Don't add audio playback here — only consume provided audio objects. Playback wiring lives in task 10.
+
+## Verification
+
+1. Load `sample.vrm` (task 02). Call `speak('hello world')` — warning about missing visemes, but jaw moves.
+2. Idle on → avatar blinks, micro-sways. FPS stable.
+3. Swap VRMs → idle re-attaches.
+4. Reduced motion → idle dampened.
+5. `dispose()` → no console errors, no lingering timers (use Chrome Performance → Memory to verify).
+
+## Scope boundaries — do NOT do these
+
+- No TTS integration. Task 10.
+- No STT integration. Task 11.
+- No LLM / brain wiring. Task 14.
+- No mirror mode / webcam driving. Task 12.
+- Do not ship animation packs beyond the minimal set.
+
+## Reporting
+
+- Upstream TalkingHead commit SHA vendored.
+- List of upstream files copied vs skipped.
+- Total bytes vendored.
+- Any patches applied with one-line justifications.
+- Measured fps cost of idle-on vs idle-off.
+- Animations shipped + their sources + licenses.
+- Any upstream bugs encountered that warrant an upstream PR.
diff --git a/prompts/avatar-platform/10-tts-visemes.md b/prompts/avatar-platform/10-tts-visemes.md
new file mode 100644
index 000000000..1f6e89870
--- /dev/null
+++ b/prompts/avatar-platform/10-tts-visemes.md
@@ -0,0 +1,76 @@
+# Task: Browser TTS with viseme timestamps (HeadTTS + Piper fallback)
+
+## Context
+
+Repo: `/workspaces/3D`. Task 09's TalkingHead adapter needs `{ audio, visemes, vtimes, vdurations }` to lipsync properly. We provide this via two cooperating paths:
+
+- **HeadTTS (Kokoro, WebGPU/WASM)** — the primary browser path. Generates speech + phoneme timestamps; phonemes are mapped to Oculus visemes. Runs fully in-browser on modern devices.
+- **[rhasspy/Piper](https://github.com/rhasspy/piper) (self-hosted server)** — the fallback for devices without WebGPU, or users who prefer a smaller client bundle.
+
+Depends on task 09.
+
+## Goal
+
+1. A `TTS` module with a single API, `async synthesize(text, voice) -> { audio: AudioBuffer, visemes: string[], vtimes: number[], vdurations: number[] }`.
+2. Automatic path selection: WebGPU-capable browsers use HeadTTS; others fall through to the Piper server (if configured) or to Web Speech API as a last resort (without visemes, best-effort jaw animation).
+3. Streaming playback: audio starts playing as soon as the first chunk is ready, not after full synthesis.
+4. TalkingHead consumes the output and lipsyncs correctly.
+
+## Deliverable
+
+1. **HeadTTS vendoring** — HeadTTS is part of the TalkingHead author's stack; vendor the browser build into `src/vendor/headtts/`. Include the Kokoro model or document its CDN URL.
+2. **Piper client** `src/agent/tts-piper.js` — POSTs text to a configured `/api/tts` endpoint, receives `{ audioUrl, phonemes: [{ phoneme, startMs, endMs }] }`, maps phonemes to Oculus visemes.
+3. **Piper server** under `services/piper/`:
+ - Dockerfile (CPU-only, small image).
+ - Serves `POST /api/tts` accepting `{ text, voice }` → returns audio + phoneme timestamps.
+ - Pick one Piper voice model (e.g., `en_US-amy-medium`) as default; allow override via `voice` param.
+4. **Unified facade** `src/agent/tts.js`:
+ - `class TTS { constructor({ prefer: 'local'|'server'|'auto' }); async synthesize(text, voice?); dispose(); }`
+ - Capability detection: WebGPU via `navigator.gpu`, WASM SIMD via a quick probe.
+ - Route: `local` → HeadTTS; `server` → Piper; `auto` → HeadTTS if capable else Piper if `/api/tts` reachable else Web Speech API.
+5. **Viseme mapping** `src/agent/viseme-map.js` — phoneme→Oculus viseme table. Oculus visemes: `sil, PP, FF, TH, DD, kk, CH, SS, nn, RR, aa, E, I, O, U`. Document gaps (not all phonemes map cleanly).
+6. **TalkingHead wiring** — update task 09's `talking-head.js` adapter: `speak(text)` now internally calls `tts.synthesize` and passes the result to the engine. The raw `speak(text, { audio, visemes, ... })` overload stays for callers that synthesize externally.
+7. **Audio playback** — use a shared `AudioContext`. Resume on first user interaction (browser autoplay policy). Document the gesture requirement in the reporting section.
+
+## Audit checklist
+
+- [ ] `npx vite build` passes; HeadTTS WASM/WebGPU assets lazy-load.
+- [ ] On a WebGPU-capable browser: `await tts.synthesize('Hello world')` returns audio + ≥ 3 visemes with monotonically increasing times.
+- [ ] Disable WebGPU → Piper server path works; returns equivalent shape.
+- [ ] No Piper server + no WebGPU → Web Speech API path runs; visemes array is empty and TalkingHead shows an "approximate lipsync" mode.
+- [ ] TalkingHead `speak('Hello world')` end-to-end produces recognizably lipsynced mouth movement.
+- [ ] First audio byte plays within 300ms of `synthesize()` resolving (streaming, not "wait for full file").
+- [ ] No audio plays without a prior user gesture; the first `speak()` before a gesture queues and plays on gesture.
+- [ ] `node --check` new JS.
+
+## Constraints
+
+- Vendor HeadTTS; do not npm.
+- Piper server is the only new backend in this task; it must scale to zero cost when unused (same deployment philosophy as task 08).
+- Do not use OpenAI TTS, ElevenLabs, Azure, or any paid cloud TTS. Local + self-hosted only.
+- Do not bundle Kokoro model weights into the main JS — lazy-load the model file.
+- The Web Speech API fallback must not be the default — it's degrade-gracefully only.
+
+## Verification
+
+1. HeadTTS path on Chrome with WebGPU. Measure time-to-first-audio-byte and total-synthesis-time for a 20-word sentence.
+2. Piper path via a locally running Docker container. Measure the same.
+3. Reduced capabilities path (Safari with Web Speech) — lipsync visibly worse but not broken.
+4. End-to-end: agent panel says "Tell me a joke" (fake it from console), TalkingHead speaks and lipsyncs.
+5. Rapid-fire: call `speak()` 3 times quickly — previous utterance cancels, new one starts cleanly (no overlapping audio).
+
+## Scope boundaries — do NOT do these
+
+- No voice cloning.
+- No multi-speaker conversation.
+- No real-time TTS (mid-utterance token streaming). Chunk-streaming is fine, but we're not aiming at duplex real-time.
+- No TTS caching by text content (yet) — each request synthesizes fresh. Caching is a future optimization.
+- Do not add telemetry on what users ask the avatar to say.
+
+## Reporting
+
+- HeadTTS commit SHA vendored + Kokoro model URL.
+- Time-to-first-audio and total-synthesis-time for a reference sentence on both paths.
+- The phoneme→viseme table, with any phonemes that don't have a clean mapping noted.
+- Piper Docker image size.
+- Known quality issues (sibilance, plosives, long vowels) and whether they suggest a different engine long-term.
diff --git a/prompts/avatar-platform/11-speech-to-text.md b/prompts/avatar-platform/11-speech-to-text.md
new file mode 100644
index 000000000..e3d533688
--- /dev/null
+++ b/prompts/avatar-platform/11-speech-to-text.md
@@ -0,0 +1,77 @@
+# Task: In-browser STT with whisper-web
+
+## Context
+
+Repo: `/workspaces/3D`. The current agent panel ([src/agent-panel.js](../../src/agent-panel.js) after task 01) uses the Web Speech API for voice input, which is Chrome/Edge-only and sends audio to Google. We replace it with [xenova/whisper-web](https://github.com/xenova/whisper-web) (MIT), which runs OpenAI's Whisper model in the browser via Transformers.js.
+
+Depends on task 01 (renamed agent panel exists).
+
+## Goal
+
+1. Browser-native STT that works in Chrome, Edge, **and Safari/Firefox** (no Google dependency).
+2. Audio never leaves the device.
+3. Mic button on the agent panel triggers whisper-web; transcription shows up inline as the user speaks (streaming partials) and finalizes on silence or button release.
+4. Fallback to Web Speech API if the device can't run whisper-web (very old / very low memory).
+
+## Deliverable
+
+1. **Vendor or npm** — whisper-web depends on `@xenova/transformers`. Install via npm (it's infrastructural-ish, and bundling Transformers.js manually is painful).
+2. **New module** `src/agent/stt.js`:
+ - `class STT { async start({ onPartial, onFinal, onError }); stop(); dispose(); }`
+ - Loads the whisper `base.en` model (or `tiny.en` on low-memory devices) lazily on first `start()`.
+ - Uses `MediaRecorder` + a VAD-ish silence detector to chunk audio into ~1s windows for streaming transcription.
+ - Supports cancel mid-utterance.
+3. **Capability detection** — `STT.canUseLocal()` returns true if:
+ - `navigator.hardwareConcurrency >= 4`.
+ - `navigator.deviceMemory >= 4` (fallback to `true` on Safari where this API is absent — treat as capable).
+ - WebAssembly SIMD probe passes.
+4. **Agent panel integration** — in `src/agent-panel.js`, replace the Web Speech API block with STT:
+ - Mic button press → `stt.start(...)`.
+ - Partial results render in the input field in a muted color.
+ - Final result commits to the input; auto-sends if "push-to-talk" mode is active (new option).
+ - Release or press-again → `stt.stop()`.
+5. **Fallback wiring** — if `STT.canUseLocal()` is false, dynamically import the old Web Speech path and route through it with the same event shape.
+6. **Model hosting** — prefer the Hugging Face CDN by default; allow override with `VITE_WHISPER_MODEL_URL` for self-hosted deploys.
+
+## Audit checklist
+
+- [ ] Whisper model loads once per session, cached by the browser.
+- [ ] On Chrome, Edge, Firefox, Safari: mic → transcription works.
+- [ ] No audio leaves the device (verify via Network tab — after model load, zero audio-bearing requests).
+- [ ] Pressing the mic button a second time mid-utterance cancels cleanly; no dangling MediaRecorder streams.
+- [ ] Accuracy on a standard test phrase ("The quick brown fox...") within reasonable bounds of whisper-base.en's known performance.
+- [ ] Reduced-motion doesn't affect STT but the "listening" pulse animation respects it.
+- [ ] Accessibility: `aria-live` updates as partial results arrive.
+- [ ] `node --check` new files.
+
+## Constraints
+
+- No cloud STT. Whisper runs locally; fallback is Web Speech (which hits Google but is already what we had).
+- Model size: `base.en` is ~150 MB; load progress UI must show download on first run.
+- Do not share the `AudioContext` with TTS (task 10) — mic capture uses its own context, deliberately separate to avoid feedback.
+- Do not transcribe audio captured by the photo-capture flow (task 04/06). That's video-only; STT is unrelated.
+- Do not log transcribed text to a server. The agent (task 14) uses it locally.
+
+## Verification
+
+1. First run on a fresh browser profile → model download progress UI shows → transcription works after load.
+2. Subsequent runs → instant start.
+3. Non-English utterance → whisper-base.en transcribes English-approximation; flag this in the reporting (a future task could upgrade to multilingual `base`).
+4. Offline (airplane mode after first load) → still works, since model is cached.
+5. Compare accuracy on three test phrases with the old Web Speech path — document delta.
+
+## Scope boundaries — do NOT do these
+
+- No speaker diarization.
+- No wake-word / "hey avatar" trigger — require button press.
+- No always-on listening.
+- No translation.
+- No push-to-server for "cloud whisper" — local only.
+
+## Reporting
+
+- Whisper model chosen + its size + load time on first visit.
+- Accuracy comparison vs Web Speech on the test phrases.
+- Any device classes that fall through to the fallback and why.
+- Memory footprint while transcribing (heap + Transformers internal).
+- Known issues (accents, background noise, very short utterances) and whether they're deal-breakers.
diff --git a/prompts/avatar-platform/12-mirror-mode.md b/prompts/avatar-platform/12-mirror-mode.md
new file mode 100644
index 000000000..d0a20a9ec
--- /dev/null
+++ b/prompts/avatar-platform/12-mirror-mode.md
@@ -0,0 +1,77 @@
+# Task: Mirror mode — webcam drives the avatar's face and upper body
+
+## Context
+
+Repo: `/workspaces/3D`. With VRM loaded (task 02) and TalkingHead attached (task 09), we can add a **mirror mode** where the user's webcam feeds [yeemachine/kalidokit](https://github.com/yeemachine/kalidokit) (MIT). Kalidokit converts MediaPipe landmarks into VRM bone rotations + blendshapes, making the avatar copy the user's face and upper-body movements in real time.
+
+Avaturn does not offer this. It's a headline differentiator for our platform.
+
+Depends on tasks 02, 09.
+
+## Goal
+
+1. A `?mirror=1` flag (or UI toggle) enables mirror mode.
+2. Webcam feeds MediaPipe; Kalidokit produces VRM rotations; the active VRM tracks the user.
+3. When mirror mode is on, TalkingHead's idle is paused (otherwise they fight).
+4. Graceful exit: toggle off → TalkingHead idle resumes; webcam released.
+5. Performance target: 30 fps mirror tracking on a 2019-era laptop.
+
+## Deliverable
+
+1. **Vendor Kalidokit** — MIT. Copy into `src/vendor/kalidokit/` with NOTICE. Kalidokit is tiny; no npm needed.
+2. **MediaPipe integration** — reuse `src/capture/face-landmarks.js` from task 07 where possible. Add a `src/capture/pose-landmarks.js` for upper-body tracking (MediaPipe Pose Landmarker).
+3. **Module** `src/agent/mirror.js`:
+ - `class MirrorMode { constructor(vrm, videoEl); async start(); stop(); dispose(); }`
+ - Starts webcam, feeds MediaPipe Face + Pose landmarker on every video frame (throttled to 30fps).
+ - Passes landmarks to Kalidokit; applies outputs to:
+ - Head bone rotation (yaw/pitch/roll).
+ - Upper-body bones (neck, chest, shoulders).
+ - Arm bones (hands optional; gate behind a sub-flag — hand tracking doubles CPU).
+ - Face blendshapes (mouth, eyes, brows) — routed into VRM expression manager.
+4. **UI** — a small toolbar button "Mirror me" that opens a permission prompt + tiny PIP video preview so the user can see what the camera sees.
+5. **Integration with TalkingHead** (task 09) — when `MirrorMode.start()` runs, call `talkingHead.idleOff()`. On stop, `idleOn()`. If the brain (task 14) calls `speak()` while mirroring, the jaw/mouth is driven by visemes (TTS) AND the user's mouth-open expression is attenuated — document the blend strategy you pick.
+6. **Performance** — render every Nth frame, not every RAF. Target: 30 landmark detections/sec, 60 render fps. Use `requestVideoFrameCallback` if available.
+
+## Audit checklist
+
+- [ ] `npm start` + `?mirror=1` → mirror mode active; avatar copies your head/face in real time.
+- [ ] Toggle off → webcam indicator disappears; idle resumes.
+- [ ] FPS ≥ 30 landmark-detection on a mid-range laptop with a face in view.
+- [ ] No sudden pops / jitter on partial occlusion (hand in front of face) — Kalidokit's smoothing is tuned appropriately.
+- [ ] Closing the tab kills the camera track (no "camera in use" indicator lingering).
+- [ ] Blendshape output uses VRM expression names (`aa`, `blink`, `happy`...) not MediaPipe's 52-blendshape names — map them.
+- [ ] `prefers-reduced-motion: reduce` → mirror mode still works (it's a direct user action), but any additional jitter-smoothing animations are skipped.
+- [ ] `node --check` new files.
+
+## Constraints
+
+- No cloud vision APIs.
+- No new npm deps (MediaPipe is loaded via CDN per task 07; Kalidokit is vendored).
+- Do not send webcam frames to any server.
+- Do not record video.
+- Do not enable mirror mode by default — it's user-activated.
+- Hands tracking is optional (sub-flag); don't enable by default — too expensive on lower-end devices.
+
+## Verification
+
+1. Mirror mode with face-only → smooth head tracking, blendshapes firing correctly.
+2. Mirror mode with upper-body pose → shoulder shrug, arm raise → avatar mirrors.
+3. Mirror mode + TalkingHead speaking → lipsync wins on the mouth; blendshape blending looks natural (not doubled).
+4. Disconnect webcam (unplug USB) → mirror mode fails gracefully with an error toast.
+5. Performance profile: 60s of mirror mode → no memory growth after GC.
+
+## Scope boundaries — do NOT do these
+
+- No full-body mocap (task 13 is the heavier option).
+- No gesture → action binding (e.g., wave → send a hello). Recognition is task 15 territory.
+- No teleconferencing / multi-user mirror.
+- No recording / replay.
+- Do not auto-crop or beauty-filter the webcam preview.
+
+## Reporting
+
+- Kalidokit commit SHA vendored.
+- Measured landmark-detection fps + render fps on your dev machine.
+- The blend strategy for conflicting TTS-mouth vs mirror-mouth (attenuate mirror when TTS is active, or override, or average — you pick and justify).
+- Known jitter scenarios (low light, partial occlusion, fast motion) and whether they need Kalidokit constants tuned.
+- Whether hand tracking is ship-ready or should stay behind a sub-flag.
diff --git a/prompts/avatar-platform/README.md b/prompts/avatar-platform/README.md
new file mode 100644
index 000000000..ec8cb968e
--- /dev/null
+++ b/prompts/avatar-platform/README.md
@@ -0,0 +1,65 @@
+# Avatar Platform
+
+Self-contained prompt files for replacing the hosted Avaturn integration with a fully self-owned, open-source avatar platform: photo-to-avatar, QR-based mobile handoff, customization editor, realtime talking head, live mirroring, and a pluggable brain.
+
+**Strategic decision already made** (see chat history leading up to this series): adopt **VRM** as the format contract (superset of GLB, standardized humanoid + expressions) and **@pixiv/three-vrm** as the runtime. Every downstream task assumes this. If the first foundation task changes that call, the rest need to be revisited.
+
+## Reference repos (all MIT / Apache / MPL)
+
+| Layer | Repo | Used in tasks |
+|---|---|---|
+| VRM runtime | [pixiv/three-vrm](https://github.com/pixiv/three-vrm) | 02, 09, 12 |
+| Editor | [M3-org/CharacterStudio](https://github.com/M3-org/CharacterStudio) | 03, 16, 17 |
+| Photo → 3D (HD) | [abdallahdib/NextFace](https://github.com/abdallahdib/NextFace) | 08 |
+| Photo → landmarks | [MediaPipe Face Landmarker](https://developers.google.com/mediapipe/solutions/vision/face_landmarker/web_js) | 07, 12 |
+| Talking head + lipsync | [met4citizen/TalkingHead](https://github.com/met4citizen/TalkingHead) | 09 |
+| TTS w/ visemes | [HeadTTS (Kokoro)](https://github.com/met4citizen/TalkingHead) + [rhasspy/Piper](https://github.com/rhasspy/piper) | 10 |
+| STT | [xenova/whisper-web](https://github.com/xenova/whisper-web) | 11 |
+| Mirror mode | [yeemachine/kalidokit](https://github.com/yeemachine/kalidokit) | 12 |
+| Full-body mocap | [ButzYung/SystemAnimatorOnline](https://github.com/ButzYung/SystemAnimatorOnline) | 13 |
+| Local LLM | [mlc-ai/web-llm](https://github.com/mlc-ai/web-llm) | 14 |
+
+## Recommended execution order
+
+### Foundation — do these in order, no parallelism
+1. [01-strip-avaturn.md](./01-strip-avaturn.md) — Remove `@avaturn/sdk`, `@avaturn-live/web-sdk`, rename `AvaturnAgent`. **Blocks everything.**
+2. [02-vrm-runtime.md](./02-vrm-runtime.md) — Add `@pixiv/three-vrm`, load VRM into the viewer. **Blocks 03, 09–13, 16.**
+3. [03-vendor-character-studio.md](./03-vendor-character-studio.md) — Vendor CharacterStudio's `CharacterManager` into `src/character/`. **Blocks 16, 17.**
+
+### Photo capture pipeline — parallelizable after 02
+4. [04-desktop-photo-capture.md](./04-desktop-photo-capture.md) — Three-shot webcam capture UI (left/center/right).
+5. [05-session-bridge.md](./05-session-bridge.md) — Session store + SSE/WebSocket relay. **Blocks 06.**
+6. [06-mobile-capture-route.md](./06-mobile-capture-route.md) — `/m/:sessionId` phone route with QR flow on desktop. **Depends on 05.**
+7. [07-photo-to-avatar-fast.md](./07-photo-to-avatar-fast.md) — Browser path: MediaPipe landmarks → morph template head.
+8. [08-photo-to-avatar-hd.md](./08-photo-to-avatar-hd.md) — Backend path: NextFace GPU service → high-fidelity rebake.
+
+### Animation stack — parallelizable after 02
+9. [09-talking-head.md](./09-talking-head.md) — Vendor `TalkingHead`, wire to the active VRM.
+10. [10-tts-visemes.md](./10-tts-visemes.md) — Browser TTS with phoneme/viseme timestamps. **Depends on 09.**
+11. [11-speech-to-text.md](./11-speech-to-text.md) — Replace Web Speech API with whisper-web.
+12. [12-mirror-mode.md](./12-mirror-mode.md) — Kalidokit-driven webcam mirroring.
+13. [13-full-body-mocap.md](./13-full-body-mocap.md) — Optional XR Animator-style full-body capture.
+
+### Brain — after 10, 11
+14. [14-agent-brain.md](./14-agent-brain.md) — Pluggable LLM interface: local (WebLLM) and cloud (Claude/OpenAI).
+15. [15-conversation-state.md](./15-conversation-state.md) — Session memory, tool invocations, viewer context.
+
+### Editor + UX — after 03
+16. [16-character-editor-ui.md](./16-character-editor-ui.md) — Branded side-panel editor driving `CharacterManager`.
+17. [17-asset-library.md](./17-asset-library.md) — Browsable VRM asset registry (from CC0 sources).
+
+### Polish
+18. [18-branding-pass.md](./18-branding-pass.md) — Scrub `avaturn-` everywhere, rename to project brand.
+19. [19-performance-dispose.md](./19-performance-dispose.md) — Render-on-demand, GPU disposal, idle throttling.
+20. [20-onboarding-flow.md](./20-onboarding-flow.md) — First-run journey: QR → photo → preview → name → ready.
+
+## Rules that apply to all tasks
+
+- **Vendor, don't npm, whenever feasible.** Copy source into `src/vendor/<name>/` with a `NOTICE` file carrying the upstream license + attribution. Only use npm for deps that are truly infrastructural (`@pixiv/three-vrm`, `three`, `vite`).
+- Respect `prefers-reduced-motion` — any motion-heavy feature (mirror, talking head idles) must pause.
+- No changes to [src/viewer.js](../../src/viewer.js) foundation beyond what task 02 explicitly does. Feature work lives under `src/character/`, `src/capture/`, `src/agent/`, `src/features/`.
+- Feature-flag everything ambitious (`?mirror=1`, `?brain=local`, etc.) until task 20 stitches the flows together.
+- `node --check` each JS file. `npx vite build` must continue to pass.
+- If an upstream repo's license is anything other than MIT / Apache-2.0 / MPL-2.0 / BSD, stop and ask before vendoring.
+- If you discover unrelated bugs, note them in reporting. Do not fix in the same change.
+- No new docs files beyond what each task explicitly requires.
diff --git a/prompts/build/00-stack-e2e-smoke.md b/prompts/build/00-stack-e2e-smoke.md
new file mode 100644
index 000000000..74e97ca82
--- /dev/null
+++ b/prompts/build/00-stack-e2e-smoke.md
@@ -0,0 +1,51 @@
+---
+mode: agent
+description: "End-to-end smoke test of the whole priority stack on a cold browser"
+---
+
+# 00 · End-to-end stack smoke test
+
+## Why it matters
+
+After any batch of pillar work lands, the loop from "open incognito → embodied agent on chain resolvable in a host" must actually work. This prompt is the pass you run before declaring a milestone done. Not a test file — a reproducible manual/scripted walk-through with clear pass/fail gates.
+
+## Prerequisites
+
+- Pillar 1–6 prompts at least partially merged.
+
+## Read these first
+
+- [prompts/build/README.md](./README.md) — stack order.
+- Each pillar's "Acceptance" block.
+
+## Build this
+
+A single `scripts/smoke-stack.sh` (or `.js`) that walks the stack:
+
+1. **Auth** — script spins up a headless wallet signer (ethers with a test private key), hits `/api/auth/siwe/nonce`, signs, posts to `/verify`, asserts 200 + session cookie.
+2. **Selfie** — upload a fixture JPEG to `/api/selfies/presign` + register.
+3. **Generate** — kick off `/api/selfies/generate`, poll until done (bypass in CI if provider unavailable; gate with env flag `E2E_RUN_GENERATE=1`).
+4. **Agent page** — HEAD `/agent/:id` and `/agent/:id/embed` → 200.
+5. **Card** — GET `/api/agents/:id/card.json` → valid JSON with required fields.
+6. **Mint** — (optional, gated `E2E_RUN_ONCHAIN=1`) run `registerAgent` on a testnet fork → assert `erc8004_agent_id` persists.
+7. **Resolve from chain** — GET `/api/agents/by-chain?...` → matches step 6.
+8. **MCP** — JSON-RPC call `render_agent` against `/api/mcp` → resource URL in response.
+
+Report: pass/fail per step, total runtime, any warnings.
+
+## Out of scope
+
+- Full frontend UI automation (Playwright) — too much overhead for a smoke script.
+- Load / stress testing.
+- Browser compatibility matrix.
+
+## Deliverables
+
+- `scripts/smoke-stack.sh` or `scripts/smoke-stack.js`.
+- A short README block in the script's header explaining env vars and how to run it.
+
+## Acceptance
+
+- `node scripts/smoke-stack.js` against a running dev server exits 0 when the stack is healthy.
+- Fails fast and loud on the first broken pillar.
+- No new runtime deps (use `node:fetch`, `ethers` already present, no Playwright).
diff --git a/prompts/build/01-01-wallet-auth-privy.md b/prompts/build/01-01-wallet-auth-privy.md
new file mode 100644
index 000000000..3bd29df17
--- /dev/null
+++ b/prompts/build/01-01-wallet-auth-privy.md
@@ -0,0 +1,44 @@
+# 01-01 — Wallet auth: Privy as alternative to MetaMask
+
+**Branch:** `feat/auth-privy`
+**Stack layer:** 1 (Wallet auth)
+**Depends on:** nothing
+**Blocks:** 06-* (onchain registration — needs a wallet the user already holds)
+
+## Why it matters
+
+Wallet auth is the foundation of the stack. Today [public/wallet-login.js](../../public/wallet-login.js) only supports MetaMask via `ethers.BrowserProvider`. Mobile users and users without a browser extension are locked out. Privy gives us email, social, and embedded-wallet login in one SDK while still producing a real EOA we can pass to SIWE.
+
+## Read these first
+
+| File | Why |
+|:---|:---|
+| [public/wallet-login.js](../../public/wallet-login.js) | Current MetaMask-only flow. You will extend it, not replace it. |
+| [api/auth/siwe/nonce.js](../../api/auth/siwe/nonce.js) | Nonce endpoint — already works, do not touch. |
+| [api/auth/siwe/verify.js](../../api/auth/siwe/verify.js) | Verifies the signed message. Works with any EOA that produces an EIP-4361 signature. |
+| [public/login.html](../../public/login.html), [public/register.html](../../public/register.html) | Shells that load `wallet-login.js`. |
+| [api/_lib/auth.js](../../api/_lib/auth.js) | Session cookie issuance — do not duplicate. |
+
+## Build this
+
+1. Add `@privy-io/react-auth`'s browser-only dependency — **skip** if it requires React. Use `@privy-io/js-sdk-core` (framework-agnostic) instead. Justify the single added dep in the PR description.
+2. In [public/wallet-login.js](../../public/wallet-login.js), expose two entry points:
+ - `loginWithMetaMask()` — existing flow, unchanged.
+ - `loginWithPrivy()` — opens Privy modal, gets an embedded or external wallet, produces an EIP-4361 signature, posts it to `/api/auth/siwe/verify` exactly like the MetaMask path.
+3. Add two buttons to [public/login.html](../../public/login.html) and [public/register.html](../../public/register.html): **"Sign in with MetaMask"** and **"Sign in with Privy"**. Same SIWE backend for both.
+4. Add `PRIVY_APP_ID` to `.env.example` (client-side, `VITE_PRIVY_APP_ID`). Document that the user must set this to enable the button; if unset, hide the Privy button.
+
+## Out of scope
+
+- Do not add email/password login flows — they already exist elsewhere.
+- Do not touch `/api/auth/siwe/verify`. Both wallets speak the same SIWE message.
+- Do not change session cookie format.
+- Do not add a React runtime. If `@privy-io/js-sdk-core` is unavailable, stop and report.
+
+## Acceptance
+
+- [ ] MetaMask path still works end-to-end from `/login` in an incognito window.
+- [ ] Privy button shown only when `VITE_PRIVY_APP_ID` is set.
+- [ ] Privy login issues a session cookie identical in shape to the MetaMask path.
+- [ ] `/api/auth/me` returns the same user shape regardless of provider.
+- [ ] `npm run build` passes.
diff --git a/prompts/build/01-01-wallet-auth-smoke-test.md b/prompts/build/01-01-wallet-auth-smoke-test.md
new file mode 100644
index 000000000..423454ca2
--- /dev/null
+++ b/prompts/build/01-01-wallet-auth-smoke-test.md
@@ -0,0 +1,66 @@
+---
+mode: agent
+description: "Smoke-test the SIWE wallet login end-to-end and patch any breakage"
+---
+
+# 01-01 · Wallet auth smoke test
+
+## Why it matters
+
+Wallet auth is pillar 1 of the product stack. Until MetaMask → session cookie → `/api/agents/me` returns the user's agent works 100% on a fresh browser, **nothing else ships**. Selfie → agent, edit, embed, onchain — all downstream of this.
+
+SIWE endpoints and `wallet-login.js` are in place (2026-04-15). This prompt is a verification pass: does the whole loop actually work in a cold browser, and what's broken?
+
+## Prerequisites
+
+- `npm run dev` runs without errors on :3000.
+- A MetaMask-like wallet extension available in the test browser (or a headless signer — see below).
+- Neon `DATABASE_URL` pointed at a writable DB with the schema applied.
+
+## Read these first
+
+- [public/login.html](../../public/login.html) — current login page markup.
+- [public/wallet-login.js](../../public/wallet-login.js) — SIWE client flow.
+- [api/auth/siwe/nonce.js](../../api/auth/siwe/nonce.js) — nonce issuance.
+- [api/auth/siwe/verify.js](../../api/auth/siwe/verify.js) — signature verification + session issuance.
+- [api/_lib/auth.js](../../api/_lib/auth.js) — `createSession`, `sessionCookie`, `getSessionUser`.
+- [api/agents.js](../../api/agents.js) — `/api/agents/me` bootstrap that runs on every page load.
+
+## Build this
+
+Execute the following and report findings. For anything broken, patch it in the same PR unless it's out of scope (see below).
+
+1. **Cold browser signin path** — private window → `/login` → click wallet → sign → land on `/dashboard/`.
+ - Expected: `users` row + `user_wallets` row created on first attempt. Session cookie set. `/api/auth/me` returns the user.
+2. **Repeat login path** — sign out → sign back in with the same wallet.
+ - Expected: existing user reused via `user_wallets.address` lookup. No duplicate row. Session rotates (old one destroyed before new one issued).
+3. **Nonce burn** — capture a valid `(message, signature)` from step 1 and `POST /api/auth/siwe/verify` with it a second time.
+ - Expected: `nonce_reused` 400, no new session.
+4. **Domain binding** — craft a SIWE message with a wrong `domain:` line and submit.
+ - Expected: `invalid_domain` 400.
+5. **Agent bootstrap** — after login, confirm `GET /api/agents/me` returns an agent (auto-created on first call). Confirm the client in [src/account.js](../../src/account.js) / [src/agent-identity.js](../../src/agent-identity.js) picks it up.
+6. **Anonymous path** — hit `/` with no session; `/api/agents/me` must return `{ agent: null }` (not 401).
+
+## Patching rules
+
+- If any step fails due to a schema mismatch, inspect [api/_lib/db.js](../../api/_lib/db.js) and the migration files; do not invent new columns.
+- If `APP_ORIGIN` / `ISSUER` env vars are missing, document what's needed in the final report — do **not** hard-code values.
+- If the CSP on `/login` blocks `https://esm.sh`, either move `wallet-login.js` into the Vite bundle entry, or widen the CSP for that page only. Prefer bundling.
+
+## Out of scope
+
+- Adding a new wallet provider (WalletConnect, Coinbase) — save for later prompt.
+- Refactoring the SIWE message to the `siwe` npm package — the hand-rolled parser is fine.
+- Any UI redesign of `/login.html`.
+- Touching ERC-8004 registration.
+
+## Deliverables
+
+- A short "what I verified / what I fixed" report in the PR description (or chat reply) with one line per step above.
+- Any patches are minimal and scoped to bugs found during the five checks.
+
+## Acceptance
+
+- All six steps above pass on a cold private window.
+- `node --check` passes on every modified `.js` file.
+- `npm run build` passes.
diff --git a/prompts/build/01-01-wallet-link-existing-account.md b/prompts/build/01-01-wallet-link-existing-account.md
new file mode 100644
index 000000000..cc306aa5b
--- /dev/null
+++ b/prompts/build/01-01-wallet-link-existing-account.md
@@ -0,0 +1,52 @@
+# 01-01 — Link a wallet to an existing email account
+
+## Why it matters
+
+SIWE sign-in creates a new passwordless user from a wallet. But a user who already registered with email needs a way to *add* a wallet to their existing account — otherwise they end up with two disconnected identities. This is required before wallet auth is "100%."
+
+## Context
+
+- SIWE endpoints already exist: [api/auth/siwe/nonce.js](../../api/auth/siwe/nonce.js), [api/auth/siwe/verify.js](../../api/auth/siwe/verify.js).
+- `user_wallets` table exists ([api/_lib/schema.sql](../../api/_lib/schema.sql)) — supports many wallets per user.
+- Session auth helper: `getSessionUser` in [api/_lib/auth.js](../../api/_lib/auth.js).
+- Dashboard shell: [public/dashboard/index.html](../../public/dashboard/index.html), [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js).
+
+## What to build
+
+### Endpoint — `api/auth/siwe/link.js`
+
+- `POST`. Requires an active session (`getSessionUser`). 401 if none.
+- Body: `{ message, signature }` (same SIWE shape as `/verify`).
+- Verifies the signature against the SIWE message + burns the nonce exactly like `/verify`.
+- On success: inserts into `user_wallets` bound to the current session's user_id.
+ - If the address is already linked to a different user → 409 `wallet_already_linked`.
+ - If already linked to *this* user → 200 `{ ok: true, wallet }` (idempotent).
+- Mirrors the primary wallet to `users.wallet_address` only if the user has no primary wallet yet.
+
+### Client — wallet linking on the dashboard
+
+In [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js) (or a new `public/dashboard/wallet-link.js` imported from the existing HTML), add:
+
+- A "Connect wallet" button in the account section.
+- Click → reuse the exact SIWE client flow from [public/wallet-login.js](../../public/wallet-login.js) but POST to `/api/auth/siwe/link` instead of `/verify`.
+- Show the linked address (`0xabc…1234`) with a "Disconnect" button beside it.
+
+### Endpoint — `DELETE /api/auth/siwe/link?address=0x…`
+
+- Session-authed. Removes a `user_wallets` row owned by the caller. 404 if the address isn't linked to this user.
+
+## Out of scope
+
+- Multi-chain bookkeeping (one chain_id is enough).
+- Re-using existing sessions across wallet changes (session stays; we're only mutating linked wallets).
+- UI for selecting a "primary" wallet beyond the first one linked.
+- Showing ENS names (follow-up).
+
+## Acceptance
+
+1. Sign in with email + password.
+2. Click "Connect wallet" → sign SIWE → see the address appear in the account section.
+3. Sign out. Open an incognito window. SIWE sign-in with that same wallet logs into the *existing* email account (not a new one).
+4. Try to link that same wallet from a *different* email account → 409.
+5. Click "Disconnect" → wallet row removed. SIWE with that wallet in a fresh session creates a new passwordless account.
+6. `node --check` passes on new files.
diff --git a/prompts/build/01-02-email-password-parity.md b/prompts/build/01-02-email-password-parity.md
new file mode 100644
index 000000000..126172151
--- /dev/null
+++ b/prompts/build/01-02-email-password-parity.md
@@ -0,0 +1,55 @@
+---
+mode: agent
+description: "Ensure email/password signup has parity with SIWE: session, user row, agent bootstrap"
+---
+
+# 01-02 · Email/password auth parity
+
+## Why it matters
+
+Wallet is the primary path, but email/password must still work for users without a wallet. If the two paths diverge (e.g. one creates an agent, the other doesn't), the dashboard breaks for half the users. Small gap to close, high blast radius if skipped.
+
+## Prerequisites
+
+- 01-01 verified the SIWE path is working end-to-end.
+
+## Read these first
+
+- [api/auth/register.js](../../api/auth/register.js)
+- [api/auth/login.js](../../api/auth/login.js)
+- [api/auth/logout.js](../../api/auth/logout.js)
+- [api/auth/me.js](../../api/auth/me.js)
+- [api/auth/siwe/verify.js](../../api/auth/siwe/verify.js) — canonical session-issue pattern; email path should mirror this.
+- [public/register.html](../../public/register.html), [public/login.html](../../public/login.html)
+
+## Build this
+
+1. **Audit the three code paths side-by-side** (register, password login, SIWE verify) and list what each does:
+ - `users` row creation / lookup
+ - `user_wallets` row (SIWE only)
+ - `destroySession()` before `createSession()`
+ - cookie flags (`HttpOnly`, `Secure`, `SameSite`)
+ - response shape (`{ user: {...} }`)
+2. **Normalize** any field that differs without reason. Pick SIWE's shape as canonical — it's the newest and reviewed.
+3. **Agent bootstrap parity** — after a new user registers with email, hitting `GET /api/agents/me` auto-creates the default agent (already true for SIWE because the endpoint is shared). Verify by registering a fresh email and hitting `/dashboard/` — the client-side `AgentIdentity.load()` should succeed.
+4. **Logout** — `POST /api/auth/logout` clears the cookie and destroys the session row. Verify `Set-Cookie` has `Max-Age=0` and `sessions.revoked_at` is set.
+5. **Session fixation check** — logging out then logging back in rotates the session id. Confirm in `sessions` table.
+
+## Out of scope
+
+- Password reset flow.
+- Email verification / magic links.
+- 2FA.
+- Merging a password account with a later-linked wallet (that's 01-05).
+
+## Deliverables
+
+- A side-by-side audit result (3–5 bullets) in the PR description.
+- Minimal diffs where the three paths diverged.
+
+## Acceptance
+
+- New email registration → dashboard → agent visible in one flow.
+- Password login and SIWE login produce cookies with identical flags.
+- Logout clears everything.
+- `node --check` + `npm run build` pass.
diff --git a/prompts/build/01-02-session-recovery-and-logout.md b/prompts/build/01-02-session-recovery-and-logout.md
new file mode 100644
index 000000000..964ce0364
--- /dev/null
+++ b/prompts/build/01-02-session-recovery-and-logout.md
@@ -0,0 +1,48 @@
+# 01-02 — Session recovery, logout UI, and /api/agents/me hardening
+
+**Branch:** `feat/auth-session-recovery`
+**Stack layer:** 1 (Wallet auth)
+**Depends on:** nothing (runs in parallel with 01-01)
+**Blocks:** every layer that relies on a stable signed-in session
+
+## Why it matters
+
+The SIWE flow works, but the user can't *leave* cleanly or recover a stale session. [/api/agents/me](../../api/agents.js) has been observed 500'ing (see project memory). Wallet auth is only "100% done" when sign-in, sign-out, and the `/me` round-trip are all green.
+
+## Read these first
+
+| File | Why |
+|:---|:---|
+| [api/auth/logout.js](../../api/auth/logout.js) | Exists but has no UI caller. |
+| [api/auth/me.js](../../api/auth/me.js) (or equivalent in `api/auth/`) | The canonical "who am I" endpoint. |
+| [api/agents.js](../../api/agents.js) | Contains the `/api/agents/me` handler and its auto-create-default-agent logic. This is where the 500 comes from. |
+| [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js) | Sign-in state read on page load. |
+| [public/wallet-login.js](../../public/wallet-login.js) | The client session-issuer. |
+
+## Build this
+
+1. **Reproduce the 500.** Call `/api/agents/me` with a valid session cookie but no existing agent row. Capture the stack trace. Fix the underlying cause — likely a null `user_wallets` join or a missing column. Do *not* paper over with a try/catch that swallows errors.
+2. **Logout button.** In [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js), add a "Sign out" item in the header user menu. POSTs `/api/auth/logout`, clears in-memory state, redirects to `/`.
+3. **Session recovery.** On every authenticated page load (`/dashboard`, `/studio` when it ships), call `/api/auth/me` first. If 401, redirect to `/login?return=<current>`. If 500, show a banner "We couldn't load your account — try signing in again" with a logout link.
+4. **Agent auto-create safety.** In [api/agents.js](../../api/agents.js), the `/api/agents/me` auto-create path must be idempotent: if a default agent already exists for the user, return it; if not, create it inside a transaction so two racing requests don't both insert.
+
+## Out of scope
+
+- Do not add multi-device session management.
+- Do not add password reset.
+- Do not touch the SIWE handshake.
+
+## Acceptance
+
+- [ ] `curl -i /api/agents/me` with a fresh-but-agentless user returns 200 with a newly-created default agent.
+- [ ] Two concurrent requests for a user with no agent row do not produce two rows.
+- [ ] Clicking "Sign out" clears the cookie, and `/api/auth/me` returns 401 immediately after.
+- [ ] Revisiting `/dashboard` after logout redirects to `/login?return=/dashboard`.
+- [ ] No 500s in the Vercel logs during the test plan below.
+
+## Test plan
+
+1. Fresh Neon row: `delete from agents where user_id=<me>` → visit `/dashboard` → default agent appears.
+2. `ab -n 20 -c 10` against `/api/agents/me` with same cookie → exactly one agent row at the end.
+3. Logout → `/api/auth/me` → 401.
+4. Logout → visit `/dashboard` → redirected to `/login?return=/dashboard`.
diff --git a/prompts/build/01-02-wallet-account-section.md b/prompts/build/01-02-wallet-account-section.md
new file mode 100644
index 000000000..52356db2a
--- /dev/null
+++ b/prompts/build/01-02-wallet-account-section.md
@@ -0,0 +1,54 @@
+# 01-02 — Dashboard account section: wallets, email, claim identity
+
+## Why it matters
+
+Wallet-only users (created via SIWE with no email) need a way to add an email + password later so they can recover their account if they lose wallet access. And all users need to see which wallets are linked. This closes the "account" loop for the wallet auth foundation.
+
+## Context
+
+- Wallet-only users are created by [api/auth/siwe/verify.js](../../api/auth/siwe/verify.js) with a synthesized email `wallet-0x…@wallet.local`.
+- Dashboard entry: [public/dashboard/index.html](../../public/dashboard/index.html), [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js).
+- `users` schema: [api/_lib/schema.sql](../../api/_lib/schema.sql) — `email citext unique`, `password_hash nullable`.
+- Password hashing: `hashPassword` in [api/_lib/auth.js](../../api/_lib/auth.js).
+
+## What to build
+
+### Endpoint — `api/auth/claim-identity.js`
+
+Single endpoint: `POST /api/auth/claim-identity`. Session-authed.
+
+Body: `{ email, password, display_name? }`.
+
+Behavior:
+- Reject if the user already has a real email (anything that doesn't match `/^wallet-0x[a-f0-9]{40}@wallet\.local$/`). Return 400 `already_claimed`.
+- Reject if the target email is taken by another user. Return 409 `email_taken`.
+- Hash password, update the row: `email`, `password_hash`, `display_name` (if provided).
+- Return `{ user: { id, email, display_name, plan } }`.
+
+### Account panel in dashboard
+
+Add an **Account** section to the dashboard:
+
+- Shows: display name (editable), email (editable if `wallet-*@wallet.local`, read-only otherwise), plan, and a "Linked wallets" list.
+- If the email is synthesized (wallet-only user), show a prominent "Claim your account — set an email and password" form that posts to `/api/auth/claim-identity`.
+- For all users: show linked wallets (GET `/api/auth/siwe/link` — see sibling prompt `01-01`). Each row: address (copy button), chain_id if present, "Disconnect" button.
+- "Connect wallet" button appears if no wallet is linked.
+
+### Endpoint — `GET /api/auth/siwe/link`
+
+Returns `{ wallets: [{ address, chain_id, is_primary, created_at, last_used_at }] }`. Session-authed. Use this for the list.
+
+## Out of scope
+
+- Changing password flow for already-claimed accounts.
+- Email verification emails.
+- Plan upgrades UI.
+
+## Acceptance
+
+1. Sign in with wallet only. Dashboard shows "Claim your account" prompt with the `wallet-0x…@wallet.local` placeholder visible.
+2. Submit email + password → account updated. Log out, log in with email/password → works.
+3. The same user can still SIWE-sign-in with the same wallet → same account.
+4. A wallet user without claiming can still use dashboard normally (avatars, etc.).
+5. Linked wallets list is accurate. Disconnect works. Connect flow works.
+6. `node --check` passes.
diff --git a/prompts/build/01-02-wallet-ens-display.md b/prompts/build/01-02-wallet-ens-display.md
new file mode 100644
index 000000000..f60f34c3a
--- /dev/null
+++ b/prompts/build/01-02-wallet-ens-display.md
@@ -0,0 +1,55 @@
+# 01-02 — Display ENS / basename for linked wallets
+
+## Why it matters
+
+Users see `0xabc…1234` today. That's hostile. Showing `nich.eth` or `nich.base.eth` when available is the cheapest possible UX upgrade for the wallet-auth layer and a prerequisite for trusting the identity we later publish on-chain (Layer 6). Without it, wallets feel like plumbing instead of identity.
+
+## Context
+
+- SIWE verify path: [api/auth/siwe/verify.js](../../api/auth/siwe/verify.js).
+- Linked-wallet table: `user_wallets` in [api/_lib/schema.sql](../../api/_lib/schema.sql).
+- Session helper: `getSessionUser` in [api/_lib/auth.js](../../api/_lib/auth.js).
+- Dashboard render: [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js).
+
+## What to build
+
+### Endpoint — `api/auth/wallets/resolve-name.js`
+
+- `GET ?address=0x…&chain_id=1|8453`. Public (no session required — names are public).
+- Resolves via public RPC, with a 24h cache keyed on `(address, chain_id)`.
+ - `chain_id=1` → ENS (`name.eth`) via reverse record.
+ - `chain_id=8453` → basename via the Base name registrar. Fall back to ENS mainnet if no basename.
+- Response: `{ address, name: "nich.eth" | null, avatar: "https://…" | null, chain_id, ttl }`.
+- Cache: use the existing rate-limit/kv pattern in [api/_lib/rate-limit.js](../../api/_lib/rate-limit.js) (Neon `kv` table or equivalent — reuse, don't invent).
+- Failures (RPC down, no record) → `{ name: null }` with 200, not 5xx.
+
+### Persist on link
+
+When `api/auth/siwe/link.js` (from 01-01) inserts a row, fire-and-forget a call to `resolve-name` and write the result to a new nullable column:
+
+```sql
+alter table user_wallets add column if not exists ens_name text;
+alter table user_wallets add column if not exists ens_avatar_url text;
+alter table user_wallets add column if not exists ens_resolved_at timestamptz;
+```
+
+Re-resolve opportunistically when `ens_resolved_at` is older than 24h on next read.
+
+### Dashboard render
+
+In [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js), replace any `0xabc…1234` render of a linked wallet with `name || shortAddress(address)`. If `ens_avatar_url` is set, show it as a 24px circle next to the name.
+
+## Out of scope
+
+- Writing ENS records. Read-only.
+- Multi-chain beyond mainnet + Base.
+- Avatar-image proxying through our CDN (use the URL returned by the resolver directly; if CSP blocks it, file a follow-up).
+- Any UI for users to "refresh" the name — the 24h auto-refresh is enough.
+
+## Acceptance
+
+1. Link a wallet that has an ENS reverse record → dashboard shows the name within the next page load.
+2. Link a wallet with no ENS record → short address still renders; no console errors.
+3. `GET /api/auth/wallets/resolve-name?address=vitalik.eth-address` returns `{ name: "vitalik.eth" }`.
+4. Second call within 24h is served from cache (check RPC hit count or log).
+5. `node --check` passes on new files.
diff --git a/prompts/build/01-02-wallet-nav-indicator.md b/prompts/build/01-02-wallet-nav-indicator.md
new file mode 100644
index 000000000..ae3f2ae2e
--- /dev/null
+++ b/prompts/build/01-02-wallet-nav-indicator.md
@@ -0,0 +1,110 @@
+# 01-02 — Wallet connection indicator in nav
+
+**Pillar 1 — Wallet auth.**
+
+## Why it matters
+
+Once a user signs in with a wallet, nothing on the page tells them they did. No chip, no address, no disconnect button. Users have reported signing in twice because they couldn't tell the first attempt worked. This is cheap to fix and unlocks trust for every higher-layer flow.
+
+## What to build
+
+A small **WalletChip** component rendered in the top-right of every authenticated page ([public/dashboard/](../../public/dashboard/), `/studio`, `/agent/:id` when owner, `/widgets-gallery` when signed in).
+
+- **Signed in (wallet):** circular blockie/jazzicon (16-char seed → hsl gradient — no deps; use address hash) + short addr `0x1234…abcd` + chevron.
+- **Signed in (email):** same chip shape, initials instead of blockie, no address.
+- **Signed out:** "Sign in" link, no chip.
+- **Menu on click:** full address with copy button, "My agents", "My avatars", "Sign out". On mobile, a bottom-sheet drawer.
+
+Source of truth: `GET /api/auth/me` on page load + local cache invalidated on 401.
+
+## Read these first
+
+| File | Why |
+|:---|:---|
+| [api/auth/me.js](../../api/auth/me.js) | Shape of the `user` object — `{ id, email, display_name, plan, avatar_url }`. Note there is NO `wallet_address` field on the returned user today. |
+| [api/_lib/auth.js](../../api/_lib/auth.js) | `getSessionUser` — source SQL. You may need to join `user_wallets` here so `/api/auth/me` returns the primary wallet. |
+| [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js) | Native DOM pattern to follow. |
+| [public/wallet-login.js](../../public/wallet-login.js) | Wallet flow — nothing to change here, but learn what a wallet-created user's `email` looks like (`[email protected]`) so you can hide that ugly string. |
+| [style.css](../../style.css) | Token palette — use `--accent`, `--bg-elevated`, etc. Don't introduce new colors. |
+
+## Build this
+
+### 1. Backend
+
+Extend [api/auth/me.js](../../api/auth/me.js) to include the primary wallet:
+
+```js
+// Inside handler, after getSessionUser:
+const wallets = await sql`
+ select address, chain_id from user_wallets
+ where user_id = ${user.id} and is_primary = true limit 1
+`;
+user.wallet = wallets[0] ? { address: wallets[0].address, chain_id: wallets[0].chain_id } : null;
+```
+
+Keep the response shape as `{ user }` — additive only.
+
+### 2. Client component
+
+Create `src/components/wallet-chip.js` (plain JS, renders a DOM subtree — follow dashboard patterns, NOT a framework component).
+
+```js
+export function mountWalletChip(containerEl, { user, onSignOut }) { ... }
+```
+
+Blockie: 8 colored cells from a hash of the address rendered as a 4x4 CSS grid (no canvas, no deps).
+
+Short address: `${addr.slice(0,6)}…${addr.slice(-4)}`.
+
+Menu: absolute-positioned popover. Close on outside click, Esc, or selection.
+
+### 3. Mount on every page
+
+Add a script tag + chip mount to:
+- [public/dashboard/index.html](../../public/dashboard/) — top-right, replacing whatever's there.
+- `public/studio/index.html` (if it exists from the widget-studio prompts — if not, skip).
+- [public/agent/index.html](../../public/agent/index.html) — top-right.
+- [public/widgets-gallery/index.html](../../public/widgets-gallery/index.html) — top-right.
+
+Do not modify the landing page [index.html](../../index.html) — it has its own header.
+
+### 4. Sign out
+
+`POST /api/auth/logout` already exists. The menu's "Sign out" calls it, then `location.reload()`.
+
+## Out of scope
+
+- Do not add account settings pages.
+- Do not add ENS resolution (even though it would look nice — add it behind a separate prompt).
+- Do not add chain-id display (chain switcher is `01-04`).
+- Do not touch the landing page nav.
+
+## Deliverables
+
+**New:**
+- `src/components/wallet-chip.js`
+
+**Modified:**
+- [api/auth/me.js](../../api/auth/me.js) — include `wallet` on user.
+- [public/dashboard/index.html](../../public/dashboard/) — mount chip.
+- [public/agent/index.html](../../public/agent/index.html) — mount chip.
+- [public/widgets-gallery/index.html](../../public/widgets-gallery/index.html) — mount chip.
+- [style.css](../../style.css) — chip + menu styles (add a small `.wallet-chip` block).
+
+## Acceptance
+
+- [ ] Signed-in wallet user sees a chip with their short address in the top-right of every authenticated page.
+- [ ] Clicking the chip opens a menu with full address + copy + sign out.
+- [ ] Clicking "Sign out" signs them out and reloads → "Sign in" link appears.
+- [ ] Email-auth user sees initials chip (no address).
+- [ ] Signed-out user sees "Sign in" link.
+- [ ] Mobile (375px): menu renders as a bottom sheet, not a broken popover.
+- [ ] `npm run build` passes.
+
+## Test plan
+
+1. Sign in with wallet → chip shows on dashboard, agent page, gallery.
+2. Copy button in menu → address is on clipboard.
+3. Sign out from menu → redirected to signed-out state.
+4. Sign in with email on a different account → chip shows initials.
+5. Resize to 375px — menu opens as bottom sheet with scrim.
diff --git a/prompts/build/01-03-link-wallet-to-existing-account.md b/prompts/build/01-03-link-wallet-to-existing-account.md
new file mode 100644
index 000000000..cfe938d13
--- /dev/null
+++ b/prompts/build/01-03-link-wallet-to-existing-account.md
@@ -0,0 +1,53 @@
+---
+mode: agent
+description: "Let a signed-in email user link a wallet without creating a second account"
+---
+
+# 01-03 · Link wallet to existing account
+
+## Why it matters
+
+If a user signs up with email then later connects a wallet, they get a second phantom account and their agent orphans. Breaks the onchain portability pillar (#6) — an agent minted under the phantom account can't be controlled from the real one.
+
+## Prerequisites
+
+- 01-01 and 01-02 verified.
+
+## Read these first
+
+- [api/auth/siwe/verify.js](../../api/auth/siwe/verify.js) — current "find or create user" branch.
+- [api/_lib/auth.js](../../api/_lib/auth.js) — `getSessionUser`, `createSession`.
+- Schema for `user_wallets` in the Neon DB (see [api/CLAUDE.md](../../api/CLAUDE.md) table list).
+
+## Build this
+
+1. **Modify `POST /api/auth/siwe/verify`** to check for an existing session *before* the find-or-create branch. If a session exists:
+ - If `user_wallets.address` is unused → insert `(user_id=session.user_id, address, chain_id, is_primary=false)`. Return the *existing* user (do not rotate session).
+ - If `user_wallets.address` belongs to the *current* user → idempotent success.
+ - If `user_wallets.address` belongs to a *different* user → return `409 wallet_in_use` with a generic message (no user leakage).
+2. **New client entry point** — add a "Link wallet" button to [public/dashboard/index.html](../../public/dashboard/index.html). Reuse [public/wallet-login.js](../../public/wallet-login.js) flow, but:
+ - POST to the same `/api/auth/siwe/verify` endpoint (which now handles the linked case).
+ - On success, show the linked address and update `users.wallet_address` if still null.
+3. **List wallets** — add `GET /api/auth/wallets` returning `[{ address, chain_id, is_primary, last_used_at }]` for the current session. Use the session auth helper only — no bearer.
+4. **Remove a wallet** — add `DELETE /api/auth/wallets/:address`. Cannot remove the primary if it's the only one. Update `users.wallet_address` to the next remaining primary if applicable.
+
+## Out of scope
+
+- UI redesign of the dashboard.
+- Wallet-level permissions (signing scopes).
+- Multi-chain handling beyond storing `chain_id`.
+- ERC-8004 registration flow.
+
+## Deliverables
+
+- `api/auth/wallets.js` (new) exporting the list/delete handlers.
+- Edits to `api/auth/siwe/verify.js` for the linked branch.
+- A small UI block in `public/dashboard/index.html` + JS in `public/dashboard/dashboard.js` or a new file.
+- `vercel.json` routes for the new endpoints.
+
+## Acceptance
+
+- Email user signs in → clicks Link Wallet → signs SIWE → same user gains the wallet, no new account.
+- Cold wallet sign-in for a fresh address still works (creates new user, unchanged).
+- Trying to link a wallet that belongs to a different user returns 409 without leaking who owns it.
+- `node --check` + `npm run build` pass.
diff --git a/prompts/build/01-03-primary-wallet-selection.md b/prompts/build/01-03-primary-wallet-selection.md
new file mode 100644
index 000000000..751815ccb
--- /dev/null
+++ b/prompts/build/01-03-primary-wallet-selection.md
@@ -0,0 +1,60 @@
+# 01-03 — Primary wallet selection
+
+## Why it matters
+
+`user_wallets` supports many wallets per user, but the `users.wallet_address` column only holds one. Today it mirrors whichever wallet was linked first. The user has no way to change it. This matters because Layer 6 (onchain portability) uses the primary wallet as the controller address that signs ERC-8004 registrations — picking the wrong one silently ties the on-chain identity to a throwaway wallet.
+
+## Context
+
+- Schema: `users.wallet_address`, `user_wallets(user_id, address, chain_id, created_at)` in [api/_lib/schema.sql](../../api/_lib/schema.sql).
+- Linking endpoints: `api/auth/siwe/link.js` (from 01-01).
+- Session helper: `getSessionUser` in [api/_lib/auth.js](../../api/_lib/auth.js).
+- Dashboard wallet section: [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js).
+
+## What to build
+
+### Schema
+
+```sql
+alter table user_wallets add column if not exists is_primary boolean not null default false;
+create unique index if not exists user_wallets_primary_per_user
+ on user_wallets(user_id) where is_primary;
+```
+
+One-time backfill (include in the same migration): for each user with ≥1 wallet and no primary, set the oldest `user_wallets` row to `is_primary = true` and mirror to `users.wallet_address`.
+
+### Endpoint — `POST /api/auth/wallets/primary`
+
+- Session-authed. Body: `{ address }`.
+- In a single transaction:
+ 1. Verify the address belongs to the caller in `user_wallets` → else 404.
+ 2. `update user_wallets set is_primary = (address = $1) where user_id = $me`.
+ 3. `update users set wallet_address = $1 where id = $me`.
+- Returns `{ ok: true, primary: address }`.
+
+### Dashboard UI
+
+In [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js), beside each linked wallet show:
+
+- A radio button "Primary" — checked if `is_primary`.
+- Clicking a non-primary radio calls the endpoint, then re-renders the list.
+- Primary wallet gets a subtle gold border or label; disconnecting the primary is blocked with a tooltip ("Set another wallet as primary first") unless it's the last wallet.
+
+### `GET /api/auth/me` response
+
+Add `wallets: [{ address, chain_id, is_primary, ens_name }]` to the session payload so the dashboard can render without a second request.
+
+## Out of scope
+
+- Per-action wallet picker (which wallet signs what). Primary is enough for now.
+- Migrating the on-chain `agentId` when the primary changes — that lands in Layer 6.
+- ENS/basename resolution (handled in 01-02).
+
+## Acceptance
+
+1. User with 2 linked wallets sees both, one marked primary.
+2. Clicking the other "Primary" radio flips the flag in ≤1 request; refresh confirms persistence.
+3. `users.wallet_address` matches the new primary after the click.
+4. Disconnecting the primary while another wallet exists is blocked in the UI.
+5. Disconnecting the only wallet clears `users.wallet_address` to null.
+6. `node --check` passes on new files.
diff --git a/prompts/build/01-04-session-expiry-ux.md b/prompts/build/01-04-session-expiry-ux.md
new file mode 100644
index 000000000..418658824
--- /dev/null
+++ b/prompts/build/01-04-session-expiry-ux.md
@@ -0,0 +1,47 @@
+---
+mode: agent
+description: "Handle expired sessions gracefully across the SPA and public pages"
+---
+
+# 01-04 · Session expiry UX
+
+## Why it matters
+
+Right now, when a session expires, the dashboard throws `401` noisily and the user is stuck on a broken page. For a product where users invest a selfie in creating an avatar, a lost session means lost trust. Quiet, reliable re-auth.
+
+## Prerequisites
+
+- 01-01 and 01-02.
+
+## Read these first
+
+- [src/account.js](../../src/account.js) — current authenticated fetch client.
+- [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js) — dashboard fetch usage.
+- [api/_lib/auth.js](../../api/_lib/auth.js) — session TTL / revocation.
+
+## Build this
+
+1. **Central fetch wrapper** — if one doesn't exist, add a thin helper in `src/account.js` that wraps `fetch` and, on 401 with `{ error: 'unauthorized' }`, redirects to `/login?next={current}`.
+2. **Soft vs hard 401** — `GET /api/agents/me` intentionally returns `{ agent: null }` for anonymous users. Make sure the client treats that as "anonymous" (allow rendering), not as "session expired" (redirect). Everything else that's 401 with a real error body is the redirect path.
+3. **Hash-preserving redirect** — if the URL has a `#model=` / `#widget=` / `#agent=` fragment, preserve it through `/login` and back. SPAs lose the fragment on a plain `location.href = '/login'`.
+4. **Logout flow** — after logout, visiting a protected page like `/dashboard/` should land on `/login?next=/dashboard/` cleanly.
+5. **Embed iframe** — `/agent/:id/embed` must never redirect to `/login`. It's an anonymous resource. Make the embed's own fetches explicitly anonymous (no `credentials: 'include'` unless the owner is previewing).
+
+## Out of scope
+
+- Refresh-token rotation (sessions are long-lived cookies).
+- Silent re-auth (we want the explicit redirect).
+- Changing session TTL values.
+
+## Deliverables
+
+- Diff to `src/account.js` (central wrapper).
+- Diff to `public/dashboard/dashboard.js` (use the wrapper).
+- Diff to any embed-side fetch call to drop `credentials: 'include'`.
+
+## Acceptance
+
+- Expire a session manually (delete cookie or set `revoked_at`) → next API call triggers a clean redirect.
+- Anonymous homepage hits `/api/agents/me` → no redirect, no console error.
+- Embed iframe on a logged-out browser renders the public avatar fine.
+- `node --check` + `npm run build` pass.
diff --git a/prompts/build/01-04-siwe-hardening.md b/prompts/build/01-04-siwe-hardening.md
new file mode 100644
index 000000000..2b0fd0fde
--- /dev/null
+++ b/prompts/build/01-04-siwe-hardening.md
@@ -0,0 +1,63 @@
+# 01-04 — SIWE nonce hardening and rate-limit audit
+
+## Why it matters
+
+Wallet auth is user-facing and unauthenticated at the entry point. Nonce reuse, unbounded nonce generation, and missing rate limits are exactly the class of bugs that get a wallet-auth flow quietly drained via scripted enumeration. Before we expose SIWE to the real internet (Layer 5 host embeds will widen attack surface), close these gaps.
+
+## Context
+
+- Nonce mint: [api/auth/siwe/nonce.js](../../api/auth/siwe/nonce.js).
+- Verify/burn: [api/auth/siwe/verify.js](../../api/auth/siwe/verify.js).
+- Link (from 01-01): `api/auth/siwe/link.js`.
+- Shared rate limit: [api/_lib/rate-limit.js](../../api/_lib/rate-limit.js).
+
+## What to build
+
+### Nonce store invariants
+
+Confirm (or add):
+
+- Nonces stored with `(nonce, issued_at, consumed_at, client_ip_hash)`.
+- TTL: 10 minutes. Expired nonces rejected with the same error as unknown nonces (no distinguishing timing).
+- Single-use: `update … set consumed_at = now() where nonce = $1 and consumed_at is null returning 1` — verify on the `returning` row count, not on a prior select.
+- A nonce is bound at mint time to a client IP hash (sha256 of IP + server salt). Verify/link rejects if the presenting IP hash differs. Document this: it breaks mobile networks that change IPs mid-flow; log at `info` and exempt if `X-SIWE-Allow-IP-Drift: 1` header is present AND the bound ENS name matches. If that logic feels fragile, drop the IP binding entirely and say so in the reporting.
+
+### Rate limits
+
+Apply via [api/_lib/rate-limit.js](../../api/_lib/rate-limit.js):
+
+- `POST /api/auth/siwe/nonce` — 20 / 10min per IP, 5 / 10min per `(IP, requested-address)` if the client sends one.
+- `POST /api/auth/siwe/verify` — 10 / 10min per IP, 5 / 10min per address.
+- `POST /api/auth/siwe/link` — 5 / 10min per authenticated user.
+
+Limits must fail closed with 429 and `Retry-After`.
+
+### Message validation
+
+In verify + link, explicitly check:
+
+- `domain` equals the request's `Host` header (not `X-Forwarded-Host` unless the trusted proxy is our own).
+- `uri` scheme is `https:` in production; allow `http://localhost` in `NODE_ENV !== 'production'`.
+- `chainId` ∈ allowlist (1, 8453). Anything else → 400 with `unsupported_chain`.
+- `issuedAt` within ±5 minutes of server time; `expirationTime`, if set, in the future.
+- `statement` must match a server-defined canonical string (no user-supplied statements).
+
+### Observability
+
+Emit a structured log line on every `nonce/verify/link/rate-limit-trip` with `{ route, outcome, ip_hash, address_hash }`. Do not log raw addresses or IPs.
+
+## Out of scope
+
+- Adding a captcha.
+- Geo-blocking.
+- Switching from cookie sessions to JWT.
+- Device fingerprinting.
+
+## Acceptance
+
+1. Manual replay of a used nonce → 400/401, never a successful login.
+2. Parallel verify races for the same nonce: exactly one succeeds, the rest 401.
+3. 25 rapid nonce requests from one IP: first ~20 succeed, rest 429 with `Retry-After`.
+4. Tampered `domain`, `chainId`, or `issuedAt` in the signed message → verify rejects.
+5. `node --check` passes on modified files.
+6. Log lines for rate-limit trips are emitted and do not contain raw PII.
diff --git a/prompts/build/01-04-wallet-chain-switch.md b/prompts/build/01-04-wallet-chain-switch.md
new file mode 100644
index 000000000..53474cfc7
--- /dev/null
+++ b/prompts/build/01-04-wallet-chain-switch.md
@@ -0,0 +1,104 @@
+# 01-04 — Chain guard and network switch prompt
+
+**Pillar 1 — Wallet auth.**
+
+## Why it matters
+
+The on-chain pillar (6) deploys ERC-8004 registries to a specific chain (Base Sepolia for now, mainnet later). Today the wallet client has no concept of "expected chain" — users on Ethereum mainnet can sign in and then hit "Register on-chain" and the tx errors out because the registry isn't deployed there. Fix the guard before we ship onchain registration UX.
+
+## What to build
+
+A reusable `NetworkGuard` helper that:
+
+1. Reads the expected chain from config (`VITE_TARGET_CHAIN_ID`).
+2. Compares against the wallet's current chain.
+3. If mismatched, shows a modal: "Switch to Base Sepolia" with a one-click switch button.
+4. Calls `wallet_switchEthereumChain` and if the chain isn't added, falls back to `wallet_addEthereumChain`.
+5. Blocks the calling action (register, sign, etc.) until the chain matches.
+
+Plus: a passive network pill in the wallet chip showing current chain name + color.
+
+## Read these first
+
+| File | Why |
+|:---|:---|
+| [src/erc8004/abi.js](../../src/erc8004/abi.js) | `REGISTRY_DEPLOYMENTS` — source of truth for supported chains. |
+| [src/erc8004/agent-registry.js](../../src/erc8004/agent-registry.js) | Existing `connectWallet`. See what chain check (if any) is there. |
+| [public/wallet-login.js](../../public/wallet-login.js) | Current sign-in — reads `chainId` but does nothing with it. |
+| [api/auth/siwe/verify.js](../../api/auth/siwe/verify.js) | Persists `chain_id` on `user_wallets`. No guard server-side — that's fine, guard is UX-only. |
+| `src/components/wallet-chip.js` (from 01-02) | Where the network pill mounts. |
+
+## Build this
+
+### 1. Chain config
+
+Create `src/lib/chains.js`:
+
+```js
+export const CHAINS = {
+ 1: { name: 'Ethereum', short: 'ETH', color: '#627eea', rpc: null, explorer: 'https://etherscan.io' },
+ 8453: { name: 'Base', short: 'BASE', color: '#0052ff', rpc: 'https://mainnet.base.org', explorer: 'https://basescan.org' },
+ 84532: { name: 'Base Sepolia', short: 'B-SEP',color: '#88aaff', rpc: 'https://sepolia.base.org', explorer: 'https://sepolia.basescan.org' },
+ // Add more as needed.
+};
+
+export function chainInfo(id) { return CHAINS[Number(id)] || { name: `Chain ${id}`, short: 'UNK', color: '#777' }; }
+
+export const TARGET_CHAIN_ID = Number(import.meta.env.VITE_TARGET_CHAIN_ID) || 84532;
+```
+
+Also document `VITE_TARGET_CHAIN_ID` in `.env.example`.
+
+### 2. `NetworkGuard`
+
+Create `src/lib/network-guard.js`:
+
+```js
+export async function ensureChain(targetId) { /* returns true if on target chain after prompt, false if user cancelled */ }
+export async function switchOrAdd(provider, chainId) { /* wallet_switchEthereumChain → wallet_addEthereumChain */ }
+```
+
+Use dynamic `BrowserProvider` from esm.sh to keep the file CDN-loadable like `wallet-login.js`.
+
+### 3. Wire into ERC-8004 actions
+
+In [src/erc8004/agent-registry.js](../../src/erc8004/agent-registry.js), before every state-changing tx, call `await ensureChain(TARGET_CHAIN_ID)`. If it returns false, throw a typed error `{ code: 'chain_mismatch' }`.
+
+Callers that show a UI should catch `chain_mismatch` and display a friendly message.
+
+### 4. Network pill
+
+Extend `src/components/wallet-chip.js` (from 01-02) to show the current chain as a pill inside the chip. Passive — just a label + colored dot. Listen to `window.ethereum` `chainChanged` event to re-render.
+
+## Out of scope
+
+- Do not add an RPC selector.
+- Do not store the chain on the server beyond what `user_wallets.chain_id` already holds.
+- Do not block wallet sign-in based on chain (sign-in is chain-agnostic — only on-chain actions need the guard).
+
+## Deliverables
+
+**New:**
+- `src/lib/chains.js`
+- `src/lib/network-guard.js`
+
+**Modified:**
+- [src/erc8004/agent-registry.js](../../src/erc8004/agent-registry.js) — add `ensureChain` calls before each write path.
+- `src/components/wallet-chip.js` — network pill + `chainChanged` listener.
+- `.env.example` — document `VITE_TARGET_CHAIN_ID`.
+
+## Acceptance
+
+- [ ] With wallet on mainnet (chain 1) and `VITE_TARGET_CHAIN_ID=84532`, hitting register opens a switch prompt.
+- [ ] Clicking "Switch" invokes MetaMask's switch dialog; accepting it updates the network pill to "Base Sepolia" in real time.
+- [ ] If Base Sepolia is not yet added in the wallet, the add-network prompt fires with the correct RPC and explorer.
+- [ ] Cancelling the switch → the calling action throws `chain_mismatch`, UI shows a friendly error, nothing on-chain happens.
+- [ ] `npm run build` passes.
+
+## Test plan
+
+1. Set `VITE_TARGET_CHAIN_ID=84532` locally.
+2. MetaMask on Ethereum mainnet. Visit dashboard → pill says "Ethereum" in blue.
+3. Click any action that calls `ensureChain` (mock with a dev-only button if the register UI from pillar 6 isn't shipped yet). Confirm switch prompt → accept → pill updates.
+4. Switch back to mainnet manually in MetaMask. Pill updates to "Ethereum" without reload.
+5. Remove Base Sepolia from MetaMask (Settings → Networks). Retry → add-network prompt fires.
diff --git a/prompts/build/02-01-selfie-capture-ui.md b/prompts/build/02-01-selfie-capture-ui.md
new file mode 100644
index 000000000..59b8d477d
--- /dev/null
+++ b/prompts/build/02-01-selfie-capture-ui.md
@@ -0,0 +1,55 @@
+# 02-01 — Selfie capture UI
+
+## Why it matters
+
+The "magic moment" of the product is: take a photo, get a 3D avatar. This prompt builds the front-end capture step only — no 3D generation yet. We need a clean, on-brand camera-capture flow that produces a single high-quality selfie image ready to hand to the generator in `02-02`.
+
+## Context
+
+- Dashboard entry: [public/dashboard/index.html](../../public/dashboard/index.html).
+- Existing "Create avatar" flow opens Avaturn via [src/avatar-creator.js](../../src/avatar-creator.js). Do **not** remove that path — add the selfie path as a second option.
+- Style baseline: match the dark theme + `--accent` purple gradient seen on [public/login.html](../../public/login.html).
+
+## What to build
+
+### New page — `public/dashboard/selfie.html`
+
+Reachable as `/dashboard/selfie`. Pure HTML + vanilla JS, no build-graph dependency (the dashboard is served from `public/`).
+
+Flow:
+
+1. **Consent screen** — short copy: "We'll use one photo to build your avatar. Photo is processed on our servers, stored with your account, and never shared. You can delete it anytime." Continue button.
+2. **Camera preview** — `getUserMedia({ video: { facingMode: 'user', width: { ideal: 1024 }, height: { ideal: 1024 } }, audio: false })`. Show a square live preview with a subtle face-outline guide overlay (SVG).
+3. **Capture** — on click, draw the video frame to a `<canvas>`, downscale to max 1024×1024, export as JPEG at quality 0.92, store as a Blob in a module-scope variable.
+4. **Review** — show the captured image with "Use this photo" and "Retake" buttons.
+5. **Submit** — "Use this photo" POSTs the blob to `/api/avatars/from-selfie` (the endpoint is built in `02-02`; for now, just POST and display whatever response comes back, or a placeholder error if 404).
+6. On success, navigate to `/dashboard/` with a query string `?new=<avatar_id>`.
+
+### Dashboard entry
+
+On [public/dashboard/index.html](../../public/dashboard/index.html), add a "From selfie" button next to the existing "Create avatar" button. It links to `/dashboard/selfie`.
+
+### Graceful failure modes
+
+- No camera permission → show clear error + "Upload a photo instead" fallback (standard `<input type="file" accept="image/*">`).
+- No camera device → same fallback.
+- Browser doesn't support `getUserMedia` → same fallback.
+
+## Out of scope
+
+- Any 3D generation. This prompt ends at "POST a JPEG to the backend."
+- Face detection / quality scoring. Just take the photo.
+- Multi-angle capture. One photo only.
+- Video / animation capture.
+- Mobile-specific native camera integration beyond `facingMode: 'user'`.
+
+## Acceptance
+
+1. Visit `/dashboard/selfie` as a signed-in user.
+2. Grant camera permission → see live preview.
+3. Click capture → see still image + Retake / Use buttons.
+4. Retake returns to live preview.
+5. Use this photo → POST fires with a JPEG blob, `Content-Type: image/jpeg`.
+6. If camera denied → upload fallback input appears and works.
+7. No errors in console. No leaked camera tracks (`stream.getTracks().forEach(t => t.stop())` runs on unmount/retake).
+8. Page passes Lighthouse accessibility ≥ 90 (labels on all interactive elements, focus visible, no color-only signals).
diff --git a/prompts/build/02-02-avatar-generation-pipeline.md b/prompts/build/02-02-avatar-generation-pipeline.md
new file mode 100644
index 000000000..7b7556043
--- /dev/null
+++ b/prompts/build/02-02-avatar-generation-pipeline.md
@@ -0,0 +1,60 @@
+# 02-02 — Avatar generation pipeline: JPEG → GLB
+
+**Branch:** `feat/avatar-generation-pipeline`
+**Stack layer:** 2 (Selfie → agent creation)
+**Depends on:** 02-01 (the selfie capture UI posts to the endpoint this prompt builds)
+**Blocks:** 02-03 (avatar↔agent link expects a persisted avatar row)
+
+## Why it matters
+
+02-01 ends with a JPEG blob POSTed to `/api/avatars/from-selfie`. Today that endpoint does not exist. Without it, the capture UI shows a 404 and the magic moment is dead. This is the glue between a selfie and a playable 3D avatar.
+
+## Read these first
+
+| File | Why |
+|:---|:---|
+| [src/avatar-creator.js](../../src/avatar-creator.js) | Existing Avaturn wrapper. Understand `initOptions.url` (session URL with a pre-seeded selfie). |
+| [api/avatars/presign.js](../../api/avatars/presign.js), [api/avatars/index.js](../../api/avatars/index.js) | R2 presign + metadata write. Reuse, don't duplicate. |
+| [api/_lib/](../../api/_lib/) | Auth middleware (`requireAuth()`), Neon client, response helpers. |
+| [public/dashboard/selfie.html](../../public/dashboard/selfie.html) *(from 02-01)* | The caller. Its POST body shape defines this endpoint's input. |
+
+## Build this
+
+### Endpoint — `POST /api/avatars/from-selfie`
+
+- **Auth:** required (`requireAuth()`).
+- **Body:** `multipart/form-data` with a single `photo` field (JPEG, ≤ 4 MB). Reject anything else with 400.
+- **Pipeline:**
+ 1. Stream the JPEG into a temp buffer. Reject non-JPEG magic bytes (`0xFFD8`).
+ 2. Upload the selfie to R2 under `selfies/<user_id>/<uuid>.jpg` — private, not publicly listable.
+ 3. Call the Avaturn (or equivalent) generation API with the R2 signed-read URL for the selfie. Env var: `AVATAR_GENERATION_API_KEY`. Document in `.env.example`.
+ 4. Poll the generation job until `status=ready` or timeout (90s). On timeout, return `202` with `{ job_id }` so the client can poll `GET /api/avatars/from-selfie/:job_id`.
+ 5. On success, fetch the generated GLB, stream it to R2 under `avatars/<user_id>/<uuid>.glb`, and create an `avatars` row via the same internal helper used by `POST /api/avatars`.
+ 6. Return the created avatar row (same shape as `POST /api/avatars`).
+
+- **Status endpoint:** `GET /api/avatars/from-selfie/:job_id` — returns `{ status: 'pending' | 'ready' | 'failed', avatar?: {...}, error?: string }`.
+
+### Error handling
+
+Only validate at the boundary: reject bad input, surface upstream provider failures verbatim (redact API keys). No defensive try/catch around internal calls. If the generation provider returns a user-facing error (e.g. "no face detected"), forward it as 422 with `{ error, hint }`.
+
+### Zero-new-dep rule
+
+Use `@aws-sdk/client-s3` (already present). For multipart parsing on Vercel serverless, use `busboy` *only if nothing already in the repo parses multipart* — grep first. If a helper exists, use it.
+
+## Out of scope
+
+- Do not bind the avatar to an agent — that's 02-03.
+- Do not build the capture UI — that's 02-01.
+- Do not implement moderation / NSFW filtering — follow-up prompt.
+- Do not add a UI for the `202 + poll` path unless needed — the 02-01 UI can block on the 200 path for the MVP.
+
+## Acceptance
+
+- [ ] POST with a valid JPEG returns a fully-populated avatar row within 90s or a 202 + job_id.
+- [ ] POST with a PNG or non-image returns 400.
+- [ ] POST without auth returns 401.
+- [ ] Generated GLB loads in [src/viewer.js](../../src/viewer.js) without errors.
+- [ ] Job status endpoint returns `ready` with the avatar row after a successful generation.
+- [ ] Upstream provider failure ("no face") surfaces as a readable 422.
+- [ ] No secrets leaked in error bodies. Check by deliberately breaking the API key.
diff --git a/prompts/build/02-02-image-to-3d-backend.md b/prompts/build/02-02-image-to-3d-backend.md
new file mode 100644
index 000000000..f69b6f2a1
--- /dev/null
+++ b/prompts/build/02-02-image-to-3d-backend.md
@@ -0,0 +1,91 @@
+# 02-02 — Selfie → 3D avatar backend
+
+## Why it matters
+
+This is the backend that turns a JPEG into a GLB. It is the single most product-defining endpoint in the app — the "magic moment" depends on it working end-to-end. Given the complexity, we use a third-party image-to-avatar provider rather than rolling our own ML.
+
+## Context
+
+- Upload frontend: `/dashboard/selfie` (built in `02-01`). Posts a JPEG to `/api/avatars/from-selfie`.
+- R2 storage helper: [api/_lib/r2.js](../../api/_lib/r2.js). Objects are served via `env.R2_PUBLIC_BASE`.
+- Avatar schema: [api/_lib/schema.sql](../../api/_lib/schema.sql) — `avatars` table. `source` column allows `'upload' | 'avaturn' | 'import'`; you'll add `'selfie'`.
+- Existing avatar create pattern: [api/avatars/index.js](../../api/avatars/index.js).
+- Session auth: `getSessionUser` in [api/_lib/auth.js](../../api/_lib/auth.js).
+- Rate limits: [api/_lib/rate-limit.js](../../api/_lib/rate-limit.js) — add a new preset `selfieGenerate`.
+
+## Provider choice
+
+Use **Ready Player Me's** "avatar from photo" API as the default provider (docs: readyplayer.me). It returns a GLB URL given a photo upload. If a different provider is preferred at build time, the provider interface must be abstracted behind `api/_lib/avatar-gen/` so it can be swapped.
+
+Configuration via env:
+
+```
+AVATAR_GEN_PROVIDER=rpm # 'rpm' | 'meshy' | ...
+AVATAR_GEN_API_KEY=<secret>
+AVATAR_GEN_APPLICATION_ID=<rpm app id> # provider-specific
+```
+
+If env is missing, the endpoint returns 503 `provider_not_configured` — do not fall back to a stub.
+
+## What to build
+
+### Provider adapter — `api/_lib/avatar-gen/index.js`
+
+```js
+export async function generateAvatarFromImage({ imageBuffer, mimeType, userId }) {
+ // Returns { glbUrl, thumbnailUrl?, providerMeta }
+}
+```
+
+First implementation: `api/_lib/avatar-gen/rpm.js`. It:
+1. Uploads the image to RPM.
+2. Polls until the avatar is ready (max 90s total; exponential backoff starting at 2s).
+3. Downloads the resulting GLB into a Buffer.
+4. Returns the buffer + any thumbnail URL RPM gives back.
+
+The returned buffer (not URL) is passed back to the endpoint so **we** control where the GLB is stored. No external URLs baked into avatar records.
+
+### Endpoint — `api/avatars/from-selfie.js`
+
+- `POST`, session-authed, rate-limited (`selfieGenerate`: 5 per hour per user).
+- Accepts `multipart/form-data` with a single file field `photo` (JPEG or PNG, ≤ 8 MB).
+- Steps:
+ 1. Enforce plan quota (reuse avatar-count check from `api/avatars/index.js`).
+ 2. Call `generateAvatarFromImage`.
+ 3. Upload GLB buffer to R2 under `avatars/<user_id>/<uuid>.glb`. Set `content-type: model/gltf-binary`.
+ 4. Insert `avatars` row: `source='selfie'`, `source_meta={ provider, provider_id }`, `visibility='private'`, `name='Me'`, slug auto-generated.
+ 5. If the user has an `agent_identities` row, link the new avatar as `avatar_id`.
+ 6. Return `{ avatar: <row> }`.
+- On provider failure → 502 `generation_failed` with a generic user-facing message. Log provider response server-side only.
+
+### Schema update
+
+Extend the `avatars.source` check constraint to include `'selfie'`. Additive migration only — do not break existing rows.
+
+### New rate-limit preset
+
+In [api/_lib/rate-limit.js](../../api/_lib/rate-limit.js):
+
+```js
+selfieGenerate: (userId) => getLimiter('selfie:gen', { limit: 5, window: '1 h' }).limit(userId),
+```
+
+## Out of scope
+
+- Multi-photo or video input.
+- Face detection / rejection (trust the provider).
+- Queued/async generation — this endpoint blocks until done. Max 90s.
+- Live progress streaming — `02-03` covers that.
+- Editing the returned model server-side.
+
+## Acceptance
+
+1. With env configured and `/dashboard/selfie` flow from `02-01`, capture a photo → receive an `avatar` JSON response with a usable GLB URL.
+2. The GLB loads in the existing viewer at `/agent/:id` for the caller.
+3. The avatar row has `source='selfie'` and a `source_meta.provider` field.
+4. Without env configured → 503, not 500.
+5. Sixth request within an hour → 429.
+6. A non-JPEG/PNG upload → 400.
+7. Oversize upload → 413.
+8. No provider secret leaks to the client (inspect Network tab).
+9. `node --check` passes.
diff --git a/prompts/build/02-02-selfie-upload-r2.md b/prompts/build/02-02-selfie-upload-r2.md
new file mode 100644
index 000000000..8ad1b7240
--- /dev/null
+++ b/prompts/build/02-02-selfie-upload-r2.md
@@ -0,0 +1,68 @@
+---
+mode: agent
+description: "Presign + upload the captured selfie to R2 under user-scoped key"
+---
+
+# 02-02 · Selfie upload to R2
+
+## Why it matters
+
+Second step of the magic moment. The selfie blob from 02-01 must land in R2 under the user's path so that (a) the avatar-generation pipeline can read it server-side, and (b) the user can later regenerate from the same photo without retaking it.
+
+## Prerequisites
+
+- 02-01 in place — `selfie:ready` event fires with a JPEG blob.
+- R2 env vars (`R2_ACCOUNT_ID`, `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY`, `R2_BUCKET`, `R2_PUBLIC_URL`) set.
+
+## Read these first
+
+- [api/avatars/presign.js](../../api/avatars/presign.js) — canonical presigned PUT flow.
+- [api/avatars/index.js](../../api/avatars/index.js) — the "register after upload" pattern including `headObject()` size check.
+- [api/_lib/r2.js](../../api/_lib/r2.js) — presign helpers.
+- [api/CLAUDE.md](../../api/CLAUDE.md) — key format: `u/{userId}/selfies/{timestamp}.jpg`.
+
+## Build this
+
+1. **New endpoint** `api/selfies/presign.js`:
+ - Session auth required (no anonymous selfies).
+ - Body: `{ content_type: 'image/jpeg', size: number }`.
+ - Validate: content_type ∈ {`image/jpeg`,`image/png`}, size ≤ 8 MB.
+ - Return `{ upload_url, storage_key, headers }`. Key: `u/${userId}/selfies/${Date.now()}.jpg`.
+ - Rate-limit: `limits.upload(userId)`.
+2. **New endpoint** `api/selfies/index.js`:
+ - `POST` after upload: body `{ storage_key }`. Verify `headObject(key)`, verify key prefix matches current user, insert row into a new `selfies` table (or reuse `avatars` with `source='selfie'` — check existing schema; if adding a table, document the migration in `schema.sql`).
+ - Returns `{ selfie: { id, storage_key, created_at } }`.
+ - `GET` list: last 10 selfies for the user.
+ - `DELETE /api/selfies/:id`: soft-delete, also queues R2 object deletion.
+3. **Client wiring** in `public/selfie/selfie.js`:
+ - Listen to the `selfie:ready` event from 02-01.
+ - Call `/api/selfies/presign` → `PUT` the blob → `POST /api/selfies` → show "Selfie saved." with the returned `selfie.id`.
+ - Preserve the blob in memory so the next step (02-03) can start immediately without a re-download.
+4. **Route** both endpoints in [vercel.json](../../vercel.json).
+
+## Schema note
+
+If a `selfies` table doesn't exist, adding it is **a schema change** — per CLAUDE.md, this requires explicit ask. Either:
+- (Preferred) Reuse `avatars` with `source='selfie'`, `content_type='image/jpeg'` and skip the size-per-avatar quota.
+- Or halt and surface the migration before writing it.
+
+## Out of scope
+
+- Generating the avatar (02-03).
+- Face detection / quality checks (could bolt on later).
+- Cropping or transformation (keep original bytes).
+
+## Deliverables
+
+- `api/selfies/presign.js`, `api/selfies/index.js`.
+- `public/selfie/selfie.js` upload wiring.
+- `vercel.json` routes.
+- A note in the PR description on the schema decision.
+
+## Acceptance
+
+- Take a selfie on `/selfie`, click "Use this photo" → object appears in R2 at `u/{userId}/selfies/{ts}.jpg`.
+- List endpoint returns it.
+- Delete endpoint removes it.
+- All endpoints use `wrap()`, `method()`, `error()`, `json()` helpers — no hand-rolled responses.
+- `npm run build` passes.
diff --git a/prompts/build/02-03-avatar-to-agent-link.md b/prompts/build/02-03-avatar-to-agent-link.md
new file mode 100644
index 000000000..6b9a9cf94
--- /dev/null
+++ b/prompts/build/02-03-avatar-to-agent-link.md
@@ -0,0 +1,43 @@
+# 02-02 — Auto-link new avatar → agent_identity on save
+
+**Branch:** `feat/avatar-agent-link`
+**Stack layer:** 2 (Selfie → agent creation)
+**Depends on:** 02-01
+**Blocks:** 03-* (edit), 04-* (embed assumes every avatar has an agent)
+
+## Why it matters
+
+Today the database has `avatars` and `agent_identities` but nothing binds them on creation. A user finishes the selfie flow and has a 3D mesh — but no *agent*, which is the actual product. This prompt makes "avatar" and "agent" inseparable from the first save.
+
+## Read these first
+
+| File | Why |
+|:---|:---|
+| [api/avatars/index.js](../../api/avatars/index.js) | Where a new avatar record is written. This is the hook point. |
+| [api/agents.js](../../api/agents.js) | Agent creation + `/api/agents/me` + default-agent logic. |
+| [src/agent-identity.js](../../src/agent-identity.js) | Client-side identity model. |
+| [api/_lib/](../../api/_lib/) migrations | Confirm the `agent_identities` schema (avatar_id column exists or needs adding). |
+
+## Build this
+
+1. **Schema check.** Confirm `agent_identities.avatar_id` exists and is nullable with a FK to `avatars(id) on delete set null`. If missing, add a migration `003_agent_avatar_fk.sql` (or next free number — verify with `ls api/_lib/migrations/`).
+2. **Server-side link on first avatar.** In [api/avatars/index.js](../../api/avatars/index.js) `POST` handler, after the avatar row is created:
+ - If the user has no agent yet, create one inside the same transaction with `avatar_id = newAvatar.id` and a sensible default name (derive from avatar name or user handle).
+ - If the user has exactly one agent and that agent has `avatar_id IS NULL`, bind the new avatar to it.
+ - If the user has ≥2 agents or their sole agent already has an avatar, do nothing — leave the avatar unbound and return it normally.
+3. **Return shape.** The POST response gains an optional `agent` field: `{ id, name, slug }` if a link happened, absent otherwise.
+4. **Client.** In [src/account.js](../../src/account.js), surface the `agent` field from the POST response. Dashboard's success state shows "Avatar saved and bound to agent <name>".
+
+## Out of scope
+
+- Do not add multi-agent UI.
+- Do not migrate existing orphan avatars — just fix the creation path. A separate one-off script is fine as a follow-up prompt.
+- Do not touch onchain identity yet — that's 06-*.
+
+## Acceptance
+
+- [ ] New user's first avatar creates and binds to their default agent atomically.
+- [ ] POST response includes the `agent` field when a link happened.
+- [ ] Two concurrent avatar POSTs for a first-time user do not create two agents.
+- [ ] `select count(*) from agent_identities where avatar_id is null and user_id in (active users)` trends to zero for new signups.
+- [ ] Existing users with avatars and agents are untouched.
diff --git a/prompts/build/02-03-generation-progress-ui.md b/prompts/build/02-03-generation-progress-ui.md
new file mode 100644
index 000000000..39cc3f5a6
--- /dev/null
+++ b/prompts/build/02-03-generation-progress-ui.md
@@ -0,0 +1,71 @@
+# 02-03 — Generation progress UI
+
+## Why it matters
+
+RPM (or any third-party image-to-avatar provider) takes 30–90 seconds. A silent spinner kills the magic — users abandon. We need honest, on-brand progress feedback so the wait feels intentional.
+
+## Context
+
+- Selfie capture UI: `public/dashboard/selfie.html` (built in `02-01`).
+- Generation endpoint: `/api/avatars/from-selfie` (built in `02-02`). Currently blocks until done.
+- Optional: extend endpoint to support SSE if the provider exposes progress events. If not, use client-side synthetic progress.
+
+## What to build
+
+### Option A (preferred) — real progress via SSE
+
+If the RPM provider exposes progress events (or if a task-id + polling pattern is easier), refactor `api/avatars/from-selfie.js` to:
+
+- Return 202 + `{ job_id }` immediately on POST.
+- Expose `GET /api/avatars/from-selfie/:job_id` as an SSE stream emitting:
+ ```
+ event: progress
+ data: { "pct": 42, "stage": "generating" }
+
+ event: complete
+ data: { "avatar": { ... } }
+
+ event: error
+ data: { "error": "generation_failed", "message": "..." }
+ ```
+- Jobs are tracked in a new `selfie_jobs` table: `id uuid, user_id uuid, status text, pct int, avatar_id uuid, error text, created_at, updated_at`.
+- Store job state in Upstash Redis for hot reads; persist terminal state to `selfie_jobs`.
+
+### Option B (fallback) — synthetic progress
+
+If the provider has no progress API and adding a job table is too much work, keep the endpoint synchronous and do client-side synthetic progress:
+
+- On POST start, animate a progress bar from 0→85% over ~45s with gentle easing (not linear — slow at 70%+).
+- On response: jump to 100%.
+- On error: replace the bar with the error message.
+
+Pick exactly one option. Document which in the PR.
+
+### UI behavior (applies to both options)
+
+On `/dashboard/selfie` after "Use this photo":
+
+- Full-width progress element with percent and a rotating stage label: *"Sending your photo"* → *"Building your avatar"* → *"Finishing touches"*.
+- Show a preview of the submitted selfie (blurred, low opacity) behind the progress.
+- After success, smooth transition (opacity fade ~300ms) into the avatar preview + "Go to dashboard" button.
+- On error, specific messages for: rate_limited, provider_not_configured, generation_failed. Each has a recover button.
+
+### Cancel
+
+- A "Cancel" button that aborts the fetch (`AbortController`) and returns to the capture step.
+- If using option A, also POST to `DELETE /api/avatars/from-selfie/:job_id` to signal provider cancellation (best-effort; don't block UI on it).
+
+## Out of scope
+
+- Background generation that persists across page navigation. If the user leaves the page, the job is abandoned from their perspective (but may still complete server-side under option A).
+- Multiple concurrent jobs per user.
+- Notifications when generation completes while on another page.
+
+## Acceptance
+
+1. Submit a selfie → progress UI appears with moving percent and changing stage labels.
+2. On success → preview of the generated avatar + navigate to dashboard.
+3. On provider failure → clear error message + retry button.
+4. Cancel button aborts the request within 500ms.
+5. No zombie spinners if the user navigates away and returns (page state is reset).
+6. `prefers-reduced-motion: reduce` makes the progress bar non-animated (just numeric updates).
diff --git a/prompts/build/02-03-selfie-to-avatar-pipeline.md b/prompts/build/02-03-selfie-to-avatar-pipeline.md
new file mode 100644
index 000000000..90f533b3d
--- /dev/null
+++ b/prompts/build/02-03-selfie-to-avatar-pipeline.md
@@ -0,0 +1,66 @@
+---
+mode: agent
+description: "Wire the uploaded selfie to the avatar-generation pipeline (Avaturn or chosen provider)"
+---
+
+# 02-03 · Selfie → avatar pipeline
+
+## Why it matters
+
+The magic moment itself. A JPEG on R2 must become a rigged GLB at `/api/avatars/:id` that loads in the viewer. After this prompt, the user takes a selfie and — within a minute or two — sees themselves as a 3D agent.
+
+## Prerequisites
+
+- 02-01 (capture) and 02-02 (upload) shipped.
+- Avaturn (or chosen provider) API credentials in env.
+
+## Read these first
+
+- [src/avatar-creator.js](../../src/avatar-creator.js) — existing Avaturn SDK integration (client-side).
+- [api/avatars/index.js](../../api/avatars/index.js) — how generated avatars get registered.
+- [api/_lib/r2.js](../../api/_lib/r2.js) — `presignGet` for handing a signed URL to a third-party generator.
+
+## Build this
+
+1. **Decision doc (one paragraph, in PR description)**: are we calling Avaturn (or Ready Player Me, or a self-hosted pipeline) from the **client** (SDK) or the **server** (REST API)? The rest of this prompt assumes server-side because it's more portable and keeps API keys out of the client. If client-side is required, note why.
+2. **New endpoint** `api/selfies/generate.js`:
+ - Session auth required.
+ - Body: `{ selfie_id }`.
+ - Resolve selfie row, generate a short-lived `presignGet` for the R2 object.
+ - Submit to provider with a webhook callback URL `/api/avatars/webhook/{provider}`.
+ - Insert an `avatar_jobs` row: `{ id, user_id, selfie_id, provider, provider_job_id, status: 'queued' }`. (New table — same schema-change constraint; reuse an existing table if possible or halt and surface.)
+ - Return `{ job_id, status: 'queued' }`.
+3. **New endpoint** `api/avatars/webhook/:provider.js`:
+ - Verify webhook signature per provider's scheme.
+ - On `completed`: download the GLB from the provider URL, `PUT` it to R2 at `u/{userId}/{slug}/{timestamp}.glb`, register it in `avatars` (reusing `api/avatars/index.js` helpers), mark the job `done`, set `agent_identities.avatar_id` to the new avatar (assign to the user's default agent — the one `/api/agents/me` would return).
+ - On `failed`: mark the job `failed`, store the error message.
+4. **Polling endpoint** `api/selfies/generate.js` → also handles `GET ?job_id=` → returns `{ status, avatar_id? }`. Keep polling simple; no websockets.
+5. **Client wiring** in `public/selfie/selfie.js`:
+ - After `POST /api/selfies` succeeds, call `POST /api/selfies/generate` with the `selfie_id`.
+ - Poll `/api/selfies/generate?job_id=...` every 3s, max 120s.
+ - On success, redirect to `/agent/${agent_id}` (or `/dashboard/` with a toast if no agent page yet — 04-01 polishes that page).
+
+## Out of scope
+
+- Picking between providers — make one call; document in the decision paragraph.
+- Editing the avatar post-generation (03-*).
+- Multiple-angle capture (single front-facing selfie).
+- Anything to do with ERC-8004 registration.
+
+## Deliverables
+
+- `api/selfies/generate.js`
+- `api/avatars/webhook/{provider}.js`
+- `public/selfie/selfie.js` (polling + redirect)
+- A decision paragraph in the PR description.
+
+## Acceptance
+
+- End-to-end: selfie capture → upload → generate job → webhook fires → avatar registered → redirected to agent page showing the generated body.
+- Failed generations surface a user-readable error and allow retry without retaking the selfie.
+- Webhook signature verification passes valid, rejects forged.
+- `npm run build` passes.
+
+## Open question to flag in the PR
+
+If the chosen provider does not support webhooks, switch to a worker-side polling loop on a cron (`vercel.json` or external scheduler). Don't invent one in this prompt — surface the gap.
diff --git a/prompts/build/02-04-first-agent-landing.md b/prompts/build/02-04-first-agent-landing.md
new file mode 100644
index 000000000..751f43bd9
--- /dev/null
+++ b/prompts/build/02-04-first-agent-landing.md
@@ -0,0 +1,52 @@
+---
+mode: agent
+description: "Post-generation landing page so a new user immediately sees their 3D self"
+---
+
+# 02-04 · First-agent landing
+
+## Why it matters
+
+After 02-03 redirects to `/agent/:id`, the page must feel like an arrival — "this is you, as an agent" — not a blank viewer. First impression of the whole product.
+
+## Prerequisites
+
+- 02-03 wired so the new user has an `agent_identities` row with a generated `avatar_id`.
+
+## Read these first
+
+- [public/agent/index.html](../../public/agent/index.html) — current agent landing page.
+- [src/agent-home.js](../../src/agent-home.js) — identity card + timeline.
+- [src/agent-identity.js](../../src/agent-identity.js) — `AgentIdentity.load()`.
+- [src/agent-avatar.js](../../src/agent-avatar.js) — Empathy Layer performer.
+
+## Build this
+
+1. **Detect first visit** — query param `?welcome=1` after the post-generation redirect triggers an inline celebratory overlay (not a modal): "Meet your agent. This is a 3D body, an identity, and a place for skills. You can edit it any time."
+2. **Celebrate via the Empathy Layer** — on load with `?welcome=1`, emit a `celebration` pulse through the agent protocol so the avatar smiles + leans forward. Use the existing scoring in [src/agent-avatar.js](../../src/agent-avatar.js) — fire an action with high celebration valence; do not invent a new state.
+3. **Name the agent** — if the agent's `name` is the default `'Agent'`, show an inline "Name your agent" input that saves via `PUT /api/agents/:id`. No modal.
+4. **Next steps strip** — three cards below the viewer:
+ - "Edit your look" → `/agent/:id/edit` (03-*)
+ - "Share your agent" → opens the existing share panel
+ - "Make it onchain" → `/agent/:id/register` (06-*) — disabled state + tooltip "Coming soon" if registration isn't wired yet.
+5. **Clean state after welcome** — once the user names the agent or dismisses the overlay, replace the URL with `history.replaceState` to drop `?welcome=1` so a refresh doesn't re-celebrate.
+
+## Out of scope
+
+- Building the edit page (03-*).
+- Any onchain registration (06-*).
+- Redesigning the existing share panel.
+- Adding a tutorial walkthrough.
+
+## Deliverables
+
+- Diff to `public/agent/index.html` (welcome overlay + next-steps strip).
+- Diff to the page's JS to wire the Empathy Layer pulse and the inline name input.
+
+## Acceptance
+
+- Fresh user lands on `/agent/:id?welcome=1` → overlay + celebration pulse visible.
+- Naming the agent persists; refreshing shows the new name.
+- Dismiss clears the query param from the URL.
+- Returning to `/agent/:id` without the param skips the overlay.
+- `npm run build` passes.
diff --git a/prompts/build/02-05-avatar-og-share-image.md b/prompts/build/02-05-avatar-og-share-image.md
new file mode 100644
index 000000000..938dddc3c
--- /dev/null
+++ b/prompts/build/02-05-avatar-og-share-image.md
@@ -0,0 +1,54 @@
+# 02-05 — Generated avatar OG / share image
+
+## Why it matters
+
+The moment a user gets their 3D avatar is also the moment they're most likely to share. If the share link unfurls as a generic card, that impulse dies. A static OG image rendered from a canonical avatar pose turns the first-agent-created moment into a recruiting surface for the product.
+
+## Context
+
+- OG endpoint scaffold exists: [api/agent-og.js](../../api/agent-og.js).
+- Per-agent record: `api/agents/[id].js`, table `agents` (reference [api/_lib/schema.sql](../../api/_lib/schema.sql)).
+- Avatar storage: `avatars.storage_key` in R2, helper in [api/_lib/r2.js](../../api/_lib/r2.js).
+- Three.js is already a dep — server-side render via `@react-three/offscreen` or node-three is NOT in scope. Use a pre-rendered "hero pose" PNG captured on the client immediately after avatar generation.
+
+## What to build
+
+### Client — hero-pose capture on the review screen
+
+At the end of Layer 2's review flow (after 02-04 "first-agent-landing"):
+
+- Spin the avatar into a canonical 3/4 hero pose (slight angle, eyes toward camera, neutral expression).
+- Grab a 1200×630 PNG from the model-viewer canvas via `toBlob()`.
+- `POST /api/agents/:id/og-image` with the blob. Server stores it at R2 key `agents/:id/og.png` and updates `agents.og_key`.
+
+### Endpoint — `api/agents/[id]/og-image.js`
+
+- `POST`: session-authed, owner-only. Multipart or raw PNG body. Validates ≤ 1 MB, dimensions exactly 1200×630.
+- `GET`: public, 302 to a signed R2 URL (short TTL) or stream bytes through with `Cache-Control: public, max-age=3600`.
+
+### Unfurl path — [api/agent-og.js](../../api/agent-og.js)
+
+Extend the existing handler:
+
+- If `agents.og_key` is set, serve that image.
+- If not, render a fallback card (text-only: agent name, handle, chip color) and stream a PNG — reuse existing fallback if one exists.
+- `Content-Type: image/png`, `Cache-Control: public, max-age=86400`.
+
+### Agent page meta
+
+On [public/agent/index.html](../../public/agent/index.html), ensure `<meta property="og:image">` points to `/api/agents/:id/og-image` (not a static asset). Same for `twitter:image`.
+
+## Out of scope
+
+- Animated OGs (video OG).
+- Server-side Three.js rendering.
+- Customising the pose per-user (one canonical pose is fine).
+- Editing existing OGs — regenerate on avatar-swap / regenerate (covered implicitly by re-running the client capture after 03-* flows).
+
+## Acceptance
+
+1. Create a new agent via the Layer 2 flow → the review screen produces an OG PNG stored in R2 within 2s.
+2. `curl -I https://…/api/agents/:id/og-image` returns `image/png`, 200.
+3. Paste the agent URL into iMessage, Slack, and Twitter → the preview card shows the avatar hero pose.
+4. Agents with no captured OG still unfurl with the fallback text card.
+5. `node --check` passes on new/modified server files.
diff --git a/prompts/build/02-05-selfie-consent-and-retry.md b/prompts/build/02-05-selfie-consent-and-retry.md
new file mode 100644
index 000000000..ab680bf68
--- /dev/null
+++ b/prompts/build/02-05-selfie-consent-and-retry.md
@@ -0,0 +1,99 @@
+# 02-05 — Selfie consent, retake, and failure recovery
+
+**Pillar 2 — Selfie → agent.**
+
+## Why it matters
+
+The selfie pipeline (02-01 → 02-04) assumes the happy path. In practice: users retake photos, change their mind about privacy mid-flow, or hit generation failures (bad lighting, face not detected, timeout). Without a graceful recovery UX, a failure loses the user forever — and this is the *magic moment* we can't afford to botch.
+
+## What to build
+
+A three-state wrapper around the existing capture → upload → generate flow:
+
+1. **Consent screen** (before camera permission is requested): one-screen "We'll use your photo to make a 3D avatar. Photo is stored in your account and never shared. [Continue] [Upload instead]". Persisted in localStorage — don't ask again for the same user.
+2. **Retake** after capture (before upload): "Looks good? [Use this] [Retake]" on a freeze-frame of the captured photo.
+3. **Recover** after generation failure: typed error codes → friendly messages + clear next action.
+
+## Read these first
+
+| File | Why |
+|:---|:---|
+| `public/studio/selfie.html` or wherever 02-01 landed | Current capture UI you are wrapping. |
+| `api/avatars/presign.js` | Upload path for the selfie. |
+| Backend generation endpoint from 02-02 / 02-03 | Error shape + retry semantics. |
+| [src/avatar-creator.js](../../src/avatar-creator.js) | Avaturn fallback flow. Reuse as "Upload instead" path. |
+
+## Build this
+
+### 1. Consent screen
+
+New component `src/components/selfie-consent.jsx` (vhtml, matches existing component style).
+
+Text: "Take a photo → get a 3D avatar. We store your photo in your account so you can regenerate your avatar later. Never shared, never sold. Delete anytime from /dashboard/privacy."
+
+Buttons:
+- **Continue** — hides the consent, kicks off camera permission.
+- **Upload instead** — opens file picker for a pre-existing photo (jpeg/png only, 8MB max).
+- **Use default avatar** — skip selfie entirely, create agent with a placeholder avatar.
+
+Persist: `localStorage.setItem('selfie-consent-v1', '1')` on Continue/Upload. Skip screen on subsequent visits unless `?reconsent=1`.
+
+### 2. Retake state
+
+After capture, freeze the canvas and show buttons. Don't upload yet. On **Retake**, return to live preview.
+
+### 3. Generation error taxonomy
+
+Backend returns typed errors (add to 02-02 if missing). Surface each with a specific message:
+
+| Code | User message | Action |
+|:---|:---|:---|
+| `no_face_detected` | "We couldn't find your face. Try better lighting and look at the camera." | [Retake] |
+| `multiple_faces` | "We saw more than one face. Use a photo of just you." | [Retake] / [Upload] |
+| `low_quality` | "Photo is too blurry or dark. Try again in better lighting." | [Retake] |
+| `provider_timeout` | "This is taking longer than usual. Retrying…" | Auto-retry once, then [Try again] |
+| `provider_quota` | "We've hit our daily limit. Try again in a few hours — or upload a GLB manually." | [Upload GLB] link to `/dashboard/avatars/new` |
+| `unknown` | "Something went wrong. If this keeps happening, drop us a note." | [Retake] / [Upload] |
+
+### 4. Auto-retry logic
+
+On `provider_timeout`, retry once after 5s. Show a progress spinner so the user knows it's still working. Do not auto-retry twice — they'll sit there.
+
+### 5. Delete-my-selfie link
+
+On /dashboard/privacy (create if missing — keep it minimal), list stored selfies with a "Delete permanently" button. Deletes from R2 + the `selfies` table row (whatever 02-02 landed as). Per-file, not a nuke-all button.
+
+## Out of scope
+
+- Do not add face-detection client-side (that's the provider's job).
+- Do not add liveness checks.
+- Do not add image filters / beauty modes.
+- Do not rewrite 02-01's capture UI — wrap it.
+
+## Deliverables
+
+**New:**
+- `src/components/selfie-consent.jsx`
+- `public/dashboard/privacy.html` + `public/dashboard/privacy.js`
+- `api/selfies/[id].js` — DELETE handler (soft-delete row, then R2 `deleteObject`).
+
+**Modified:**
+- Existing capture UI from 02-01 — wrap with consent + retake.
+- Backend generator (02-02) — emit typed error codes.
+
+## Acceptance
+
+- [ ] First-time user sees consent screen before camera permission prompt.
+- [ ] Returning user skips consent, goes straight to camera.
+- [ ] Captured photo → "Use this / Retake" works in both directions.
+- [ ] Simulating each failure code shows the right message + action.
+- [ ] Deleting a selfie from /privacy actually removes the R2 object (verify via aws s3 cli or R2 dashboard).
+- [ ] `npm run build` passes.
+
+## Test plan
+
+1. Clear localStorage. Visit selfie flow → consent appears. Click Continue → camera.
+2. Capture → freeze → Retake → new capture works.
+3. Force each error code (add a dev-only `?mock-error=no_face_detected` param to the capture page wired into the error state) → verify messages.
+4. Delete selfie from /privacy → the R2 key is gone.
+5. Reload after consent — consent screen skipped.
diff --git a/prompts/build/02-06-no-wallet-guest-creation.md b/prompts/build/02-06-no-wallet-guest-creation.md
new file mode 100644
index 000000000..2d06150aa
--- /dev/null
+++ b/prompts/build/02-06-no-wallet-guest-creation.md
@@ -0,0 +1,118 @@
+# 02-06 — Guest selfie → agent, claim later with wallet
+
+**Pillar 2 — Selfie → agent.**
+
+## Why it matters
+
+Asking users to sign in before they see their 3D self is backwards. The magic moment should come first, then the "save your agent" prompt should drive sign-up. Today, `/dashboard/avatars/new` requires auth.
+
+Without this, most first-touch users bounce before they ever see themselves in 3D. We need a guest flow that keeps the magic up-front and converts via wallet sign-in *after* they're hooked.
+
+## What to build
+
+A guest creation flow at `/try` (or `/create`, pick shorter) that:
+
+1. Anonymous user lands, sees a 10-second pitch + [Try it with my face] CTA.
+2. Selfie capture → generation — fully client-side progress.
+3. When the avatar is ready, it renders on screen with one big button: **Claim this agent** → triggers SIWE.
+4. After sign-in, the guest-created avatar + agent row is reassigned to the now-authenticated user atomically.
+5. A 24-hour guest-session token (not our `__Host-sid`) scopes the unclaimed avatar so no one else can claim it.
+
+## Read these first
+
+| File | Why |
+|:---|:---|
+| [api/auth/siwe/verify.js](../../api/auth/siwe/verify.js) | SIWE flow. The claim step reuses this + a follow-up handoff. |
+| [api/avatars/index.js](../../api/avatars/index.js) | Avatar create flow — will need a guest mode that stamps a guest user placeholder. |
+| [api/_lib/auth.js](../../api/_lib/auth.js) | Session helpers. |
+| Backend from 02-02 / 02-03 | Generation pipeline — needs to accept guest-session token. |
+| [api/agents.js](../../api/agents.js) | Agent auto-create on `GET /api/agents/me`. |
+
+## Build this
+
+### 1. Guest session
+
+New endpoint `POST /api/guest/start` — no auth. Mints a short token (JWT, 24h TTL) tied to a freshly-created `guests` row:
+
+```sql
+create table if not exists guests (
+ id text primary key,
+ token_hash text not null,
+ created_at timestamptz default now(),
+ expires_at timestamptz not null,
+ claimed_user_id text references users(id),
+ claimed_at timestamptz
+);
+```
+
+Returns `{ guest_token }`. Client stores in `sessionStorage` (not localStorage — tied to tab).
+
+### 2. Guest-scoped APIs
+
+Extend `api/avatars/presign.js` and `api/avatars/index.js` to accept `Authorization: Bearer guest:<token>` as an alternative to session. A guest can upload ONE selfie and create ONE avatar. Record `guest_id` on the avatar row so the claim step can find it.
+
+Same for `POST /api/selfies/*` if 02-02 added one.
+
+### 3. Generation on guest path
+
+Fire the generator with guest_token. On completion, the avatar row exists but has `owner_id = null` and `guest_id = <id>`.
+
+### 4. Agent auto-create for guest
+
+Skip on the guest path — we don't create an agent until the user claims. Just cache the generated GLB URL in memory.
+
+### 5. Claim flow
+
+Button on the result page: **Claim this agent**. Runs SIWE (or email sign-up). After `verify` returns 200, call `POST /api/guest/claim` with:
+- `Authorization: Bearer guest:<token>`
+- Cookie: the brand-new `__Host-sid`
+
+Server atomically:
+1. Looks up `guest_id` by token hash.
+2. Confirms `claimed_user_id IS NULL`.
+3. Transfers the avatar row: `update avatars set owner_id = <user>, guest_id = null where guest_id = <guest>`.
+4. Creates an `agent_identities` row for the user (if they don't already have one) and sets `avatar_id`.
+5. Marks guest `claimed_user_id = <user>, claimed_at = now()`.
+6. Returns `{ user, agent }`.
+
+Race-free via `SELECT … FOR UPDATE` inside a transaction.
+
+### 6. Cleanup
+
+A cron-friendly (or Vercel cron) endpoint `POST /api/guest/reap` that deletes unclaimed guest avatars + R2 objects older than 24h. Auth by `Authorization: Bearer <env CRON_SECRET>`.
+
+## Out of scope
+
+- Do not give guests access to any other avatars / agents. One guest = one avatar.
+- Do not support guest sharing / embeds. The unclaimed avatar is not publicly routable.
+- Do not build an account merge flow (existing users with avatars can't absorb a guest avatar from the same device).
+- Do not persist guest rows beyond the TTL unless claimed.
+
+## Deliverables
+
+**New:**
+- `api/guest/start.js`
+- `api/guest/claim.js`
+- `api/guest/reap.js`
+- `public/try/index.html`, `public/try/try.js`
+- Migration: `guests` table + `avatars.guest_id` column (ask before running).
+
+**Modified:**
+- `api/avatars/presign.js` + `api/avatars/index.js` — accept guest bearer.
+- `vercel.json` — `/try` route, guest endpoints, cron entry for `/api/guest/reap`.
+
+## Acceptance
+
+- [ ] `/try` works in incognito. Guest flow completes without auth prompt until the claim button.
+- [ ] Claim → SIWE → lands on `/dashboard/` with the just-created avatar already in the list.
+- [ ] Attempting to claim twice → 409.
+- [ ] Expired guest tokens get reaped; R2 object is deleted.
+- [ ] Network trace shows zero `/api/auth/*` calls before the claim step.
+- [ ] `npm run build` passes.
+
+## Test plan
+
+1. Open `/try` in incognito. Hit button. Capture selfie. Wait for generation. See the avatar.
+2. Click claim → SIWE → dashboard shows the avatar under the new user.
+3. In a second incognito window, start a guest flow, complete capture, but don't claim. Wait 24h (or call reap with `CRON_SECRET` + set `expires_at` to past via a dev tool) → avatar + selfie + guest row gone.
+4. Try to POST another avatar with the same guest token → 409 `guest_quota_exceeded`.
diff --git a/prompts/build/03-01-avatar-swap.md b/prompts/build/03-01-avatar-swap.md
new file mode 100644
index 000000000..8494a72e8
--- /dev/null
+++ b/prompts/build/03-01-avatar-swap.md
@@ -0,0 +1,55 @@
+---
+mode: agent
+description: "Swap an agent's avatar GLB without breaking identity, skills, memory, or onchain record"
+---
+
+# 03-01 · Swap avatar without losing identity
+
+## Why it matters
+
+Pillar 3: editing. The agent IS the identity — skills, memory, wallet, onchain registration. The avatar is the body. A user must be able to replace the body and keep the identity.
+
+## Prerequisites
+
+- 02-* shipped (at least one avatar exists).
+
+## Read these first
+
+- [api/agents.js](../../api/agents.js) — `PUT /api/agents/:id` already accepts `avatar_id`.
+- [api/avatars/index.js](../../api/avatars/index.js) — avatar list.
+- [public/agent/index.html](../../public/agent/index.html) — agent landing (where the edit action lives).
+
+## Build this
+
+1. **New page** `public/agent/edit.html` + accompanying JS. Route `/agent/:id/edit` in `vercel.json`.
+2. **Layout**:
+ - Left: current avatar in the viewer.
+ - Right: three tabs — **Retake selfie** (links to `/selfie`) · **Choose from library** (user's existing avatars + a small curated public list) · **Upload GLB** (drag-drop).
+ - Bottom: **Save changes** (disabled until something changed) and **Cancel**.
+3. **Swap logic**:
+ - Chosen avatar's `avatar_id` → `PUT /api/agents/:id` with `{ avatar_id }`.
+ - Nothing else changes: `name`, `description`, `wallet_address`, `erc8004_agent_id`, `skills`, `meta` all preserved.
+ - After save, redirect to `/agent/:id` with a toast "Avatar updated."
+4. **History** — before saving, write the previous `avatar_id` into `agent_identities.meta.avatar_history` (array, capped at 5). Minimal — enough that a user can roll back if needed.
+5. **Owner-only guard** — page JS hits `GET /api/agents/:id` and if `user_id !== currentUser.id`, redirect to the public `/agent/:id` view.
+
+## Out of scope
+
+- Live editing the avatar mesh (03-02).
+- Uploading a selfie (02-*).
+- Onchain consequences of the avatar change (06-* — the CID should change but that's not enforced here).
+- Versioned avatar entities (the history list is lightweight meta, not a new table).
+
+## Deliverables
+
+- `public/agent/edit.html`
+- `public/agent/edit.js`
+- Route in `vercel.json`
+- Link from `public/agent/index.html` → edit page (owner only).
+
+## Acceptance
+
+- Owner can swap avatar; identity, skills, memory untouched in DB.
+- Non-owner visiting `/agent/:id/edit` is redirected.
+- `meta.avatar_history` grows on each change (≤ 5).
+- `npm run build` passes.
diff --git a/prompts/build/03-01-dashboard-edit-tab.md b/prompts/build/03-01-dashboard-edit-tab.md
new file mode 100644
index 000000000..9e4998dd1
--- /dev/null
+++ b/prompts/build/03-01-dashboard-edit-tab.md
@@ -0,0 +1,63 @@
+# 03-01 — Implement the dashboard Edit tab
+
+**Branch:** `feat/dashboard-edit-tab`
+**Stack layer:** 3 (Edit avatar)
+**Depends on:** 02-03 (avatars are bound to agents)
+**Blocks:** 03-02 (regenerate/swap), 04-* (embed polish reveals editing gaps)
+
+## Why it matters
+
+[public/dashboard/dashboard.js](../../public/dashboard/dashboard.js) declares `tabs.edit = renderEdit` but `renderEdit()` is undefined — the tab 404s. Users can create an avatar but can't rename, retag, or toggle visibility without hitting the API manually. This is the smallest unlock that makes the "edit" pillar exist.
+
+## Read these first
+
+| File | Why |
+|:---|:---|
+| [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js) | Tab routing, state shape, existing tab renderers as templates (especially the avatar list renderer). |
+| [api/avatars/[id].js](../../api/avatars/[id].js) | PATCH handler already supports `name`, `description`, `visibility`, `tags`. |
+| [src/account.js](../../src/account.js) | Client helpers — extend, don't duplicate. |
+| [style.css](../../style.css) | Existing form field styles. |
+
+## Build this
+
+### `renderEdit(avatarId)` in `dashboard.js`
+
+Native DOM, same pattern as existing tab renderers. Fetch the avatar by id (`GET /api/avatars/:id`), then render a form:
+
+- **Name** — text input, required, max 80.
+- **Description** — textarea, max 500.
+- **Visibility** — radio group: `public` / `unlisted` / `private`. Inline help: "Unlisted can be embedded anywhere via the direct URL. Private is only visible to you."
+- **Tags** — comma-separated text input, trimmed + deduped on blur.
+- **Thumbnail** — preview only (no reupload here — that's 03-02).
+- **Save** / **Cancel** — Save PATCHes `/api/avatars/:id`; Cancel returns to list.
+- **Delete** — destructive, requires type-to-confirm (the avatar's name). Calls `DELETE /api/avatars/:id`.
+
+### Tab wiring
+
+From the avatar list, each card gains an "Edit" button that routes to `?tab=edit&id=<avatar_id>`. Back-button restores list state.
+
+### Success / error states
+
+- Save success → toast "Saved", stay on the edit tab.
+- Save error → inline field-level error if a known validation code, else a top-of-form banner.
+- Delete success → redirect to list, toast "Deleted".
+
+### Accessibility
+
+All fields have `<label>` + programmatic focus on first field after mount. Escape key on the delete modal closes it.
+
+## Out of scope
+
+- Do not add avatar regeneration or GLB swap — that's 03-02.
+- Do not add agent-identity editing (names, skills) — that's a separate layer.
+- Do not build a bulk-edit view.
+
+## Acceptance
+
+- [ ] Clicking "Edit" on an avatar card opens the form populated with current values.
+- [ ] Save persists and reloads cleanly; reopening shows the saved values.
+- [ ] Visibility change from `public` → `private` removes the avatar from public `GET /api/avatars?visibility=public` results.
+- [ ] Delete requires typing the exact name; mismatched input keeps the Delete button disabled.
+- [ ] After delete, the avatar no longer appears in the list, and any agent previously bound has `avatar_id = NULL`.
+- [ ] Keyboard-only navigation works.
+- [ ] `npm run build` passes.
diff --git a/prompts/build/03-01-regenerate-from-new-selfie.md b/prompts/build/03-01-regenerate-from-new-selfie.md
new file mode 100644
index 000000000..e10e0f86c
--- /dev/null
+++ b/prompts/build/03-01-regenerate-from-new-selfie.md
@@ -0,0 +1,53 @@
+# 03-01 — Regenerate an existing avatar from a new selfie
+
+## Why it matters
+
+Users will generate an avatar, dislike the result, and want to try again without losing their agent identity, wallet links, or memories. "Regenerate from photo" keeps the agent, swaps only the 3D body.
+
+## Context
+
+- Agent → avatar link: `agent_identities.avatar_id` references `avatars.id` ([api/_lib/schema.sql](../../api/_lib/schema.sql)).
+- Existing selfie pipeline: `/api/avatars/from-selfie` (`02-02`).
+- Selfie capture UI: `/dashboard/selfie` (`02-01`).
+- Agent API: [api/agents.js](../../api/agents.js) and [api/agents/[id].js](../../api/agents/[id].js).
+
+## What to build
+
+### Endpoint — extend `api/avatars/from-selfie.js`
+
+Accept an optional form field `replace_avatar_id` (UUID). When present:
+
+- Assert ownership: the avatar belongs to the caller.
+- After generating the new GLB and creating the new `avatars` row (same as the normal flow):
+ - If the caller's `agent_identities.avatar_id` equals `replace_avatar_id`, update it to point at the new avatar.
+ - Soft-delete the old avatar (`deleted_at = now()`).
+ - Keep the R2 object for 7 days (don't hard-delete immediately).
+- Return `{ avatar: <new_row>, replaced: <old_id> }`.
+
+No change to the normal path (no `replace_avatar_id`).
+
+### UI — regenerate button on the agent/avatar view
+
+On the agent page [public/agent/index.html](../../public/agent/index.html), when the viewer is the avatar owner, show a "Regenerate from photo" button near the existing edit controls. Clicking navigates to `/dashboard/selfie?replace=<avatar_id>`.
+
+On `/dashboard/selfie`, read `?replace=` from the URL and include it as `replace_avatar_id` in the form submission.
+
+### UX guardrails
+
+- Before submission, show a confirmation: "This will replace your current avatar. Agent identity, memories, and wallet links are preserved."
+- After success, navigate to the agent page, not the dashboard.
+
+## Out of scope
+
+- Keeping both the old and new avatar side-by-side for A/B comparison.
+- Multi-version history of avatars per agent (`avatars.version` exists but we won't use it here).
+- Restoring a deleted avatar.
+
+## Acceptance
+
+1. Create an avatar via selfie. Note the agent id.
+2. Visit the agent page, click "Regenerate from photo."
+3. Capture a new selfie, submit.
+4. On completion, the agent page shows the new avatar. Agent id, name, and memory are unchanged.
+5. `agent_identities.avatar_id` in DB points to the new avatar. Old avatar row has `deleted_at` set.
+6. A non-owner cannot trigger regeneration for another user's avatar (403).
diff --git a/prompts/build/03-02-avatar-regenerate-and-swap.md b/prompts/build/03-02-avatar-regenerate-and-swap.md
new file mode 100644
index 000000000..5204cfabc
--- /dev/null
+++ b/prompts/build/03-02-avatar-regenerate-and-swap.md
@@ -0,0 +1,58 @@
+# 03-02 — Regenerate from a new selfie, swap avatar on an existing agent
+
+**Branch:** `feat/avatar-regenerate-swap`
+**Stack layer:** 3 (Edit avatar)
+**Depends on:** 03-01, 02-02
+**Blocks:** nothing critical, but improves 04-* user flow
+
+## Why it matters
+
+After 03-01, users can rename and delete. They still can't *improve* their avatar without starting over and losing the agent identity. Two operations close this gap:
+
+1. **Regenerate** — take a new selfie, produce a new GLB, attach it to the *same* avatar row (preserves `agent_identities.avatar_id`).
+2. **Swap** — pick a different existing avatar from your library as the agent's body.
+
+Both keep agent identity, memory, and on-chain records intact across a visual refresh.
+
+## Read these first
+
+| File | Why |
+|:---|:---|
+| [api/avatars/[id].js](../../api/avatars/[id].js) | PATCH/DELETE handler. Regenerate will add a new sub-route. |
+| [api/avatars/from-selfie.js](../../api/avatars/from-selfie.js) *(from 02-02)* | Generation pipeline — reuse its internals. |
+| [api/agents.js](../../api/agents.js) | Agent PATCH accepts `avatar_id`. |
+| [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js) | Where 03-01 placed the edit tab. |
+| [src/agent-identity.js](../../src/agent-identity.js) | Client model — nothing to change; just confirm it holds no GLB state directly. |
+
+## Build this
+
+### Regenerate — `POST /api/avatars/:id/regenerate`
+
+- **Auth:** required, must own the avatar.
+- **Body:** `multipart/form-data` with `photo` (same contract as `POST /api/avatars/from-selfie`).
+- **Behavior:** reuse the selfie-generation pipeline, but on success, **overwrite** the existing avatar's `r2_key` / `model_url` and bump `updated_at`. Do not create a new `avatars` row. Preserve `id`, `created_at`, `name`, and every other field.
+- **Cleanup:** delete the old GLB object from R2 after the new one is committed.
+
+### Swap — agent-side
+
+Expose in the dashboard agent view a "Change body" button. It opens a picker listing the user's other avatars. Selecting one does `PATCH /api/agents/:agent_id { avatar_id }`. No new endpoint needed if `PATCH /api/agents/:id` already accepts `avatar_id` — verify first; if not, extend it.
+
+### UI
+
+- On the edit tab (from 03-01), add a "Regenerate from new selfie" button that reuses the 02-01 capture flow but posts to `/api/avatars/:id/regenerate` instead.
+- Busy state during regeneration; live-refresh the thumbnail + 3D preview on success.
+- Swap: a modal listing the user's avatars with thumbnails; click to swap.
+
+## Out of scope
+
+- Do not add GLB upload from disk as a regenerate source — only selfie.
+- Do not add multi-agent-per-user UI.
+- Do not touch onchain identity — the wallet + chain_id stay with the agent, not the avatar.
+
+## Acceptance
+
+- [ ] Regenerate with a new selfie keeps `avatars.id` stable and updates `model_url`.
+- [ ] Old R2 object is gone after regenerate (or GC'd async — document which).
+- [ ] Viewer picks up the new GLB on reload.
+- [ ] Swap changes `agent_identities.avatar_id` and the agent-home page renders the new body without losing memory or skills.
+- [ ] Agent's wallet / onchain record untouched after swap.
diff --git a/prompts/build/03-02-avatar-regenerate.md b/prompts/build/03-02-avatar-regenerate.md
new file mode 100644
index 000000000..c22343a61
--- /dev/null
+++ b/prompts/build/03-02-avatar-regenerate.md
@@ -0,0 +1,46 @@
+---
+mode: agent
+description: "Re-run the selfie→avatar pipeline reusing the stored selfie, keeping the same agent id"
+---
+
+# 03-02 · Regenerate avatar from stored selfie
+
+## Why it matters
+
+Sometimes the first generation is off (pose, lighting, artifacts). Users should be able to "try again" without retaking a selfie. Cheap retention win.
+
+## Prerequisites
+
+- 02-02 (selfies stored in R2).
+- 02-03 (generation pipeline + webhook).
+- 03-01 (edit page exists).
+
+## Read these first
+
+- [api/selfies/generate.js](../../api/selfies/generate.js) — create one in 02-03.
+- [api/avatars/webhook/](../../api/avatars/) — webhook handler from 02-03.
+
+## Build this
+
+1. **New action on edit page** (`/agent/:id/edit`): "Regenerate from my selfie" button under the Retake tab. Disabled if the user has no stored selfie.
+2. **Endpoint** `POST /api/selfies/generate` already takes `{ selfie_id }`. Reuse it. After the webhook lands the new GLB and registers a new `avatars` row, also `PUT /api/agents/:id` with `{ avatar_id: new_id }` — **only if the current agent still belongs to this user** (race guard).
+3. **UX**: same polling loop as 02-03 but keep the user on the edit page with a progress pill. On success, refresh the viewer with the new `avatar.url`.
+4. **Cost guard**: cap regenerations at 5 per user per 24h. Use `limits.upload(userId)` or a dedicated `limits.avatarGenerate` preset (if adding a preset, do it in `api/_lib/rate-limit.js` — that's a normal helper change, not a schema change).
+
+## Out of scope
+
+- New selfie capture.
+- Streaming progress from the provider (polling is fine).
+- Multiple selfies per user (use the latest).
+
+## Deliverables
+
+- Button + flow in `public/agent/edit.js`.
+- Any rate-limit preset addition in `api/_lib/rate-limit.js`.
+- No new endpoints.
+
+## Acceptance
+
+- Click "Regenerate from my selfie" → avatar is replaced within ~120s, agent id unchanged.
+- Attempt #6 in 24h returns `429 rate_limited`.
+- `npm run build` passes.
diff --git a/prompts/build/03-02-swap-avatar-on-agent.md b/prompts/build/03-02-swap-avatar-on-agent.md
new file mode 100644
index 000000000..3a3309c49
--- /dev/null
+++ b/prompts/build/03-02-swap-avatar-on-agent.md
@@ -0,0 +1,49 @@
+# 03-02 — Swap which avatar an agent uses
+
+## Why it matters
+
+A user may have multiple avatars (from multiple selfies, or from upload/Avaturn) but one agent identity. They need a dashboard control to pick which avatar is the "face" of their agent. This is the minimum edit primitive: no model tweaking, just selection.
+
+## Context
+
+- Agent ↔ avatar link: `agent_identities.avatar_id` ([api/_lib/schema.sql](../../api/_lib/schema.sql)).
+- Agent update endpoint: [api/agents/[id].js](../../api/agents/[id].js) — `PUT` accepts `avatar_id`.
+- Avatar listing: [api/avatars/index.js](../../api/avatars/index.js) — `GET` returns caller's avatars.
+- Agent fetch: `/api/agents/me` via [api/agents.js](../../api/agents.js).
+- Dashboard entry: [public/dashboard/index.html](../../public/dashboard/index.html).
+
+## What to build
+
+### Dashboard — avatar picker for the agent
+
+On the dashboard, add a section labeled **"My agent."** It shows:
+
+- The current agent's name (editable inline, PUT to `/api/agents/:id`).
+- A grid of the user's avatars as thumbnails. The currently-selected avatar has a highlighted border.
+- Clicking another avatar → optimistic swap, then PUT `/api/agents/:id { avatar_id }`. On error, revert and show a toast.
+
+Reuse the existing dashboard CSS theme. No new page.
+
+### Thumbnail endpoint (if not already present)
+
+The avatar grid needs a thumbnail. If `avatars.thumbnail_key` is populated and served via R2 public base, use it. If not, render the GLB into a still PNG on first access and cache it.
+
+- New endpoint `api/avatars/[id]/thumbnail.js` (GET, 302 redirects to R2 public URL once generated).
+- Generation strategy: open a headless puppeteer-less renderer is overkill — instead, require the upload flow to set `thumbnail_key`. For selfie-generated avatars, capture a frame during generation (RPM typically returns one). For legacy avatars without thumbnails, fall back to a stock silhouette image.
+
+If rendering thumbnails is too heavy to ship in this prompt, stub the endpoint to return a default PNG and defer real thumbnails to a later prompt. Document the decision.
+
+## Out of scope
+
+- Avatar deletion from this UI (covered elsewhere).
+- Renaming avatars from this UI.
+- Multiple agents per user (one agent is the v1 assumption).
+
+## Acceptance
+
+1. Dashboard shows "My agent" section with agent name and avatar grid.
+2. Clicking a different avatar updates the selection visibly within 200ms.
+3. Refreshing the page shows the new selection persisted.
+4. `/agent/:id` renders with the chosen avatar.
+5. Setting `avatar_id` to an avatar owned by someone else → server returns 400/403 (verify the existing endpoint already enforces ownership; add check if missing).
+6. Editing the agent name persists.
diff --git a/prompts/build/03-03-edit-agent-metadata.md b/prompts/build/03-03-edit-agent-metadata.md
new file mode 100644
index 000000000..898b2067c
--- /dev/null
+++ b/prompts/build/03-03-edit-agent-metadata.md
@@ -0,0 +1,48 @@
+---
+mode: agent
+description: "Inline editing of name, description, and skill list for an agent"
+---
+
+# 03-03 · Edit agent metadata
+
+## Why it matters
+
+The agent is not just the avatar — name, description, and the skill list define what the agent *is* and *does*. Users need a place to change these without opening a DB client.
+
+## Prerequisites
+
+- 01-* (auth), 03-01 (edit page scaffold).
+
+## Read these first
+
+- [api/agents.js](../../api/agents.js) — `PUT /api/agents/:id` handler.
+- [src/agent-skills.js](../../src/agent-skills.js) — canonical skill names.
+
+## Build this
+
+1. **On `/agent/:id/edit`**, add a "Details" tab with:
+ - Name (text input, 1–100 chars).
+ - Description (textarea, 0–500 chars).
+ - Skills — checkbox list of canonical skills (`greet`, `present-model`, `validate-model`, `remember`, `think`, `sign-action`). No custom skills in this prompt.
+2. **Persist** via `PUT /api/agents/:id`. Use optimistic UI: update locally, revert on failure.
+3. **Validation** on the server side — `api/agents.js` already truncates; add zod validation matching the limits above via [api/_lib/validate.js](../../api/_lib/validate.js). Don't hand-roll.
+4. **Home URL** — if the user filled `home_url`, show it on the agent page as the "official home" link. Accept empty / `null` / a full URL.
+
+## Out of scope
+
+- Adding new skills (custom skill DSL is a separate initiative).
+- Markdown in descriptions.
+- Avatar changes (03-01).
+- Wallet linking (06-*).
+
+## Deliverables
+
+- "Details" tab in `public/agent/edit.js`.
+- zod schema for the update body in `api/_lib/validate.js`.
+
+## Acceptance
+
+- Changing name + saving reflects on `/agent/:id` after reload.
+- Empty description saves as null.
+- Non-canonical skill submitted via API returns 400 `validation_error`.
+- `npm run build` passes.
diff --git a/prompts/build/03-04-animation-set-per-agent.md b/prompts/build/03-04-animation-set-per-agent.md
new file mode 100644
index 000000000..065ef77bd
--- /dev/null
+++ b/prompts/build/03-04-animation-set-per-agent.md
@@ -0,0 +1,58 @@
+# 03-04 — Animation set per agent
+
+## Why it matters
+
+The Empathy Layer (idle, wave, nod, shake, think) is the difference between a static model and an embodied agent. Today the Mixamo bundle is global and ad-hoc. Each agent needs a *chosen, persisted* animation set so the avatar reads the same across the agent page, embeds, and host integrations (Layers 4–5).
+
+## Context
+
+- Animation manager: [src/animation-manager.js](../../src/animation-manager.js).
+- Fetch script: `npm run fetch-animations` (Mixamo bundle in [public/animations/](../../public/animations/)).
+- Manifest spec: [specs/AGENT_MANIFEST.md](../../specs/AGENT_MANIFEST.md).
+- Per-agent record: `agents` table in [api/_lib/schema.sql](../../api/_lib/schema.sql).
+
+## What to build
+
+### Schema
+
+```sql
+alter table agents add column if not exists animation_set jsonb not null default '{}'::jsonb;
+```
+
+Shape: `{ idle: "breathing", wave: "wave-hello", nod: "nod-yes", shake: "shake-no", think: "thinking" }`. Keys are the canonical Empathy Layer slots (defined in the spec); values are animation clip names that exist in the shared bundle.
+
+### Endpoint — `PUT /api/agents/:id/animations`
+
+- Owner-authed. Body validates against a whitelist of clip names served by `GET /api/animations/catalog` (new endpoint that lists clips in the bundle).
+- Reject unknown clip names with 400. Missing slots inherit the defaults from the spec.
+- Bump `agents.updated_at`.
+
+### Catalog endpoint — `GET /api/animations/catalog`
+
+- Public. Returns `[{ name, duration_ms, category, preview_url }]` for every clip in the bundle. Cacheable for 1h.
+- Source of truth: a static JSON committed alongside the bundle, regenerated by `fetch-animations`.
+
+### Dashboard UI — animation picker
+
+- New "Animations" tab on the agent detail page in [public/dashboard/](../../public/dashboard/).
+- Each Empathy slot is a dropdown of compatible clips (filtered by `category`).
+- Inline preview: picking a clip plays it on an inline `<model-viewer>`.
+- Save button PUTs the set; optimistic update with rollback on error.
+
+### Runtime consumption
+
+[src/agent-avatar.js](../../src/agent-avatar.js) reads `manifest.animation_set` and wires each Empathy bus event to the chosen clip. If a slot is missing, fall back to the spec default. No behavioral change for agents that haven't picked yet.
+
+## Out of scope
+
+- Authoring new animations (upload / blending). Bundle is read-only.
+- Per-event timing tuning or blend weights.
+- Animation marketplaces or sharing across users.
+
+## Acceptance
+
+1. A new agent uses defaults; the avatar idles and waves as before.
+2. Swap the "nod" slot to a different clip → save → reload the agent page → the new clip plays on nod.
+3. Swap to a clip that doesn't exist via curl → 400, record unchanged.
+4. `GET /api/animations/catalog` lists every clip in [public/animations/](../../public/animations/) and the list survives a hard refresh (cached).
+5. `node --check` passes on modified files.
diff --git a/prompts/build/03-04-skill-install-from-registry.md b/prompts/build/03-04-skill-install-from-registry.md
new file mode 100644
index 000000000..053e35339
--- /dev/null
+++ b/prompts/build/03-04-skill-install-from-registry.md
@@ -0,0 +1,112 @@
+# 03-04 — Install a skill onto an existing agent
+
+**Pillar 3 — Edit avatar / agent.**
+
+## Why it matters
+
+Today `agent_identities.skills` is a static array set at creation (`['greet', 'present-model', 'validate-model', 'remember', 'think']`). There's no UI to add, remove, or install a third-party skill onto an existing agent. Without this, the "skill marketplace" called out in [src/CLAUDE.md](../../src/CLAUDE.md) has no front door.
+
+## What to build
+
+A **Skills** tab on the agent edit page (`/agent/:id/edit` or the dashboard agent detail view) that:
+
+1. Lists currently-installed skills with a remove button (disable remove on the 5 built-ins).
+2. "Install from URL" field — paste a skill bundle URL (https, ipfs://, ar://, or `agent://chain/id`).
+3. Preview of the skill's manifest + tools + permissions before install.
+4. Stores the installed skill list on `agent_identities.skills` (string array: built-in names; external URLs otherwise).
+
+## Read these first
+
+| File | Why |
+|:---|:---|
+| [src/skills/index.js](../../src/skills/index.js) | `SkillRegistry.install(spec, { bundleBase })` — reuse, don't reinvent. |
+| [src/manifest.js](../../src/manifest.js) | Manifest normalization. Skills may live inside a manifest or alone. |
+| [api/agents.js](../../api/agents.js) — `handleUpdate` | Already accepts `skills` in the PUT body. Update is a no-op if you only add/remove strings from the array. |
+| [specs/](../../specs/) | Skill format spec — what's in a skill bundle (`SKILL.md`, `tools.json`, `handlers.js`). |
+| [src/runtime/tools.js](../../src/runtime/tools.js) | Built-in tools the agent already has. Third-party skills add to this set at runtime. |
+
+## Build this
+
+### 1. Skills tab UI
+
+Create `public/agent/edit-skills.html` + `edit-skills.js` (or add as a tab inside an existing `/agent/:id/edit` page).
+
+Layout:
+- Header: "Skills for <agent name>"
+- Installed list, each row: name · short description · source · [Remove]
+- Divider
+- "Install from URL" input + [Install] button
+- Empty state: "Give your agent new abilities. Paste a skill bundle URL."
+
+### 2. Install preview modal
+
+On paste + Install, fetch the skill bundle via [src/skills/index.js](../../src/skills/index.js) (read-only parse — don't register yet). Show a modal with:
+
+- Name, version, author, description
+- Tools it adds (name + description for each)
+- Dependencies (other skills it will pull in)
+- Permissions: "Needs: read memory, fetch from `example.com`, sign actions"
+- Warning banner if `author` doesn't match any wallet the user trusts
+- [Cancel] / [Install]
+
+### 3. Server — add skill to agent
+
+Reuse `PUT /api/agents/:id` with a modified `skills` array. No new endpoint.
+
+The `skills` column holds either:
+- built-in skill name (`"greet"`, `"remember"`, etc.)
+- external skill URL (`"https://..."`, `"ipfs://..."`, `"agent://..."`)
+
+The runtime (browser) resolves external URLs via SkillRegistry at agent boot.
+
+### 4. Remove
+
+Remove button PATCHes `skills` with the string filtered out. Built-in skills are not removable (show a tooltip: "Built-in skill, cannot be removed").
+
+### 5. Trust modes
+
+The agent record has a `meta.skill_trust` field:
+- `any` (default) — allows any URL.
+- `owned-only` — only skills authored by the agent's wallet address.
+- `whitelist` — explicit list of authors in `meta.skill_authors`.
+
+Expose a trust dropdown on the tab. Default new agents to `owned-only` once this ships (existing agents keep `any` — don't mass-migrate).
+
+### 6. Runtime load
+
+At agent boot (`element.js` / `agent-home`), iterate `identity.skills`. For each string, if it's a built-in name, skip. Otherwise call `SkillRegistry.install(url, { bundleBase: url, trust: identity.meta.skill_trust })`. If install fails, log but don't crash the whole agent — skip that skill.
+
+## Out of scope
+
+- Do not build a skill publishing flow.
+- Do not build a browsable skill registry (that's a separate future prompt).
+- Do not implement sandboxing beyond what `handlers.js` already provides (it runs as a module — revisit if we allow arbitrary JS later).
+- Do not add skill-level billing or paid skills.
+
+## Deliverables
+
+**New:**
+- `public/agent/edit-skills.html`
+- `public/agent/edit-skills.js`
+
+**Modified:**
+- [src/element.js](../../src/element.js) — iterate `identity.skills`, call `SkillRegistry.install` for URLs.
+- [src/agent-home.js](../../src/agent-home.js) — render installed skills list in the home UI (read-only).
+
+## Acceptance
+
+- [ ] User visits their agent's edit page → Skills tab lists 5 built-ins.
+- [ ] Paste `examples/coach-leo/` (served locally) skill URL → preview modal shows name, tools, permissions.
+- [ ] Install → agent row's `skills` array contains the URL.
+- [ ] Reload `/agent/:id` → new skill is active (its tools are callable via the runtime).
+- [ ] Remove a third-party skill → it's gone; built-ins can't be removed.
+- [ ] Trust mode `owned-only` blocks a skill whose author isn't the agent's wallet.
+- [ ] `npm run build` passes.
+
+## Test plan
+
+1. Spin up a local skill bundle at `http://localhost:3000/examples/coach-leo/` or similar.
+2. Edit your agent → Skills tab → paste the URL → preview → install.
+3. Talk to the agent via the runtime chat → call one of the new tools.
+4. Remove the skill → the tool is no longer listed.
+5. Set trust to `owned-only`, try to install an unsigned skill → install blocked with a clear error.
diff --git a/prompts/build/03-05-avatar-version-history.md b/prompts/build/03-05-avatar-version-history.md
new file mode 100644
index 000000000..a9d9a25f5
--- /dev/null
+++ b/prompts/build/03-05-avatar-version-history.md
@@ -0,0 +1,71 @@
+# 03-05 — Avatar version history and rollback
+
+## Why it matters
+
+Layer 3 lets users regenerate the GLB without breaking their `agentId` — but every regenerate today clobbers the previous avatar. A user who prefers the v2 look over v3 has no recovery path, which makes them afraid to experiment. Version history turns the "edit avatar" flow from destructive into safe.
+
+## Context
+
+- Avatar table: `avatars` in [api/_lib/schema.sql](../../api/_lib/schema.sql) — already has `version int not null default 1` and `checksum_sha256`.
+- Agent record: `agents.avatar_id` in the same schema.
+- Swap endpoint: scoped in `03-01-avatar-swap.md` / `03-02-swap-avatar-on-agent.md`. This prompt assumes one of them is merged.
+- R2 helper: [api/_lib/r2.js](../../api/_lib/r2.js).
+
+## What to build
+
+### Schema
+
+```sql
+create table if not exists agent_avatar_versions (
+ id uuid primary key default gen_random_uuid(),
+ agent_id uuid not null references agents(id) on delete cascade,
+ avatar_id uuid not null references avatars(id) on delete restrict,
+ version int not null,
+ source text not null, -- 'upload' | 'regenerated' | 'swap'
+ source_meta jsonb not null default '{}'::jsonb,
+ created_by uuid not null references users(id) on delete set null,
+ created_at timestamptz not null default now(),
+ active boolean not null default false,
+ unique (agent_id, version)
+);
+create unique index if not exists agent_avatar_active_per_agent
+ on agent_avatar_versions(agent_id) where active;
+```
+
+### Write path
+
+Every time `agents.avatar_id` changes (swap, regenerate, cosmetic):
+
+- Insert a new `agent_avatar_versions` row with the new `avatar_id` and incremented `version`.
+- Flip `active = false` on the prior row, `true` on the new row, inside one transaction.
+- **Do not delete the prior avatar row or R2 object.**
+
+### Endpoints — `api/agents/[id]/versions.js`
+
+- `GET` — owner-only. Returns the array sorted desc by version, each item including a thumbnail URL.
+- `POST { version }` — owner-only. Makes the specified version active (flip `active` + update `agents.avatar_id`). Returns the new active record.
+
+### Retention policy
+
+- Keep the last 10 versions per agent. Prune older ones on each new version insert: mark `avatar_id` for soft-delete in `avatars` (set `deleted_at`) and schedule R2 deletion via a simple cleanup column. Never prune the currently-active version.
+
+### Dashboard UI
+
+- On the agent detail page, a "History" panel lists versions with thumbnail, date, and a "Restore" button.
+- Restoring prompts with a non-modal inline confirm ("This will replace your current avatar. You can restore back any time.") and calls the POST endpoint.
+
+## Out of scope
+
+- Branching / non-linear history.
+- Diffing avatars (no visual diff tool).
+- Per-version annotations or notes.
+- Version history for animation sets or metadata (avatar GLB only).
+
+## Acceptance
+
+1. Regenerate an agent's avatar 3 times. `GET /versions` returns 4 entries (original + 3). The latest is `active: true`.
+2. Restore to v2 → active flips; page reload shows v2.
+3. Regenerate again after restore → becomes v5 (monotonic version numbers).
+4. 11th regenerate: oldest (non-active) version is soft-deleted; the R2 object is queued for cleanup.
+5. Direct DB edit to delete the active version row returns 409 from the restore endpoint (integrity guard).
+6. `node --check` passes on new files.
diff --git a/prompts/build/03-05-memory-review-and-edit.md b/prompts/build/03-05-memory-review-and-edit.md
new file mode 100644
index 000000000..b9e31a4ec
--- /dev/null
+++ b/prompts/build/03-05-memory-review-and-edit.md
@@ -0,0 +1,104 @@
+# 03-05 — Memory inspector: review, edit, delete agent memories
+
+**Pillar 3 — Edit avatar / agent.**
+
+## Why it matters
+
+The agent accumulates memories of 4 types (user / feedback / project / reference) silently. Owners can't see what their agent has remembered, which is both a trust problem and a correctness problem (wrong memories → confident-wrong agent behavior). Every major personal AI product exposes memory controls — we should too, and it's cheap given we already have `agent_memories` tables and a memory skill.
+
+## What to build
+
+A **Memory** tab on the agent edit page:
+
+1. List rows from `agent_memories` grouped by type, sorted by `created_at` desc.
+2. Each row: type badge, content (truncate > 160 chars), tags, salience (0–1), created, expires.
+3. Actions per row: Edit (opens textarea), Delete (soft-delete).
+4. "Add memory" form at the top (type + content + tags, optional expires date).
+5. "Clear all memories of type X" with a confirm dialog (red button; consequential action).
+
+## Read these first
+
+| File | Why |
+|:---|:---|
+| [src/agent-memory.js](../../src/agent-memory.js) | In-memory 4-type store. |
+| [api/agent-memory.js](../../api/agent-memory.js) | Server CRUD. If this file is thin today, extend rather than replace. |
+| [api/_lib/schema.sql](../../api/_lib/schema.sql) | `agent_memories` columns: `agent_id, type, content, tags, context, salience, expires_at`. |
+| [src/memory/index.js](../../src/memory/index.js) | File-based memory variant — you don't touch this for this task, but understand the shared type vocabulary. |
+
+## Build this
+
+### 1. Server
+
+Extend [api/agent-memory.js](../../api/agent-memory.js):
+
+- `GET /api/agent-memory?agent_id=<id>` — list memories for the agent. Owner-only (verify via session).
+- `POST /api/agent-memory` — create.
+- `PATCH /api/agent-memory/:id` — edit content/tags/salience/expires.
+- `DELETE /api/agent-memory/:id` — soft-delete (add `deleted_at` column if missing — ask first for the migration).
+
+All writes verify the session user owns the parent agent.
+
+Zod schema for the body (4 types only; `salience` 0–1; `content` 1..4000; `tags` ≤ 16 strings).
+
+### 2. Memory tab UI
+
+`public/agent/edit-memory.html` + `edit-memory.js`.
+
+Type colors (reuse from agent-home if already defined):
+- `user` — indigo
+- `feedback` — amber
+- `project` — green
+- `reference` — teal
+
+Empty state: "Your agent hasn't remembered anything yet. It will as it works — or add a seed memory here."
+
+### 3. Inline edit
+
+Click Edit → row expands into a textarea + tags field + save/cancel. Salience is a 0–1 slider. Expires is an optional date picker.
+
+### 4. Search / filter
+
+Simple substring search box. `?q=` query param for bookmarking.
+
+### 5. Export
+
+"Download JSON" button exports all memories for the agent. Useful for the user to inspect + for future migration to chain-pinned memory.
+
+### 6. Zero in on the Empathy Layer connection
+
+Memories of type `feedback` with high salience should influence future emotion blends. Out of scope for this prompt; log a TODO in the PR body so a future prompt can wire it.
+
+## Out of scope
+
+- Do not build memory embeddings / semantic search.
+- Do not build cross-agent memory sharing.
+- Do not expose memories to the public agent page — this is owner-only.
+- Do not rewrite [src/agent-memory.js](../../src/agent-memory.js).
+
+## Deliverables
+
+**New:**
+- `public/agent/edit-memory.html`
+- `public/agent/edit-memory.js`
+
+**Modified:**
+- [api/agent-memory.js](../../api/agent-memory.js) — full CRUD + auth.
+- [api/_lib/schema.sql](../../api/_lib/schema.sql) — add `deleted_at` column (ask first).
+- [src/agent-memory.js](../../src/agent-memory.js) — respect `deleted_at` in reads.
+
+## Acceptance
+
+- [ ] Owner visits Memory tab → sees all their agent's memories grouped by type.
+- [ ] Edit a memory → content changes persist on refresh.
+- [ ] Delete a memory → disappears from the list and from agent recall.
+- [ ] Clear all of type X → all rows of that type are soft-deleted; other types untouched.
+- [ ] Non-owner hitting `GET /api/agent-memory?agent_id=<not-theirs>` → 403.
+- [ ] `npm run build` passes.
+
+## Test plan
+
+1. Chat with your agent → trigger `remember` skill → memory gets created.
+2. Go to Memory tab → see it. Edit it. Refresh — edit persisted.
+3. Ask the agent to recall it — it surfaces the edited content.
+4. Delete it — agent can no longer recall it.
+5. Export JSON → has every current memory row with valid types and salience ranges.
diff --git a/prompts/build/04-01-agent-og-image.md b/prompts/build/04-01-agent-og-image.md
new file mode 100644
index 000000000..ec8ba8032
--- /dev/null
+++ b/prompts/build/04-01-agent-og-image.md
@@ -0,0 +1,56 @@
+# 04-01 — OG image endpoint for agent pages
+
+**Branch:** `feat/agent-og-image`
+**Stack layer:** 4 (View + embed)
+**Depends on:** 02-03 (every agent has an avatar)
+**Blocks:** nothing, but every embed share-path is uglier without it
+
+## Why it matters
+
+[public/agent-home.html](../../public/agent-home.html) references `/api/agent-og?id=<id>` in `<meta property="og:image">`, but that endpoint doesn't exist. When an agent link is pasted into Slack, Discord, Telegram, Twitter, or Claude, the preview shows nothing or a broken image. OG images are how the product spreads.
+
+## Read these first
+
+| File | Why |
+|:---|:---|
+| [public/agent-home.html](../../public/agent-home.html) | References `/api/agent-og`. See the exact param shape it expects. |
+| [api/agents.js](../../api/agents.js) | `GET /api/agents/:id` — used to look up the avatar model URL and agent name. |
+| [vercel.json](../../vercel.json) | Current route table. |
+
+## Build this
+
+### Endpoint — `GET /api/agent-og`
+
+- **Auth:** public (rate-limited via Upstash).
+- **Query:** `id` (agent id) or `slug`. At least one required.
+- **Output:** `image/png`, 1200×630, `Cache-Control: public, s-maxage=3600, stale-while-revalidate=86400`.
+
+### Rendering approach — two-tier fallback
+
+**Tier 1 (preferred): cached server-rendered PNG.** On first request, render the agent's GLB in a headless three.js context via `@napi-rs/canvas` or `node-canvas` + a Node-side GL shim. If this is too heavy for Vercel serverless limits, skip to Tier 2. Store the resulting PNG in R2 under `og/<agent_id>.png` and redirect there.
+
+**Tier 2 (ship this first): SVG template rendered to PNG.** Compose a 1200×630 SVG with:
+- Agent name (big)
+- Short tagline (from agent bio, truncated)
+- Avatar thumbnail (use the `thumbnail_url` field from avatars — if absent, fall back to a generic silhouette)
+- Brand background (use the `--accent` colour from [style.css](../../style.css))
+
+Convert the SVG to PNG via `@resvg/resvg-js` (small, fast, Vercel-friendly). Add the dep with a one-line PR justification.
+
+### Invalidation
+
+On agent name change or avatar swap (see 03-02), delete the cached `og/<agent_id>.png` so the next request regenerates.
+
+## Out of scope
+
+- Do not render a full 3D scene unless Tier 1 fits the serverless envelope easily. Ship Tier 2 and leave Tier 1 as a follow-up prompt.
+- Do not add Twitter-specific meta tags — OG covers the major platforms and Twitter falls back to OG.
+- Do not animate. A static PNG is the spec.
+
+## Acceptance
+
+- [ ] `GET /api/agent-og?id=<existing>` returns a 1200×630 PNG in under 2s warm, under 5s cold.
+- [ ] Pasting an agent URL into Slack / Discord shows the preview card.
+- [ ] Missing agent returns a 404, not a broken image.
+- [ ] Twitter/X card validator and Facebook sharing debugger both show the card.
+- [ ] Renaming the agent or swapping the avatar invalidates the cache — next share shows the new image.
diff --git a/prompts/build/04-01-agent-page-polish.md b/prompts/build/04-01-agent-page-polish.md
new file mode 100644
index 000000000..bd9abd728
--- /dev/null
+++ b/prompts/build/04-01-agent-page-polish.md
@@ -0,0 +1,61 @@
+# 04-01 — Agent page polish (the "home" of each agent)
+
+## Why it matters
+
+`/agent/:id` is where a shared agent lives. Right now it renders the avatar but the page feels developer-first, not shareable. We want a single clean page that someone receiving the link — cold, no context — understands in 3 seconds: who the agent is, what it can do, and a way to engage.
+
+## Context
+
+- Agent page: [public/agent/index.html](../../public/agent/index.html).
+- Agent data: `/api/agents/:id` ([api/agents/[id].js](../../api/agents/[id].js)) returns public fields when not owner.
+- Embed variant (no chrome): [public/agent/embed.html](../../public/agent/embed.html). **Don't touch it here** — it's the chrome-less one.
+- OG tag endpoint: [api/agent-og.js](../../api/agent-og.js).
+
+## What to build
+
+Edit only [public/agent/index.html](../../public/agent/index.html) and its companion JS. Do not touch the webcomponent, embed.html, or the head OG tags (other prompts own those).
+
+### Layout (desktop)
+
+- Left column: the 3D avatar viewer (existing canvas).
+- Right column: identity card.
+ - Agent name (h1).
+ - Optional description (≤ 280 chars, rendered as plain text — sanitize).
+ - Skills list as subtle pill chips.
+ - "Powered by 3D Agent" attribution with link to the product home.
+ - Owner-only actions section (only visible to the signed-in owner):
+ - "Regenerate from photo" → `/dashboard/selfie?replace=<avatar_id>` (see prompt `03-01`).
+ - "Change avatar" → scrolls to the dashboard avatar picker (prompt `03-02`).
+ - "Copy embed code" button — copies the `<script src="...">` snippet to clipboard.
+ - "Edit" link → dashboard.
+
+### Layout (mobile)
+
+- Stacked: avatar on top (min 60vh), identity card below.
+- Owner-only actions collapse into a single menu button.
+
+### Shareability
+
+- One-line "Share" control in the identity card: native `navigator.share` on mobile; copy-to-clipboard on desktop. Copies the canonical `/agent/:id` URL.
+
+### Loading state
+
+- While `/api/agents/:id` resolves, show a skeleton with a soft pulsing rectangle where the identity card will be.
+- On 404, show a friendly "This agent doesn't exist or was removed" page, not a raw error.
+
+## Out of scope
+
+- Chat UI or live agent responses (covered by host-embed prompts).
+- Editing from this page (dashboard owns editing).
+- Analytics.
+- Custom themes per agent.
+
+## Acceptance
+
+1. Open `/agent/:id` for someone else's agent → see identity card, avatar, skills, attribution. No owner-only actions visible.
+2. Open your own → owner-only buttons appear.
+3. Copy embed code → clipboard contains the correct `<script>` snippet.
+4. On mobile viewport, layout stacks cleanly.
+5. Bogus id → friendly 404 page, not a crash.
+6. Lighthouse accessibility ≥ 90.
+7. No regression: the existing avatar canvas still mounts and renders with memory + actions.
diff --git a/prompts/build/04-01-agent-public-page-polish.md b/prompts/build/04-01-agent-public-page-polish.md
new file mode 100644
index 000000000..bc934d032
--- /dev/null
+++ b/prompts/build/04-01-agent-public-page-polish.md
@@ -0,0 +1,48 @@
+---
+mode: agent
+description: "Polish /agent/:id so it works as a shareable public page on desktop + mobile"
+---
+
+# 04-01 · Agent public page polish
+
+## Why it matters
+
+The agent's public home is what a pasted link resolves to. It's the unfurl destination, the anchor of the identity, and the target of every "visit my agent" link. Must be fast, mobile-clean, and informative.
+
+## Prerequisites
+
+- Pillar 2 complete (at least one agent exists with a generated avatar).
+
+## Read these first
+
+- [public/agent/index.html](../../public/agent/index.html) — current layout.
+- [src/agent-home.js](../../src/agent-home.js) — identity card, timeline, memory bar.
+- [src/agent-avatar.js](../../src/agent-avatar.js) — Empathy Layer.
+
+## Build this
+
+1. **Above the fold on mobile** — hero 3D viewer fills the viewport width, aspect 1:1, capped at 480px. Identity card slides in under it.
+2. **Identity card** — name, description (collapsed to 3 lines, expandable), wallet short-address (if linked), ERC-8004 badge (if registered), skill chips.
+3. **Action timeline** — latest 10 actions from the protocol bus, rendered with timestamp. Already provided by `src/agent-home.js` — wire it in if not already.
+4. **Share button** — opens the existing iframe/link/`<agent-3d>` share panel. No redesign.
+5. **Owner-only bar** — if viewer === owner, show a thin top bar with "Edit" (→ `/agent/:id/edit`) and "Register onchain" (→ 06-*).
+6. **404** — if the agent id doesn't exist or is soft-deleted, render a friendly 404 page, not a 500.
+7. **Lazy loading** — three.js and avatar assets load after the identity card is visible, so first paint is fast even on mobile.
+
+## Out of scope
+
+- OG/oEmbed unfurl (04-02).
+- Editing (03-*).
+- Chat / talking agent widget (widget-studio prompts).
+
+## Deliverables
+
+- Diff to `public/agent/index.html`.
+- Any helper JS in the same page or a sibling file.
+
+## Acceptance
+
+- Lighthouse mobile Performance ≥ 70 on the landing page (three.js is heavy but lazy).
+- 404 on a non-existent id renders the 404 UI, not a blank page.
+- Owner bar only visible to the owner.
+- `npm run build` passes.
diff --git a/prompts/build/04-02-agent-web-component.md b/prompts/build/04-02-agent-web-component.md
new file mode 100644
index 000000000..691912a1e
--- /dev/null
+++ b/prompts/build/04-02-agent-web-component.md
@@ -0,0 +1,73 @@
+# 04-02 — `<agent-avatar>` web component for drop-in embeds
+
+## Why it matters
+
+Third-party hosts (blogs, portfolios, and eventually Lobehub and Claude Artifacts) embed an agent by dropping in a single HTML tag. A proper custom element with an attribute API is the cleanest integration surface — far cleaner than an iframe for interior widgets, and necessary for the host-embed prompts in pillar 05.
+
+## Context
+
+- Library build output: `dist-lib/agent-3d.js` ([vite.config.js](../../vite.config.js) `TARGET=lib`).
+- Library entry: [src/lib.js](../../src/lib.js).
+- Viewer class: [src/viewer.js](../../src/viewer.js).
+- Existing element bootstrap (if any): check `src/element.js`.
+- Runtime: [src/runtime/index.js](../../src/runtime/index.js).
+
+## What to build
+
+### `<agent-avatar>` custom element
+
+Registered from [src/lib.js](../../src/lib.js). Tag name: `agent-avatar`.
+
+Attributes:
+
+- `agent-id` — UUID of the agent. When set, the element fetches `/api/agents/:id` from its `origin` attribute (default: `https://3dagent.vercel.app`) and renders.
+- `origin` — Override the API origin (for self-hosted deployments).
+- `mode` — `"display" | "interactive"`. Default `"display"` (orbit camera, no chat). `"interactive"` enables NichAgent if mounted in a host that supports it.
+- `height` — CSS value, default `480px`.
+- `background` — CSS color or `"transparent"`.
+- `auto-rotate` — boolean; when present, avatar slowly rotates.
+- `onchain-id` — optional; when present, bypasses the API and loads from chain (see pillar 06).
+
+Public methods on the element:
+
+- `perform(action)` — emit an action into the element's internal protocol bus.
+- `setIdentity(record)` — force-set the identity (for onchain and offline cases).
+
+Events dispatched:
+
+- `agent-ready` — avatar loaded.
+- `agent-action` — when the internal protocol emits an action, bubble it out.
+- `agent-error` — with `{ error, message }` detail.
+
+### Shadow DOM
+
+All styles and the `<canvas>` live inside a shadow root. Host page CSS cannot reach in. The element exposes CSS custom properties for brand color if needed:
+
+- `--agent-accent`, `--agent-bg`, `--agent-fg`.
+
+### Minimum bundle
+
+Target ≤ 350 KB gzipped. Accept that Three.js + ethers are heavy; keep everything else trim. Use dynamic imports inside the element so a host that only renders avatars (no wallet) doesn't load ethers.
+
+### Demo page
+
+Create `public/embed-test.html` that loads the element directly from `/dist-lib/agent-3d.js` (dev) and shows 3 side-by-side instances with different `agent-id`s. This is not user-facing — it's an internal verification page.
+
+## Out of scope
+
+- Server-rendered thumbnails for SEO (separate concern).
+- Voice / chat UI — pillar 05 covers chat embeds.
+- Slot content customization.
+
+## Acceptance
+
+1. Drop the following into any HTML page, it works:
+ ```html
+ <script type="module" src="https://3dagent.vercel.app/agent-3d.js"></script>
+ <agent-avatar agent-id="..." height="400px"></agent-avatar>
+ ```
+2. Changing `agent-id` re-loads the avatar.
+3. `agent-ready` event fires with avatar metadata.
+4. Gzipped bundle is ≤ 350 KB (report actual).
+5. Element works inside a host page that already uses Three.js at a different version (no global clash).
+6. `prefers-reduced-motion` disables auto-rotate.
diff --git a/prompts/build/04-02-embed-policy-crud.md b/prompts/build/04-02-embed-policy-crud.md
new file mode 100644
index 000000000..75d3de3d4
--- /dev/null
+++ b/prompts/build/04-02-embed-policy-crud.md
@@ -0,0 +1,72 @@
+# 04-02 — Finish embed-policy CRUD (origin allowlist per agent)
+
+**Branch:** `feat/embed-policy-crud`
+**Stack layer:** 4 (View + embed)
+**Depends on:** 01-02 (stable session)
+**Blocks:** 05-* (host embeds need a policy to enforce against Claude / Lobehub origins)
+
+## Why it matters
+
+[api/agents/[id]/embed-policy.js](../../api/agents/[id]/embed-policy.js) exists as a stub — it returns 200 with no enforcement logic. Without it, any origin can iframe any agent. Once the product ships to Lobehub / Claude, the owner will want to restrict embeds to specific hosts. This is also the last piece of Layer 4 before we can honestly call the agent "shareable by default, lockable on demand."
+
+## Read these first
+
+| File | Why |
+|:---|:---|
+| [api/agents/[id]/embed-policy.js](../../api/agents/[id]/embed-policy.js) | Current stub. |
+| [agent-embed.html](../../agent-embed.html) | The iframe page. Its `Content-Security-Policy` + `X-Frame-Options` must reflect the policy. |
+| [api/_lib/](../../api/_lib/) | Auth + Neon helpers. |
+| [api/agents.js](../../api/agents.js) | Schema for agents and how ownership is checked. |
+
+## Build this
+
+### Schema
+
+Add a migration adding `embed_policy jsonb` to `agent_identities` (or extend the existing `agents` table — match current naming). Shape:
+
+```json
+{
+ "mode": "open" | "allowlist" | "private",
+ "allowed_origins": ["https://claude.ai", "https://chat.lobehub.com"]
+}
+```
+
+Default `{ "mode": "open", "allowed_origins": [] }`.
+
+### Endpoints — `/api/agents/:id/embed-policy`
+
+- `GET` — public, returns the policy. Used by the embed iframe itself to decide rendering.
+- `PUT` — owner only, replaces the policy. Validate with `zod`: `mode` enum, `allowed_origins` array of valid origin strings (parsable via `new URL()`, no path / query).
+
+### Enforcement
+
+In [agent-embed.html](../../agent-embed.html) (and any server-side render of it):
+
+1. Server reads the policy on each request.
+2. If `mode === 'private'`, require auth + ownership; 403 otherwise.
+3. If `mode === 'allowlist'`, set:
+ - `Content-Security-Policy: frame-ancestors <allowed_origins>`
+ - `X-Frame-Options: SAMEORIGIN` as a safety net (modern browsers prefer CSP).
+4. If `mode === 'open'`, set `frame-ancestors *`.
+
+### Dashboard UI
+
+On the agent edit view (from 03-01 extended, or a new "Embed" tab), surface:
+- Mode selector (Open / Allowlist / Private).
+- Allowed origins list with add/remove (validate format on blur).
+- Live preview of a test iframe loaded from a picker origin to confirm enforcement.
+- Copy-ready iframe snippet.
+
+## Out of scope
+
+- Do not add per-origin analytics — separate prompt.
+- Do not add signed embed tokens — separate prompt.
+- Do not validate that the given origins *actually* resolve to real hosts. We trust the user to know their deployment.
+
+## Acceptance
+
+- [ ] `PUT` rejects malformed origins (paths, wildcards beyond `*`, non-URL strings).
+- [ ] Policy in `allowlist` mode blocks iframing from an origin not on the list (check via a local HTML file).
+- [ ] Policy in `private` mode returns 403 for unauthenticated embed requests.
+- [ ] Dashboard UI round-trips: set allowlist → save → reload → values persist → iframe from an allowed origin works.
+- [ ] Open mode still renders everywhere (baseline preserved).
diff --git a/prompts/build/04-02-og-oembed.md b/prompts/build/04-02-og-oembed.md
new file mode 100644
index 000000000..d269aae2f
--- /dev/null
+++ b/prompts/build/04-02-og-oembed.md
@@ -0,0 +1,49 @@
+---
+mode: agent
+description: "OG image + oEmbed so pasted /agent/:id links unfurl on Slack, X, Discord"
+---
+
+# 04-02 · Unfurl with OG image + oEmbed
+
+## Why it matters
+
+The viral channel: paste an agent link → see a real preview, not a URL. Without this, sharing an agent looks like sharing a random domain.
+
+> There is an existing prompt [prompts/embed/01-og-oembed.md](../embed/01-og-oembed.md) with fuller detail. This file is the stack-priority version — if the embed one is already done, mark this prompt complete.
+
+## Prerequisites
+
+- 04-01 in place so the page itself is worth unfurling.
+
+## Read these first
+
+- [prompts/embed/01-og-oembed.md](../embed/01-og-oembed.md) — existing detailed spec.
+- [api/agent-og.js](../../api/agent-og.js), [api/agent-oembed.js](../../api/agent-oembed.js) — already exist.
+- [public/agent/index.html](../../public/agent/index.html) — `<head>` meta tags.
+
+## Build this
+
+Verify the three pieces are wired:
+
+1. `/api/agent-og?id=X` returns a 1200×630 PNG preview of the agent (avatar rendered headlessly *or* a static thumbnail from the avatar's thumbnail_key if GPU rendering is unavailable).
+2. `/api/agent-oembed?url=X` returns JSON oEmbed with `type=rich`, `html=<iframe src="/agent/:id/embed">`.
+3. `<head>` of `/agent/:id` includes `og:title`, `og:description`, `og:image`, `og:type=website`, `twitter:card=summary_large_image`, `twitter:image`, and `<link rel="alternate" type="application/json+oembed" href="/api/agent-oembed?url=...">`.
+
+If any of the three is missing or broken, fix it referencing [prompts/embed/01-og-oembed.md](../embed/01-og-oembed.md). If all three work, close the prompt and move on.
+
+## Out of scope
+
+- Referrer allowlist (that's a separate concern in `prompts/embed/03-embed-allowlist.md`; not priority).
+- A shiny custom unfurl design beyond OG basics.
+
+## Deliverables
+
+- Tests: paste the URL into Slack / X preview tool / Discord — unfurl renders.
+- Any patches to meta tags or endpoints.
+
+## Acceptance
+
+- `curl https://3dagent.vercel.app/api/agent-og?id=...` returns a PNG.
+- `curl https://3dagent.vercel.app/api/agent-oembed?url=https://3dagent.vercel.app/agent/...` returns valid oEmbed JSON.
+- Slack unfurl preview renders.
+- `npm run build` passes.
diff --git a/prompts/build/04-03-embed-reliability.md b/prompts/build/04-03-embed-reliability.md
new file mode 100644
index 000000000..bb9506ab1
--- /dev/null
+++ b/prompts/build/04-03-embed-reliability.md
@@ -0,0 +1,52 @@
+---
+mode: agent
+description: "Harden /agent/:id/embed so it renders in third-party iframes under CSP"
+---
+
+# 04-03 · Embed iframe reliability
+
+## Why it matters
+
+Pillar 5 (host embed in Claude Artifacts and Lobehub) depends on the embed URL working under strict CSP and in cross-origin iframes. Miss one header and the avatar is a blank rectangle inside Claude.
+
+## Prerequisites
+
+- 02-* complete so an agent can actually be embedded.
+
+## Read these first
+
+- [public/agent/embed.html](../../public/agent/embed.html)
+- [vercel.json](../../vercel.json) — current headers block.
+- [src/agent-resolver.js](../../src/agent-resolver.js) — resolves `agent-id` on the web component.
+
+## Build this
+
+1. **Response headers** for `/agent/:id/embed`:
+ - `X-Frame-Options`: remove (it blocks cross-origin iframes).
+ - `Content-Security-Policy`: `frame-ancestors *` (or an allowlist — see 04-04).
+ - `Permissions-Policy`: allow `camera=(), microphone=(), clipboard-write=(self)` depending on which widgets are enabled.
+2. **Transparent background mode** — query param `?bg=transparent` sets the canvas clear alpha to 0 so the avatar sits on host chrome. `?bg=000000` forces opaque. Default: opaque `#111`.
+3. **Kiosk mode** — `?kiosk=1` hides dat.gui, the share panel, and the owner bar. Purely the avatar.
+4. **postMessage bridge** — document and implement the minimal contract:
+ - Host → iframe: `{ type: 'agent:action', action }` — forwarded to the protocol bus.
+ - Iframe → host: `{ type: 'agent:ready' }`, `{ type: 'agent:action', action }` (echo), `{ type: 'agent:resize', height }`.
+ - All messages include `agentId` so the host can multiplex.
+5. **Resize observer** — post `agent:resize` when the iframe content height changes so hosts can auto-size the iframe.
+
+## Out of scope
+
+- Referrer allowlist (optional; see 04-04 or `prompts/embed/03-embed-allowlist.md`).
+- Actual Claude/Lobehub integration (05-*).
+
+## Deliverables
+
+- `vercel.json` header rules for `/agent/:id/embed` and `/api/agent-og`.
+- Updates to `public/agent/embed.html` for `bg`, `kiosk`, resize observer.
+- A short "bridge contract" comment at the top of `public/agent/embed.html` documenting the messages.
+
+## Acceptance
+
+- Embed loads inside a cross-origin test page (e.g. a CodePen iframe) under default CSP.
+- `?bg=transparent&kiosk=1` shows just the avatar on a transparent canvas.
+- Host page observes `agent:ready` and `agent:resize` messages.
+- `npm run build` passes.
diff --git a/prompts/build/04-03-public-agent-decorate.md b/prompts/build/04-03-public-agent-decorate.md
new file mode 100644
index 000000000..99e453a25
--- /dev/null
+++ b/prompts/build/04-03-public-agent-decorate.md
@@ -0,0 +1,60 @@
+# 04-03 — Harden public agent fetch: redact private fields
+
+**Branch:** `feat/agent-public-decorate`
+**Stack layer:** 4 (View + embed)
+**Depends on:** nothing
+**Blocks:** 05-* (host embeds call the public endpoint and should not leak internals)
+
+## Why it matters
+
+`GET /api/agents/:id` is public. Today it runs a `decorate()` helper on the row before returning, but there's no guarantee it strips owner identifiers, unfinished skills, internal flags, or wallet metadata. Once the agent URL is embedded anywhere, this response is the public surface of the user's data. The audit turned up that `decorate()` exists but its redaction surface is unclear.
+
+## Read these first
+
+| File | Why |
+|:---|:---|
+| [api/agents.js](../../api/agents.js) | `decorate()` function and the GET handler. |
+| [api/_lib/](../../api/_lib/) | Any shared response-shaping helpers. |
+| [src/agent-identity.js](../../src/agent-identity.js) | Client expectation of the agent shape. |
+| [agent-embed.html](../../agent-embed.html), [public/agent-home.html](../../public/agent-home.html) | Public consumers of the endpoint. |
+
+## Build this
+
+### Enumerate what goes out
+
+In [api/agents.js](../../api/agents.js), replace the current `decorate()` with a whitelist-based `toPublicAgent(row)` function. Only these fields leave the server for a public request:
+
+```
+id, slug, name, tagline, avatar { id, model_url, thumbnail_url, name },
+skills (public subset: { id, name, description }),
+reputation_summary, erc8004 { chain_id, agent_id, registry, registration_uri },
+created_at
+```
+
+Explicitly excluded: `user_id`, `owner_id`, `embed_policy` internals beyond `mode`, raw `agent_memories`, any field starting with `_` or ending in `_internal`, wallet private metadata, and any column the handler hasn't been updated to know about.
+
+### Authenticated owner branch
+
+When the caller is the owner, return the full row (merged with public fields). Unknown callers get only the whitelist.
+
+### Test the whitelist
+
+Add a tiny runtime assertion in the handler: after constructing the response, walk the object and confirm every leaf key is in the allowlist. Fail closed with 500 + a log line if an unknown field is about to be sent. (This guards against a future schema addition silently leaking.)
+
+### Update the client
+
+[src/agent-identity.js](../../src/agent-identity.js) — drop any field reads that are now excluded for public calls. Do not add re-derivation logic; the public surface is the spec.
+
+## Out of scope
+
+- Do not add field-level ACLs for the owner branch.
+- Do not add auditing / logging of access — separate prompt.
+- Do not change the route path.
+
+## Acceptance
+
+- [ ] `curl -s /api/agents/<id> | jq` as an unauthenticated caller returns only allowlisted fields.
+- [ ] Adding a new column to the agents table does not automatically leak it — the assertion catches it.
+- [ ] Owner-authenticated fetch still returns the full row.
+- [ ] Agent home + embed pages still render correctly with the trimmed payload.
+- [ ] `npm run build` passes.
diff --git a/prompts/build/04-04-agent-card-json.md b/prompts/build/04-04-agent-card-json.md
new file mode 100644
index 000000000..88a716263
--- /dev/null
+++ b/prompts/build/04-04-agent-card-json.md
@@ -0,0 +1,52 @@
+---
+mode: agent
+description: "Publish agent-card.json and agent-registration.json for A2A discovery"
+---
+
+# 04-04 · A2A discovery: agent-card.json
+
+## Why it matters
+
+A2A (Agent-to-Agent) discovery — other agent runtimes find and introspect yours by fetching a stable JSON at a known path. Required for Lobehub and Claude host integrations (pillar 5) and for onchain portability (pillar 6) since the CID that goes onchain is this file.
+
+## Prerequisites
+
+- Pillar 2 complete — agents have avatars.
+
+## Read these first
+
+- [specs/](../../specs/) — check for an existing manifest spec.
+- [src/manifest.js](../../src/manifest.js) — current manifest loader.
+- [api/agents.js](../../api/agents.js) — agent record shape.
+
+## Build this
+
+1. **New endpoint** `GET /api/agents/:id/card.json`:
+ - Returns the agent card in the A2A convention (use the spec in `specs/` if present; if not, match the shape below).
+ - `{ name, description, home, avatar: { url, content_type, size }, skills: [...], identity: { wallet?, chain_id?, erc8004_agent_id? }, endpoints: { embed, postmessage_bridge }, schema_version }`.
+ - No auth required — this is public discovery.
+ - Etag on the response (hash of the content) so hosts can cache.
+2. **Well-known alias** `GET /.well-known/agent-card.json?id=...` → same response. Some consumers only read `.well-known`.
+3. **Registration card** `GET /api/agents/:id/registration.json`:
+ - Smaller, onchain-bound subset: `{ card_url, card_sha256, avatar_sha256, created_at, wallet }`.
+ - Field to record what was pinned to IPFS — the card CID goes onchain in pillar 6.
+4. **Viewer link** — add `<link rel="agent-card" href="/api/agents/:id/card.json">` to `/agent/:id` page head.
+
+## Out of scope
+
+- Pinning to IPFS (06-*).
+- Onchain registration (06-*).
+- Signing the card (06-*).
+
+## Deliverables
+
+- `api/agents/[id]/card.js` or equivalent route.
+- `api/agents/[id]/registration.js`.
+- `<link>` tag in the agent page head.
+- Route entries in `vercel.json`.
+
+## Acceptance
+
+- `curl /api/agents/<id>/card.json` returns valid JSON with all documented fields.
+- Response has correct `content-type: application/json` and an `etag`.
+- `npm run build` passes.
diff --git a/prompts/build/05-01-claude-artifact-build.md b/prompts/build/05-01-claude-artifact-build.md
new file mode 100644
index 000000000..013238903
--- /dev/null
+++ b/prompts/build/05-01-claude-artifact-build.md
@@ -0,0 +1,63 @@
+# 05-01 — Single-file HTML build for Claude.ai Artifacts
+
+## Why it matters
+
+Claude.ai Artifacts run in a sandboxed iframe and can't load arbitrary cross-origin modules freely. For "my agent appears next to me in Claude," we need a build target that emits a **single self-contained HTML file** — everything inlined — that a Claude message can drop into an Artifact and have a fully-rendered, interactive agent appear.
+
+This is the first pillar-5 step. It's a packaging prompt, not a runtime prompt.
+
+## Context
+
+- Library build: [vite.config.js](../../vite.config.js) `TARGET=lib` → `dist-lib/agent-3d.js`.
+- Web component (pillar 04-02): `<agent-avatar>`.
+- Artifacts have constraints: no external `<script>` fetches without specific allowlisted CDNs, limited iframe sandbox.
+
+## Claude Artifact constraints (verify before building)
+
+- External scripts allowed from: `cdn.jsdelivr.net`, `unpkg.com`, `cdn.tailwindcss.com`, and a few specific origins.
+- Network calls via `fetch` to other origins work if the server responds with permissive CORS.
+- No localStorage persistence is guaranteed across Artifact reloads.
+
+Confirm the current allowlist against Anthropic's documentation before assuming. If `cdn.jsdelivr.net` is available, we can load `agent-3d.js` from a published npm package. If not, we inline.
+
+## What to build
+
+### New build target — `TARGET=artifact`
+
+Extend [vite.config.js](../../vite.config.js) with a third target. Output: `dist-artifact/agent-artifact.html` — a single HTML file with:
+
+- All JS inlined as `<script type="module">` blocks (no external deps).
+- All CSS inlined.
+- A sensible demo UI: centered `<agent-avatar>` with an input field and buttons.
+- Accepts `?agent=<id>` or `?onchain=<id>` in the URL; if neither, shows a centered input prompting for an agent ID.
+- Fetches agent data from `https://3dagent.vercel.app/api/agents/:id` (hardcoded but env-overridable at build time).
+
+Use Vite's `viteSingleFile` plugin (add as dep) or a build script that concatenates.
+
+### Artifact template — `public/artifact.html.template`
+
+A separate template file that mirrors what would get pasted into a Claude Artifact. It loads `<agent-avatar>` either from the inlined bundle or from jsDelivr (if allowed). Comment the two modes clearly so users can pick.
+
+### Publish path
+
+- Emit to `dist-artifact/agent-artifact.html` as a build artifact of `npm run build:artifact`.
+- Also publish to the static site: `/artifact/agent.html` via an entry in [vercel.json](../../vercel.json). This way Claude users can link to it directly.
+
+### CORS on the API
+
+Confirm `/api/agents/:id` responds with `Access-Control-Allow-Origin: *` for GET. If not, add a specific allowlist: `*` for public GETs, credentialed origins only for mutating endpoints.
+
+## Out of scope
+
+- A full Claude-native "artifact tool" (i.e. teaching Claude to emit these automatically) — that's a separate research/API integration.
+- Chat streaming from inside the Artifact to the Claude API.
+- State persistence inside Artifacts beyond URL query params.
+
+## Acceptance
+
+1. `npm run build:artifact` produces `dist-artifact/agent-artifact.html` under 1 MB.
+2. Opening that file directly in a browser renders an agent given `?agent=<id>`.
+3. Pasting the file's contents into a Claude Artifact in claude.ai renders the agent.
+4. No external resources fail to load (all same-origin or inlined).
+5. Console is clean.
+6. Works with a real agent id on production: the avatar loads and orbits.
diff --git a/prompts/build/05-01-claude-artifact-embed.md b/prompts/build/05-01-claude-artifact-embed.md
new file mode 100644
index 000000000..2620ef779
--- /dev/null
+++ b/prompts/build/05-01-claude-artifact-embed.md
@@ -0,0 +1,54 @@
+---
+mode: agent
+description: "Agent embeds cleanly inside a Claude.ai Artifact with the right iframe hints"
+---
+
+# 05-01 · Embed in a Claude Artifact
+
+## Why it matters
+
+The novel unlock of pillar 5. A Claude user pastes an agent URL into a chat → Claude renders it as an Artifact → the agent appears embodied, in-conversation, not as JSON. First visible win for "the universal frontend other agents must render into."
+
+## Prerequisites
+
+- 04-03 (embed iframe is reliable under CSP).
+- 04-04 (agent-card.json exists).
+
+## Read these first
+
+- [public/agent/embed.html](../../public/agent/embed.html)
+- Claude Artifacts documentation — find the CSP / iframe / allowed-source rules that apply. Link them in the PR description.
+- [src/agent-resolver.js](../../src/agent-resolver.js) — lets `<agent-3d agent-id="X">` resolve without a manifest URL.
+
+## Build this
+
+1. **Claude-friendly HTML snippet** — produce a canonical Artifact-ready snippet and display it on `/agent/:id` under Share → "Claude Artifact":
+ ```html
+ <iframe src="https://3dagent.vercel.app/agent/<ID>/embed?kiosk=1&bg=transparent"
+ width="100%" height="520"
+ style="border:0;border-radius:16px"
+ allow="autoplay; fullscreen"
+ referrerpolicy="no-referrer-when-downgrade">
+ </iframe>
+ ```
+2. **Static HTML fallback** — under the iframe, include a "No-iframe fallback" snippet (for hosts that strip iframes): a link + a static thumbnail image. Claude sometimes strips iframes; graceful degradation matters.
+3. **Dynamic resize** — Claude Artifacts can't observe `agent:resize` messages; size the iframe with a fixed aspect ratio fallback. Use a `padding-top: 100%` CSS trick wrapper for square.
+4. **Test in a real Claude conversation** — paste the snippet, confirm rendering, record browser console errors if any. If CSP blocks something, narrow the permissions rather than widening.
+5. **Document** in PR description exactly what Claude-side constraints apply (CSP, allow-list, script-src). Don't change our own CSP unless a real blocker shows up.
+
+## Out of scope
+
+- Lobehub integration (05-02).
+- MCP tool for spawning agents (05-03).
+- Adding OAuth to the embed (it's anonymous).
+
+## Deliverables
+
+- A "Claude Artifact" tab added to the share panel on `/agent/:id`.
+- A short compatibility note in the PR.
+
+## Acceptance
+
+- Pasting the snippet into a Claude conversation renders the avatar inside the Artifact.
+- Pasting into a hostile CSP renders the fallback gracefully.
+- `npm run build` passes.
diff --git a/prompts/build/05-01-claude-artifact-export.md b/prompts/build/05-01-claude-artifact-export.md
new file mode 100644
index 000000000..ea6f46439
--- /dev/null
+++ b/prompts/build/05-01-claude-artifact-export.md
@@ -0,0 +1,64 @@
+# 05-01 — "Embed in Claude Artifacts" — one-click artifact export
+
+**Branch:** `feat/claude-artifact-export`
+**Stack layer:** 5 (Host embed — Claude)
+**Depends on:** 04-01 (OG image), 04-02 (embed policy), 04-03 (redacted public fetch)
+**Blocks:** 06-* (onchain resolution wants a concrete host integration to validate against)
+
+## Why it matters
+
+Claude Artifacts are self-contained HTML documents. A user pastes the artifact into a Claude chat and the agent appears *embodied in the conversation* — exactly the novel unlock in the priority stack. This prompt produces the artifact HTML on demand, scoped to a single agent.
+
+## Read these first
+
+| File | Why |
+|:---|:---|
+| [src/element.js](../../src/element.js) | `<agent-3d>` web component — the minimal embed surface. |
+| [agent-embed.html](../../agent-embed.html) | Current iframe shell; structurally close to what the artifact will contain. |
+| [api/agents.js](../../api/agents.js), the public `toPublicAgent` helper from 04-03 | The data that goes into the artifact. |
+| Claude Artifacts docs — assume: single HTML file, external resources allowed, sandboxed iframe context. |
+
+## Build this
+
+### Endpoint — `GET /api/agents/:id/artifact.html`
+
+- **Auth:** public; rate-limited.
+- **Output:** a single, self-contained HTML document (content-type `text/html; charset=utf-8`) that:
+ 1. Loads the built web-component bundle from the production origin (`<script type="module" src="https://3dagent.vercel.app/dist-lib/agent-3d.js">`).
+ 2. Renders `<agent-3d agent-id="<id>" host="claude"></agent-3d>`.
+ 3. Sets a viewport meta tag, a dark background, and sane mobile defaults.
+ 4. Includes Open Graph meta tags (reusing the 04-01 OG image) so previews of the artifact render correctly outside Claude too.
+
+The goal: drop-in paste into Claude Artifacts, shows the agent.
+
+### Dashboard UI
+
+On the agent home / dashboard, add a **"Embed in Claude"** button. Clicking it:
+- Generates a copy-to-clipboard snippet containing the artifact HTML (inlined — not a URL).
+- Also offers a short-lived signed URL (`/api/agents/:id/artifact.html?token=...`) for users who prefer linking.
+
+### `host=claude` behaviour
+
+The web component reads its `host` attribute. When `host=claude`:
+- Disable any hover-only UI (Claude artifacts may sandbox pointer events).
+- Default to `kiosk=true` (no dat.gui, no header).
+- Cap the canvas devicePixelRatio at 2 to keep perf bounded inside Claude.
+- Post a `window.parent.postMessage({ type: 'agent:ready', id })` so Claude-side listeners (if any) can react.
+
+### Library build
+
+[dist-lib/](../../dist-lib/) must contain a single `agent-3d.js` ESM bundle. If `npm run build:lib` doesn't already produce this, update the Vite lib config.
+
+## Out of scope
+
+- Do not implement chat-proxy for the agent talking back inside Claude — separate prompt, needs MCP wiring.
+- Do not write a Claude-side skill/extension.
+- Do not add analytics to the artifact.
+
+## Acceptance
+
+- [ ] `curl /api/agents/<id>/artifact.html` returns a valid HTML document that renders the agent in a fresh Chrome tab offline-from-dashboard.
+- [ ] Pasting the artifact into a Claude chat shows the 3D avatar.
+- [ ] The copy button on the dashboard yields ready-to-paste HTML.
+- [ ] The web component builds cleanly via `npm run build:lib` and the resulting bundle is under 500 KB gzipped.
+- [ ] `host=claude` disables the dat.gui + header.
diff --git a/prompts/build/05-01-claude-artifacts-shim.md b/prompts/build/05-01-claude-artifacts-shim.md
new file mode 100644
index 000000000..8204fb8eb
--- /dev/null
+++ b/prompts/build/05-01-claude-artifacts-shim.md
@@ -0,0 +1,49 @@
+# 05-01 — Host embed: Claude.ai Artifacts shim
+
+**Branch:** `feat/host-claude-artifacts`
+**Stack layer:** 5 (Host embed)
+**Depends on:** 04-03 (embed reliability)
+**Blocks:** demo of "your agent inside Claude"
+
+## Why it matters
+
+Claude.ai Artifacts run user-pasted HTML inside a sandboxed iframe (`sandbox="allow-scripts"` only — no `allow-same-origin`). Today our embed assumes same-origin to call `/api/agents/:id`. If a user pastes our snippet into an Artifact, it silently fails. This shim makes `<agent-3d>` boot in an opaque-origin context by routing all backend reads through a public, CORS-enabled, no-cookie endpoint.
+
+## Read these first
+
+| File | Why |
+|:---|:---|
+| [src/element.js](../../src/element.js) | The `<agent-3d>` web component. Detect Artifact context here. |
+| [src/manifest.js](../../src/manifest.js) | Manifest loader — currently uses same-origin fetch. |
+| [api/agents/[id].js](../../api/agents/[id].js) | Public read shape; verify CORS + cache headers. |
+| [public/agent/embed.html](../../public/agent/embed.html) | Iframe target — must work in nested sandbox. |
+| [vercel.json](../../vercel.json) | Add CORS headers to the public read routes. |
+
+## Build this
+
+1. In [src/element.js](../../src/element.js), detect opaque origin: `try { document.cookie } catch { isArtifact = true }` (Artifacts throw `SecurityError`). Also set when `window.location.origin === 'null'`.
+2. When `isArtifact`, force absolute URL for every backend call: `https://3dagent.vercel.app/api/...` (read host from `data-host` attribute on the script tag, fall back to `3dagent.vercel.app`).
+3. Add CORS headers to public-read endpoints: `Access-Control-Allow-Origin: *`, `Access-Control-Allow-Methods: GET, OPTIONS`, no credentials. Apply to: `/api/agents/:id`, `/api/widgets/:id`, `/api/avatars/public`, `/api/agents/:id/embed-policy`. Reuse the helper in [api/_lib/http.js](../../api/_lib/http.js) — add `corsPublic(res)`.
+4. Reject any `credentials: 'include'` fetch when `isArtifact` (cookies are useless in sandbox; sending them just confuses CORS).
+5. Add a `data-host` attribute to the canonical embed snippet generator at [embed.html](../../embed.html).
+
+## Out of scope
+
+- Do not add a write path for Artifacts (no auth = no writes).
+- Do not modify the SIWE flow.
+- Do not bundle a polyfill for `BroadcastChannel` or `localStorage` — gracefully degrade.
+- Do not add an MCP-style proxy.
+
+## Acceptance
+
+- [ ] Pasting our embed snippet into a Claude Artifact renders the avatar with no console errors.
+- [ ] Network tab shows absolute-URL fetches with `Origin: null` and successful 200s.
+- [ ] Same snippet still works on a normal page (non-sandbox).
+- [ ] `npm run build` passes.
+
+## Test plan
+
+1. `npm run dev`. Open the dashboard, generate an embed snippet for any public agent.
+2. Copy snippet. Open Claude.ai → New Artifact → paste as HTML.
+3. Verify: avatar loads, no errors, can orbit on touch.
+4. Repeat in a normal `<iframe>` on a scratch HTML page — same behavior.
diff --git a/prompts/build/05-02-lobehub-plugin.md b/prompts/build/05-02-lobehub-plugin.md
new file mode 100644
index 000000000..a56542050
--- /dev/null
+++ b/prompts/build/05-02-lobehub-plugin.md
@@ -0,0 +1,60 @@
+---
+mode: agent
+description: "Produce a Lobehub plugin manifest so an agent URL renders embodied in Lobehub chat"
+---
+
+# 05-02 · Lobehub plugin manifest
+
+## Why it matters
+
+The user maintains a Lobehub fork. The product's killer demo is: paste an agent URL into Lobehub → the 3D body appears in-line in the chat stream. Not a link card, not JSON — the avatar.
+
+## Prerequisites
+
+- 04-03 (embed works in iframes).
+- 04-04 (agent-card.json exists).
+
+## Read these first
+
+- Lobehub plugin docs (external). Link and summarize in the PR description — Lobehub uses a `lobe-chat-plugin` manifest convention. We need to produce:
+ - A plugin manifest JSON.
+ - An openapi-ish schema describing inputs.
+ - A render hint so Lobehub renders our iframe rather than JSON.
+- [public/agent/embed.html](../../public/agent/embed.html)
+- Existing `src/element.js` — `<agent-3d>` web component.
+
+## Build this
+
+1. **New endpoint** `GET /.well-known/lobehub-plugin.json` (or the exact path Lobehub requires — confirm from the docs):
+ - Describes the plugin: name, description, icon, author, homepage.
+ - Declares a `renderer` of type `iframe` pointing at `/agent/{id}/embed?kiosk=1`.
+ - Inputs: `agent_id` (string).
+2. **New endpoint** `POST /api/lobehub/resolve`:
+ - Accepts `{ agent_id }`, returns `{ iframe_url, card_url, name, description }`.
+ - Uses `agent-card.json` internally for the metadata.
+3. **Installation snippet** — on `/agent/:id` Share panel, add a "Lobehub" tab with:
+ - A one-click "Install in your Lobehub" link that deep-links into the user's Lobehub fork plugin registry (confirm Lobehub deep-link format from docs).
+ - A manual JSON snippet for users whose Lobehub doesn't support deep-link install.
+4. **User's fork** — note in the PR: if the plugin needs to be pre-registered in the fork's plugin registry rather than self-hosted, we add a PR to the fork. Don't write that PR here; flag it as next step.
+
+## Out of scope
+
+- Modifying Lobehub itself — plugin lives at our domain.
+- Multi-agent chat (we resolve one agent at a time per iframe).
+- Chat protocol with the agent — Lobehub's chat is the host LLM; our iframe is a body, not a model. Hook that up only if stack item says so.
+
+## Deliverables
+
+- `api/lobehub/plugin.js` (well-known manifest) or static JSON at `public/.well-known/lobehub-plugin.json`.
+- `api/lobehub/resolve.js`.
+- Share-panel "Lobehub" tab.
+
+## Acceptance
+
+- Installing the plugin in a fresh Lobehub instance and pasting an agent URL renders the iframe embodied in the chat.
+- `curl /.well-known/lobehub-plugin.json` returns a valid manifest.
+- `npm run build` passes.
+
+## Report
+
+Note in the PR exactly which Lobehub version / fork commit you tested against.
diff --git a/prompts/build/05-03-mcp-spawn-agent-tool.md b/prompts/build/05-03-mcp-spawn-agent-tool.md
new file mode 100644
index 000000000..501d58223
--- /dev/null
+++ b/prompts/build/05-03-mcp-spawn-agent-tool.md
@@ -0,0 +1,58 @@
+---
+mode: agent
+description: "Expose a render_agent MCP tool so Claude/hosts can spawn an agent body in a conversation"
+---
+
+# 05-03 · MCP `render_agent` tool
+
+## Why it matters
+
+Pillar 5's reach. Any MCP-compatible host (Claude, Claude Desktop, Lobehub) that speaks our MCP server can call `render_agent({id})` and receive a renderable card — letting the host spawn agents dynamically from a conversation, not just from pasted URLs.
+
+## Prerequisites
+
+- `api/mcp.js` already running.
+- 04-04 (agent-card.json exists).
+
+## Read these first
+
+- [api/mcp.js](../../api/mcp.js) — current MCP tool catalog.
+- [api/CLAUDE.md](../../api/CLAUDE.md) — MCP tool response shape (`content`, `structuredContent`, rate-limit buckets).
+
+## Build this
+
+1. **Add tool** `render_agent` to the MCP tool list in `api/mcp.js`:
+ - Inputs: `{ id: string }`.
+ - Scope: none (public). No auth required — the returned card is already public.
+ - Returns:
+ ```json
+ {
+ "content": [
+ { "type": "text", "text": "Render this 3D agent: <name>" },
+ { "type": "resource", "resource": { "uri": "https://.../agent/<id>/embed?kiosk=1", "mimeType": "text/html" } }
+ ],
+ "structuredContent": { "card_url": "...", "embed_url": "...", "name": "...", "description": "..." }
+ }
+ ```
+ - Rate-limit: reuse `limits.mcpIp` or add a `limits.mcpRender` preset if usage justifies.
+2. **Usage event** — emit a `usage_events` row with `kind='mcp_render_agent', tool='render_agent'`.
+3. **Update MCP catalog** in any `/.well-known` descriptor and the tool list endpoint if present.
+4. **Smoke test** with the MCP inspector (`npx @modelcontextprotocol/inspector`) pointing at the dev server.
+
+## Out of scope
+
+- OAuth changes for the tool (public tool).
+- A `list_agents` tool for a specific user (separate prompt; needs scoped auth).
+- Live streaming of agent actions over MCP (separate prompt).
+
+## Deliverables
+
+- Diff to `api/mcp.js` adding the tool and its dispatch.
+- A `usage_events` insertion.
+
+## Acceptance
+
+- MCP inspector lists `render_agent`.
+- Calling it with a valid id returns a resource pointing at the embed URL.
+- Rate-limit enforced.
+- `npm run build` passes.
diff --git a/prompts/build/05-03-postmessage-event-bridge.md b/prompts/build/05-03-postmessage-event-bridge.md
new file mode 100644
index 000000000..ab870585a
--- /dev/null
+++ b/prompts/build/05-03-postmessage-event-bridge.md
@@ -0,0 +1,61 @@
+# 05-03 — Host embed: postMessage event bridge
+
+**Branch:** `feat/host-bridge`
+**Stack layer:** 5 (Host embed)
+**Depends on:** 05-01
+**Blocks:** 05-04, 05-08
+
+## Why it matters
+
+Hosts (Claude Artifacts, Lobehub, ChatGPT canvas, generic iframes) need a uniform way to talk to the embedded agent. Today every host integration would write its own bridge. A single, documented `host:*` postMessage protocol means we ship one bridge and route every host through it.
+
+## Read these first
+
+| File | Why |
+|:---|:---|
+| [src/element.js](../../src/element.js) | Mount point for the bridge. |
+| [src/agent-protocol.js](../../src/agent-protocol.js) | Bus that bridges messages dispatch into. |
+| [specs/EMBED_SPEC.md](../../specs/EMBED_SPEC.md) | Embed spec — append the host-message protocol section here. |
+| [src/agent-skills.js](../../src/agent-skills.js) | Skill execution — what `host:perform-skill` calls. |
+
+## Build this
+
+1. Add `src/host-bridge.js` — small ESM module exporting `mountHostBridge(element, protocol)`. Listens to `window.message`, validates origin against `element.dataset.allowOrigins` (CSV) or a sane default (Claude, Lobehub, same-origin).
+2. Define and document the protocol (extend [specs/EMBED_SPEC.md](../../specs/EMBED_SPEC.md)):
+
+ **Inbound (host → agent):**
+ - `host:hello` `{ host, version }` → reply `agent:ready { agentId, capabilities, version }`
+ - `host:set-context` `{ agentId?, theme?, locale? }` → swap context live
+ - `host:perform-skill` `{ skill, args, callId }` → reply `agent:skill-result { callId, ok, result|error }`
+ - `host:say` `{ text }` → triggers `speak` action on bus
+ - `host:resize` `{ width, height }` → element adopts dimensions
+
+ **Outbound (agent → host):**
+ - `agent:ready` (boot complete)
+ - `agent:action` `{ type, payload }` (mirror of every protocol bus event)
+ - `agent:request-resize` `{ height }` (when content height changes)
+ - `agent:request-auth` (when user clicks something requiring SIWE)
+
+3. Wire `mountHostBridge` from `<agent-3d>` connected callback. Tear down on disconnect.
+4. Add a `data-host-debug="1"` attribute that logs every inbound + outbound message to console (off by default).
+
+## Out of scope
+
+- Do not add JSON-RPC framing — flat `{ type, ... }` is enough.
+- Do not implement encryption between host and agent.
+- Do not require host to register before sending — origin check is the gate.
+- Do not add a request/response queue with retries; replies are best-effort.
+
+## Acceptance
+
+- [ ] `mountHostBridge` is unit-testable as a pure function (export accepts a fake `EventTarget`).
+- [ ] Spec section in [specs/EMBED_SPEC.md](../../specs/EMBED_SPEC.md) lists every message type with shape + example.
+- [ ] Origin-mismatched messages are silently dropped (no console spam).
+- [ ] `npm run build` passes.
+
+## Test plan
+
+1. Open a scratch HTML page on `localhost` that hosts an iframe of `/agent/<id>/embed`.
+2. Send each `host:*` message from the parent and verify the reply / behavior.
+3. Verify `agent:action` events fire on every bus event (subscribe in the parent and log).
+4. Try posting from a non-allowed origin (use a different port) → no reply, no crash.
diff --git a/prompts/build/05-04-host-theme-sync.md b/prompts/build/05-04-host-theme-sync.md
new file mode 100644
index 000000000..5f0dc5e02
--- /dev/null
+++ b/prompts/build/05-04-host-theme-sync.md
@@ -0,0 +1,47 @@
+# 05-04 — Host embed: theme sync
+
+**Branch:** `feat/host-theme`
+**Stack layer:** 5 (Host embed)
+**Depends on:** 05-03
+
+## Why it matters
+
+When our agent embeds in Lobehub or Claude Artifacts, a black background on a white host looks broken. The host already knows its color scheme; we just need to listen for it and adapt.
+
+## Read these first
+
+| File | Why |
+|:---|:---|
+| [src/host-bridge.js](../../src/host-bridge.js) | Bridge to extend. |
+| [src/viewer.js](../../src/viewer.js) | `setBackgroundColor`, `setEnvironment`. |
+| [src/agent-home.js](../../src/agent-home.js) | Renders the identity card — needs to honor theme. |
+| [style.css](../../style.css) | CSS tokens — verify `--bg`, `--fg`, `--accent` exist. |
+
+## Build this
+
+1. Extend `host:set-context` to accept `theme: 'light' | 'dark' | 'auto'` (auto = follow `prefers-color-scheme`).
+2. When theme changes:
+ - Toggle a `data-theme="light|dark"` attribute on the embed root.
+ - Switch viewer background: dark → `#0a0a0a`, light → `#f7f7f7`.
+ - Switch HDR environment to `studio-soft` (light) vs `neutral` (dark) — only if the user hasn't pinned an env in the widget config.
+3. Add CSS rules under `[data-theme="light"]` overriding the dark tokens (`--bg`, `--fg`, etc.) — keep it minimal, no new design system.
+4. If the host doesn't send a theme, fall back to `prefers-color-scheme`.
+
+## Out of scope
+
+- Do not add a per-component theme prop. Only the root attribute.
+- Do not add light-mode HDRs unless one already ships — reuse what's there.
+- Do not animate the theme transition (CSS handles it).
+
+## Acceptance
+
+- [ ] `host:set-context { theme: 'light' }` flips the root attribute and updates background within one frame.
+- [ ] No flash-of-wrong-theme on initial paint when host sends `host:hello` synchronously.
+- [ ] Existing dark embeds with no host messages render unchanged.
+- [ ] `npm run build` passes.
+
+## Test plan
+
+1. From the scratch host page, send `host:set-context { theme: 'light' }` after `agent:ready`. Verify swap.
+2. Toggle back to `dark`. Verify swap.
+3. Send `theme: 'auto'` and toggle the OS color scheme — verify the embed follows.
diff --git a/prompts/build/05-04-postmessage-bridge-spec.md b/prompts/build/05-04-postmessage-bridge-spec.md
new file mode 100644
index 000000000..1f6d4cc21
--- /dev/null
+++ b/prompts/build/05-04-postmessage-bridge-spec.md
@@ -0,0 +1,64 @@
+---
+mode: agent
+description: "Freeze the host↔agent postMessage bridge as a versioned contract + tiny JS SDK"
+---
+
+# 05-04 · Host ↔ agent postMessage bridge
+
+## Why it matters
+
+Third-party hosts (Lobehub fork, Claude Artifacts, future embedders) only work reliably if the postMessage contract between host and iframe is documented, versioned, and stable. Without this, every host integration drifts.
+
+## Prerequisites
+
+- 04-03 (embed reliability) shipped.
+
+## Read these first
+
+- [public/agent/embed.html](../../public/agent/embed.html) — where the bridge is implemented.
+- [src/agent-protocol.js](../../src/agent-protocol.js) — event bus the bridge forwards into.
+
+## Build this
+
+1. **Document the contract** at the top of `public/agent/embed.html` as a comment block:
+ ```
+ Bridge v1
+ Host → iframe:
+ { type: 'agent:action', agentId, action } // forward action to protocol bus
+ { type: 'agent:hello', agentId, host } // handshake; iframe replies with agent:ready
+ { type: 'agent:ping', id } // liveness; replies agent:pong
+ Iframe → host:
+ { type: 'agent:ready', agentId, version, capabilities: [...] }
+ { type: 'agent:action', agentId, action } // echo of actions emitted
+ { type: 'agent:resize', agentId, height }
+ { type: 'agent:pong', id }
+ All messages include `agentId`. Unknown `type` values are ignored.
+ ```
+2. **Implement** matching handlers in `public/agent/embed.html` if any are missing.
+3. **Add a tiny JS SDK** `public/embed-sdk.js` (≤ 100 lines) that a host developer can `<script src="...">` and use:
+ ```js
+ const bridge = Agent3D.connect(iframeEl, { agentId, onAction, onReady, onResize });
+ bridge.send({ type: 'present-model', url: '...' });
+ ```
+ - Two-way message routing.
+ - Auto-resize the iframe to reported height.
+ - Timeout on hello → fallback behavior.
+4. **Link from Share panel** — add a "Custom embed" tab that shows the bridge docs and links to `embed-sdk.js`.
+
+## Out of scope
+
+- Bidirectional audio / video streams over the bridge.
+- Encrypted messaging.
+- Version 2 of the bridge. This is v1; freeze it.
+
+## Deliverables
+
+- Comment block at top of `public/agent/embed.html`.
+- `public/embed-sdk.js` (new).
+- Share panel "Custom embed" tab.
+
+## Acceptance
+
+- Host page using `Agent3D.connect(...)` receives `agent:ready` within 2s.
+- Actions sent from host appear on iframe's protocol bus.
+- `npm run build` passes.
diff --git a/prompts/build/05-05-host-resize-and-mode.md b/prompts/build/05-05-host-resize-and-mode.md
new file mode 100644
index 000000000..97debd002
--- /dev/null
+++ b/prompts/build/05-05-host-resize-and-mode.md
@@ -0,0 +1,52 @@
+# 05-05 — Host embed: resize and display mode protocol
+
+**Branch:** `feat/host-resize-mode`
+**Stack layer:** 5 (Host embed)
+**Depends on:** 05-03 (postMessage bridge)
+
+## Why it matters
+
+The agent needs to fit the host's layout — sometimes inline (300px), sometimes floating (avatar bubble in the corner), sometimes fullscreen (presentation mode). Today these modes are set once at boot via the `mode` attribute. Hosts need to flip them live as the user resizes their chat panel or maximizes the artifact.
+
+## Read these first
+
+| File | Why |
+|:---|:---|
+| [src/element.js](../../src/element.js) | Existing `mode` attribute (inline | floating | section | fullscreen). |
+| [src/host-bridge.js](../../src/host-bridge.js) | Bridge to extend (created in 05-03). |
+| [src/viewer.js](../../src/viewer.js) | `resize()` method or equivalent — the canvas needs to react. |
+| [style.css](../../style.css) | Mode-specific CSS classes. |
+
+## Build this
+
+1. Extend the bridge inbound protocol with `host:set-mode { mode }` — accepted values: `inline | floating | section | fullscreen`.
+2. On mode change:
+ - Update `data-mode` on the embed root.
+ - Call `viewer.resize()` after the next animation frame.
+ - In `floating` mode, position absolute bottom-right with a 16px margin and a max-size of 240×240.
+ - In `fullscreen` mode, fix to viewport, hide all chrome.
+3. Add `agent:request-resize { width, height }` outbound — emit when the avatar's natural display height changes (e.g. caption text wraps to a new line).
+4. Listen to `ResizeObserver` on the host iframe element (when `data-host-bridge-track="1"`) and call `viewer.resize()` automatically.
+5. Honor `prefers-reduced-motion` — disable the floating-mode entrance bounce.
+
+## Out of scope
+
+- Do not implement drag-to-reposition for floating mode (later).
+- Do not add a settings panel for picker modes.
+- Do not touch the dat.gui visibility logic — that's controlled by `kiosk` separately.
+
+## Acceptance
+
+- [ ] `host:set-mode` flips modes live with no remount.
+- [ ] Canvas resizes correctly without distortion or blur.
+- [ ] `agent:request-resize` fires when caption text wraps.
+- [ ] Floating mode positions bottom-right, fullscreen covers viewport.
+- [ ] `npm run build` passes.
+
+## Test plan
+
+1. Boot a scratch host page with the embed in `inline` mode.
+2. Send `host:set-mode { mode: 'floating' }` — verify position and size.
+3. Resize the host iframe — verify the canvas tracks.
+4. Send `host:set-mode { mode: 'fullscreen' }` — verify viewport coverage.
+5. Toggle `prefers-reduced-motion` — confirm no entrance animation.
diff --git a/prompts/build/06-01-erc8004-mint-from-ui.md b/prompts/build/06-01-erc8004-mint-from-ui.md
new file mode 100644
index 000000000..d40d8886f
--- /dev/null
+++ b/prompts/build/06-01-erc8004-mint-from-ui.md
@@ -0,0 +1,54 @@
+---
+mode: agent
+description: "Let a signed-in user mint an ERC-8004 agent id from the agent page"
+---
+
+# 06-01 · Mint ERC-8004 id from UI
+
+## Why it matters
+
+Pillar 6 begins here. The agent record lives on-chain, portable across hosts. Today the ERC-8004 contracts exist under `contracts/`, and `src/erc8004/` has registration code — but the UI path from "agent page → minted id" isn't wired for every user.
+
+## Prerequisites
+
+- Pillar 1 (wallet linked to account).
+- Pillar 2 (agent has an avatar, so there's something to register).
+- ERC-8004 identity registry deployed; addresses in [src/erc8004/abi.js](../../src/erc8004/abi.js).
+
+## Read these first
+
+- [contracts/src/IdentityRegistry.sol](../../contracts/src/IdentityRegistry.sol)
+- [src/erc8004/abi.js](../../src/erc8004/abi.js)
+- [src/erc8004/agent-registry.js](../../src/erc8004/agent-registry.js)
+- [src/erc8004/register-ui.js](../../src/erc8004/register-ui.js) — existing UI helper.
+- [api/agents.js](../../api/agents.js) — `POST /api/agents/:id/wallet` accepts `erc8004_agent_id`.
+
+## Build this
+
+1. **New page** `/agent/:id/register` (owner-only) with a step wizard:
+ - Step 1 — connect wallet (reuse `wallet-login.js` logic; if already linked via 01-03, skip).
+ - Step 2 — preview the agent-card.json payload that will be committed.
+ - Step 3 — confirm chain + network fee, sign & send the `registerAgent` tx via the user's wallet (ethers `BrowserProvider`).
+ - Step 4 — on success: extract the `AgentRegistered` event's `agentId`, `PUT /api/agents/:id/wallet` with `{ erc8004_agent_id, chain_id, wallet_address }`.
+2. **Error states** — wrong network, insufficient funds, user rejected, contract revert — each gets a clear message and a retry button. No cryptic hex strings shown.
+3. **Display on `/agent/:id`** — if `erc8004_agent_id` is set, show "On-chain: #<id> on <chain>" with a block-explorer link. Read-only badge.
+4. **Anti-double-register guard** — if agent already has `erc8004_agent_id`, the register page shows a "Already registered" state with the id and link; no double-mint.
+
+## Out of scope
+
+- Pinning the card to IPFS (06-02).
+- Signing actions with the wallet (06-04).
+- Deploying contracts (separate op; see `docs/deploy-erc8004-contracts.md`).
+
+## Deliverables
+
+- `public/agent/register.html` + JS.
+- Any owner-only guard code.
+- Link from `/agent/:id` owner bar → register page.
+
+## Acceptance
+
+- Owner with a wallet can successfully mint and see the id stored in `agent_identities.erc8004_agent_id`.
+- Attempting to register twice is blocked client + server side.
+- Block-explorer link resolves.
+- `npm run build` passes.
diff --git a/prompts/build/06-02-pin-card-to-ipfs.md b/prompts/build/06-02-pin-card-to-ipfs.md
new file mode 100644
index 000000000..69bde0315
--- /dev/null
+++ b/prompts/build/06-02-pin-card-to-ipfs.md
@@ -0,0 +1,52 @@
+---
+mode: agent
+description: "Pin agent-card.json to IPFS and record the CID before/with on-chain registration"
+---
+
+# 06-02 · Pin agent-card to IPFS
+
+## Why it matters
+
+The onchain registry stores a **CID** pointing at the agent's card, not the card itself. Hosts pull `ipfs://<cid>` to resolve the agent. If pinning is unreliable, onchain portability (pillar 6) silently breaks — chain says "agent exists" but hosts can't load the body.
+
+## Prerequisites
+
+- 04-04 (card exists).
+- An IPFS pinning provider available (e.g. web3.storage, Pinata, nft.storage). Env var `IPFS_PIN_TOKEN`.
+
+## Read these first
+
+- [src/ipfs.js](../../src/ipfs.js) — existing IPFS/Arweave URI resolver (client-side fetch with gateway fallback).
+- [api/agents.js](../../api/agents.js) — `registration_cid` column exists on `agent_identities` (see `decorate()`).
+
+## Build this
+
+1. **New endpoint** `POST /api/agents/:id/pin` (owner-only):
+ - Build the canonical card JSON via the same code path as `/api/agents/:id/card.json`.
+ - Pin it via the provider SDK (server-side — keep the token off the client).
+ - `UPDATE agent_identities SET registration_cid = $1 WHERE id = $2`.
+ - Return `{ cid, gateway_url }`.
+2. **Wire it into the register page** (06-01):
+ - Before signing the on-chain tx, call `/pin` and include the returned CID in the registration payload.
+ - The registry function signature expects a `bytes32` CID or `string` URI — check `IdentityRegistry.sol` and match exactly. If it's `bytes32`, store the raw digest; document the encoding in the endpoint response.
+3. **Re-pin on change** — if the owner edits metadata (03-03) or swaps avatar (03-01), show a "Re-pin" button that calls `/pin` again. New CID overrides old. Only the owner can trigger this; only after registration.
+4. **Resolver integration** — `src/agent-resolver.js` should try fetching `registration_cid` from the card first (authoritative), fall back to `/api/agents/:id/card.json`.
+
+## Out of scope
+
+- Paying for pinning on the user's behalf long-term (usage quota).
+- Arweave mirror (future).
+- Deleting / unpinning on agent deletion (the data is public; graveyard is acceptable).
+
+## Deliverables
+
+- `api/agents/[id]/pin.js`.
+- Wiring in `public/agent/register.html` (created in 06-01).
+- Resolver fallback update in `src/agent-resolver.js`.
+
+## Acceptance
+
+- Register flow pins the card, stores CID, writes it on-chain.
+- `https://ipfs.io/ipfs/<cid>` (or configured gateway) resolves to the card JSON.
+- Re-pin after an edit produces a new CID and records it.
+- `npm run build` passes.
diff --git a/prompts/build/06-03-resolve-agent-from-chain.md b/prompts/build/06-03-resolve-agent-from-chain.md
new file mode 100644
index 000000000..7553595de
--- /dev/null
+++ b/prompts/build/06-03-resolve-agent-from-chain.md
@@ -0,0 +1,52 @@
+---
+mode: agent
+description: "Given an on-chain agent id, resolve to a full rendered agent in any host"
+---
+
+# 06-03 · Resolve agent from chain
+
+## Why it matters
+
+The payoff of pillar 6. Any host — Lobehub, Claude, a random site — can take an `(chain_id, erc8004_agent_id)` tuple and get back a fully rendered embodied agent. This is the universal-frontend moment.
+
+## Prerequisites
+
+- 06-01 (mint) and 06-02 (pin) shipped so there's something to resolve.
+
+## Read these first
+
+- [src/erc8004/abi.js](../../src/erc8004/abi.js)
+- [src/erc8004/index.js](../../src/erc8004/index.js)
+- [src/agent-resolver.js](../../src/agent-resolver.js)
+- [api/agents/[id].js](../../api/agents/[id].js)
+
+## Build this
+
+1. **Server-side resolver** `GET /api/agents/by-chain?chain_id=X&erc8004_id=Y`:
+ - Look up the on-chain record via a read-only RPC (reuse any provider config).
+ - Extract the pinned CID.
+ - Fetch the card JSON from IPFS (multi-gateway fallback via `src/ipfs.js`).
+ - Resolve the avatar URL from the card.
+ - Return `{ id?, name, description, avatar: { url }, card_cid, card_url, embed_url }`. If the agent is *also* in our Neon DB (one of ours), include the local `id`.
+ - Cache the response (CDN, 60s) — on-chain reads are slow.
+2. **Client helper** — extend `src/agent-resolver.js` so `<agent-3d chain-id="1" erc8004-id="42">` works, using `/api/agents/by-chain`.
+3. **Embed resolver** — `/agent/chain/:chainId/:erc8004Id` route that renders the embed for a chain-resolved agent (not an internal id). Lets hosts paste chain-native URLs.
+4. **Card trust** — verify the card's declared `wallet` matches the on-chain owner before rendering; reject otherwise. Protects against a CID that points to a spoofed card.
+
+## Out of scope
+
+- Writing a cross-chain aggregator (one chain at a time via `chain_id`).
+- Caching CIDs in our DB (optional optimization; skip).
+- Minting from chain (this is read-only).
+
+## Deliverables
+
+- `api/agents/by-chain.js`.
+- Route in `vercel.json` for `/agent/chain/:chainId/:erc8004Id`.
+- Extension to `src/agent-resolver.js` / `src/element.js`.
+
+## Acceptance
+
+- A fresh browser with no session and no knowledge of our DB can resolve `/agent/chain/1/42` and see the agent render.
+- Spoofed card (wallet mismatch) returns a 400 / error card.
+- `npm run build` passes.
diff --git a/prompts/build/06-04-lobehub-onchain-import.md b/prompts/build/06-04-lobehub-onchain-import.md
new file mode 100644
index 000000000..92c021f4c
--- /dev/null
+++ b/prompts/build/06-04-lobehub-onchain-import.md
@@ -0,0 +1,43 @@
+---
+mode: agent
+description: "Lobehub (or any MCP host) imports an agent directly from its on-chain record"
+---
+
+# 06-04 · Lobehub onchain import
+
+## Why it matters
+
+This is the specific demo that proves the whole product thesis: a user in Lobehub pastes an on-chain agent id → the embodied agent appears in chat, pulled from the chain, not from our DB. If we can do this for Lobehub, the pattern generalizes to every host.
+
+## Prerequisites
+
+- 05-02 (Lobehub plugin) and 06-03 (chain resolver).
+
+## Read these first
+
+- [prompts/build/05-02-lobehub-plugin.md](./05-02-lobehub-plugin.md) — plugin shape.
+- Lobehub plugin docs for "variable input" patterns.
+
+## Build this
+
+1. **Extend the Lobehub plugin manifest** (05-02) with an alternate input mode:
+ - `{ chain_id, erc8004_id }` instead of / in addition to `{ agent_id }`.
+2. **Resolver call** — plugin renderer calls `/api/agents/by-chain?...` (06-03) and renders the returned `embed_url` in its iframe renderer.
+3. **Native chat command** — document a `/3d-agent chain:1 id:42` slash-command pattern for the Lobehub fork. Include a minimal command-parser snippet in the PR; the user will wire it into their fork.
+4. **End-to-end test** — in the user's Lobehub fork, trigger the import with a known on-chain id and verify the avatar appears embodied inline.
+
+## Out of scope
+
+- Writing code inside the Lobehub fork repo — we deliver the integration points; the user owns fork changes.
+- Cross-chain aggregation.
+
+## Deliverables
+
+- Updated plugin manifest endpoint.
+- A short "How to wire in your fork" note (in the PR description only — not a new docs file).
+
+## Acceptance
+
+- Slash-command in a local Lobehub build pulls the agent from chain and renders.
+- Error states (no such chain id, no such agent id) are clear.
+- `npm run build` passes.
diff --git a/prompts/build/06-05-signed-action-log.md b/prompts/build/06-05-signed-action-log.md
new file mode 100644
index 000000000..90879b22b
--- /dev/null
+++ b/prompts/build/06-05-signed-action-log.md
@@ -0,0 +1,48 @@
+---
+mode: agent
+description: "Sign every agent action with the linked wallet so the action log is verifiable"
+---
+
+# 06-05 · Wallet-signed action log
+
+## Why it matters
+
+The onchain identity is worth nothing if the agent's *actions* are unsigned — a host can't distinguish real moves from forged ones. Signing each action with the owner wallet (off-chain, stored in `agent_actions.signature`) makes the action log cryptographically attributable.
+
+## Prerequisites
+
+- Pillar 1 (wallet linked).
+- 06-01 (ERC-8004 id minted — gives you a canonical signer address).
+
+## Read these first
+
+- [src/agent-skills.js](../../src/agent-skills.js) — `sign-action` skill.
+- [src/agent-identity.js](../../src/agent-identity.js) — wallet plumbing.
+- [api/agent-actions.js](../../api/agent-actions.js) — current action persistence.
+
+## Build this
+
+1. **Action signing on the client** — before `POST /api/agent-actions`, run the action payload through `wallet.signMessage(canonicalize(action))`. Canonicalize via sorted keys + no whitespace. Store `{ signature, signer_address, message_digest }` alongside the action.
+2. **Server verification** — on insert, verify the signature recovers the agent's `wallet_address`. Reject if mismatch.
+3. **Unsigned fallback** — anonymous visitors (no linked wallet) continue to write actions *without* signatures; those rows get `signature IS NULL`. Signed vs unsigned is filterable.
+4. **Expose signed-only timeline on public views** — on `/agent/:id`, an optional toggle "Verified actions only" shows rows where `signer_address = agent.wallet_address`. Default: show all.
+5. **Prompt the user** to sign once per session — use a "delegation" message (SIWE-style) that authorizes the browser session to sign subsequent actions locally with a session-scoped key. Rather than wallet-popup-per-action, which kills UX.
+
+## Out of scope
+
+- Onchain action anchoring (Merkle commits).
+- Revocation of the session-scoped signing key (keep it session-lifetime for v1).
+- Cross-host verification SDKs.
+
+## Deliverables
+
+- Client code in `src/agent-skills.js` (sign-action) and/or a new signer helper.
+- Verification branch in `api/agent-actions.js`.
+- Toggle on `/agent/:id` for verified-only view.
+
+## Acceptance
+
+- With a linked wallet, emitting an action produces a row with a valid signature that recovers the wallet address.
+- Tampering with the stored action body breaks verification.
+- Anonymous actions still land, unsigned.
+- `npm run build` passes.
diff --git a/prompts/build/README.md b/prompts/build/README.md
new file mode 100644
index 000000000..6e340b6fb
--- /dev/null
+++ b/prompts/build/README.md
@@ -0,0 +1,76 @@
+# Build prompts — the real stack
+
+Prompts in this directory are scoped to the product priority stack. If a prompt isn't here, it's not on the critical path. Ignore `prompts/embed/`, `prompts/pretext/`, `prompts/scalability/`, and `prompts/widget-studio/` unless explicitly asked — they rat-hole on secondary concerns.
+
+## Priority stack (build in this order)
+
+1. **Wallet auth** — user can sign in with MetaMask and have a real backend session. Largely shipped (2026-04-15); gap-fills in `01-*`.
+2. **Selfie → agent** — take a photo, get a 3D avatar. The magic moment. `02-*`.
+3. **Edit avatar** — swap, regenerate, tweak without destroying identity. `03-*`.
+4. **View & embed** — agent page polish and iframe/oEmbed so the avatar can be shared. `04-*`.
+5. **Host embed** — avatar lives inside Claude.ai Artifacts and Lobehub chat (user has a Lobehub fork — primary integration target). `05-*`.
+6. **Onchain portability** — the agent is pulled *from chain* into any host. The novel unlock. `06-*`.
+
+## Prompt file format
+
+Each prompt is self-contained. An agent should be able to implement it without reading the others. Every prompt declares:
+
+- **Why it matters** (one paragraph, tied to the stack)
+- **What to build** (concrete files and behaviors)
+- **Out of scope** (to prevent drift)
+- **Acceptance** (verifiable)
+
+## Rules for agents executing these prompts
+
+- Do **not** add features, refactors, or abstractions beyond what's specified.
+- Do **not** write tests unless explicitly required.
+- Do **not** create documentation files unless explicitly required.
+- If the spec conflicts with reality (file moved, dep missing, API changed), stop and report — don't improvise.
+- If you finish early, stop. Don't find extra work.
+
+## Sequencing
+
+Pillars 1–3 are mostly sequential (auth → selfie → edit). Pillars 4–6 can proceed in parallel once 1–3 are solid.
+
+Within a pillar, suffix numbers indicate sequence: `02-01-*` before `02-02-*`.
+
+## Prompts
+
+**Stack-wide**
+- [00-stack-e2e-smoke.md](./00-stack-e2e-smoke.md) — end-to-end smoke script
+
+**Pillar 1 — Wallet auth**
+- [01-01-wallet-auth-smoke-test.md](./01-01-wallet-auth-smoke-test.md)
+- [01-02-email-password-parity.md](./01-02-email-password-parity.md)
+- [01-03-link-wallet-to-existing-account.md](./01-03-link-wallet-to-existing-account.md)
+- [01-04-session-expiry-ux.md](./01-04-session-expiry-ux.md)
+
+**Pillar 2 — Selfie → agent**
+- [02-01-selfie-capture-ui.md](./02-01-selfie-capture-ui.md)
+- [02-02-selfie-upload-r2.md](./02-02-selfie-upload-r2.md)
+- [02-03-selfie-to-avatar-pipeline.md](./02-03-selfie-to-avatar-pipeline.md)
+- [02-04-first-agent-landing.md](./02-04-first-agent-landing.md)
+
+**Pillar 3 — Edit avatar**
+- [03-01-avatar-swap.md](./03-01-avatar-swap.md)
+- [03-02-avatar-regenerate.md](./03-02-avatar-regenerate.md)
+- [03-03-edit-agent-metadata.md](./03-03-edit-agent-metadata.md)
+
+**Pillar 4 — View & embed**
+- [04-01-agent-public-page-polish.md](./04-01-agent-public-page-polish.md)
+- [04-02-og-oembed.md](./04-02-og-oembed.md)
+- [04-03-embed-reliability.md](./04-03-embed-reliability.md)
+- [04-04-agent-card-json.md](./04-04-agent-card-json.md)
+
+**Pillar 5 — Host embed**
+- [05-01-claude-artifact-embed.md](./05-01-claude-artifact-embed.md)
+- [05-02-lobehub-plugin.md](./05-02-lobehub-plugin.md)
+- [05-03-mcp-spawn-agent-tool.md](./05-03-mcp-spawn-agent-tool.md)
+- [05-04-postmessage-bridge-spec.md](./05-04-postmessage-bridge-spec.md)
+
+**Pillar 6 — Onchain portability**
+- [06-01-erc8004-mint-from-ui.md](./06-01-erc8004-mint-from-ui.md)
+- [06-02-pin-card-to-ipfs.md](./06-02-pin-card-to-ipfs.md)
+- [06-03-resolve-agent-from-chain.md](./06-03-resolve-agent-from-chain.md)
+- [06-04-lobehub-onchain-import.md](./06-04-lobehub-onchain-import.md)
+- [06-05-signed-action-log.md](./06-05-signed-action-log.md)
diff --git a/prompts/claude-artifact/01-artifact-snippet.md b/prompts/claude-artifact/01-artifact-snippet.md
new file mode 100644
index 000000000..d46380b76
--- /dev/null
+++ b/prompts/claude-artifact/01-artifact-snippet.md
@@ -0,0 +1,100 @@
+# Task: Ship the minimal Claude Artifact HTML snippet
+
+## Context
+
+Repo: `/workspaces/3D`. Claude.ai's **Artifacts** feature renders HTML/JS content in a sandboxed iframe. We want a Claude user to paste **one small HTML snippet** into a Claude chat, open it as an Artifact, and immediately see a live embodied agent avatar — fetched by `agentId`.
+
+Relevant existing files:
+
+- [../../public/agent/embed.html](../../public/agent/embed.html) — our current iframe embed. It imports from `/src/...` via ES modules served from our origin. An Artifact can't do that — it runs on Claude's origin and has to load everything over public URLs.
+- [../../src/element.js](../../src/element.js) — the `<agent-3d>` web component. Currently ships as part of the Vite build; not CDN-ready as-is.
+- [../../src/agent-avatar.js](../../src/agent-avatar.js) — the Empathy Layer. Must run inside the Artifact.
+- [../../src/agent-protocol.js](../../src/agent-protocol.js) — event bus the avatar subscribes to.
+- [../../public/embed.js](../../public/embed.js) — our existing script-tag embed for widgets (reference for how we bootstrap into an iframe).
+- [../lobehub-embed/](../lobehub-embed/) — sibling priority-5 directory for the LobeHub side of the same integration story.
+
+The snippet in this task is a thin HTML wrapper. The JS payload lives in the bundle produced by [./02-zero-dep-viewer-bundle.md](./02-zero-dep-viewer-bundle.md).
+
+## Goal
+
+Create a copy-pasteable HTML template, &lt;2 KB, that a Claude user drops into chat as an `html` Artifact. Opening the Artifact fetches `agentId` via our public API, loads the avatar GLB, and renders a breathing embodied avatar with the Empathy Layer running idle. No user interaction required.
+
+## Deliverable
+
+1. **File created** — `public/artifact/index.html`. This is both the documentation of the snippet and a working preview page when hit directly. Contents are the snippet verbatim, wrapped only in enough surrounding `<html><body>` to render standalone.
+2. **File created** — `public/artifact/snippet.html`. The *exact* string users copy/paste. Minified where safe. Ends with a comment naming the project and version.
+3. **File created** — `prompts/claude-artifact/TESTED-SNIPPET.md` (NOT a codebase doc — it lives in this prompts dir only) — the verbatim snippet that was tested in a real Claude Artifact, plus a note on the date tested and the Claude model used.
+4. **Edit** — add a "Claude Artifact" tab to the share panel on [public/agent/index.html](../../public/agent/index.html) next to the existing iframe/link/`<agent-3d>` tabs, exposing a copy button that yields the snippet from `snippet.html` with `agentId` substituted in.
+
+## Required shape of the snippet
+
+```html
+<!doctype html>
+<html><head><meta charset="utf-8"></head>
+<body style="margin:0;background:#0b0d10">
+<div id="a" style="width:100%;height:100vh"></div>
+<script src="https://3dagent.vercel.app/artifact.js"></script>
+<script>
+ Agent3D.mount('#a', { agentId: 'AGENT_ID_HERE' });
+</script>
+</body></html>
+```
+
+- Background is a reasonable default (dark). The user can change it.
+- `#a` fills the artifact viewport — Claude Artifacts vary in size; no fixed px.
+- `Agent3D` is the global exposed by the bundle (task 02).
+- `Agent3D.mount(target, opts)` API must be documented here even though the bundle task owns the implementation.
+
+## Required fallback paths
+
+The snippet must handle:
+
+1. Bundle script fails to load (CDN blocked) → show one-line text fallback inside `#a` saying "Agent viewer couldn't load. See: https://3dagent.vercel.app/agent/AGENT_ID_HERE".
+2. `agentId` not found → the bundle should render an empty sad-face stand-in; the snippet just passes the id through.
+3. Avatar GLB fails to load → bundle handles; snippet just doesn't crash.
+
+Implement (1) inline with a small `onerror` handler on the script tag. (2) and (3) are delegated to task 02.
+
+## Audit checklist — must handle all of these
+
+- Snippet is &lt;2 KB. Measure with `wc -c`.
+- No inline event handlers beyond the `onerror` on the bundle script tag.
+- No `<iframe>` — this IS the iframe (the Artifact sandbox itself).
+- No `type="module"` — keep it classic script for maximum compatibility across Artifact sandbox versions.
+- No external CSS files — style in `style=""` attributes only.
+- No tracking / telemetry / analytics.
+- Works whether the user pastes it directly into the Artifact code editor or Claude generates it for them.
+- If `AGENT_ID_HERE` is left unreplaced, the bundle must show a clear "replace `AGENT_ID_HERE` with an agent id" instruction overlay (bundle task 02 owns this behavior; note it in the snippet as an HTML comment).
+- Copy button in the share panel produces output that is byte-identical to `snippet.html` except for the `AGENT_ID_HERE` substitution.
+
+## Constraints
+
+- No new runtime deps.
+- No changes to `/api` in this task — that is task 02's territory.
+- Do not edit `src/element.js`. The Artifact bundle is a separate build artifact with its own surface.
+- Do not edit [../../public/agent/embed.html](../../public/agent/embed.html) — the iframe embed stays as-is for non-Claude hosts.
+
+## Verification
+
+1. `wc -c public/artifact/snippet.html` — report bytes.
+2. `npx vite build` — report result.
+3. Manually: open a Claude chat, paste the snippet with a real agentId (`0x-demo-agent` or equivalent) into an `html` artifact. Screenshot or describe the result. If the avatar renders and breathes, verification passes.
+4. Paste the snippet with `AGENT_ID_HERE` *unchanged* — expect a clear instruction overlay, not a silent blank.
+5. Verify the share-panel copy button in `public/agent/index.html` yields the exact bytes of `snippet.html` with id substituted.
+
+## Scope boundaries — do NOT do these
+
+- Do not build the bundle. Task 02 owns `https://3dagent.vercel.app/artifact.js`.
+- Do not design the idle animation. Task 03 owns it.
+- Do not write an ERC-8004 lookup path here. Task 04 covers the onchain template.
+- Do not add Claude-specific telemetry, postMessage handshake, or branding beyond a single HTML comment naming the project.
+- Do not introduce a new Vercel route — serve `public/artifact/index.html` and `public/artifact/snippet.html` as static files.
+
+## Reporting
+
+At the end, summarise:
+- Byte count of `snippet.html`.
+- Which files were created and which edited (list sections in `public/agent/index.html`).
+- The exact snippet that was pasted into a live Claude Artifact and what happened.
+- Any sandbox surprise (blocked domain, CSP error, broken fallback path).
+- Any unverified Artifact-sandbox assumption that should be re-checked before shipping to users.
diff --git a/prompts/claude-artifact/02-zero-dep-viewer-bundle.md b/prompts/claude-artifact/02-zero-dep-viewer-bundle.md
new file mode 100644
index 000000000..ffd5c90b4
--- /dev/null
+++ b/prompts/claude-artifact/02-zero-dep-viewer-bundle.md
@@ -0,0 +1,120 @@
+# Task: Build the hosted single-file viewer bundle for Claude Artifacts
+
+## Context
+
+Repo: `/workspaces/3D`. Task [./01-artifact-snippet.md](./01-artifact-snippet.md) defines a minimal HTML snippet users paste into Claude.ai Artifacts. That snippet pulls **one script** from our CDN:
+
+```
+<script src="https://3dagent.vercel.app/artifact.js"></script>
+```
+
+This task produces `artifact.js` — a single self-contained, zero-install, CDN-ready bundle that:
+
+1. Loads three.js (via CDN, not bundled).
+2. Fetches the agent identity + avatar GLB via our public API.
+3. Mounts a `<canvas>` into a user-provided target.
+4. Runs the Empathy Layer in idle mode (see [./03-idle-animation-loop.md](./03-idle-animation-loop.md) for the animation spec — this task just exposes the hook).
+5. Supports both `agentId` lookup and **ERC-8004 onchain lookup** (delegating to [../../src/agent-resolver.js](../../src/agent-resolver.js) logic, ported into the bundle as needed).
+
+Relevant existing modules:
+- [../../src/element.js](../../src/element.js) — full web component. Too heavy for an Artifact bundle. Cannibalise selectively.
+- [../../src/viewer.js](../../src/viewer.js) — ~11k LOC. Do **not** bundle as-is; port only the minimum: GLB load, render loop, camera setup.
+- [../../src/agent-avatar.js](../../src/agent-avatar.js) — Empathy Layer. Small and self-contained. Port whole.
+- [../../src/agent-protocol.js](../../src/agent-protocol.js) — event bus. Port whole.
+- [../../src/agent-identity.js](../../src/agent-identity.js) — identity fetch logic. Trim to what the bundle needs.
+- [../../src/agent-resolver.js](../../src/agent-resolver.js) — `resolveAgentById`. Port.
+- [../../api/agents/[id]/index.js](../../api/) and [../../api/avatars/](../../api/avatars/) — the endpoints the bundle calls. Must return CORS-permissive headers.
+
+## Goal
+
+Ship `public/artifact.js` — a UMD/IIFE bundle, &lt;150 KB gzipped (three.js excluded), that exposes a global `Agent3D` with a minimal public API and works inside a Claude Artifact sandbox.
+
+## Public API
+
+The bundle MUST expose exactly this surface on the global `Agent3D`:
+
+```js
+Agent3D.mount(target, opts) → Promise<Instance>
+// target: string (CSS selector) | HTMLElement
+// opts: {
+// agentId?: string, // our internal id
+// chain?: string, // 'mainnet' | 'base' | 'sepolia' | etc.
+// onchainId?: string | number, // ERC-8004 agentId — requires chain
+// wallet?: string, // 0x... — resolve the wallet's primary agent
+// glbUrl?: string, // skip identity lookup, just render this GLB
+// background?: 'transparent' | 'dark' | 'light' | '#rrggbb',
+// idle?: boolean, // default true — breathing + head glance loop
+// onReady?: (instance) => void,
+// onError?: (err) => void,
+// }
+//
+// Returns: { dispose(), say(text), emote(name, weight), identity }
+```
+
+- Exactly one of `agentId`, `onchainId`+`chain`, `wallet`, `glbUrl` must be provided.
+- If zero or more than one is provided, render the "replace `AGENT_ID_HERE`" instruction overlay referenced in task 01.
+
+## Deliverable
+
+1. **New directory** `artifact-bundle/` at the repo root with its own `package.json`, `src/index.js`, `rollup.config.js` (or `esbuild.config.js`). This is a separate build pipeline from the main Vite app — its output is `public/artifact.js`, committed, not gitignored, so Vercel serves it statically.
+2. **Build script** wired into the root `package.json` as `npm run build:artifact`. CI-safe (`npm run build` does NOT need to run it — but document clearly in the bundle's README that `build:artifact` must be re-run before shipping changes).
+3. **Port, don't re-depend** — the bundle must not import the full [src/viewer.js](../../src/viewer.js). Extract the render loop + GLB load into `artifact-bundle/src/mini-viewer.js`. The Empathy Layer ([src/agent-avatar.js](../../src/agent-avatar.js)) and protocol ([src/agent-protocol.js](../../src/agent-protocol.js)) can be imported or copy-forwarded — document the choice in the bundle README.
+4. **CORS** — add `Access-Control-Allow-Origin: *` to responses from `/api/agents/:id`, `/api/avatars/:id`, and `/api/agents/:id/resolve` (or whatever the resolver consumes). Verify in [api/_lib/](../../api/_lib/) that CORS middleware exists or add it. Allowed origins MUST include at minimum: `claude.ai`, `*.claude.ai`, `claude.com`, `*.claude.com`, `anthropic.com`, `*.anthropic.com`, or be `*`.
+5. **three.js loading** — inside `mount()`, dynamically inject `<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.min.js">` and the GLTFLoader companion. Wait for `window.THREE`. If already present, skip.
+6. **Output file** — committed at `public/artifact.js`. Vercel serves `/artifact.js` at edge.
+
+## Audit checklist — must handle all of these
+
+- Bundle exposes `window.Agent3D` with exactly the documented public API. No more, no less.
+- Mount can be called multiple times on different targets in the same Artifact.
+- `dispose()` is idempotent and detaches all listeners (mirror the discipline in [../scalability/01-dispose.md](../scalability/01-dispose.md)).
+- three.js is loaded once even if `mount()` is called repeatedly.
+- Bundle size (gzipped, three.js excluded) ≤ 150 KB. Report the actual number.
+- Empathy Layer's per-frame tick is wired into the mini-viewer's render loop — check by logging emotion state briefly during dev.
+- When `agentId` is missing or `AGENT_ID_HERE`, render an instruction overlay inside the target element ("Set `agentId` to an agent — get one at 3dagent.vercel.app").
+- When the GLB fails to load, render a static stand-in avatar (embed a tiny base64 GLB in the bundle OR a CSS silhouette — your call, document it).
+- Errors never throw out of `mount()`; they resolve with `onError(err)` called and the overlay set.
+- No usage of `localStorage` / `sessionStorage` / `IndexedDB` / `document.cookie`. The Artifact sandbox may block these.
+- No `import.meta.url` / Node-style imports. Plain JS output.
+- Bundle is side-effect-free until `Agent3D.mount()` is called.
+
+## ERC-8004 onchain path
+
+- When `opts.onchainId` + `opts.chain` is provided, the bundle calls `GET /api/agents/resolve?chain=CHAIN&id=ID` on our API. That endpoint already exists or must be added — check [../../api/agents/](../../api/agents/). If missing, write a thin serverless function that does an RPC `IdentityRegistry.getAgent()` call via a public RPC URL we already use in [../../src/erc8004/abi.js](../../src/erc8004/abi.js).
+- Do NOT bundle ethers/viem into the Artifact bundle. The RPC call lives server-side; the Artifact just fetches the resolved record as JSON.
+
+## Constraints
+
+- No new runtime deps in the main app.
+- The bundle's build pipeline may use rollup + rollup-plugin-terser (or esbuild). Pick whichever is smaller. Report the choice.
+- Do not edit [src/element.js](../../src/element.js), [src/viewer.js](../../src/viewer.js), [src/agent-avatar.js](../../src/agent-avatar.js), or [src/agent-protocol.js](../../src/agent-protocol.js) in this task except to **add exports** if the bundle needs access. If you cannot avoid a source change, stop and report.
+- Do not add new URL hash params to [src/app.js](../../src/app.js).
+- Do not break `npx vite build` for the main app.
+
+## Verification
+
+1. `node --check` every modified JS file.
+2. `npm run build:artifact` — produces `public/artifact.js`. Report size (raw + gzipped).
+3. `npx vite build` — main app still builds.
+4. `curl -I https://localhost:PORT/api/agents/SOME_ID` (or equivalent) — confirm CORS headers on the endpoints consumed by the bundle.
+5. Serve `public/artifact/index.html` (from task 01) locally — the snippet's script tag resolves, `Agent3D` appears on window, avatar renders.
+6. **Claude Artifact end-to-end** — paste the task-01 snippet into a fresh Claude chat. Describe what rendered.
+7. Try all four `mount()` modes: `agentId`, `onchainId+chain`, `wallet`, `glbUrl`. Describe which work.
+
+## Scope boundaries — do NOT do these
+
+- Do not design the idle animation loop details. Task 03 writes it — just expose a hook.
+- Do not build the example gallery. Task 04.
+- Do not add Claude-specific branding or telemetry.
+- Do not expose `Agent3D.runtime` or chat/LLM features. This bundle is render-only. Chat happens via postMessage in task 04.
+- Do not implement pointer/orbit controls. Artifacts often swallow pointer events; idle-loop-only.
+
+## Reporting
+
+At the end, summarise:
+- `public/artifact.js` size (raw + gzipped).
+- Which files from `src/` were ported vs imported vs rewritten.
+- CORS changes shipped (which endpoints, what headers).
+- Exact sequence of testing in a live Claude Artifact (chat URL optional) and which `mount()` modes worked.
+- Any sandbox surprise (blocked CDN, CORS refusal, CSP block).
+- Any unverified Claude-Artifact assumption the next maintainer should re-check.
diff --git a/prompts/claude-artifact/README.md b/prompts/claude-artifact/README.md
new file mode 100644
index 000000000..f59a879fa
--- /dev/null
+++ b/prompts/claude-artifact/README.md
@@ -0,0 +1,54 @@
+# Claude Artifact embed task prompts
+
+Self-contained prompt files for shipping an embodied 3D Agent avatar as a **Claude.ai Artifact**. Each file is designed to be dropped into a fresh Claude Code session without extra context.
+
+Priority 5 in the overall stack (see [../README.md](../README.md)). Sibling to [../lobehub-embed/](../lobehub-embed/).
+
+## The goal in one paragraph
+
+Claude.ai renders each `html` Artifact in a sandboxed iframe. A Claude user should be able to paste **one short HTML snippet** into chat, open it as an Artifact, and immediately see a live, breathing, embodied agent avatar — fetched either by `agentId` or via an ERC-8004 onchain lookup — with the Empathy Layer running idle. No server changes on Anthropic's end, no install for the user.
+
+## What's the deliverable exactly
+
+Not code. The deliverable for this directory is *prompts* that a future Claude Code session will execute to produce:
+
+1. A copy-pasteable minimal HTML snippet (task 01).
+2. A hosted single-file bundle, `https://3dagent.vercel.app/artifact.js`, that the snippet loads (task 02).
+3. An idle-animation loop so the avatar looks alive in the Artifact viewer — Artifacts often have no pointer input (task 03).
+4. A curated gallery of ready-to-paste templates covering the main use cases (task 04).
+
+## Known Artifact sandbox constraints (VERIFY before shipping)
+
+The tasks below reference these constraints. The author of each task MUST verify via WebFetch against `https://docs.claude.com/en/docs/build-with-claude/artifacts` (and `https://platform.claude.com/docs/...` if redirected) and flag uncertainty in their work.
+
+- Artifacts run in a **sandboxed iframe** — treat it like a hostile environment.
+- CDN `<script src="...">` loading from major CDNs (cdnjs, unpkg, jsdelivr, esm.sh) is expected to work but must be verified per-CDN — start with `cdnjs.cloudflare.com` as the most commonly cited.
+- `fetch()` to external origins is expected to work for CORS-permitted endpoints. Our API at `https://3dagent.vercel.app/api/...` must return permissive CORS. Verify in task 02.
+- `postMessage` to `window.parent` (Claude's chat UI) is expected to work but Claude chat does not listen — postMessage is useful for cross-artifact tricks, not host integration.
+- `localStorage` / `IndexedDB` may be blocked or ephemeral per session. Assume no persistence.
+- No import maps. No Node-style imports. Plain `<script>` only, or `type="module"` with fully-qualified URLs.
+- Pointer / wheel events may be swallowed by Claude's UI chrome — don't depend on drag-orbit.
+- Canvas / WebGL is supported — three.js works.
+
+If any of these turn out to be wrong during implementation, update the affected task file with a footnote.
+
+## Recommended execution order
+
+1. [01-artifact-snippet.md](./01-artifact-snippet.md) — the HTML template. Foundation.
+2. [02-zero-dep-viewer-bundle.md](./02-zero-dep-viewer-bundle.md) — the hosted bundle the snippet pulls. Unblocks 03, 04.
+3. [03-idle-animation-loop.md](./03-idle-animation-loop.md) — breathing + head glance loop. Depends on 02.
+4. [04-example-gallery.md](./04-example-gallery.md) — curated templates. Depends on 01, 02.
+
+## Rules that apply to all tasks
+
+- No new runtime dependencies in the main app (devDeps only if the task needs them for its bundle build).
+- No new docs files (README.md, CLAUDE.md) inside `src/` or `public/` unless the task says so.
+- `node --check` every modified JS file before reporting done.
+- Run `npx vite build` and note whether it breaks. Pre-existing `@avaturn/sdk` resolution warning is unrelated — ignore.
+- The Artifact bundle must stay **tiny** (budget: &lt; 150 KB gzipped for the bundle itself, excluding three.js CDN). Measure and report.
+- No new backend endpoints without CORS. Every endpoint consumed by an Artifact MUST return `Access-Control-Allow-Origin: *` (or a permissive allowlist that includes `claude.ai`, `claude.com`, `*.anthropic.com`).
+- If you discover an unrelated bug, note it in the reporting section. Do not fix it in the same change.
+
+## Reporting
+
+Each task ends with a short report: files created, files edited (which sections), commands run and their output, the exact Artifact test payload pasted into Claude, screenshot / description of what the user saw, any sandbox surprises.
diff --git a/prompts/claude-lobehub/00-README.md b/prompts/claude-lobehub/00-README.md
new file mode 100644
index 000000000..fd481a222
--- /dev/null
+++ b/prompts/claude-lobehub/00-README.md
@@ -0,0 +1,40 @@
+# Band 5 — Claude.ai + LobeHub Integration
+
+## The end state
+
+**Claude.ai / Artifacts**: An MCP tool call returns a self-contained HTML artifact that renders the agent's 3D avatar inline in the Claude conversation. User sees an embodied agent, not a JSON blob.
+
+**LobeHub**: In the user's LobeHub fork (they are the primary integration target), the chat panel has an always-on 3D avatar beside the messages. The avatar:
+- is summoned from an agent id or wallet address
+- reacts to chat events (typing, speaking, emoting)
+- persists across turns in the same session
+- can be swapped by entering a different agent id
+
+The novelty is that *the same agent* renders identically in both hosts, because both pull from the same public URL (band 4) or on-chain record (band 6).
+
+## Current state
+
+- `render_avatar` MCP tool exists (`api/mcp.js`) and returns a `<model-viewer>` HTML string. Claude Artifacts accept HTML, so this is 80% there — needs art direction: must be self-contained, no external writes, correct sandbox posture.
+- LobeHub is the user's fork. We don't own it — the deliverable is a plugin / component that drops into it.
+- Agent protocol (`src/agent-protocol.js`) and the Empathy Layer (`src/agent-avatar.js`) exist — these emit/consume events. LobeHub integration wires chat events into the protocol.
+
+## Prompts in this band
+
+| # | File | Depends on |
+|---|---|---|
+| 01 | [claude-artifact.md](./01-claude-artifact.md) | band 4 public embed solid |
+| 02 | [lobehub-plugin-scaffold.md](./02-lobehub-plugin-scaffold.md) | — |
+| 03 | [lobehub-chat-bridge.md](./03-lobehub-chat-bridge.md) | 02 |
+| 04 | [agent-from-url-or-id.md](./04-agent-from-url-or-id.md) | 02 |
+
+## Done = merged when
+
+- In Claude.ai, invoking `render_avatar` opens an Artifact that shows the avatar interactively — no blank frame, no broken fonts, no external auth required.
+- In the user's LobeHub fork, opening a chat shows a persistent avatar pane; typing in chat triggers a subtle emotion response; changing the agent id in a config field swaps the avatar without reloading the page.
+- Both hosts render the **same** avatar from a shared agent id and look ~identical.
+
+## Off-limits for this band
+
+- Don't fork LobeHub in our repo. Ship a plugin / component they can drop in.
+- Don't build a generic `<agent-3d>` web component here if one already exists — extend it.
+- Don't wire on-chain resolution here — band 6 owns that. Use URL / id-based resolution for now.
diff --git a/prompts/cz-demo/01-preregister-cz-onchain.md b/prompts/cz-demo/01-preregister-cz-onchain.md
new file mode 100644
index 000000000..0f99b8989
--- /dev/null
+++ b/prompts/cz-demo/01-preregister-cz-onchain.md
@@ -0,0 +1,88 @@
+# Task 01 — Pre-register the CZ agent onchain
+
+## Why this exists
+
+Before the demo, the CZ agent must already exist as an onchain record on Base Sepolia (or mainnet, depending on the call made in this task). "Existing onchain" = a row in `IdentityRegistry.agents` with a known `agentId`, a metadata URI pointing to the registration JSON (IPFS), and either `owner = 0x0` (claimable) or `owner = us` (transferable). This is the anchor every other CZ-demo task depends on.
+
+## Shared context
+
+- Contracts: [contracts/src/IdentityRegistry.sol](../../contracts/src/IdentityRegistry.sol), deploy script [contracts/script/Deploy.s.sol](../../contracts/script/Deploy.s.sol). Foundry project.
+- Registration helpers (client-side, used today for user flows): [src/erc8004/agent-registry.js](../../src/erc8004/agent-registry.js) — functions `registerAgent`, `buildRegistrationJSON`, `pinToIPFS`.
+- Canonical CZ avatar: [public/avatars/cz.glb](../../public/avatars/cz.glb) — already in repo. Do **not** regenerate.
+- Known addresses in [src/erc8004/abi.js](../../src/erc8004/abi.js) under `REGISTRY_DEPLOYMENTS`. If Base Sepolia is not in there, [onchain/01-deploy-identityregistry-base-sepolia.md](../onchain/01-deploy-identityregistry-base-sepolia.md) deploys it — run that task first.
+- IPFS: [src/ipfs.js](../../src/ipfs.js) handles gateway resolution. Pinning uses web3.storage / Filebase tokens from env.
+
+## What to build
+
+### 1. Registration JSON for the CZ agent
+
+Create `scripts/cz-demo/registration-cz.json` (committed, not generated). Shape:
+
+```json
+{
+ "type": "agent-registration/0.1",
+ "name": "CZ",
+ "description": "Test agent for the CZ demo — the canonical embodied agent for demonstrating portable onchain identity.",
+ "body": {
+ "uri": "https://3d.irish/avatars/cz.glb",
+ "format": "glb"
+ },
+ "brain": { "provider": "anthropic", "model": "claude-opus-4-6" },
+ "skills": ["greet", "present-model", "validate-model", "remember", "think", "sign-action"],
+ "owner": "0x0000000000000000000000000000000000000000",
+ "createdAt": "2026-04-15T00:00:00Z",
+ "demo": { "slug": "cz" }
+}
+```
+
+`owner: 0x0` signals "claimable." If the contract requires a non-zero owner at register-time, set it to a disposable ops-owned EOA and have task 03 do a `transferOwner` call instead.
+
+### 2. Pin to IPFS script
+
+Create `scripts/cz-demo/pin-registration.mjs`:
+
+- Read `registration-cz.json`.
+- Read `WEB3_STORAGE_TOKEN` (or `FILEBASE_TOKEN`) from env.
+- Pin via `src/ipfs.js` helpers or a minimal in-script HTTP call. Output the returned CID to stdout.
+- Verify by fetching `https://ipfs.io/ipfs/{cid}` and diffing against the source JSON.
+- Save `{ cid, pinned_at }` into `scripts/cz-demo/.state.json` (gitignored) so follow-up scripts can read it.
+
+### 3. Register onchain script
+
+Create `scripts/cz-demo/register-onchain.mjs`:
+
+- Read `CHAIN_ID` (default `84532` for Base Sepolia) and `DEPLOYER_PRIVATE_KEY` from env. Document both in `scripts/cz-demo/README.md`.
+- Use `viem` (`createWalletClient`, `http` transport with `Base Sepolia` chain from `viem/chains`).
+- Read CID from `.state.json`.
+- Call `IdentityRegistry.registerAgent(owner, metadataURI)` with `metadataURI = "ipfs://{cid}"` and `owner` per step 1's decision.
+- Wait for receipt. Extract the emitted `AgentRegistered(agentId, owner, metadataURI)` event. Parse `agentId`.
+- Append `{ chainId, agentId, txHash, registeredAt }` into `.state.json`.
+- Print the human-facing URL: `https://3d.irish/agent/chain/{chainId}/{agentId}` (this route ships in [onchain/04-chain-hydrate-route.md](../onchain/04-chain-hydrate-route.md)).
+
+### 4. Publish the CZ identity locally
+
+Add an `agent_identities` row with `erc8004_agent_id = {agentId}`, `erc8004_registry = {address}`, `registration_cid = {cid}`, `avatar_id` pointing to the `cz` avatar record, `meta.demo = "cz"`. Do this via a one-shot SQL file `scripts/cz-demo/insert-local-row.sql` that the operator runs explicitly.
+
+This local row lets `/api/agents/me` resolve a server-side record for the demo even before the chain-hydrate path ships.
+
+## Files you own
+
+- Create: `scripts/cz-demo/registration-cz.json`, `scripts/cz-demo/pin-registration.mjs`, `scripts/cz-demo/register-onchain.mjs`, `scripts/cz-demo/insert-local-row.sql`, `scripts/cz-demo/README.md` (operator runbook), `.gitignore` addition for `scripts/cz-demo/.state.json`
+
+## Files off-limits
+
+- The contracts themselves — do not edit. If the contract interface doesn't match the `registerAgent(owner, metadataURI)` call, stop and report.
+- `src/erc8004/*` — may be used as libraries from your scripts, but don't modify.
+- Any deployment of contracts — that's [onchain/01-deploy-identityregistry-base-sepolia.md](../onchain/01-deploy-identityregistry-base-sepolia.md).
+
+## Acceptance test
+
+1. Run `node scripts/cz-demo/pin-registration.mjs` — prints a CID, `.state.json` updated.
+2. Run `node scripts/cz-demo/register-onchain.mjs` — prints agentId + tx hash, `.state.json` updated with them.
+3. Check the tx on Basescan — event `AgentRegistered` emitted with the expected metadata URI.
+4. Fetch `ipfs://{cid}` via any public gateway — contents match `registration-cz.json` byte-for-byte (ordering may differ if pinning re-serializes — normalize both with `JSON.stringify(JSON.parse(...))` before diff).
+5. Load [onchain/04-chain-hydrate-route.md](../onchain/04-chain-hydrate-route.md)'s route (if shipped) at `/agent/chain/84532/{agentId}` — avatar loads.
+
+## Reporting
+
+Report: `agentId` minted, `txHash`, CID, gas used, chain + contract address used, whether `owner` ended up as `0x0` or an EOA (and why), operator-runbook summary.
diff --git a/prompts/cz-demo/README.md b/prompts/cz-demo/README.md
new file mode 100644
index 000000000..c02d353ec
--- /dev/null
+++ b/prompts/cz-demo/README.md
@@ -0,0 +1,38 @@
+# CZ demo — the ship target
+
+The north star for the current build cycle: **CZ (or any notable guest) interacts with their own embodied 3D agent, and it's onchain, and it's embedded inside a host app they already use.** Everything in [wallet-auth/](../wallet-auth/), [selfie-agent/](../selfie-agent/), [onchain/](../onchain/), [lobehub-embed/](../lobehub-embed/), and [claude-artifact/](../claude-artifact/) rolls up here.
+
+## The demo, in one paragraph
+
+CZ opens a link. He sees a 3D CZ avatar standing in a scene — pre-registered onchain on Base Sepolia by us before the demo. A "This is your agent. Claim it." panel appears. He connects his wallet, signs a SIWE message, the agent's `owner` field flips to his address via a signed claim tx. He now opens his LobeHub fork (or a page we host that embeds LobeHub), and the CZ-agent is in the chat sidebar — not as JSON, as a visible, emoting 3D body that reacts to his messages. He types; the Empathy Layer responds. He speaks; it lip-syncs. It's the same agent from onchain. Portable.
+
+## What's load-bearing for this demo
+
+| Block | Must work | Nice-to-have |
+|---|---|---|
+| Wallet auth | SIWE login end-to-end, no 500s, session survives reload | Multi-chain, ENS display |
+| Selfie → agent | Skip for CZ demo — `cz.glb` is pre-made | Generic users can do it post-demo |
+| Edit avatar | Skip for CZ demo | Post-demo for users |
+| Onchain | `cz.glb` registered on Base Sepolia before the event; "Claim" button flips owner via user-signed tx | ENS reverse resolution on-chain records |
+| Embed in LobeHub | CZ agent renders inside a LobeHub chat message/sidebar, receives `speak` events from the chat, emits `skill-done` events back | Native LobeHub plugin (not just an iframe) |
+| Empathy + voice | Avatar visibly reacts (smiles, nods, tilts) to his messages; optional TTS on agent responses | Lip sync |
+
+## Prompts in this set
+
+| # | File | Ships |
+|---|---|---|
+| 01 | [01-preregister-cz-onchain.md](./01-preregister-cz-onchain.md) | Script + one-time deploy action that mints the CZ agent onchain on Base Sepolia with a known `agentId`, metadata URI on IPFS, `cz.glb` in the registration JSON. |
+| 02 | [02-cz-landing-page.md](./02-cz-landing-page.md) | Bespoke `/cz` route — dark theme, shows the pre-registered CZ agent, "Claim your agent" CTA, post-claim confetti state. |
+| 03 | [03-claim-transfer-flow.md](./03-claim-transfer-flow.md) | Onchain ownership transfer: current owner (us) signs a pre-authorized transfer that CZ's wallet can consume in one click. Or pre-registered agent has `owner = 0x0` and CZ's claim is a first-time `setOwner` call. Task decides the pattern. |
+| 04 | [04-lobehub-embed-drop-in.md](./04-lobehub-embed-drop-in.md) | Instructions + code for dropping the agent embed into your LobeHub fork's chat message renderer, hydrated from chain by `chainId + agentId`. |
+| 05 | [05-demo-script-and-fallbacks.md](./05-demo-script-and-fallbacks.md) | Live-demo runbook: what to have loaded ahead of time, failure modes, kill-switch if the chain RPC flaps, air-gapped fallback. |
+
+## Run order
+
+01 is the dependency root — without the onchain record, nothing else renders "real." 02 + 04 can run in parallel after 01. 03 depends on 01 + the wallet-auth / onchain passport work. 05 is written last, once the flow is working end-to-end.
+
+## Hard constraints
+
+- Demo must survive **zero internet** for at least 5 seconds of the flow. Cache the avatar GLB and identity JSON in a service worker before the demo starts; read-on-chain should be resilient to RPC hiccups.
+- The claim tx uses a user-pays gas model on Base Sepolia. Pre-fund CZ's address with ~0.005 ETH testnet ETH if there's any doubt he has it, or sponsor it via a paymaster. Task 03 covers this decision.
+- No secrets in prompt files. The pre-register script reads from env.
diff --git a/prompts/embed/04-public-agent-page.md b/prompts/embed/04-public-agent-page.md
new file mode 100644
index 000000000..98b80d285
--- /dev/null
+++ b/prompts/embed/04-public-agent-page.md
@@ -0,0 +1,63 @@
+# 04 — Public `/agent/:id` page polish
+
+## Why it matters
+
+This is the canonical URL a user shares when they want the world to see their agent. It needs to load fast, render confidently, and expose "how to embed" without burying it.
+
+## Context
+
+- Current page: [public/agent/index.html](../../public/agent/index.html), [public/agent/embed.html](../../public/agent/embed.html).
+- Metadata: [api/agent-og.js](../../api/agent-og.js), [api/agent-oembed.js](../../api/agent-oembed.js).
+- URL scheme: `/agent/:id` → renders the agent. The id is a UUID owned by `agent_identities`.
+
+## What to build
+
+### Metadata
+
+- `<title>` — "{{name}} · 3D Agent".
+- `<meta name="description">` — agent's description or fallback.
+- Open Graph + Twitter card: image (OG endpoint), URL, title, description. See existing `api/agent-og.js`.
+
+### Above-the-fold
+
+- Viewer canvas takes the full viewport on mobile, 70% on desktop.
+- Below: the agent name + a 2-line description + three compact action buttons:
+ - **Chat** — opens the Nich agent chat drawer.
+ - **Embed** — opens a modal with an iframe snippet and `<agent-3d id="…">` snippet.
+ - **Share** — uses `navigator.share` if available, else copies the page URL.
+- Owner-only: a "Manage" button linking to the edit panel.
+
+### Embed modal content
+
+```html
+<script src="https://3dagent.vercel.app/dist/lib.js" defer></script>
+<agent-3d id="{{agentId}}" style="width:100%; height:500px"></agent-3d>
+```
+
+Plus iframe fallback:
+
+```html
+<iframe src="https://3dagent.vercel.app/agent/{{agentId}}?kiosk=1" width="100%" height="500" allow="accelerometer; gyroscope; camera" style="border:0"></iframe>
+```
+
+Copy-to-clipboard buttons for each.
+
+### Not-found
+
+- Unknown `:id` → render "Agent not found" card with a link back to `/`. Do NOT serve default CZ avatar.
+
+## Out of scope
+
+- Comments / reactions.
+- Follow system.
+- Sharing to specific platforms (Twitter share link).
+- Auth-gated views of private agents — all `/agent/:id` are public in v1.
+
+## Acceptance
+
+1. Open `/agent/<valid-id>` on mobile and desktop → loads within 2s, renders correctly.
+2. Share modal copies the page URL.
+3. Embed modal snippets paste + render correctly on a blank `.html` scratchpad.
+4. Open graph meta renders in a Slack / Twitter preview (verify via Twitter card validator or visual paste).
+5. `/agent/<unknown-id>` → not-found card.
+6. `npx vite build` passes.
diff --git a/prompts/embed/05-agent3d-element-docs.md b/prompts/embed/05-agent3d-element-docs.md
new file mode 100644
index 000000000..902f9984e
--- /dev/null
+++ b/prompts/embed/05-agent3d-element-docs.md
@@ -0,0 +1,53 @@
+# 05 — `<agent-3d>` element attribute docs + defaults audit
+
+## Why it matters
+
+`<agent-3d>` is the public embed primitive. A partner (Lobehub, Claude artifact) needs to be able to paste it with zero ceremony and have it just work. Today the attribute surface is scattered across [src/element.js](../../src/element.js) and implicit defaults — making integration error-prone.
+
+## Context
+
+- Element source: [src/element.js](../../src/element.js).
+- Spec doc: [specs/EMBED_SPEC.md](../../specs/EMBED_SPEC.md) (already exists — update, don't replace).
+- Existing attributes include: `agent-id`, `model`, `eager`, `kiosk`, `brain`, `proxy-url`, likely others.
+
+## What to build
+
+### Attribute audit
+
+Read [src/element.js](../../src/element.js) + [specs/EMBED_SPEC.md](../../specs/EMBED_SPEC.md). List every attribute the element reads. For each:
+- Name (kebab-case as attribute, camelCase as property).
+- Accepted values + type.
+- Default when absent.
+- Whether it can change after mount (`attributeChangedCallback`).
+
+### Spec update
+
+Rewrite the attribute table in [specs/EMBED_SPEC.md](../../specs/EMBED_SPEC.md). Add these sections if missing:
+- **Loading** — `eager` vs IntersectionObserver lazy-load.
+- **Kiosk vs interactive** — `kiosk` hides all chrome.
+- **Brain** — `brain="none"` (pattern match) vs `brain="anthropic"` + `proxy-url`.
+- **Sizing** — must set `width`/`height` via CSS; the element does not size itself.
+- **CSP** — required `connect-src` entries when the host enforces CSP.
+
+### Defaults alignment
+
+Check that `element.js` defaults match the spec. Fix mismatches by updating the code to match the spec (the spec is the contract). Do NOT fix the spec to match the code unless the code's default is obviously more correct — flag it in your report if you do.
+
+### Example gallery
+
+Add two new worked examples to [specs/EMBED_SPEC.md](../../specs/EMBED_SPEC.md):
+- Minimum embed (just `agent-id`).
+- Kiosk with a custom brain proxy.
+
+## Out of scope
+
+- New attributes (those need a separate spec change).
+- Runtime changes to the brain/runtime loop.
+- React/Vue wrappers.
+
+## Acceptance
+
+- Every attribute in the code is documented in the spec and vice versa.
+- Spec's default values match the code.
+- The two new examples paste + work on a blank HTML scratchpad.
+- `node --check src/element.js` passes. `npx vite build` passes.
diff --git a/prompts/embed/06-iframe-sandbox.md b/prompts/embed/06-iframe-sandbox.md
new file mode 100644
index 000000000..df1d2826e
--- /dev/null
+++ b/prompts/embed/06-iframe-sandbox.md
@@ -0,0 +1,52 @@
+# 06 — iframe sandbox + CSP fixes for host embeds
+
+## Why it matters
+
+Claude artifacts and many other host environments iframe-embed with `sandbox` attributes. Our agent must still work inside a sandboxed frame with no escalation tricks — microphone access, `localStorage`, `postMessage` to parent, and WebGL all need to degrade gracefully.
+
+## Context
+
+- Entry point for embed: [public/agent/embed.html](../../public/agent/embed.html).
+- CSP: defined in [vercel.json](../../vercel.json) headers.
+- Postmessage protocol (for host bidirectional): landing in `prompts/lobehub-embed/02-postmessage-protocol.md`.
+
+## What to build
+
+### Sandbox-safe boot
+
+In the embed entry script:
+1. Detect `window.top !== window.self && sandbox attribute present`.
+2. If `localStorage` is blocked (DOMException on write) → fall back to `sessionStorage`.
+3. If `sessionStorage` is also blocked → memory-only identity (no persistence).
+4. If `getUserMedia` not granted → hide any UI that depends on it (avatar creator's selfie option).
+5. If WebGL 2 unavailable → render a static poster image (use the avatar thumbnail from the manifest).
+
+### CSP audit
+
+Document required CSP:
+```
+default-src 'self' https://3dagent.vercel.app;
+img-src 'self' data: blob: https:;
+media-src 'self' blob:;
+connect-src 'self' https://api.anthropic.com https://*.infura.io https://*.alchemyapi.io https://ipfs.io https://dweb.link https://cloudflare-ipfs.com;
+script-src 'self' 'wasm-unsafe-eval';
+```
+
+Add a section to [specs/EMBED_SPEC.md](../../specs/EMBED_SPEC.md) listing these so host integrators know what to allowlist.
+
+### Kiosk auto-detection
+
+If inside an iframe AND hostname is not the main `3dagent.vercel.app` → default to `kiosk=1` behavior regardless of URL param. Allow host to override with `kiosk=0`.
+
+## Out of scope
+
+- Wildcard CSP relaxations.
+- Post-message API (next prompt in lobehub series).
+- Camera passthrough from host.
+
+## Acceptance
+
+1. Embed the `/agent/:id` URL in a blank `.html` file with `<iframe sandbox="allow-scripts allow-same-origin">` → renders, no console CSP errors.
+2. With `sandbox="allow-scripts"` only (no same-origin) → renders in memory-only mode, no localStorage errors.
+3. The agent's selfie option is hidden when `getUserMedia` is unavailable.
+4. `npx vite build` passes. Manual test documented in the report.
diff --git a/prompts/lobehub-embed/01-plugin-manifest.md b/prompts/lobehub-embed/01-plugin-manifest.md
new file mode 100644
index 000000000..8b3234fc5
--- /dev/null
+++ b/prompts/lobehub-embed/01-plugin-manifest.md
@@ -0,0 +1,80 @@
+# Task 01 — LobeHub plugin manifest for 3D Agent
+
+## Context
+
+Repo: `/workspaces/3D`. LobeHub is the primary host-integration target (see [series README](./README.md)). A LobeHub plugin is defined by a JSON manifest that LobeHub's plugin loader fetches from a public URL. The manifest declares:
+
+- Plugin identity (name, author, homepage, version, description, tags)
+- The UI surface — an iframe URL that LobeHub renders inside a chat message
+- Optional API surface — tool schemas the chat model can call
+
+Our iframe page already exists: [public/agent/embed.html](../../public/agent/embed.html). It renders a GLB avatar, attaches [AgentAvatar](../../src/agent-avatar.js) (the Empathy Layer), and exposes a `postMessage` bridge. This task wraps it into a LobeHub-compatible plugin.
+
+We already publish an A2A-style card at `.well-known/agent-card.json` ([agent-card.json](../../public/.well-known/agent-card.json)) which enumerates the skills we expose. Do **not** assume LobeHub auto-consumes that — the plugin manifest is a separate format.
+
+## Goal
+
+Produce a LobeHub plugin manifest, hosted at a stable public URL under this deployment, that lets any LobeHub instance install the 3D Agent plugin and get an embodied avatar in chat.
+
+## Deliverable
+
+1. **Manifest file** at `public/.well-known/lobehub-plugin.json` (served at `https://<host>/.well-known/lobehub-plugin.json`) that declares:
+ - `identifier` — kebab-case, e.g. `3d-agent`
+ - `meta` — `{ title, description, avatar, tags }`
+ - `author`, `homepage`, `version` (read from `package.json`'s version at build if trivial; otherwise hard-code `0.1.0` and note)
+ - `ui.url` — absolute URL to our iframe (e.g. `https://<host>/agent/{AGENT_ID}/embed?host=lobehub`). Use a placeholder token if LobeHub supports runtime interpolation; otherwise require the user to edit.
+ - `ui.height` — default iframe height (e.g. `520`)
+ - `api` — tool schemas the chat model can call, each with `name`, `description`, `parameters` (JSON Schema). Start with:
+ - `render_agent({ agentId })` — mount the avatar for a given agent id
+ - `speak({ text, sentiment? })` — make the avatar speak with emotional valence
+ - `gesture({ name, duration? })` — trigger a named gesture (wave, nod, point, shrug)
+ - `emote({ trigger, weight? })` — inject an emotion (`concern`, `celebration`, `patience`, `curiosity`, `empathy`)
+ - `systemRole` — optional priming text so the LobeHub chat model knows an embodied agent is present
+2. **Vercel route** — add a route to `vercel.json` that serves the manifest with `Content-Type: application/json` and `Cache-Control: public, max-age=300`. Place the route in the existing `.well-known/*` block if present; otherwise add it grouped with other well-known entries.
+3. **Served copy for discovery** — if LobeHub reads from `.well-known/` specifically, no extra work. If not, also link it from the top of `.well-known/agent-card.json` via a non-breaking `lobehub_plugin_url` field.
+
+## Audit checklist
+
+- `identifier` must be URL-safe, lowercase, stable — do **not** regenerate per request
+- Every `api.*.parameters` JSON Schema must validate with a standard validator (`ajv`) — test this mentally, don't ship broken schemas
+- `ui.url` must resolve to the embed page, not the top-level agent page. The embed page handles transparent-bg and hides UI chrome.
+- The manifest must be a static JSON file — no runtime generation. LobeHub may cache it aggressively.
+- `tags` include: `3d`, `avatar`, `agent`, `embodied`, `empathy`, `erc-8004`
+- If the LobeHub spec requires a field we're unsure about (e.g. `openapi` link vs. inline `api` array, `locale` mapping), **flag it in a top-of-file comment** with "// TODO(lobehub-spec): confirm against https://lobehub.com/docs/usage/plugins/development" rather than guessing.
+
+## Constraints
+
+- **No new runtime dependencies.** The manifest is static JSON.
+- Do **not** hard-code a specific agent id. The plugin is generic; per-agent binding happens via the handshake (see [02-iframe-handshake.md](./02-iframe-handshake.md)).
+- Do **not** disable the Empathy Layer in the embed. The plugin's whole value is embodied emotion.
+- Keep the manifest small — LobeHub will render its description in its plugin marketplace UI.
+
+## Verification
+
+1. `node --check` is not applicable (JSON). Run `node -e "JSON.parse(require('fs').readFileSync('public/.well-known/lobehub-plugin.json','utf8'))"` to confirm parseable.
+2. `npx vite build` succeeds and copies the file to `dist/.well-known/lobehub-plugin.json`.
+3. `curl -I https://localhost:5173/.well-known/lobehub-plugin.json` (or deployed URL) returns `Content-Type: application/json`.
+4. Load it in a LobeHub dev instance — see [05-plugin-submission.md](./05-plugin-submission.md) for the full flow. For this task, you may stop at schema validity.
+5. `ajv validate` each `api.*.parameters` against its own schema with a sample payload.
+
+## Scope boundaries — do NOT do these
+
+- Do **not** implement the `postMessage` handshake inside the embed. That is task [02](./02-iframe-handshake.md).
+- Do **not** implement host auth. That is task [03](./03-host-auth-handoff.md).
+- Do **not** wire the tool-call relay. That is task [04](./04-action-passthrough.md).
+- Do **not** package or submit to the marketplace. That is task [05](./05-plugin-submission.md).
+- Do **not** modify [src/element.js](../../src/element.js) — that is the browser-native web component, unrelated to LobeHub plugin surface.
+
+## Files off-limits
+
+- [public/agent/embed.html](../../public/agent/embed.html) — task 02 owns the handshake code inside it
+- `public/.well-known/agent-card.json` — only add the non-breaking `lobehub_plugin_url` field if explicitly needed; do not restructure
+
+## Reporting
+
+- Path + line count of the manifest file
+- The vercel route block added (verbatim)
+- Any field you flagged as "confirm against current LobeHub docs" — enumerate each
+- `ajv` results for each tool parameter schema
+- Whether `vite build` copies `.well-known/` to `dist/` (it should; if not, flag it)
+- Any unrelated bugs noticed — note, don't fix
diff --git a/prompts/lobehub-embed/02-iframe-handshake.md b/prompts/lobehub-embed/02-iframe-handshake.md
new file mode 100644
index 000000000..b5f5584bb
--- /dev/null
+++ b/prompts/lobehub-embed/02-iframe-handshake.md
@@ -0,0 +1,109 @@
+# Task 02 — iframe ↔ LobeHub `postMessage` handshake
+
+## Context
+
+Repo: `/workspaces/3D`. The file [public/agent/embed.html](../../public/agent/embed.html) is the iframe page LobeHub will load inside a chat message (see [01-plugin-manifest.md](./01-plugin-manifest.md)). Today it already:
+
+- Resolves `agent-id` from the URL path (`/agent/:id/embed`)
+- Runs the embed policy check (`/api/agents/:id/embed-policy`)
+- Builds a `Viewer` and attaches [AgentAvatar](../../src/agent-avatar.js)
+- Listens for `{ __agent, type: 'action', action }` messages and relays them to [agent-protocol](../../src/agent-protocol.js)
+- Posts a `{ type: 'ready' }` back to parent on boot
+
+This is a bare bridge. LobeHub needs a richer, versioned protocol: an explicit **init handshake** (so the host can bind the iframe to an agent id it owns), bidirectional action relay, resize events (so the chat message box grows/shrinks with the avatar), and a structured error surface.
+
+This task is the entire `postMessage` layer. It must not regress the existing query-param path (people already embed via `?bg=dark` etc.).
+
+## Goal
+
+Replace the ad-hoc bridge with a versioned, typed, bidirectional protocol between the LobeHub host frame and our embed. Protocol is JSON-over-`postMessage`, namespaced so it coexists with other bridges.
+
+## Deliverable
+
+1. **Protocol module** — new file `src/embed-host-bridge.js`. Pure JS, no runtime deps. Exports a class `EmbedHostBridge` with:
+ - Constructor: `new EmbedHostBridge({ protocol, identity, viewer, avatarCtl, agentId })`
+ - `attach()` — starts listening for host messages, posts `hello`
+ - `detach()` — removes listeners
+ - `postToHost(type, payload)` — envelope helper
+ - Internal event vocabulary below
+2. **Edit embed page** — [public/agent/embed.html](../../public/agent/embed.html) imports the bridge and replaces the inline `window.addEventListener('message', ...)` block. The existing `ready`/`blocked` posts should be routed through the bridge.
+3. **Version** — first line of every envelope: `{ v: 1, ns: '3d-agent', ... }`. Reject unknown `v`.
+
+## Event vocabulary
+
+All messages are JSON objects. Outbound (embed → host) and inbound (host → embed) share the envelope `{ v: 1, ns: '3d-agent', type, id?, payload }`. Replies echo the inbound `id`.
+
+### Inbound (host → embed)
+
+| type | payload | effect |
+|---|---|---|
+| `host:hello` | `{ hostName, hostVersion, capabilities: string[] }` | Handshake. Embed replies with `embed:hello` including its capability list. |
+| `host:set-agent` | `{ agentId }` | Rebind to a different agent id. Tear down current avatar, resolve new one, boot. |
+| `host:action` | `{ action: { type, payload, sourceSkill? } }` | Emit on `protocol`. Covered in full in [04-action-passthrough.md](./04-action-passthrough.md); for this task, keep the existing relay wrapped in the new envelope. |
+| `host:pause` | `{}` | Call `viewer.pause?.()` or stop RAF. |
+| `host:resume` | `{}` | Resume viewer. |
+| `host:theme` | `{ mode: 'dark' \| 'light' \| 'transparent', accent? }` | Apply background + accent without reload. |
+| `host:ping` | `{}` | Reply with `embed:pong`. Used by host to detect stale iframes. |
+
+### Outbound (embed → host)
+
+| type | payload | when |
+|---|---|---|
+| `embed:hello` | `{ embedVersion, agentId, capabilities }` | On `host:hello` or first post after DOM ready |
+| `embed:ready` | `{ agentId, name, avatarUrl }` | Avatar GLB loaded, `AgentAvatar` attached |
+| `embed:blocked` | `{ reason: 'policy' }` | Embed-policy check failed |
+| `embed:error` | `{ code, message, phase }` | Any boot or runtime error (phases: `policy`, `identity`, `avatar`, `viewer`, `bridge`) |
+| `embed:action` | `{ action: { type, payload, sourceSkill, timestamp, agentId } }` | Mirrors every `protocol` event outward so the host can log what the avatar did. Filter to protocol's `ACTION_TYPES` only. |
+| `embed:resize` | `{ width, height, contentHeight }` | When the viewer reports a new content height (e.g. name plate grew, error shown) |
+| `embed:pong` | `{}` | Reply to `host:ping` |
+
+## Audit checklist
+
+- **Origin discipline.** Reject inbound messages whose `event.origin` is not one of: same-origin, the origin passed via `?host=<encoded-origin>` URL param, or (if unset) any origin but with a console warn flag. **Never** trust `event.data` blindly.
+- **Envelope validation.** Drop any message without `v === 1`, missing `ns === '3d-agent'`, or missing `type`. Do not throw — just return.
+- **Id correlation.** If inbound carries an `id`, the reply must echo it.
+- **No duplicate listeners.** If `attach()` is called twice, the second call must be a no-op or cleanly replace.
+- **Teardown.** `detach()` must remove every `window.addEventListener('message', ...)` registered, cancel any pending `resize` `ResizeObserver`, and null internal refs.
+- **ResizeObserver** on the stage element feeds `embed:resize`. Debounce to ~100ms so a drag doesn't flood the host.
+- **Action filter.** `embed:action` must not mirror `host:action` back out — that would create a loop. Tag host-originated emits with `sourceSkill: 'host'` (or a marker) and filter.
+- **Backward compat.** The legacy `{ __agent: agentId, type: 'action', action }` format used by existing embedders must continue to work for at least one version. Accept both; deprecate-log the legacy form.
+- **Preserve Empathy Layer.** Every `host:action` with `type: 'speak'` must still hit [agent-protocol](../../src/agent-protocol.js) so emotion blending runs. Do not shortcut to `viewer.speak()` or similar.
+
+## Constraints
+
+- No new runtime deps.
+- Pure ES module, importable by the embed page via `<script type="module">`.
+- All console logs tagged `[3d-agent:bridge]` for filter-ability.
+- If a LobeHub-specific field differs from the spec here (e.g. LobeHub posts `{type: 'tool_call'}` not wrapped in our envelope), flag it with `// TODO(lobehub-spec): confirm` — **do not** auto-adapt by guessing.
+
+## Verification
+
+1. `node --check src/embed-host-bridge.js public/agent/embed.html` (embed.html won't parse as JS, but run `node --check` on the bridge module).
+2. `npx vite build` succeeds.
+3. Manual — open `public/agent/:id/embed?preview=1` at top-level. In devtools, confirm no host-bridge errors fire when there is no parent (the embed should still work standalone).
+4. Write a tiny ad-hoc `test-host.html` (do **not** commit it) that iframes `/agent/:id/embed` and posts each inbound message type. Observe replies. Take a screenshot for the report.
+5. Confirm `embed:action` mirrors every `speak`/`gesture`/`emote` etc. in the parent's message log.
+6. Trigger a fake policy block and confirm `embed:blocked` fires with correct envelope.
+
+## Scope boundaries — do NOT do these
+
+- Do **not** implement host-auth/SIWE. That is [03](./03-host-auth-handoff.md).
+- Do **not** add tool-call semantics. That is [04](./04-action-passthrough.md). The handshake carries raw `action` objects; meaning-mapping lives elsewhere.
+- Do **not** touch the plugin manifest. That is [01](./01-plugin-manifest.md).
+- Do **not** refactor [src/element.js](../../src/element.js) — the web component has its own surface.
+- Do **not** change the embed-policy flow in `checkPolicy()`.
+
+## Files off-limits
+
+- `public/.well-known/lobehub-plugin.json` — owned by [01](./01-plugin-manifest.md)
+- `api/agents/[id]/embed-policy.js` — settled, do not touch
+
+## Reporting
+
+- New file `src/embed-host-bridge.js` — line count, exported symbols
+- Edits to `public/agent/embed.html` — which block was replaced, line count delta
+- All `TODO(lobehub-spec)` flags, enumerated verbatim
+- `node --check` + `vite build` results
+- Manual handshake-test screenshot or console log dump
+- Whether backward compat with legacy `{ __agent, type: 'action' }` is preserved (yes/no + how verified)
+- Any unrelated bugs noticed in `embed.html` — note, don't fix
diff --git a/prompts/lobehub-embed/03-host-auth-handoff.md b/prompts/lobehub-embed/03-host-auth-handoff.md
new file mode 100644
index 000000000..561facb0d
--- /dev/null
+++ b/prompts/lobehub-embed/03-host-auth-handoff.md
@@ -0,0 +1,91 @@
+# Task 03 — host auth handoff (LobeHub user → agent viewer)
+
+## Context
+
+Repo: `/workspaces/3D`. When a LobeHub user loads a chat with our plugin, the embedded iframe needs to know **who** is viewing so the avatar can behave as "their" agent (use their wallet-linked identity, read their own memory namespace, etc.). LobeHub provides user-identity context in its host; we need to consume it across the iframe boundary safely.
+
+Parallel context:
+
+- The `postMessage` handshake — see [02-iframe-handshake.md](./02-iframe-handshake.md) — already carries `host:hello` with a capabilities list.
+- Wallet auth today uses SIWE inside our own pages; see [src/erc8004/](../../src/erc8004/) and the top-level `wallet-auth` prompt series.
+- [AgentIdentity](../../src/agent-identity.js) is the record layer — `walletAddress`, memory namespace, signed-action diary.
+
+Important: LobeHub user ≠ wallet. A LobeHub user may or may not have a wallet linked. The embed must work for **anonymous** viewers (no identity known) and **authenticated** viewers (LobeHub user id only) and **wallet-linked** viewers (SIWE-completed) — with a smooth upgrade path between them.
+
+## Goal
+
+Define and implement the three-tier viewer identity handoff inside the embed, and a minimal opt-in SIWE-on-open flow so a LobeHub viewer can link their wallet without leaving the chat.
+
+## Deliverable
+
+1. **Extend the handshake** in `src/embed-host-bridge.js` (created in [02](./02-iframe-handshake.md)) with two new envelope types:
+ - Inbound: `host:identity` — `{ hostUserId, hostUserName?, hostUserAvatar?, hostSignedToken? }`
+ - Outbound: `embed:identity-request` — `{ want: ['wallet' | 'host-user'], reason }` (embed asks host to either (a) reveal its user id, or (b) trigger wallet link)
+2. **Viewer identity state machine** — new file `src/embed-viewer-identity.js`:
+ - Tiers: `anon` → `host-user` → `wallet-linked`
+ - Transitions stored in `sessionStorage` under key `3d-agent:viewer-identity:<agentId>`
+ - Methods: `current()`, `setHostUser(info)`, `linkWallet({ address, chainId, signature, message })`, `clear()`
+ - Expose a read-only object: `{ tier, hostUserId?, walletAddress?, chainId? }`
+3. **Optional SIWE-on-open** — an opt-in flow:
+ - Embed renders a small, dismissible prompt in the corner: "Link wallet to let [agent name] act as you" with a "Connect" button.
+ - Clicking "Connect" posts `embed:identity-request { want: ['wallet'] }` to host so LobeHub can open its wallet UI — **or** if host capability `inline-wallet` is false, opens a same-origin SIWE pop-up using our existing wallet infra.
+ - Completed SIWE stores tier=`wallet-linked`, notifies host with `embed:identity-change`.
+ - The prompt must be **dismissible** and **remembered** per agent id for the session.
+4. **Avatar behavior gating** — when tier is `anon`:
+ - Avatar still renders with full Empathy Layer (do **not** flatten).
+ - Memory operates in "ephemeral" mode (in-process only, no persistence to the agent's wallet-scoped namespace).
+ - Skills that require `ctx.wallet` or `ctx.sign` return `{ ok: false, error: 'wallet-required' }` instead of throwing.
+5. **Propagation to the runtime** — when tier changes, re-hydrate [AgentIdentity](../../src/agent-identity.js) with the new scope. Existing avatar instance is **not** re-mounted (avoid full reboot); only the identity record is swapped.
+
+## Audit checklist
+
+- **Anon path works with no flags.** Paste the embed URL into a bare-HTML iframe, no host messages — confirm avatar renders, speaks, gestures, blends emotion. This is the floor.
+- **LobeHub token trust.** If LobeHub passes a `hostSignedToken`, verify signature against a configured LobeHub public key **server-side** via a new endpoint `POST /api/embed/verify-host-token` (stub, returns 200 unless a env var `LOBEHUB_HOST_JWKS_URL` is set). Do not blindly trust the token client-side.
+- **SIWE pop-up vs in-iframe.** Reading `window.parent` to open a pop-up from inside an iframe is fragile. Prefer posting `embed:identity-request` and letting the host handle it. Fall back to `window.open` only if host capability `inline-wallet` === `false`.
+- **Session scope.** Do not persist `wallet-linked` beyond `sessionStorage` here; the canonical wallet link belongs to [AgentIdentity](../../src/agent-identity.js). Session storage is a cache for the current tab.
+- **Dismiss state.** The SIWE prompt must not re-appear after dismiss within the same session.
+- **Empathy Layer untouched.** No emotion logic lives in this file. If you find yourself editing [src/agent-avatar.js](../../src/agent-avatar.js), stop — you're off-scope.
+- **Origin check.** `host:identity` must still pass the origin whitelist from [02](./02-iframe-handshake.md). Do not loosen.
+
+## Constraints
+
+- No new runtime deps. SIWE is already available via existing wallet infra — reuse.
+- The new API endpoint `api/embed/verify-host-token.js` must be a Vercel serverless handler, small (~30 lines), and gracefully no-op when `LOBEHUB_HOST_JWKS_URL` is unset.
+- **LobeHub spec uncertainty.** We do **not** know at this time the exact shape of LobeHub's user-context envelope. Flag each assumption with `// TODO(lobehub-spec): confirm against https://lobehub.com/docs/usage/plugins/development` and keep the code resilient to field renames.
+- Prompt UI: plain HTML in the embed page, not a framework component. Absolute-positioned, small, accessible (tabbable, ESC to dismiss).
+
+## Verification
+
+1. `node --check src/embed-viewer-identity.js api/embed/verify-host-token.js` passes.
+2. `npx vite build` succeeds.
+3. Manual matrix:
+ - **Anon**: iframe the embed, send no messages. Avatar works.
+ - **Host-user only**: iframe sends `host:identity { hostUserId: 'u1' }`. Prompt appears. Dismiss persists.
+ - **Host-user + wallet**: dismiss then re-init with a `linkWallet()` call in console. Tier flips to `wallet-linked`. `embed:identity-change` fires.
+ - **Tier downgrade**: call `clear()`. Avatar keeps running; memory flips to ephemeral. Skills fail softly.
+4. Unit-test the state machine in isolation via a quick node REPL (`import('./src/embed-viewer-identity.js')`). Document what you ran.
+
+## Scope boundaries — do NOT do these
+
+- Do **not** implement the plugin manifest (task [01](./01-plugin-manifest.md)).
+- Do **not** build the base handshake (task [02](./02-iframe-handshake.md)) — this task only **extends** it with identity envelopes.
+- Do **not** wire chat tool-call relay (task [04](./04-action-passthrough.md)).
+- Do **not** package or submit (task [05](./05-plugin-submission.md)).
+- Do **not** modify [src/agent-avatar.js](../../src/agent-avatar.js) — the Empathy Layer is out of scope.
+- Do **not** modify the top-level SIWE/wallet-auth flow. Call it, don't reshape it.
+
+## Files off-limits
+
+- `public/.well-known/lobehub-plugin.json` — owned by [01](./01-plugin-manifest.md)
+- `src/embed-host-bridge.js` — owned by [02](./02-iframe-handshake.md) for its core shape. You add two envelope types; keep diffs tight and in a clearly delimited `// ── identity ──` block.
+- `src/erc8004/*` — reuse, do not refactor
+- `src/agent-identity.js` — call, do not rewrite
+
+## Reporting
+
+- New files created with line counts
+- Exact additions to `src/embed-host-bridge.js` (which block, how many lines)
+- All `TODO(lobehub-spec)` flags, enumerated verbatim with file:line
+- Matrix results (anon / host-user / wallet-linked / downgrade) — pass/fail for each
+- `node --check` + `vite build` results
+- Any unrelated bugs noticed — note, don't fix
diff --git a/prompts/lobehub-embed/README.md b/prompts/lobehub-embed/README.md
new file mode 100644
index 000000000..3a70ef2e6
--- /dev/null
+++ b/prompts/lobehub-embed/README.md
@@ -0,0 +1,43 @@
+# LobeHub embed — series index
+
+Priority 5 in the [top-level stack](../README.md). One of two parallel host-integration series; the other is [claude-artifact/](../claude-artifact/).
+
+## Why this series matters
+
+LobeHub is the **primary** integration target for embodied-agent rendering inside a host chat. When a LobeHub chat talks to a 3D Agent, the agent should render **embodied** — a 3D avatar driven by the [Empathy Layer](../../src/agent-avatar.js) — inside the chat UI, not as invisible JSON.
+
+The user has a LobeHub fork. We are building a first-class plugin that:
+
+1. Declares a LobeHub plugin manifest pointing at our hosted [public/agent/embed.html](../../public/agent/embed.html).
+2. Handshakes with the LobeHub chat host via `postMessage`.
+3. Passes the chat model's tool calls and messages **into** our [agent-protocol](../../src/agent-protocol.js) so the avatar speaks, gestures, and reacts emotionally in real time.
+4. Passes signed agent actions **back out** to LobeHub so the chat history records what the avatar did.
+5. Ships to the LobeHub plugin marketplace.
+
+## Tasks — execute in order
+
+| # | File | Ships |
+|---|---|---|
+| 01 | [01-plugin-manifest.md](./01-plugin-manifest.md) | LobeHub plugin JSON manifest; hosted at a public URL; declares iframe + API surface |
+| 02 | [02-iframe-handshake.md](./02-iframe-handshake.md) | `postMessage` protocol between host and embed: init, agent-id resolution, action relay, resize, errors |
+| 03 | [03-host-auth-handoff.md](./03-host-auth-handoff.md) | Identify LobeHub viewer; optional wallet link via SIWE; graceful anon path |
+| 04 | [04-action-passthrough.md](./04-action-passthrough.md) | Chat → protocol relay (speak, gesture, emote); avatar-signed actions → chat |
+| 05 | [05-plugin-submission.md](./05-plugin-submission.md) | Package, local-test against LobeHub dev instance, marketplace submission PR |
+
+## Rules that apply to every task in this series
+
+**These are not quick tasks.** LobeHub is the primary integration target — each task must be thorough, not rushed. If LobeHub API details are unclear at the time of writing, the task prompts say "confirm against current LobeHub docs" rather than fabricating. The doing-agent should honor that and read the current docs.
+
+- No new runtime dependencies unless the task file explicitly allows them.
+- No new docs files (README.md, CLAUDE.md) unless the task says so.
+- `node --check` every modified JS file.
+- `npx vite build` and report result. Pre-existing `@avaturn/sdk` warning is unrelated — ignore.
+- The [Empathy Layer](../../src/agent-avatar.js) is the novel selling point. **Every task must protect its behavior.** Do not disable, bypass, or flatten emotion blending for "embed mode". The embed context is where it shines.
+- `.well-known/agent-card.json` is an A2A card; LobeHub may or may not natively consume it. Treat as auxiliary, not primary.
+- [ERC-8004 identity](../../src/erc8004/) is wired but **must be optional** for the embed to work. Anon LobeHub users should get a functional avatar.
+- Respect `Files off-limits` sections — other tasks may be editing them.
+- If you discover an unrelated bug, note it in your report. Do not fix it in the same change.
+
+## Reporting
+
+Each task ends with a short report: files created, files edited (which sections), commands run and their output, manual verification URLs hit against a local LobeHub dev instance or mock, any uncertainty flagged for later confirmation.
diff --git a/prompts/onchain/00-README.md b/prompts/onchain/00-README.md
new file mode 100644
index 000000000..5175d4c77
--- /dev/null
+++ b/prompts/onchain/00-README.md
@@ -0,0 +1,41 @@
+# Band 6 — On-chain Agent Deployment
+
+## The end state
+
+A user's agent exists on-chain. The record contains:
+- owner wallet
+- agent id (also an NFT or ERC-8004 entry)
+- GLB URI (IPFS or Arweave for permanence)
+- metadata URI (name, description, skills manifest)
+
+From any host (Claude, LobeHub, the user's personal site, a random iframe on X), you paste an address or ENS name and **the same avatar appears**. No server on our side required to resolve — the host reads the chain, fetches the pinned GLB, renders.
+
+## Current state
+
+- ERC-8004 registration scaffolding exists — `src/erc8004/agent-registry.js`, `src/erc8004/register-ui.js`. The UI does the on-chain write; the contract side may not be deployed.
+- `.github/prompts/deploy-erc8004-contracts.md` covers contract deploy. Treat it as a dependency of this band — if not deployed, deploy first.
+- Agent records in Postgres have optional `wallet_address` and `chain_id` columns. They are not yet synced to on-chain state.
+- No IPFS / Arweave pinning — GLBs live in R2 today.
+
+## Prompts in this band
+
+| # | File | Depends on |
+|---|---|---|
+| 01 | [erc8004-write-flow.md](./01-erc8004-write-flow.md) | contracts deployed |
+| 02 | [ipfs-arweave-pinning.md](./02-ipfs-arweave-pinning.md) | — |
+| 03 | [agent-by-address-resolver.md](./03-agent-by-address-resolver.md) | 01, 02 |
+| 04 | [ens-naming.md](./04-ens-naming.md) | 03 |
+| 05 | [action-provenance-signing.md](./05-action-provenance-signing.md) | band 1 wallet auth |
+
+## Done = merged when
+
+- Owner clicks **Deploy on-chain** on their agent page; we estimate gas, they approve, transaction confirms, the agent page shows "on-chain ✓" with an explorer link.
+- GLB is pinned on IPFS (via a pinning service) and the pin endures across cache evictions.
+- Any host (including `curl`) can resolve an agent from a wallet address / ENS name via `GET /api/agents/by-address/:addr` — returns the same record whether the host queries us or queries the chain directly.
+- Action history entries are signed by the wallet and the signatures verify independently (anyone with an explorer and the contract address can audit the agent's behavior).
+
+## Off-limits for this band
+
+- Don't deploy to mainnet without user approval. Default to Base Sepolia / Sepolia for all prompt work.
+- Don't re-implement ENS resolution — use `ethers.resolveName`.
+- Don't introduce a second blob store. IPFS for on-chain canonical; R2 stays as the fast-path cache.
diff --git a/prompts/onchain/01-erc8004-write-flow.md b/prompts/onchain/01-erc8004-write-flow.md
new file mode 100644
index 000000000..11bbc5f8f
--- /dev/null
+++ b/prompts/onchain/01-erc8004-write-flow.md
@@ -0,0 +1,83 @@
+# Task 01 — ERC-8004 write flow
+
+## Why
+
+Owners must be able to deploy their agent on-chain with a single click and end up with a verifiable identity record: `{ owner, agentURI }` committed to the ERC-8004 IdentityRegistry.
+
+## Read first
+
+- [src/erc8004/abi.js](../../src/erc8004/abi.js) — `REGISTRY_DEPLOYMENTS` map, the ABIs. Verify what's actually deployed on Base Sepolia / Sepolia today (grep the file).
+- [src/erc8004/agent-registry.js](../../src/erc8004/agent-registry.js) — existing helpers (`connectWallet`, `registerAgent`, `buildRegistrationJSON`, `pinToIPFS`)
+- [src/erc8004/register-ui.js](../../src/erc8004/register-ui.js) — existing UI stub
+- [contracts/](../../contracts/) — Foundry project. Run `forge test` if possible; look at the `IdentityRegistry.sol` signature.
+
+## Build this
+
+### 1. Confirm contract state
+
+- Read `REGISTRY_DEPLOYMENTS` from `abi.js`.
+- For each chainId listed, make an `eth_getCode` RPC call to confirm the contract is actually deployed (not just a TODO).
+- Produce a table in the PR description: chainId | address | status | explorer link.
+- If **no chain** has a deployed contract, stop. Bubble up: "Needs `.github/prompts/deploy-erc8004-contracts.md` to run first."
+
+### 2. `/agent/:id` "Deploy on-chain" button
+
+On the agent page, if `agent.owner_user_id === current_user.id` **and** `agent.chain_id` is null, show a button:
+
+```
+[ ⬢ Deploy on-chain ]
+```
+
+Click flow:
+1. Open modal: "Choose network" — radio list of deployed chains (from step 1). Default to Base Sepolia.
+2. Load network for their wallet; prompt to switch if needed.
+3. Build the `agentURI` metadata JSON (`buildRegistrationJSON`):
+ ```json
+ {
+ "name": "…",
+ "description": "…",
+ "avatar": { "uri": "ipfs://<cid>", "mimeType": "model/gltf-binary" },
+ "skills": [...],
+ "schema": "agent-manifest/0.1"
+ }
+ ```
+4. Pin that JSON to IPFS (task 02 wires the pinning; here just call the helper with a clear error if pinning fails).
+5. Estimate gas. Show fee preview. Require explicit confirm.
+6. Call `IdentityRegistry.register(agentURI)` via ethers.
+7. On `TransactionReceipt`, extract the `agentId` from the emitted event.
+8. `POST /api/agents/:id/chain` with `{ chainId, agentId, txHash, agentURI }`.
+9. Server updates the DB row with those fields; responds with the updated record.
+10. UI replaces the button with "On-chain ✓ · `0xabcd…ef12`" linking to the explorer.
+
+### 3. Server endpoint
+
+`POST /api/agents/:id/chain` (auth + owner gate):
+- Validates `chainId` is a known deployment.
+- Validates `agentId` by reading the chain (`IdentityRegistry.getAgent(agentId) == caller`).
+- Updates `agent_identities` row.
+- Returns the full record.
+
+### 4. Status surface
+
+Anywhere the agent is rendered (dashboard, /agent/:id, embed), if `chain_id` is set, show the on-chain chip. Use a shared component — don't copy-paste.
+
+## Don't do this
+
+- Do not default to mainnet. Base Sepolia / Sepolia only until user explicitly approves mainnet.
+- Do not hand-roll contract calls — use the ABIs in `abi.js`.
+- Do not store the private key anywhere. User's wallet signs, server only records.
+- Do not swallow revert reasons — surface them verbatim in the UI.
+
+## Acceptance
+
+- [ ] "Deploy on-chain" button visible only to owners of unregistered agents.
+- [ ] Click → wallet prompt → after confirm, agent record shows on-chain chip.
+- [ ] Explorer link opens the IdentityRegistry contract page on the block explorer.
+- [ ] A second registration attempt on the same agent is blocked client-side + server-side (409 Conflict).
+- [ ] `npm run build` passes.
+
+## Reporting
+
+- Contract deployment table
+- Screenshots of the register flow, including a revert case (low balance)
+- The updated `agent_identities` row after success
diff --git a/prompts/onchain/01-hydrate-agent-from-chain.md b/prompts/onchain/01-hydrate-agent-from-chain.md
new file mode 100644
index 000000000..1656ed5e5
--- /dev/null
+++ b/prompts/onchain/01-hydrate-agent-from-chain.md
@@ -0,0 +1,78 @@
+# Task: Hydrate an AgentIdentity from (chainId, agentId) — read-only
+
+## Context
+
+Repo: `/workspaces/3D`. Canonical ERC-8004 identity contracts are already deployed and wired in [src/erc8004/abi.js](../../src/erc8004/abi.js) — you do **not** need to deploy anything.
+
+Today, [src/agent-identity.js](../../src/agent-identity.js) loads an agent from localStorage or the backend (`/api/agents/:id`). It has no path to hydrate directly **from chain** when all you have is `(chainId, agentId)`. [src/manifest.js](../../src/manifest.js) knows how to resolve `agent://chain/id` into a normalized manifest via `loadFromAgentURI`, but that output is a manifest, not an `AgentIdentity`, and the resolver is not wired from the identity layer.
+
+## Goal
+
+Add a read-only hydration path so any caller with `(chainId, agentId)` can build an `AgentIdentity` — no wallet, no signer required. This unblocks the `/agent/:id` page when the agent exists on-chain but not in our backend, and it is the foundation for 02 (wallet → agents) and 05 (reputation display).
+
+## Deliverable
+
+1. New file [src/erc8004/hydrate.js](../../src/erc8004/hydrate.js) exporting:
+ - `async function hydrateFromChain({ chainId, agentId, rpcURL? })` → returns a **plain record** shaped like `AgentRecord` in [agent-identity.js](../../src/agent-identity.js) (`id`, `name`, `description`, `avatarId` — leave `null` if only a body URI is known, `homeUrl`, `walletAddress`, `chainId`, `skills: []`, `meta`, `createdAt`, `isRegistered: true`). Must also set a `meta.onchain = { chainId, agentId, registryAddr, tokenURI, ownerAddress, agentRegistry }` block.
+ - Internally:
+ - Resolve registry address via `REGISTRY_DEPLOYMENTS[chainId].identityRegistry`. Throw a typed error (`new Error('unknown-chain')` etc.) if missing.
+ - Use `JsonRpcProvider` from `ethers` with the given `rpcURL` or fall back to a known default (extend `DEFAULT_RPCS` in [manifest.js](../../src/manifest.js) if new chains are needed, do **not** fork it — import and reuse).
+ - Read `tokenURI(agentId)` and `ownerOf(agentId)` via the identity registry.
+ - Resolve the `tokenURI` through [src/ipfs.js](../../src/ipfs.js) `resolveURI` / `fetchWithFallback`, then parse the registration JSON.
+ - Pass the JSON through `normalize()` in [src/manifest.js](../../src/manifest.js) to reuse the ERC-8004 adapter (preferred) OR read the relevant fields directly — but if you read directly, cover the ERC-8004 `registrations[]` shape and the nested `image` / `body.uri` fallback.
+ - Shape the return value so `AgentIdentity` can consume it without further translation.
+2. Extend [src/agent-identity.js](../../src/agent-identity.js):
+ - Add constructor option `{ onchain: { chainId, agentId, rpcURL? } }`.
+ - When `onchain` is set and `autoLoad` is true, the internal `_loadAsync` **tries chain first**, falls back to localStorage/backend if chain hydration throws.
+ - Add a new method `async hydrateOnchain({ chainId, agentId, rpcURL? })` that callers can invoke later to merge on-chain fields into the current record (merging only non-empty fields — never overwrite a user-set local name/description with an empty on-chain one).
+3. Minimal unit-ish smoke in a REPL (document in the verification block below) — no new test file required.
+
+## Audit checklist
+
+- `hydrateFromChain` works with **no signer** — uses `JsonRpcProvider` only.
+- Handles `tokenURI` that returns `''` → throw `Error('no-token-uri')`.
+- Handles `tokenURI` that returns a non-JSON body (e.g. the initial placeholder `ipfs://<glbCID>` before `setAgentURI` is called) → return a partial record with `meta.onchain.tokenURI` set and `name: 'Agent #' + agentId`; do not throw.
+- Handles `ownerOf` revert (burned / never minted) → throw `Error('not-found')`.
+- Handles the ERC-8004 JSON's `registrations[0].agentRegistry` field shape `"eip155:<chainId>:<addr>"` — parse and expose in `meta.onchain.agentRegistry`. Does **not** assume chain from the requested `chainId` arg alone; if the JSON disagrees, prefer the JSON's chain and log a warning.
+- Idempotent: calling it twice returns equivalent records.
+- Never writes to localStorage from `hydrate.js` directly — that's `AgentIdentity`'s job.
+- No `totalSupply()` call — the canonical contract reverts it (see [README](./README.md)).
+
+## Constraints
+
+- No new dependencies.
+- Do **not** change `REGISTRY_DEPLOYMENTS` contract addresses. You may add new `DEFAULT_RPCS` entries if a task reviewer asks.
+- Stay read-only: do not import `connectWallet`, do not touch `_signer`.
+- Keep `hydrate.js` under ~150 lines. It's a thin adapter.
+- Do not break the existing `new AgentIdentity({ userId, agentId, autoLoad })` call sites in [app.js](../../src/app.js) and [element.js](../../src/element.js).
+
+## Verification
+
+1. `node --check src/erc8004/hydrate.js src/agent-identity.js`.
+2. `npx vite build` — passes (ignore `@avaturn/sdk` warning).
+3. In a browser console on a running dev server:
+ ```js
+ const { hydrateFromChain } = await import('/src/erc8004/hydrate.js');
+ const rec = await hydrateFromChain({ chainId: 84532, agentId: 1 });
+ console.log(rec);
+ // Expect: { id: '84532:1', meta: { onchain: { registryAddr: '0x8004A818...', tokenURI: 'ipfs://...', ownerAddress: '0x...' } }, ... }
+ ```
+4. Use `new AgentIdentity({ agentId: null, autoLoad: false, onchain: { chainId: 84532, agentId: 1 } }); await ident.load();` and confirm the loaded record has `isRegistered === true` and `meta.onchain.tokenURI` set.
+5. Negative case: pass `agentId: 99999999` on a testnet and confirm `Error('not-found')`.
+
+## Scope boundaries — do NOT do these
+
+- Do not add a UI for this (05 handles reputation display; the dashboard/profile pages will consume this later).
+- Do not wire signer-requiring calls — this task is strictly read-only.
+- Do not add reputation queries here (that's 05).
+- Do not add wallet enumeration (that's 02).
+- Do not change the backend `/api/agents/:id` contract.
+- Do not redeploy or change any contract addresses.
+
+## Reporting
+
+- Files created / edited (name the exported symbols added).
+- Any `DEFAULT_RPCS` entries added and why.
+- Any ERC-8004 registration JSONs you encountered in the wild that didn't fit the normalized shape — note them, do not "fix" them.
+- Verification console output (paste the record shape you observed).
+- Any unrelated bug noticed (report only — do not fix).
diff --git a/prompts/onchain/02-ipfs-arweave-pinning.md b/prompts/onchain/02-ipfs-arweave-pinning.md
new file mode 100644
index 000000000..4a0c5094d
--- /dev/null
+++ b/prompts/onchain/02-ipfs-arweave-pinning.md
@@ -0,0 +1,65 @@
+# Task 02 — IPFS / Arweave pinning
+
+## Why
+
+On-chain records must point to content-addressed storage, not to our R2 URLs. Without pinning, the chain record decays the moment we reshape R2.
+
+## Read first
+
+- [src/erc8004/agent-registry.js](../../src/erc8004/agent-registry.js) — existing `pinToIPFS()` stub
+- [src/ipfs.js](../../src/ipfs.js) — gateway resolution, already handles `ipfs://` and `ar://`
+- R2 flow in [api/avatars/index.js](../../api/avatars/index.js) + [api/avatars/presign.js](../../api/avatars/presign.js)
+- Pinata / web3.storage / nft.storage / Filebase docs (pick one, justify in code)
+
+## Build this
+
+### 1. Pick a pinning provider
+
+Must support: JSON pins + binary (GLB) pins, dashboard, API keys, free tier. Recommend **Pinata** (most mature API) or **web3.storage** (UCAN-based, slicker). Document the choice at the top of the new `api/pin/` file.
+
+### 2. Server endpoint
+
+`POST /api/pin` (auth required):
+```
+body: { kind: 'json' | 'glb', uri?: string, data?: object, contentType?: string }
+```
+
+- If `kind: 'json'`, `data` is the raw JSON; server pins it directly.
+- If `kind: 'glb'`, `uri` points to an existing R2 URL we control; server fetches it server-side and pins. (Never accept arbitrary URLs from the client — only R2 URLs belonging to this user's avatars.)
+- Response: `{ cid, gateway: 'https://ipfs.io/ipfs/<cid>', size, pinnedAt }`.
+- Store a row in a new `pins` table: `id, user_id, kind, cid, r2_key, size, pinned_at, provider, provider_pin_id`.
+
+### 3. Auto-pin on "Deploy on-chain"
+
+Hook from task 01: before registering, call `/api/pin` for both the GLB and the metadata JSON. Return `ipfs://<cid>` URIs to the caller.
+
+### 4. Redundancy
+
+Pin to **two** providers (primary + secondary) if env configured. Store both provider IDs. Document how to un-pin from one (dashboard link).
+
+### 5. Rate limit
+
+Cap at 10 pins / user / hour. Return 429 with `{ retry_after }` on overflow.
+
+## Don't do this
+
+- Do not delete the R2 source after pinning. R2 stays as the fast-read cache.
+- Do not expose pin API keys in client code. Server-only.
+- Do not pin to a provider that deletes free-tier content after N days — check the terms.
+- Do not re-pin if the `cid` for this `user_id + r2_key` already exists.
+
+## Acceptance
+
+- [ ] `POST /api/pin` signed out → 401.
+- [ ] Signed in, pin a JSON → returns a CID, `ipfs cat <cid>` via gateway returns the same JSON.
+- [ ] Pin the same JSON twice → second call returns the cached CID (no new upload).
+- [ ] Pin the user's avatar GLB → resulting CID loads in the viewer via `ipfs://<cid>`.
+- [ ] 11th pin in an hour → 429.
+- [ ] `npm run build` passes.
+
+## Reporting
+
+- Provider chosen + why
+- Pinata dashboard screenshot (or equivalent) showing pinned content
+- `pins` table schema + migration file
+- curl transcripts for the success + rate-limit cases
diff --git a/prompts/onchain/02-wallet-to-agents.md b/prompts/onchain/02-wallet-to-agents.md
new file mode 100644
index 000000000..87e7525c8
--- /dev/null
+++ b/prompts/onchain/02-wallet-to-agents.md
@@ -0,0 +1,79 @@
+# Task: List all agents owned by a wallet address
+
+## Context
+
+Repo: `/workspaces/3D`. Canonical ERC-8004 identity is already wired in [src/erc8004/abi.js](../../src/erc8004/abi.js). The ABI exposes `balanceOf(address)` and the `Registered` / `Transfer` events — but **does not** expose an ERC-721 enumerable `tokenOfOwnerByIndex`. The canonical identity contract is non-enumerable and **reverts on `totalSupply()`**.
+
+The dashboard at [public/dashboard/](../../public/dashboard/) needs a "my agents" view that lists every agent a connected wallet owns, across the chains we support. Today there is no chain-side resolver for this; the dashboard only reads from our backend.
+
+Task 01 ([01-hydrate-agent-from-chain.md](./01-hydrate-agent-from-chain.md)) provides `hydrateFromChain({ chainId, agentId })`. This task builds the list-of-ids step that feeds into it.
+
+## Goal
+
+Add a read-only function that takes `(walletAddress, chainId)` and returns an array of `agentId`s currently owned by that address. Must handle the non-enumerable contract, must use **event log scanning** (`Transfer` + `Registered`), must tolerate RPC log-range limits, and must be reasonably fast (< 2s cold on Base Sepolia).
+
+## Deliverable
+
+1. New file [src/erc8004/wallet-agents.js](../../src/erc8004/wallet-agents.js) exporting:
+ - `async function listAgentsByOwner({ owner, chainId, rpcURL?, fromBlock? })` → `Promise<{ agentId: bigint, tokenURI: string | null }[]>`
+ - `async function listAgentsAcrossChains({ owner, chainIds?, rpcURL? })` → `Promise<{ chainId, agents }[]>` — defaults to iterating every chain in `REGISTRY_DEPLOYMENTS`, concurrency cap of 4.
+2. Strategy inside `listAgentsByOwner`:
+ - First pass: call `balanceOf(owner)`. If it returns 0n → return `[]` early.
+ - Second pass: scan `Transfer(from, to, tokenId)` where `to === owner` from `fromBlock` (default: chain deployment block if known, else `0`) to `latest`, in chunks of 10_000 blocks (configurable const `LOG_CHUNK = 10_000`), retrying halved on `-32005` / `range too large` errors down to `LOG_CHUNK_MIN = 500`.
+ - Collect `tokenId`s where the most recent Transfer whose party is `owner` resulted in `owner` being the `to`. Verify final ownership with `ownerOf(tokenId)` and drop tokens that have since moved.
+ - For each surviving token, call `tokenURI(tokenId)` in parallel with a 6-wide limit. Swallow `tokenURI` errors as `tokenURI: null` — a token with no URI is still owned.
+3. Dashboard integration:
+ - In [public/dashboard/](../../public/dashboard/), find the module that renders "my agents" (look for the fetch to `/api/agents/me`). Add a secondary list sourced from `listAgentsAcrossChains` for the currently connected wallet, merged with the backend list by `meta.onchain.agentId`. De-dupe: if an agent already shows in the backend list with a matching `(chainId, agentId)`, **don't add it twice**; decorate the backend card with an "on-chain" badge instead.
+4. Expose the helper in [src/erc8004/index.js](../../src/erc8004/index.js) (create if missing) as a barrel export next to `registerAgent`.
+
+## Audit checklist
+
+- No `totalSupply()` anywhere.
+- Works on any chain in `REGISTRY_DEPLOYMENTS`.
+- Handles RPCs that cap `eth_getLogs` ranges: back off + chunk.
+- Concurrency caps: 4 chains at a time, 6 `tokenURI` reads at a time. No unbounded `Promise.all`.
+- Owner-address comparison is case-insensitive (`getAddress()` checksum both sides before comparing).
+- Returns `bigint` agentIds. Downstream must `.toString()` before passing to `hydrateFromChain`.
+- Does not require a signer.
+- Cold path on an empty wallet completes in < 500ms (balance 0 → bail).
+- Never throws on a single-chain failure in `listAgentsAcrossChains`; logs and returns `{ chainId, agents: [], error }` for that chain.
+
+## Constraints
+
+- No new dependencies.
+- `ethers` only. `JsonRpcProvider` only — no signer.
+- Use the RPCs in `DEFAULT_RPCS` from [src/manifest.js](../../src/manifest.js). Extend it if a chain you need is missing.
+- Don't add this to `AgentIdentity`. This is a list utility, not an identity.
+- Don't cache to localStorage in the util. Dashboard may cache at its own layer.
+- The dashboard HTML/JS is vanilla — do not introduce a framework.
+
+## Verification
+
+1. `node --check src/erc8004/wallet-agents.js` plus any file you edited in `public/dashboard/`.
+2. `npx vite build` — passes (ignore `@avaturn/sdk`).
+3. In a browser console on dev server:
+ ```js
+ const { listAgentsByOwner, listAgentsAcrossChains } = await import('/src/erc8004/wallet-agents.js');
+ const agents = await listAgentsByOwner({ owner: '0x...', chainId: 84532 });
+ console.log(agents.length, agents.slice(0,3));
+ const all = await listAgentsAcrossChains({ owner: '0x...' });
+ console.log(all);
+ ```
+4. On the dashboard, connect a wallet that owns ≥ 1 on-chain agent (use the pre-registered CZ agent after [cz-demo/02](../cz-demo/02-cz-preregistered-agent.md) lands). Confirm it appears with the "on-chain" badge. Confirm backend agents still render.
+5. Empty wallet: no crash, empty state shown.
+
+## Scope boundaries — do NOT do these
+
+- Do not build a new dashboard UI from scratch — integrate with the existing one.
+- Do not add a backend endpoint for this — it's a client-side chain read.
+- Do not query a third-party indexer (Alchemy, The Graph). RPC + logs only.
+- Do not write the hydration logic (that's 01). Just return ids + tokenURIs.
+- Do not paginate across `Registered` events as the source of truth; `Registered` fires at mint time but tokens may have been transferred since. `Transfer` is authoritative.
+
+## Reporting
+
+- Files created / edited.
+- Observed wall-clock on a wallet with 3–5 on-chain agents on Base Sepolia.
+- Any chain whose default RPC choked on log range limits — note the fallback you used.
+- Any dashboard wiring surprises.
+- `npx vite build` status.
diff --git a/prompts/onchain/03-agent-by-address-resolver.md b/prompts/onchain/03-agent-by-address-resolver.md
new file mode 100644
index 000000000..6b10c5a8e
--- /dev/null
+++ b/prompts/onchain/03-agent-by-address-resolver.md
@@ -0,0 +1,71 @@
+# Task 03 — Resolve an agent by wallet address
+
+## Why
+
+Hosts (Claude, LobeHub) paste a wallet address. We must return the canonical agent record — fetched from chain if we haven't seen the address, cached if we have.
+
+## Read first
+
+- [src/agent-resolver.js](../../src/agent-resolver.js) — existing client resolver
+- [src/erc8004/abi.js](../../src/erc8004/abi.js) — contract addresses
+- [api/agents/[id].js](../../api/agents/[id].js) — existing single-agent endpoint
+- Tasks 01 + 02 deliverables
+
+## Build this
+
+### 1. `GET /api/agents/by-address/:addr`
+
+Public (no auth). Accepts:
+- `0x…` address (EIP-55 or lowercased)
+- Optional `?chain=base-sepolia` (default: try every deployed chain in order, first hit wins)
+
+Flow:
+1. Normalize address to lowercase.
+2. Check `agents` cache: `select * from agent_identities where lower(wallet_address) = $1`. If hit and `chain_id` set, return.
+3. Otherwise, for each chainId in `REGISTRY_DEPLOYMENTS`:
+ - `IdentityRegistry.agentOf(address)` → `agentId` (or 0)
+ - If nonzero, `IdentityRegistry.getAgent(agentId)` → `agentURI`
+ - Fetch `agentURI` (IPFS → HTTPS gateway fallback, using the `ipfs.js` helper)
+ - Build a cache row in `agent_identities` (mark `_source: 'chain'`). Use the metadata's `name`, `description`, `avatar.uri`, `skills`.
+ - Return it.
+4. If nothing on any chain, 404 with `{ ok: false, error: 'not_registered' }`.
+
+### 2. Client resolver update
+
+Extend [src/agent-resolver.js](../../src/agent-resolver.js):
+```js
+export async function resolveAgentByAddress(addr, opts) { … }
+```
+
+`<agent-3d agent-address="0x…">` — add support in [src/element.js](../../src/element.js). If present and no `agent-id` / `src`, resolve via address and render.
+
+### 3. Caching
+
+- In-memory (`Map`) LRU cache, 5-minute TTL, per chainId.
+- Cache miss triggers chain read; cache hits never do.
+- Purge cache for an address on `POST /api/agents/by-address/:addr/refresh` (auth: owner only).
+
+### 4. ENS readback
+
+If `addr` looks like an ENS name (`*.eth`), resolve to address first using `ethers.getDefaultProvider('mainnet').resolveName(ensName)`. Task 04 expands this; here just make the happy path work.
+
+## Don't do this
+
+- Do not require auth. This endpoint is the integration point for third-party hosts.
+- Do not call the chain on every request. Cache aggressively.
+- Do not try to reverse `address → ENS` name here. Out of scope.
+
+## Acceptance
+
+- [ ] `curl /api/agents/by-address/0xabc…` returns an agent record sourced from chain.
+- [ ] Second call is served from cache (measure with server timing header `X-Cache: HIT`).
+- [ ] `/refresh` forces a re-read.
+- [ ] `<agent-3d agent-address="0x…">` in an HTML page renders the avatar.
+- [ ] Unregistered address → 404 JSON.
+- [ ] `npm run build` passes.
+
+## Reporting
+
+- curl transcripts: miss → hit → refresh → miss
+- Server timing summary (avg ms cache hit vs miss)
+- Any chain-RPC quirks
diff --git a/prompts/onchain/04-ens-naming.md b/prompts/onchain/04-ens-naming.md
new file mode 100644
index 000000000..70d00db42
--- /dev/null
+++ b/prompts/onchain/04-ens-naming.md
@@ -0,0 +1,63 @@
+# Task 04 — ENS naming
+
+## Why
+
+"Render `vitalik.eth`'s agent" is a much better UX than "paste this 0x…". Add ENS resolution to the address resolver.
+
+## Depends on
+
+Task 03 must be shipped.
+
+## Read first
+
+- ethers v6 ENS docs — `provider.resolveName`, `provider.lookupAddress`
+- [src/agent-resolver.js](../../src/agent-resolver.js)
+- [api/agents/by-address/](../../api/agents/) (from task 03)
+
+## Build this
+
+### 1. `GET /api/agents/by-name/:name`
+
+- Accepts any ENS name (`vitalik.eth`, `nick.base.eth`).
+- Server-side: `ethers.getDefaultProvider('mainnet').resolveName(name)` → address → reuse task 03's `resolveByAddress`.
+- For Base names (`*.base.eth`), resolve via Basename resolver (`0xB94704422c2a1E396835A571837Aa5AE53285a95` on Base mainnet) — if Basename library exists use it; otherwise raw call.
+- Cache ENS → address 10 minutes.
+- Respond 404 if the name doesn't resolve, 404 if the resolved address has no agent.
+
+### 2. Web component attribute
+
+```html
+<agent-3d agent-name="vitalik.eth"></agent-3d>
+```
+
+In [src/element.js](../../src/element.js), add this as a fourth resolution path (after `src`, `agent-id`, `agent-address`).
+
+### 3. Reverse lookup (cosmetic)
+
+When rendering the agent page for someone who arrived via address, do a reverse ENS lookup (`provider.lookupAddress(addr)`). If it resolves back to a name AND the forward resolution matches, display `vitalik.eth` instead of the hex address. Otherwise show the hex.
+
+### 4. UX on /agent
+
+URL shapes:
+- `/agent/0xabc…` — address
+- `/agent/vitalik.eth` — ENS (redirect to `/agent/<resolved-address>`? or keep the name in the URL? Pick the one that keeps the URL stable across name changes — lean **address-canonical** with a small ENS chip in the header)
+
+## Don't do this
+
+- Do not require mainnet ETH balance to query ENS. Use a free public RPC (`cloudflare-eth.com` or similar) by default.
+- Do not blindly trust the name without forward-resolve verification.
+- Do not resolve CCIP-read names without validating the signing address — just skip them for now with a clear "unsupported" response.
+
+## Acceptance
+
+- [ ] `curl /api/agents/by-name/vitalik.eth` — 404 `not_registered` (expected, Vitalik has no 3D agent yet) but shows the resolved address in the body.
+- [ ] An agent registered under an address with an ENS name resolves via name + renders the name in the header.
+- [ ] Unknown name → 404.
+- [ ] Basenames resolve via Base mainnet resolver.
+- [ ] `npm run build` passes.
+
+## Reporting
+
+- Provider RPCs used
+- Resolution latency (time to first render) for a cold ENS lookup
+- curl transcripts for 4 cases: real name registered, real name unregistered, junk name, Basename
diff --git a/prompts/onchain/05-action-provenance-signing.md b/prompts/onchain/05-action-provenance-signing.md
new file mode 100644
index 000000000..8a5f5bf02
--- /dev/null
+++ b/prompts/onchain/05-action-provenance-signing.md
@@ -0,0 +1,104 @@
+# Task 05 — Signed action provenance
+
+## Why
+
+Each agent action ("I said X", "I did Y") should be signed by the agent's wallet. Anyone with the public key can verify the log is tamper-proof. This is what turns an agent from "a chat with nice graphics" into "an auditable participant."
+
+## Depends on
+
+- Band 1 wallet auth (specifically task 06 — agent wallet binding) must be shipped.
+- This task assumes `agent_identities.wallet_address` is verified, not just self-declared.
+
+## Read first
+
+- [api/agent-actions.js](../../api/agent-actions.js) — existing action recorder
+- [src/agent-identity.js](../../src/agent-identity.js) — client-side identity + action log
+- [src/agent-protocol.js](../../src/agent-protocol.js) — which events get recorded
+- EIP-191 signing via `signer.signMessage`
+
+## Build this
+
+### 1. Action envelope
+
+Every action sent to `/api/agent-actions` becomes a canonical JSON:
+
+```json
+{
+ "agentId": "agt_…",
+ "type": "speak|remember|sign|skill-done|validate|load-end",
+ "payload": { … },
+ "timestamp": 1713139200000,
+ "prevHash": "sha256(prev action canonical JSON)",
+ "nonce": 12345
+}
+```
+
+- Canonicalize with RFC 8785 (JCS) or plain sorted-keys JSON.
+- Hash with SHA-256 to get `actionHash`.
+- Client signs the hash with the wallet (EIP-191: `signer.signMessage(hashBytes)`).
+- Server stores the action with `action_hash`, `prev_hash`, `signature`, `signer_address`.
+
+### 2. Hash chain
+
+Each action's `prevHash` references the previous action's `actionHash`. The chain:
+- Is per-agent.
+- Genesis action's `prevHash = 0x00…00`.
+- A broken chain means tampering — server rejects.
+
+### 3. Server endpoint
+
+`POST /api/agent-actions`:
+- Verify `signer_address` matches `agents.wallet_address`.
+- Verify `prevHash` matches last stored action's `action_hash`.
+- Recompute `actionHash` server-side from the canonical JSON; ensure match.
+- Insert row.
+- Return `{ ok: true, actionHash, index }`.
+
+Reject with `{ ok: false, error: 'signature_invalid' | 'chain_mismatch' | 'stale_prev' }`.
+
+### 4. Client batch
+
+Many events per second (speak + emote + think). Batch every 300ms:
+- Collect actions in a queue.
+- Build a single Merkle root over the batch; sign the root.
+- Send `/api/agent-actions/batch` with `{ items: […], merkleRoot, signature }`.
+- Server unfolds, verifies each against its prevHash, stores.
+
+### 5. Public audit endpoint
+
+`GET /api/agent-actions/:agentId/verify?from=<n>&to=<m>`:
+- Returns a proof bundle (all actions + sigs + Merkle paths).
+- Client-side verifier at `/agent/:id/audit` re-verifies every sig + chain link in-browser and shows ✓ / ✗ per link.
+
+### 6. UI
+
+On `/agent/:id`, the Timeline already exists. Add a small green/red chip per entry:
+- ✓ = signature verified locally
+- ✗ = signature invalid (should only happen if someone tampered)
+- hover → shows signer address
+
+### 7. Gas considerations
+
+Do NOT put every action on-chain. Store signatures off-chain (our DB + pinned to IPFS in rolling snapshots every 1000 actions or 1 hour). Snapshot Merkle root CAN be committed on-chain via `ValidationRegistry.recordValidation(agentId, rootHash)` — gas-cheap, once per snapshot.
+
+## Don't do this
+
+- Do not put raw actions on-chain. Only snapshot roots.
+- Do not use the session JWT to authorize action signing. Use the wallet signature itself.
+- Do not trust `signer_address` in the client request — always recover from signature server-side.
+- Do not break backward compat — existing rows without `action_hash` / `signature` are marked `unverified` and render grayed out.
+
+## Acceptance
+
+- [ ] New actions have signatures + chain hashes.
+- [ ] `/api/agent-actions/:id/verify` returns proofs; browser verifier shows all ✓.
+- [ ] Manually tamper with one row in DB → verifier shows ✗ at that index.
+- [ ] Snapshot Merkle root is committed on-chain hourly (or manually triggerable).
+- [ ] `npm run build` passes.
+
+## Reporting
+
+- Canonicalization choice (JCS vs sorted-keys) + why
+- Latency overhead on action emission
+- Snapshot committing frequency + gas cost estimate
+- A screenshot of the audit page showing the verification chain
diff --git a/prompts/onchain/README.md b/prompts/onchain/README.md
new file mode 100644
index 000000000..6e4111d39
--- /dev/null
+++ b/prompts/onchain/README.md
@@ -0,0 +1,49 @@
+# Onchain (priority 6) — task prompts
+
+Self-contained prompt files for wiring the 3D Agent platform to its on-chain identity. Each file is designed to be dropped into a fresh Claude Code session without extra context.
+
+## The big thing that is already done
+
+**Canonical ERC-8004 contracts are already wired.** See [../../src/erc8004/abi.js](../../src/erc8004/abi.js). The reference deployments (CREATE2 — same address on every EVM chain) live there keyed by `chainId`:
+
+- Testnets: identity `0x8004A818BFB912233c491871b3d84c89A494BD9e`, reputation `0x8004B663056A597Dffe9eCcC1965A193B7388713`, validation `0x8004Cb1BF31DAf7788923b405b754f57acEB4272`
+- Mainnets: identity `0x8004A169FB4a3325136EB29fA0ceB6D2e539a432`, reputation `0x8004BAa17C55a88189AE136b182e5fdA19dE9b63`. Validation `''` — not yet deployed on mainnet, treat as read-only-via-testnet only.
+
+**Do not propose redeploying contracts.** That decision is settled. Every prompt in this series assumes those addresses are correct and the ABIs in `abi.js` are authoritative.
+
+## What still needs to happen
+
+The remaining work is **integration + UX**. The registration code path exists ([agent-registry.js](../../src/erc8004/agent-registry.js)) and the registration UI exists ([register-ui.js](../../src/erc8004/register-ui.js)), but:
+
+- Agents discovered on-chain don't hydrate cleanly into an `AgentIdentity` without extra plumbing.
+- There's no "wallet → my agents" surface powering the dashboard.
+- The registration flow lacks gas estimation, pending UX, and a post-register handoff.
+- The avatar-edit flow doesn't propagate updates to `setAgentURI`.
+- Reputation has helpers but no UI.
+- Cross-chain resolution defaults to Base instead of reading the `agentRegistry: "eip155:<chainId>:<addr>"` field.
+
+## Execution order
+
+| # | File | Depends on |
+|---|---|---|
+| 1 | [01-hydrate-agent-from-chain.md](./01-hydrate-agent-from-chain.md) | — |
+| 2 | [02-wallet-to-agents.md](./02-wallet-to-agents.md) | 01 (shares hydrate path) |
+| 3 | [03-register-flow-polish.md](./03-register-flow-polish.md) | — |
+| 4 | [04-update-agent-uri.md](./04-update-agent-uri.md) | 03 helpful but not required |
+| 5 | [05-reputation-display-and-submit.md](./05-reputation-display-and-submit.md) | 01 (uses hydrate on `/agent/:id`) |
+| 6 | [06-cross-chain-lookup.md](./06-cross-chain-lookup.md) | 01 |
+
+## Rules for every task
+
+- **No redeploys. Do not touch [abi.js](../../src/erc8004/abi.js) contract addresses.** You may extend helper exports.
+- No new runtime dependencies. `ethers` is the only chain lib; `@privy-io/*` only where already imported.
+- `node --check` every modified JS file before reporting done.
+- `npx vite build` and report result. Ignore the pre-existing `@avaturn/sdk` resolution warning.
+- The canonical identity contract **reverts on `totalSupply()`** — any enumeration must use event scanning, not `totalSupply`.
+- The mainnet validation contract address is `''`. Any code that imports validation helpers must guard `if (!deployment.validationRegistry) { … }` and fail gracefully on mainnet.
+- Read-only flows (hydrate, list, lookup) must work **without a signer** — use `JsonRpcProvider` with the default RPC from [manifest.js](../../src/manifest.js) `DEFAULT_RPCS` (extend it if needed for new chains).
+- Keep the split: `src/erc8004/` for chain plumbing, other files consume it.
+
+## Reporting
+
+Each task ends with a short report: files created, files edited (which functions/sections), commands run and their output, manual verification URLs or console snippets, any surprises or unrelated bugs noticed.
diff --git a/prompts/portable-embed/00-README.md b/prompts/portable-embed/00-README.md
new file mode 100644
index 000000000..dab22698f
--- /dev/null
+++ b/prompts/portable-embed/00-README.md
@@ -0,0 +1,36 @@
+# Band 4 — Portable Embed (the view + embed polish band)
+
+## The end state
+
+Anyone with the share URL sees a public, interactive 3D agent page. Anyone with the embed snippet can paste it into their Substack / blog / docs / README and the avatar loads with chrome-free styling. Owners can get a one-click snippet from the agent's page.
+
+## Current state
+
+- Public viewer exists at `public/agent/index.html`; embed at `public/agent/embed.html`.
+- OG/oEmbed metadata partially shipped (see `prompts/embed/01-og-oembed.md`).
+- Agent-id resolver work in flight (`prompts/embed/02-agent-id-resolver.md`).
+- Per-agent embed allowlist spec exists (`prompts/embed/03-embed-allowlist.md`) — *not* a priority right now; owners can worry about it later.
+
+## Prompts in this band
+
+| # | File | Depends on |
+|---|---|---|
+| 01 | [share-panel.md](./01-share-panel.md) | — |
+| 02 | [embed-snippet-generator.md](./02-embed-snippet-generator.md) | 01 |
+| 03 | [public-agent-page-polish.md](./03-public-agent-page-polish.md) | — |
+| 04 | [embed-sizing-and-theming.md](./04-embed-sizing-and-theming.md) | — |
+
+All four can run in parallel after a quick scan of `public/agent/`.
+
+## Done = merged when
+
+- Owner clicks **Share** on `/agent/:slug`; a panel shows a short public URL, an iframe snippet, a JS snippet, and an OG preview card.
+- Pasting the iframe snippet into a WordPress / Substack / README renders the avatar with no scrollbars, no chrome.
+- The embed iframe is responsive (16:9 default, optional square, `?height=` / `?width=` params).
+- The public page has OG / Twitter / oEmbed metadata that renders a proper preview card in Slack, Discord, iMessage.
+
+## Off-limits for this band
+
+- Don't do Claude.ai / LobeHub integration here — that's band 5. This band is about the *generic* embed being solid first.
+- Don't build a CDN. R2 is the blob store; Vercel serves the HTML.
+- Don't introduce a new model-viewer component. `<model-viewer>` is fine.
diff --git a/prompts/selfie-agent/01-camera-capture-ui.md b/prompts/selfie-agent/01-camera-capture-ui.md
new file mode 100644
index 000000000..249d19aa5
--- /dev/null
+++ b/prompts/selfie-agent/01-camera-capture-ui.md
@@ -0,0 +1,100 @@
+# Task: Build the `/create` camera-capture UI
+
+## Context
+
+Repo: `/workspaces/3D`. A Vite + vanilla JS SPA where the current "create avatar" flow is a single button in [index.html](../../index.html) (id `create-avatar-btn`) that opens the Avaturn iframe via [src/avatar-creator.js](../../src/avatar-creator.js), wired in `setupAvatarCreator()` in [src/app.js](../../src/app.js) around line 402.
+
+We are about to ship the hero demo: take a selfie on a phone, get a personalized 3D avatar in 30 seconds. Step 1 is the capture surface. The Avaturn handoff (step 2), R2 pin + `agent_identities` row (step 3), name/description (step 4), and post-creation scene (step 5) are separate prompts in this series — do not reach into them.
+
+The existing Avaturn modal lives in [src/avatar-creator.js](../../src/avatar-creator.js) and is kept. This task **adds a new route** that replaces the current one-click button as the primary onboarding entry, and falls back to the existing Avaturn modal only for users who pick "skip selfie".
+
+## Goal
+
+Ship a `/create` route (or fullscreen panel — same effect) where a signed-in or anonymous user can:
+
+1. Grant camera permission via `navigator.mediaDevices.getUserMedia`.
+2. See a live square preview.
+3. Tap a capture button, see the frozen JPEG, decide retake or accept.
+4. If permission denied or no camera, fall back to an `<input type="file" accept="image/*" capture="user">` upload.
+
+On accept, the flow hands the `Blob` off to a single exported function `onCaptureReady(blob)` — **do not** call Avaturn from this task. Leave a TODO wired to a named event/callback that prompt 02 will hook into.
+
+## Deliverable
+
+1. **New file: `src/selfie-capture.js`** — class `SelfieCapture` with:
+ - `constructor(rootEl, { onCaptureReady })`
+ - `mount()` / `unmount()` — idempotent
+ - Internal `_startCamera()`, `_stopCamera()`, `_capture()`, `_showReview(blob)`, `_retake()`, `_handleUploadFallback(file)`
+ - All `addEventListener` callbacks stored on `this._…` fields so `unmount()` can remove them cleanly (follow the stored-bound-handler pattern used in [src/avatar-creator.js](../../src/avatar-creator.js)).
+2. **New file: `public/create.html`** — minimal skeleton (DOCTYPE, meta viewport, single `<div id="create-root">`). Import `../src/selfie-capture.js` via a `<script type="module">` and call `new SelfieCapture(root, { onCaptureReady }).mount()`.
+3. **Edit [vercel.json](../../vercel.json)** — add `{ "src": "/create", "dest": "/public/create.html" }` and `{ "src": "/create/", "dest": "/public/create.html" }` above the catch-all `/public/$1` route.
+4. **Edit [index.html](../../index.html)** — make `#create-avatar-btn` navigate to `/create` (use an `<a>` or plain `window.location = '/create'` click handler). Keep the existing in-page Avaturn modal reachable via a "Skip — use the editor" link inside `/create` for users without a camera.
+5. **Edit [style.css](../../style.css)** — add scoped styles under a `.selfie-capture` root class. No global rules. Mobile-first: the capture button must be at least 64×64px and thumb-reachable on a 375px viewport.
+
+## Audit checklist — must handle all of these
+
+**Camera lifecycle**
+- Request camera only after the user explicitly taps "Start camera" — never on mount. iOS Safari requires the prompt to happen inside a user gesture.
+- Request `{ video: { facingMode: 'user', width: { ideal: 1024 }, height: { ideal: 1024 } }, audio: false }`.
+- Store the `MediaStream` on `this._stream` and always stop all tracks (`this._stream.getTracks().forEach(t => t.stop())`) on: `unmount()`, retake-that-reopens-camera is fine but the previous stream must stop first, successful accept, navigation away (`pagehide` listener), and tab hidden (`visibilitychange` → pause/stop).
+
+**Capture**
+- Draw `<video>` onto a 1024×1024 `<canvas>` with center-crop (match shorter edge, centered).
+- `canvas.toBlob(cb, 'image/jpeg', 0.92)`.
+- Reject images smaller than 128×128 with an inline message.
+
+**Review step**
+- Show the frozen JPEG via `URL.createObjectURL(blob)` and `URL.revokeObjectURL` on retake / accept.
+- Two buttons: **Use this photo** and **Retake**. Both must be thumb-reachable on mobile.
+
+**Upload fallback**
+- Hidden `<input type="file" accept="image/*" capture="user">`. `capture="user"` triggers the rear/front camera picker on mobile browsers that support it.
+- Same review step as camera capture.
+- Enforce a 10 MB client-side cap, reject anything else with an inline message.
+
+**Errors** (no `alert()` — render inline under the preview)
+- `NotAllowedError` / `PermissionDeniedError` → "Camera permission denied. Upload a photo instead." + surface the upload button.
+- `NotFoundError` / `OverconstrainedError` → "No camera detected. Upload a photo instead."
+- `NotReadableError` → "Camera is busy in another app. Close it and retry."
+
+**Accessibility**
+- The capture button is a real `<button>` with `aria-label="Take photo"`.
+- Live preview `<video>` has `playsinline`, `muted`, `autoplay`, and no controls.
+- Review step images have `alt="Captured photo"`.
+
+## Constraints
+
+- No new runtime dependencies.
+- No framework. Plain DOM, same style as [src/avatar-creator.js](../../src/avatar-creator.js).
+- Do not call Avaturn from this file. `onCaptureReady(blob)` is the seam for prompt 02.
+- Do not persist the blob anywhere — not localStorage, not IndexedDB, not a fetch call. Prompt 03 handles persistence.
+- Do not redesign the existing Avaturn modal. The "Skip" link reuses it unchanged.
+
+## Verification
+
+1. `node --check src/selfie-capture.js` — parses.
+2. `npx vite build` — passes. Pre-existing `@avaturn/sdk` warning is expected; anything new is a regression.
+3. Manual desktop: navigate to `/create`, allow camera, capture, retake, accept — verify `onCaptureReady` fires with a `Blob` whose `type === 'image/jpeg'` and `size > 10_000`.
+4. Manual mobile (or DevTools mobile emulation + real device for camera): visit `/create` on an iPhone-sized viewport, capture works portrait, buttons are thumb-reachable.
+5. Manual deny-permission: in chrome://settings block the camera, reload `/create`, confirm inline error + upload fallback path still yields a valid blob.
+6. Manual leak check: mount, unmount, mount again — no double-listener, no orphan `MediaStream` (check `chrome://media-internals` or `navigator.mediaDevices.enumerateDevices()` pre/post).
+
+## Scope boundaries — do NOT do these
+
+- Do not hand the blob to Avaturn. That's prompt 02.
+- Do not upload to R2. That's prompt 03.
+- Do not collect name / description. That's prompt 04.
+- Do not add confetti, share buttons, or post-creation animation. That's prompt 05.
+- Do not add face-alignment overlays, beauty filters, or background removal.
+- Do not add a new dependency for image processing — `<canvas>` is enough.
+- Do not touch [src/viewer.js](../../src/viewer.js) or any three.js code.
+
+## Reporting
+
+Report:
+- Files created and their line counts.
+- Files edited and which sections.
+- Commands run (`node --check`, `npx vite build`) and their output.
+- Manual verification URLs you tested against and on what device.
+- Any listener or `MediaStream` you could not find a clean teardown for.
+- Any unrelated bug you spotted (do not fix).
diff --git a/prompts/selfie-agent/README.md b/prompts/selfie-agent/README.md
new file mode 100644
index 000000000..e1b404233
--- /dev/null
+++ b/prompts/selfie-agent/README.md
@@ -0,0 +1,50 @@
+# Selfie -> agent (priority 2)
+
+Self-contained prompt files for the "take a selfie, get an avatar agent in 30 seconds" flow. This is the magic moment that makes the platform feel alive — a photo becomes a 3D body that can speak, sign, and remember. Each file is designed to drop into a fresh Claude Code agent without extra context.
+
+See [../README.md](../README.md) for where this series sits in the overall priority stack.
+
+## State going in
+
+- Layer 1 (wallet auth) is shipped. `/api/agents/me` returns a real user's default agent.
+- Avaturn SDK is already a runtime dep (`@avaturn/sdk` in [package.json](../../package.json)) and wired via [src/avatar-creator.js](../../src/avatar-creator.js). The pre-existing Vite resolution warning for that package is unrelated to this series — ignore.
+- R2 presign + avatar-register endpoints already exist: [api/avatars/presign.js](../../api/avatars/presign.js) + [api/avatars/index.js](../../api/avatars/index.js).
+- [src/agent-identity.js](../../src/agent-identity.js) is the class each finalized avatar must end up attached to.
+- The single "Create Avatar" button in [index.html](../../index.html) opens the current Avaturn flow via `setupAvatarCreator()` in [src/app.js](../../src/app.js) around line 402.
+
+## Recommended execution order
+
+| # | File | Ships |
+|---|---|---|
+| 01 | [01-camera-capture-ui.md](./01-camera-capture-ui.md) | `/create` route + `getUserMedia` capture, photo review, retry, upload fallback |
+| 02 | [02-avaturn-session-bridge.md](./02-avaturn-session-bridge.md) | Hand the captured image to Avaturn SDK, await the generated GLB; error / quota / timeout handling |
+| 03 | [03-glb-pin-and-store.md](./03-glb-pin-and-store.md) | Pin the finalized GLB to R2 via the existing presign flow + create an `agent_identities` row |
+| 04 | [04-name-and-description.md](./04-name-and-description.md) | Claim a short name + one-line description with per-wallet uniqueness, slug reservation, denylist |
+| 05 | [05-first-meet-moment.md](./05-first-meet-moment.md) | Post-creation scene renders, avatar waves, confetti, share CTA, redirect to `/agent/:id` |
+
+### Sequencing
+
+- 01 ships first — nothing else works without a captured image.
+- 02 depends on 01 (needs the `Blob`).
+- 03 depends on 02 (needs the GLB URL) and on wallet-auth layer 1 (needs a signed-in user / linked wallet).
+- 04 can be built in parallel with 03 but must merge first — the `agent_identities` insert in 03 needs the chosen name + slug.
+- 05 ships last — pure UX polish on top of 01-04.
+
+## Rules that apply to every task
+
+- **No new runtime dependencies.** `@avaturn/sdk`, `ethers`, `@aws-sdk/client-s3`, `zod`, and the in-tree three.js bundle are already available — use those. If a task thinks it needs a new dep, stop and escalate.
+- **No TypeScript.** This codebase is vanilla JS (ESM). No `.ts` files, no `.d.ts`.
+- **No new README / CLAUDE.md files** unless the task file explicitly allows them.
+- **Every new or changed `.js` file must pass `node --check`** before reporting done.
+- **Every change must be followed by `npx vite build`** and the result reported. The pre-existing `@avaturn/sdk` resolution warning is expected — ignore it. Any *new* error is yours.
+- **Any new route must be added to [vercel.json](../../vercel.json)** in the same task that creates it.
+- **Mobile matters.** The hero demo is "take a selfie on your phone". Anything gated behind desktop-only APIs (drag-drop, hover, large modals) must have a mobile-first fallback.
+- **If you discover an unrelated bug,** note it in the reporting section. Do not fix it in the same change.
+
+## Out of scope for the whole series
+
+- Morph / outfit / accessory editing post-creation — that's layer 3 ([../avatar-edit/](../avatar-edit/)).
+- Alternate avatar providers (Ready Player Me, etc.).
+- ERC-8004 on-chain registration — that's layer 6 ([../onchain/](../onchain/)).
+- Voice / persona training.
+- LLM-generated names or descriptions — layer 04 is a plain input field + denylist only.
diff --git a/prompts/selfie-onboarding/00-README.md b/prompts/selfie-onboarding/00-README.md
new file mode 100644
index 000000000..4373e9aa0
--- /dev/null
+++ b/prompts/selfie-onboarding/00-README.md
@@ -0,0 +1,44 @@
+# Band 2 — Selfie → Agent
+
+## The end state
+
+A new user (signed in via wallet — band 1) is shown a camera viewfinder. They tap **Take selfie**. In under 60 seconds, a rigged 3D avatar that looks like them appears in the viewer, bound to their wallet identity. Their first agent is created.
+
+## Why this matters
+
+Typing a name, picking a body type, dragging sliders — all friction. A selfie is the *magic moment* that makes the product obvious. Every downstream priority (edit, embed, on-chain) is post-creation; if creation is slow or unclear, nothing else matters.
+
+## Current state
+
+- `@avaturn/sdk` (v0.7.0) is installed but not wired. Avaturn takes a selfie and returns a rigged GLB.
+- `src/avatar-creator.js` may exist but hasn't been verified in this audit — band 2 prompt 01 is to discover it and plan around what's there.
+- Existing avatar flow is drag-and-drop a GLB file (`src/app.js` load path). We preserve that — selfie is an additional entry point, not a replacement.
+- `api/avatars/*` endpoints handle avatar CRUD and R2 storage. A created avatar must be stored there so the rest of the stack works.
+
+## Prompts in this band
+
+| # | File | Depends on |
+|---|---|---|
+| 01 | [camera-capture.md](./01-camera-capture.md) | — |
+| 02 | [avaturn-pipeline.md](./02-avaturn-pipeline.md) | 01 |
+| 03 | [readyplayerme-fallback.md](./03-readyplayerme-fallback.md) | 01 |
+| 04 | [onboarding-flow.md](./04-onboarding-flow.md) | 02 |
+| 05 | [commit-and-name.md](./05-commit-and-name.md) | 02, 04 |
+
+01 unblocks 02 and 03 in parallel. 04 sits on top of 02. 05 is the final mile.
+
+## Done = merged when
+
+- Signed-in user at `/create` sees a camera preview within 200ms of page load.
+- User can take photo, retake, confirm.
+- A rigged GLB (via Avaturn) appears in `<model-viewer>` and in the editor within ~60s on a warm network.
+- That GLB is uploaded to R2 via the existing `/api/avatars` endpoint and a new agent row is created.
+- The user is redirected to `/agent/:slug` with the avatar live.
+- Fail cases (denied camera permission, bad photo, API failure) each show a specific message and a retry path.
+
+## Off-limits for this band
+
+- Do not try to build a custom photogrammetry pipeline. Use Avaturn (primary) and Ready Player Me (fallback).
+- Do not require the user to pick a body type before the photo — if the SDK needs it, default intelligently and let them change it in the editor later.
+- Do not add face landmark detection or on-device ML. Upload the photo; let the SDK do the work.
+- Do not gate this behind a paywall yet.
diff --git a/prompts/wallet-auth/00-README.md b/prompts/wallet-auth/00-README.md
new file mode 100644
index 000000000..b13b23eb9
--- /dev/null
+++ b/prompts/wallet-auth/00-README.md
@@ -0,0 +1,43 @@
+# Band 1 — Wallet Auth, 100%
+
+## The end state
+
+A user lands on `3d.irish`, clicks **Sign in with wallet**, approves a MetaMask / Privy / WalletConnect signature, and now has a session. Every authenticated endpoint (`/api/avatars`, `/api/agents`, `/dashboard`) works for them. No email required. Email sign-in continues to work for existing accounts. A user can link a wallet to an existing email account.
+
+## Current state (audit 2026-04-15)
+
+- Wallet connect client-side works — `src/erc8004/agent-registry.js:32-57` via Privy + injected fallback — but it's only used for ERC-8004 agent registration, not user login.
+- No SIWE endpoints (`/api/auth/siwe/nonce`, `/api/auth/siwe/verify` do not exist).
+- `users` table has **no** `wallet_address` column (see `api/_lib/schema.sql`).
+- No nonce storage table → replay attack risk if SIWE were bolted on naively.
+- No "Sign in with wallet" button on the home page or login form.
+- Session infra is solid: `__Host-sid` HttpOnly cookie, 30-day TTL, `getSessionUser(req)` pattern — see `api/_lib/auth.js`.
+
+## Prompts in this band
+
+| # | File | Depends on |
+|---|---|---|
+| 01 | [siwe-schema.md](./01-siwe-schema.md) | — |
+| 02 | [siwe-nonce-endpoint.md](./02-siwe-nonce-endpoint.md) | 01 |
+| 03 | [siwe-verify-endpoint.md](./03-siwe-verify-endpoint.md) | 01, 02 |
+| 04 | [signin-ui.md](./04-signin-ui.md) | 02, 03 |
+| 05 | [privy-backend-verify.md](./05-privy-backend-verify.md) | 03 |
+| 06 | [link-wallet-to-account.md](./06-link-wallet-to-account.md) | 03 |
+
+01 → 02 → 03 → 04 is the critical path. 05 and 06 can run in parallel with 04.
+
+## Done = merged when
+
+- Chrome + MetaMask → "Sign in with wallet" → signature prompt → back on the site as a signed-in user.
+- Refresh the page → still signed in.
+- Sign out → session cookie cleared, protected routes return 401.
+- Same flow in Brave (injected) and with WalletConnect (mobile) both work.
+- `document.cookie` shows `__Host-sid` after signin — not some custom cookie.
+- `GET /api/auth/me` returns the wallet user record.
+- Existing email-password users still work unchanged.
+
+## Off-limits for this band
+
+- Do not introduce a new auth library. Use `ethers` (already a dep) for `verifyMessage`/`recoverAddress`.
+- Do not redesign the session model. Reuse `createSession` / `__Host-sid`.
+- Do not change the `users` table primary key. Add the column, don't restructure.
diff --git a/prompts/wallet-auth/01-fix-agents-me-500.md b/prompts/wallet-auth/01-fix-agents-me-500.md
new file mode 100644
index 000000000..4eecb8d1e
--- /dev/null
+++ b/prompts/wallet-auth/01-fix-agents-me-500.md
@@ -0,0 +1,94 @@
+# Task: Diagnose and fix the `GET /api/agents/me` 500
+
+## Context
+
+Repo: `/workspaces/3D`. `/api/agents/me` is called by every page that boots an agent (home, dashboard, embed, studio, `src/agent-identity.js` on every page load). When it 500s, the whole client falls back to a local-only identity, `window.VIEWER.agent` is wrong, and action logging silently fails. The top-level README memo calls this out as a known bug.
+
+The handler lives in [api/agents.js](../../api/agents.js) — specifically `handleList` (branches on `/me`) and `handleGetOrCreateMe` (lines ~55–86). The route is wired up in [vercel.json](../../vercel.json) with:
+
+```
+{ "src": "/api/agents/me", "dest": "/api/agents" }
+{ "src": "/api/agents/([^/]+)/wallet", "dest": "/api/agents/[id]" }
+{ "src": "/api/agents/([^/]+)", "dest": "/api/agents/[id]" }
+```
+
+`handleGetOrCreateMe` already has a `try/catch` that swallows `42P01` (missing table) — that path returns `{ agent: null, warning: 'agents_table_missing' }`. But other failure modes (e.g. unique-constraint race on the auto-insert, JSON coercion on `skills`, cold-start timeout on Neon) currently bubble up as 500.
+
+Auth is resolved in `resolveAuth()`: session cookie first, then bearer. If neither resolves, anonymous callers hitting `/me` get `200 { agent: null }` — **that behavior must be preserved**.
+
+## Goal
+
+`GET /api/agents/me` returns 200 for 100% of legitimate requests — anonymous, signed-in-with-agent, and signed-in-without-agent. No 500s. A minimal regression test exercises the three cases.
+
+## Deliverable
+
+1. Modified [api/agents.js](../../api/agents.js):
+ - `handleGetOrCreateMe` hardened against race on insert (two concurrent requests creating the default agent).
+ - Error branches tagged in logs with a stable prefix like `[agents/me]` so future 500s are grep-able.
+ - No behavior change for anonymous callers (`auth === null` → `200 { agent: null }`).
+2. A minimal regression test file — plain Node, no new dev deps. Either:
+ - `scripts/test-agents-me.mjs` — a standalone script that hits the endpoint with three cookie states and asserts status 200 + expected body shape; or
+ - Inline `assert` block in an existing test harness if one exists in `scripts/`.
+3. Report the exact root cause you found. If the bug was a race, say "race on concurrent insert into `agent_identities`." If it was a schema mismatch, name the column. Don't report "hardened the handler" without a root cause.
+
+## Audit checklist
+
+**Reproduce before fixing**
+
+- [ ] Hit `/api/agents/me` with **no** cookie → expect `200 { agent: null }`. Confirm this branch still works after your change.
+- [ ] Hit `/api/agents/me` with a valid session cookie for a user who has **zero** rows in `agent_identities` → this is the suspected 500 path. Capture the actual Postgres error and include it in your report.
+- [ ] Hit `/api/agents/me` with a valid session cookie for a user who **already has** a default agent → expect `200 { agent: {...} }`.
+- [ ] Fire 10 concurrent requests (`xargs -P10`) for a brand-new user and count the resulting rows in `agent_identities` — must be exactly 1.
+
+**Handler correctness**
+
+- [ ] Auto-create path is race-safe. Options: wrap in a transaction + `select … for update`, or add a partial unique index on `(user_id) where deleted_at is null` and catch `23505` → re-select. Pick one; document why.
+- [ ] `skills` default is a real array literal, not a JSON-coerced string. Current code passes `${['greet', ...]}` — Neon's serverless driver should handle this as a Postgres array, but double-check it doesn't become `{greet,…}` text on the insert.
+- [ ] The existing `42P01` fallback stays. Don't delete the `agents_table_missing` warning path.
+- [ ] Any `catch` added logs with `console.error('[agents/me] …', err)` before returning, so Vercel logs are greppable.
+- [ ] `json(res, 200, { agent })` — `decorate(agent)` is called so the response shape matches the happy path.
+
+**Don't regress**
+
+- [ ] `list` path (`/api/agents`, not `/me`) still returns 401 for anonymous callers.
+- [ ] `POST /api/agents` still requires auth.
+- [ ] The `/me` route rewrite in [vercel.json](../../vercel.json) is untouched.
+
+## Constraints
+
+- **Do not change the route rewrite.** The `vercel.json` plumbing works; the bug is in the handler.
+- **Do not add a new runtime dependency.** `sql` from `_lib/db.js`, `zod`, `jose` are all that's allowed.
+- **Do not silently swallow unknown errors.** The existing `42P01` swallow is the *only* acceptable silent fallback — anything else must `throw` so `wrap()` can 500 it visibly. The goal is to eliminate 500s by fixing root causes, not by hiding them.
+- Keep the file under 300 lines. If your fix balloons the file, move helpers into `_lib/`.
+
+## Verification
+
+1. `node --check api/agents.js`
+2. `npx vite build` — should pass (ignore pre-existing `@avaturn/sdk` warning).
+3. Run your regression script against a local dev deploy:
+ ```bash
+ node scripts/test-agents-me.mjs
+ ```
+ Output should show three passing cases: anonymous → 200 null, fresh user → 200 agent, existing user → 200 agent.
+4. Concurrency check — with `DATABASE_URL` pointed at a dev branch:
+ ```bash
+ for i in {1..10}; do curl -s -b "__Host-sid=$SID" https://localhost/api/agents/me & done; wait
+ psql "$DATABASE_URL" -c "select count(*) from agent_identities where user_id = '<uid>' and deleted_at is null"
+ ```
+ Must return `1`.
+
+## Scope boundaries — do NOT do these
+
+- Do not add logout UX, session refresh, or a "log out everywhere" endpoint. That is task 05.
+- Do not redesign how wallets link to users. That is task 03.
+- Do not touch SIWE nonce/verify. That is task 02.
+- Do not refactor `api/agents.js` into multiple files.
+- Do not add a new auth mode.
+
+## Reporting
+
+- Root cause (one sentence).
+- The diff summary for [api/agents.js](../../api/agents.js) (which functions changed, which lines).
+- The regression-test file path + output.
+- Concurrency check result.
+- Any unrelated bugs noticed (don't fix — just note).
diff --git a/prompts/wallet-auth/01-siwe-schema.md b/prompts/wallet-auth/01-siwe-schema.md
new file mode 100644
index 000000000..a2c952352
--- /dev/null
+++ b/prompts/wallet-auth/01-siwe-schema.md
@@ -0,0 +1,71 @@
+# Task 01 — SIWE schema migration
+
+## Why this exists
+
+We have `users` (email + password) and `agent_identities` (per-agent wallet). We have **no** place to store the fact that a wallet address *is* a user, and no place to store single-use auth nonces. Without both, SIWE sign-in is either impossible (no user mapping) or replayable (no nonce tracking).
+
+## Files you own
+
+- Create: `specs/schema/NNN-siwe-auth.sql` (look in `api/_lib/schema.sql` and `specs/schema/` to find the current highest number; use the next).
+- Edit: `api/_lib/schema.sql` — same DDL appended so a fresh bootstrap still works end-to-end.
+
+Do not touch any other migration file.
+
+## Deliverable
+
+### Column additions on `users`
+
+```sql
+ALTER TABLE users
+ ADD COLUMN IF NOT EXISTS wallet_address text,
+ ADD COLUMN IF NOT EXISTS wallet_chain_id integer,
+ ADD COLUMN IF NOT EXISTS wallet_linked_at timestamptz;
+
+CREATE UNIQUE INDEX IF NOT EXISTS users_wallet_address_unique
+ ON users (lower(wallet_address))
+ WHERE wallet_address IS NOT NULL;
+```
+
+Notes:
+- `wallet_address` nullable — existing email users keep working.
+- Case-insensitive unique — EIP-55 checksummed and all-lowercase addresses must collide.
+- `wallet_chain_id` optional because SIWE can be chain-agnostic; store the chain the user signed on for audit.
+
+### New table `auth_nonces`
+
+```sql
+CREATE TABLE IF NOT EXISTS auth_nonces (
+ nonce text PRIMARY KEY,
+ purpose text NOT NULL, -- 'siwe-login' | 'siwe-link'
+ issued_to text, -- wallet address if known at issue time, else null
+ expires_at timestamptz NOT NULL,
+ used_at timestamptz,
+ created_at timestamptz NOT NULL DEFAULT now()
+);
+
+CREATE INDEX IF NOT EXISTS auth_nonces_expires_idx ON auth_nonces (expires_at);
+```
+
+Notes:
+- `nonce` is 16+ random bytes base64url'd on the server; treat it as an opaque PK.
+- `used_at` is set on successful verify — never allow the same nonce twice.
+- A nightly cron / lazy cleanup can prune `expires_at < now()` rows; don't build it here.
+
+## Constraints
+
+- Use `CREATE ... IF NOT EXISTS` everywhere so re-running the bootstrap is safe.
+- Don't add triggers. Don't add RLS policies unless the rest of the project uses them.
+- Don't change column order on `users`; only append.
+
+## Acceptance test
+
+1. `psql` against a throwaway DB: run `api/_lib/schema.sql` fresh → no errors.
+2. Run the new migration file on an existing DB (simulate: load `schema.sql` once, then the migration) → idempotent, no errors.
+3. `INSERT INTO users (id, email, wallet_address, wallet_chain_id, wallet_linked_at) VALUES (gen_random_uuid(), '[email protected]', '0xABC...', 8453, now());` succeeds.
+4. Attempting to insert a second row with the same address in different case fails the unique constraint.
+5. `INSERT INTO auth_nonces (nonce, purpose, expires_at) VALUES ('abc', 'siwe-login', now() + interval '5 minutes');` succeeds.
+
+## Reporting
+
+- Migration file path and full SQL.
+- Any existing schema oddities you had to work around.
diff --git a/prompts/wallet-auth/02-siwe-nonce-endpoint.md b/prompts/wallet-auth/02-siwe-nonce-endpoint.md
new file mode 100644
index 000000000..ce7ae132b
--- /dev/null
+++ b/prompts/wallet-auth/02-siwe-nonce-endpoint.md
@@ -0,0 +1,70 @@
+# Task 02 — SIWE nonce endpoint
+
+## Why this exists
+
+Before a user signs anything with their wallet, we must hand them a server-issued, single-use, time-limited nonce. If we let the client pick the nonce, we get replay attacks and cross-origin confusion.
+
+## Files you own
+
+- Create: `api/auth/siwe-nonce.js`
+- Edit: `vercel.json` — add one route immediately after the other `/api/auth/*` routes.
+- Edit: `api/_lib/rate-limit.js` — add a new preset `siweNonceIp`.
+
+Do not touch `api/auth/login.js`, `api/auth/register.js`, `api/auth/me.js`, or `api/_lib/auth.js`.
+
+## Deliverable
+
+### Endpoint behavior
+
+`POST /api/auth/siwe/nonce` (JSON body optional: `{ purpose?: "login" | "link", address?: "0x..." }`)
+
+- Generates a 128-bit random value, base64url-encoded → `nonce`.
+- Computes `expires_at = now + 5 minutes`.
+- Inserts into `auth_nonces` with `purpose` defaulting to `'siwe-login'` and `issued_to` = lowercased `address` if provided.
+- Responds `200 { nonce, expiresAt, domain, statement, chainId, version }` — include the full SIWE message fields so the client can build the exact string to sign.
+
+Suggested `statement`: `"Sign in to 3D Agent. This request will not trigger a transaction or cost gas."`
+
+Include `domain = new URL(env.APP_ORIGIN).host` and `chainId` as a server-advertised number (1 for mainnet, or whatever matches `env.SIWE_CHAIN_ID` — add that env var with a default of 1).
+
+### Rate limiting
+
+Add to `api/_lib/rate-limit.js`:
+
+```js
+siweNonceIp: (ip) => getLimiter('siwe:nonce:ip', { limit: 30, window: '10 m' }).limit(ip),
+```
+
+Call it first thing in the handler with `clientIp(req)`; on `!success`, return 429 with `retry_after`.
+
+### Error shape
+
+Reuse the existing `json(res, body, status)` and `error(res, code, msg, status)` helpers from `api/_lib/http.js` — don't roll your own.
+
+### Vercel route
+
+After the last `/api/auth/...` line in `vercel.json`:
+
+```json
+{ "src": "/api/auth/siwe/nonce", "dest": "/api/auth/siwe-nonce" },
+```
+
+## Constraints
+
+- Use `crypto.randomBytes(16).toString('base64url')` for the nonce. No `Math.random()`, no client-supplied randomness.
+- Do not return `Set-Cookie` here. Session issuance happens only after `verify`.
+- Do not look up the user here. This endpoint is callable pre-auth.
+
+## Acceptance test
+
+1. `node --check api/auth/siwe-nonce.js` passes.
+2. `curl -X POST $APP_ORIGIN/api/auth/siwe/nonce -H 'content-type: application/json' -d '{}'` returns `{ nonce, expiresAt, domain, statement, chainId, version }`.
+3. The returned `nonce` is 22 chars (base64url of 16 bytes, no padding).
+4. `SELECT * FROM auth_nonces ORDER BY created_at DESC LIMIT 1;` shows the row with `used_at IS NULL`.
+5. Hammer the endpoint 40× from one IP — the 31st returns 429.
+
+## Reporting
+
+- Final `statement` string used (it appears in the user's wallet — copy matters).
+- `chainId` default chosen and why.
+- Any deviations from the EIP-4361 SIWE message schema.
diff --git a/prompts/wallet-auth/03-siwe-verify-endpoint.md b/prompts/wallet-auth/03-siwe-verify-endpoint.md
new file mode 100644
index 000000000..7aaeb3681
--- /dev/null
+++ b/prompts/wallet-auth/03-siwe-verify-endpoint.md
@@ -0,0 +1,86 @@
+# Task 03 — SIWE verify endpoint
+
+## Why this exists
+
+The user signs the SIWE message client-side. The server must:
+1. Recover the signing address.
+2. Validate the nonce is ours, unused, unexpired.
+3. Bind that address to a user row (find-or-create).
+4. Issue our standard `__Host-sid` session cookie.
+
+Without this, a signed message is meaningless to the rest of the app.
+
+## Files you own
+
+- Create: `api/auth/siwe-verify.js`.
+- Edit: `vercel.json` — one route line.
+- Edit: `api/_lib/rate-limit.js` — add `siweVerifyIp` preset.
+
+Do not touch existing auth handlers.
+
+## Deliverable
+
+### Endpoint behavior
+
+`POST /api/auth/siwe/verify`
+
+Body:
+```json
+{
+ "message": "<full EIP-4361 message the user signed>",
+ "signature": "0x...",
+ "purpose": "login"
+}
+```
+
+Steps:
+
+1. IP rate limit: `siweVerifyIp` (60 / 10m). On fail → 429.
+2. Parse the SIWE message. Extract: `domain`, `address`, `statement`, `uri`, `version`, `chainId`, `nonce`, `issuedAt`, `expirationTime`.
+ - Minimum viable parser: regex out the fields. No new dep.
+3. Reject if `domain !== new URL(env.APP_ORIGIN).host`.
+4. Reject if `version !== '1'`.
+5. Reject if `expirationTime` is present and past, or if `issuedAt` is >10 min old.
+6. Recover signer: `ethers.verifyMessage(message, signature)` (ethers v6 is already a dep). Reject if `recovered.toLowerCase() !== address.toLowerCase()`.
+7. `SELECT * FROM auth_nonces WHERE nonce = $1 FOR UPDATE` inside a transaction. Reject if row absent, `expires_at < now`, or `used_at IS NOT NULL`. Then `UPDATE auth_nonces SET used_at = now() WHERE nonce = $1`.
+8. Find-or-create user:
+ - `SELECT * FROM users WHERE lower(wallet_address) = lower($1)`.
+ - If missing, `INSERT INTO users (id, wallet_address, wallet_chain_id, wallet_linked_at, created_at) VALUES (...)`. `email` stays NULL.
+9. Issue session: reuse `createSession({ userId, userAgent, ip })` from `api/_lib/auth.js`. Set `__Host-sid` cookie with the same attributes the email login uses.
+10. Respond `200 { user: { id, walletAddress, chainId, createdAt } }`.
+
+### Rate limit preset
+
+```js
+siweVerifyIp: (ip) => getLimiter('siwe:verify:ip', { limit: 60, window: '10 m' }).limit(ip),
+```
+
+### Route
+
+```json
+{ "src": "/api/auth/siwe/verify", "dest": "/api/auth/siwe-verify" },
+```
+
+## Constraints
+
+- Use only `ethers` for signature verification — no new deps.
+- Treat the SIWE message as untrusted. Never `eval`, never pass it to `new Function`. Parse with regex/split only.
+- Enforce the domain check. An attacker tricking the user to sign a message bound to another host must not succeed here.
+- Do NOT auto-link the wallet to an email user. If the wallet is not known, create a **new** wallet-only user. Linking is task 06.
+- Return a generic error message on all failures (`{ error: "invalid signature" }`). Do not leak which specific check failed — that helps attackers.
+
+## Acceptance test
+
+1. `node --check api/auth/siwe-verify.js` passes.
+2. End-to-end from the browser: fetch `/api/auth/siwe/nonce`, build SIWE message, sign with MetaMask, POST to `/api/auth/siwe/verify` → receive `200` with `Set-Cookie: __Host-sid=...`.
+3. `GET /api/auth/me` with that cookie returns the wallet user.
+4. Replay the same `{message, signature}` → `400`.
+5. Tamper with one byte of the signature → `400`.
+6. Sign a message with `domain = evil.com` → `400`.
+7. Database shows the `auth_nonces` row with `used_at` set.
+
+## Reporting
+
+- Exact SIWE parser used (paste the regex/function).
+- Any deviations from EIP-4361 and why.
+- Session cookie attributes (should match email login exactly).
diff --git a/prompts/wallet-auth/04-signin-ui.md b/prompts/wallet-auth/04-signin-ui.md
new file mode 100644
index 000000000..8b0b675ba
--- /dev/null
+++ b/prompts/wallet-auth/04-signin-ui.md
@@ -0,0 +1,76 @@
+# Task 04 — Sign-in-with-wallet UI
+
+## Why this exists
+
+Tasks 01–03 built the backend. Without a visible button and a working client-side dance, none of it is reachable. This task makes the flow real for users.
+
+## Files you own
+
+- Create: `src/wallet-auth.js` — a tiny client module. No framework.
+- Edit: `index.html` — add a button in the header nav.
+- Edit: `public/dashboard/login.html` (or whatever the current login page is — locate it first) — add a second button: "Sign in with wallet".
+- Edit: `src/erc8004/agent-registry.js` — **export** `connectWallet` if it isn't already; do not change its logic.
+
+Do not edit `src/app.js` beyond a one-line import if strictly needed.
+
+## Deliverable
+
+### `src/wallet-auth.js`
+
+Exports a single async function `signInWithWallet({ chainId } = {})` that:
+
+1. Calls `connectWallet()` from `src/erc8004/agent-registry.js` → `{ provider, signer, address, chainId: connectedChainId }`.
+2. `POST /api/auth/siwe/nonce` with `{ purpose: 'login', address }` — receives `{ nonce, expiresAt, domain, statement, version }`.
+3. Builds the EIP-4361 message string client-side:
+ ```
+ ${domain} wants you to sign in with your Ethereum account:
+ ${address}
+
+ ${statement}
+
+ URI: ${location.origin}
+ Version: ${version}
+ Chain ID: ${connectedChainId}
+ Nonce: ${nonce}
+ Issued At: ${new Date().toISOString()}
+ ```
+4. `signature = await signer.signMessage(message)`.
+5. `POST /api/auth/siwe/verify` with `{ message, signature, purpose: 'login' }` and `credentials: 'include'`.
+6. On success: `window.location.assign('/dashboard')`.
+7. On any error, throw with a user-readable message; the caller renders it in the UI.
+
+Also export `signOut()` that `POST /api/auth/logout` and reloads the page.
+
+### Header button (`index.html`)
+
+A single `<button id="btn-wallet-signin" class="btn-wallet">Sign in with wallet</button>` placed next to the existing nav items. When the user is already signed in (detect via `GET /api/auth/me` on load), hide it and show a small chip with the truncated wallet address + a "sign out" option.
+
+Keep the styling minimal — reuse existing `--accent-*` tokens. No new font loads, no new color palette.
+
+### Login page second option
+
+Under the existing "email + password" form, a visual divider ("— or —") and the same "Sign in with wallet" button.
+
+## Constraints
+
+- Do **not** add Privy UI here if Privy isn't already invoked; task 05 covers Privy backend integration.
+- Do not introduce a bundler config change. `src/wallet-auth.js` is imported lazily from the button click handler.
+- On devices without injected ethereum and without Privy configured, surface a clear message: "No wallet detected. Install MetaMask or switch to a browser with wallet support."
+- Do not `alert(...)`. Use a small inline status region under the button.
+
+## Acceptance test
+
+1. `node --check src/wallet-auth.js` passes.
+2. `npx vite build` — no new warnings.
+3. Manual (Chrome + MetaMask):
+ - Click "Sign in with wallet" in the header → MetaMask opens with the SIWE message → approve → redirected to `/dashboard` as a signed-in user.
+ - Refresh the page → stays signed in, chip shows truncated address.
+ - Click sign out → cookie cleared, button returns.
+4. Manual (no injected wallet): button shows a message instead of throwing.
+5. DevTools Network tab shows exactly: `nonce` (POST), one `personal_sign` RPC to the wallet, `verify` (POST).
+
+## Reporting
+
+- Screenshots (or a recorded gif) of the signed message in MetaMask — the `statement` and `domain` should be clearly readable and trustworthy.
+- Any friction moments (double-prompts, hanging promises, race conditions on fast clicks).
+- How the signed-in state detection works (cookie? `me` fetch on load?) and the tradeoffs.
diff --git a/prompts/wallet-auth/05-privy-backend-verify.md b/prompts/wallet-auth/05-privy-backend-verify.md
new file mode 100644
index 000000000..580c29b1f
--- /dev/null
+++ b/prompts/wallet-auth/05-privy-backend-verify.md
@@ -0,0 +1,66 @@
+# Task 05 — Privy-issued token → backend verify
+
+## Why this exists
+
+Privy (already a client-side dep) gives us embedded wallets, email-based wallet login, and WalletConnect UX for free. Today it is used only on the ERC-8004 registration page. If we accept a Privy access token at the backend, we get:
+- Users without a browser wallet can still sign in (Privy issues them an embedded wallet).
+- Mobile / Brave / Safari users without MetaMask can still sign in via WalletConnect UX.
+- Existing MetaMask users keep working because task 03 still accepts raw SIWE.
+
+## Files you own
+
+- Create: `api/auth/privy-verify.js`.
+- Edit: `api/_lib/env.js` — add optional `PRIVY_APP_ID` and `PRIVY_APP_SECRET`. If both absent, this endpoint responds 501 and the SIWE flow from task 03 remains the only path.
+- Edit: `vercel.json` — one route line.
+- Edit: `src/wallet-auth.js` (from task 04) — add an alternative path `signInWithPrivy()` that calls Privy SDK, grabs the access token, and POSTs to `/api/auth/privy/verify`.
+
+Do not rewrite task 03.
+
+## Deliverable
+
+### Endpoint
+
+`POST /api/auth/privy/verify`
+
+Body: `{ accessToken: "eyJ..." }` (Privy-issued JWT).
+
+Steps:
+1. If `env.PRIVY_APP_ID` or `env.PRIVY_APP_SECRET` unset → `501 { error: "privy not configured" }`.
+2. Verify the JWT with Privy's JWKS. Use `jose` (already a dep). Fetch JWKS from `https://auth.privy.io/api/v1/apps/${appId}/jwks.json`, cache for 10 minutes in memory.
+3. Require `aud === env.PRIVY_APP_ID` and `iss === 'privy.io'`. Reject expired tokens.
+4. From the decoded token, read the linked wallet address (Privy puts it under custom claims — check `linked_accounts` / `wallet` depending on SDK version; document what you found).
+5. Find-or-create a `users` row by `wallet_address` — same logic as task 03.
+6. Issue the same `__Host-sid` session cookie via `createSession`.
+
+### Client helper
+
+In `src/wallet-auth.js`, add:
+
+```js
+export async function signInWithPrivy() {
+ // Load @privy-io/js-sdk-core lazily; get accessToken; POST to /api/auth/privy/verify.
+}
+```
+
+Wire a second button "Sign in with Privy" that appears only if `PRIVY_APP_ID` is present on the frontend (expose via an `/api/config` or a `<meta>` tag — do not inline the secret, only the public app id).
+
+## Constraints
+
+- Do not trust anything in the Privy JWT besides what's signed (no unsigned `info` blobs).
+- Do not call Privy's REST API from every request — verify the JWT locally with JWKS.
+- JWKS fetch must have a 3s timeout and a cached fallback.
+- If the Privy token has no linked wallet, reject — we require a wallet for the identity binding. Document this in `Reporting`.
+
+## Acceptance test
+
+1. `node --check api/auth/privy-verify.js` passes.
+2. With Privy configured: sign in via the Privy modal → `accessToken` retrieved → POST verify → session cookie set → signed in.
+3. Without Privy configured: button is hidden; if someone manually hits the endpoint, they get 501.
+4. Expired Privy token → 401.
+5. Token signed by a different Privy app → 401.
+
+## Reporting
+
+- Which claim in the Privy JWT carries the wallet address — paste an example token payload.
+- JWKS cache strategy and TTL.
+- Graceful-degradation behavior when Privy is down (pick one, document it).
diff --git a/prompts/wallet-auth/06-link-wallet-to-account.md b/prompts/wallet-auth/06-link-wallet-to-account.md
new file mode 100644
index 000000000..e35c27557
--- /dev/null
+++ b/prompts/wallet-auth/06-link-wallet-to-account.md
@@ -0,0 +1,68 @@
+# Task 06 — Link a wallet to an existing email account
+
+## Why this exists
+
+Existing users signed up with email + password. They shouldn't have to create a second account to use wallet features. Conversely, a wallet-only user should be able to add an email for password recovery. This task builds the linking flow in both directions without breaking either.
+
+## Files you own
+
+- Create: `api/auth/wallet-link.js`.
+- Create: `api/auth/wallet-unlink.js`.
+- Create: `public/dashboard/settings-wallet.html` (or add a panel to the existing dashboard settings page if one exists — inspect `public/dashboard/` first).
+- Edit: `vercel.json` — two route lines, adjacent to the SIWE routes.
+
+Do not modify `api/auth/login.js` or `api/auth/register.js`.
+
+## Deliverable
+
+### `POST /api/auth/wallet/link`
+
+Requires existing session (email or wallet).
+
+Body: `{ message, signature, purpose: "link" }` (same shape as siwe-verify).
+
+Steps:
+1. `getSessionUser(req)` → user. 401 if missing.
+2. Do the full SIWE verification (lift the verify helper from task 03 into `api/_lib/siwe.js` and import here — if the helper wasn't extracted in 03, extract it now but keep the 03 behavior byte-identical).
+3. Require `purpose === 'link'` on the nonce; reject `'login'` nonces here.
+4. If the recovered address already belongs to **another** user → 409 `{ error: "wallet already linked to another account" }`.
+5. Otherwise: `UPDATE users SET wallet_address = $1, wallet_chain_id = $2, wallet_linked_at = now() WHERE id = $userId`.
+6. Respond `200 { user }`.
+
+### `POST /api/auth/wallet/unlink`
+
+Requires existing session. Body: `{}`.
+
+- Refuse if the user has NO email (otherwise they lose all access). Return 409 with a clear message.
+- Otherwise clear the three wallet columns, respond 200.
+
+### Settings UI
+
+A simple panel:
+- "Linked wallet: `0xABC…` (Base Mainnet) — *Unlink*"
+- Or: "No wallet linked — [Link your wallet] button"
+- The *Link* button triggers the client-side SIWE dance with `purpose: "link"`.
+- The *Unlink* button hits the unlink endpoint.
+
+Use the dashboard's existing CSS and layout. Do not introduce new global styles.
+
+## Constraints
+
+- Do not auto-link on sign-in. Users must explicitly click "link" from settings. This prevents session fixation / drive-by linking.
+- The `wallet-link` endpoint requires BOTH a valid session AND a valid signature. Either alone is not enough.
+- Preserve case-insensitive uniqueness — check with `lower(wallet_address)` in the 409 query.
+
+## Acceptance test
+
+1. Email user → settings → link wallet (SIWE) → success; `users.wallet_address` populated.
+2. Try linking the same wallet from a second email user → 409.
+3. Wallet-only user → settings → link wallet returns a sensible message (already linked).
+4. Email+wallet user → unlink → success; wallet columns null.
+5. Wallet-only user (no email) → unlink → 409, stays linked.
+6. Replay the link message+signature → 400 (nonce consumed).
+
+## Reporting
+
+- Where the shared SIWE helper landed (`api/_lib/siwe.js`?) and its exported surface.
+- Any UX gotchas when the user has to switch accounts in their wallet mid-flow.
+- Confirmation that both directions (email → +wallet, wallet → +email) are reachable.
diff --git a/public/dashboard/dashboard.js b/public/dashboard/dashboard.js
index 772fa2d36..4483be2bb 100644
--- a/public/dashboard/dashboard.js
+++ b/public/dashboard/dashboard.js
@@ -13,6 +13,12 @@ export const api = {
listKeys: () => j('GET', '/api/keys'),
createKey: (body) => j('POST', '/api/keys', body),
revokeKey: (id) => j('DELETE', `/api/keys/${id}`),
+ listWidgets: () => j('GET', '/api/widgets'),
+ getWidget: (id) => j('GET', `/api/widgets/${encodeURIComponent(id)}`),
+ patchWidget: (id, patch) => j('PATCH', `/api/widgets/${encodeURIComponent(id)}`, patch),
+ deleteWidget: (id) => j('DELETE', `/api/widgets/${encodeURIComponent(id)}`),
+ duplicateWidget: (id) => j('POST', `/api/widgets/${encodeURIComponent(id)}/duplicate`),
+ widgetStats: (id) => j('GET', `/api/widgets/${encodeURIComponent(id)}/stats`),
};
async function j(method, path, body) {
@@ -50,6 +56,7 @@ const tabs = {
create: renderCreate,
edit: renderEdit,
upload: renderUpload,
+ widgets: renderWidgets,
embed: renderEmbed,
keys: renderKeys,
mcp: renderMcp,
@@ -617,6 +624,7 @@ async function renderEmbed(root) {
<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>
+ ${onchainCard(agent)}
</div>
</div>
`;
@@ -635,6 +643,8 @@ async function renderEmbed(root) {
}
});
}
+
+ bindOnchainDeploy(body, agent);
}
function snippetBlock(title, code, _lang) {
@@ -650,11 +660,698 @@ function snippetBlock(title, code, _lang) {
`;
}
+// ── Onchain deploy card ─────────────────────────────────────────────────────
+// Mints the agent on ERC-8004 so any host (Lobehub / Claude / etc.) can resolve
+// it from its onchain ID instead of needing the /agent/:id URL. Uses the
+// wallet the user already connected for SIWE; pins the avatar GLB + manifest
+// to IPFS; calls register() on the Identity Registry; writes the resulting
+// agentId back to our DB so the agent row becomes the bridge between our host
+// and the onchain record.
+function onchainCard(agent) {
+ const alreadyDeployed = !!agent.erc8004_agent_id;
+ const chainHint = agent.chain_id ? ` on chain ${esc(String(agent.chain_id))}` : '';
+ const statusHtml = alreadyDeployed
+ ? `<p style="margin:0 0 10px; color:#9a8cff">Deployed: agentId <code>${esc(String(agent.erc8004_agent_id))}</code>${chainHint}.</p>`
+ : `<p class="muted" style="margin:0 0 10px">Mint your agent as an ERC-8004 onchain identity. Any client that knows the agentId can resolve your avatar, skills, and reputation — no off-chain registry lookup needed.</p>`;
+ return `
+ <div class="card" id="onchain-card" style="margin-top:14px">
+ <h3 style="margin:0 0 6px">Deploy onchain (ERC-8004)</h3>
+ ${statusHtml}
+ <div class="row" style="gap:8px; flex-wrap:wrap">
+ <input id="onchain-ipfs-token" placeholder="web3.storage or Filebase API token" style="flex:1; min-width:260px" type="password">
+ <button class="btn" id="onchain-deploy" type="button">${alreadyDeployed ? 'Redeploy' : 'Deploy now'}</button>
+ </div>
+ <div id="onchain-log" class="muted" style="margin-top:10px; font-family: ui-monospace, SF Mono, Menlo, monospace; font-size:12px; white-space:pre-wrap"></div>
+ </div>
+ `;
+}
+
+// Attach the click handler after the embed DOM has been rendered. Called from
+// renderEmbed below via a mutation after body.innerHTML is set.
+function bindOnchainDeploy(body, agent) {
+ const btn = body.querySelector('#onchain-deploy');
+ const log = body.querySelector('#onchain-log');
+ const token = body.querySelector('#onchain-ipfs-token');
+ if (!btn) return;
+
+ btn.addEventListener('click', async () => {
+ btn.disabled = true;
+ const say = (msg, isError = false) => {
+ log.style.color = isError ? '#ffb3b3' : '#888';
+ log.textContent = (log.textContent ? log.textContent + '\n' : '') + msg;
+ };
+ log.textContent = '';
+
+ if (!agent.avatar_id) {
+ say('Your agent has no avatar yet. Create one from a selfie first.', true);
+ btn.disabled = false;
+ return;
+ }
+
+ try {
+ say('Fetching avatar GLB…');
+ const avRes = await fetch(`/api/avatars/${encodeURIComponent(agent.avatar_id)}`, { credentials: 'include' });
+ if (!avRes.ok) throw new Error((await avRes.json()).error_description || 'avatar fetch failed');
+ const avatarRow = (await avRes.json()).avatar;
+ const glbUrl = avatarRow.url || avatarRow.model_url;
+ if (!glbUrl) throw new Error('avatar has no URL');
+ const glbBlob = await (await fetch(glbUrl)).blob();
+ const glbFile = new File([glbBlob], `${agent.id}.glb`, { type: 'model/gltf-binary' });
+
+ say('Opening registration flow… (loading chain module)');
+ const { registerAgent } = await import('/src/erc8004/agent-registry.js');
+
+ const result = await registerAgent({
+ glbFile,
+ name: agent.name || 'Agent',
+ description: agent.description || `3D agent ${agent.id}`,
+ apiToken: token.value.trim() || undefined,
+ onStatus: (msg) => say(msg),
+ });
+
+ say(`Persisting onchain IDs to your account…`);
+ const wallet = window.ethereum?.selectedAddress || '';
+ const chainId = Number((await window.ethereum?.request?.({ method: 'eth_chainId' })) || 0) || undefined;
+ await fetch(`/api/agents/${encodeURIComponent(agent.id)}/wallet`, {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ wallet_address: wallet,
+ chain_id: chainId ? parseInt(chainId.toString(16) === chainId.toString() ? chainId : String(chainId), 10) || null : null,
+ erc8004_agent_id: result.agentId,
+ }),
+ });
+
+ say(`✓ Done. agentId=${result.agentId}, registration=ipfs://${result.registrationCID}, tx=${result.txHash}`);
+ } catch (err) {
+ say(err.message || String(err), true);
+ } finally {
+ btn.disabled = false;
+ }
+ });
+}
+
// ── Billing placeholder ─────────────────────────────────────────────────────
function renderBilling(root) {
root.innerHTML = `<h1>Plan &amp; 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>`;
}
+// ── Widgets ─────────────────────────────────────────────────────────────────
+// Saved 3D experiences the user has generated in the Studio. Each gets its own
+// card with a live, lazy-loaded preview iframe. Editing happens in /studio —
+// the dashboard is for managing what already exists.
+
+const WIDGET_TYPE_META = {
+ 'turntable': { label: 'Turntable', color: '#6a5cff' },
+ 'animation-gallery': { label: 'Animations', color: '#ff5ca8' },
+ 'talking-agent': { label: 'Talking Agent', color: '#00e5a0' },
+ 'passport': { label: 'Passport', color: '#f0c14b' },
+ 'hotspot-tour': { label: 'Hotspot Tour', color: '#5cc8ff' },
+};
+
+const WIDGET_PREFS_KEY = 'dashboard.widgets.prefs';
+const DEFAULT_WIDGET_PREFS = { sort: 'updated', type: '', q: '' };
+
+function loadWidgetPrefs() {
+ try { return { ...DEFAULT_WIDGET_PREFS, ...JSON.parse(localStorage.getItem(WIDGET_PREFS_KEY) || '{}') }; }
+ catch { return { ...DEFAULT_WIDGET_PREFS }; }
+}
+function saveWidgetPrefs(prefs) {
+ try { localStorage.setItem(WIDGET_PREFS_KEY, JSON.stringify(prefs)); } catch {}
+}
+
+async function renderWidgets(root) {
+ const prefs = loadWidgetPrefs();
+ root.innerHTML = `
+ <div class="widgets-header">
+ <div>
+ <h1>Your widgets</h1>
+ <p class="sub">Embeddable 3D experiences — each gets a stable URL.</p>
+ </div>
+ <a class="btn-primary" href="/studio">+ New widget</a>
+ </div>
+ <div class="widget-toolbar" role="toolbar" aria-label="Widget filters">
+ <label class="sr-only" for="w-search">Search widgets</label>
+ <input id="w-search" type="search" placeholder="Search by name…" value="${attr(prefs.q)}">
+ <label class="sr-only" for="w-type">Filter by type</label>
+ <select id="w-type" aria-label="Filter by widget type">
+ <option value="">All types</option>
+ ${Object.entries(WIDGET_TYPE_META).map(([t, m]) =>
+ `<option value="${attr(t)}" ${prefs.type===t?'selected':''}>${esc(m.label)}</option>`).join('')}
+ </select>
+ <label class="sr-only" for="w-sort">Sort widgets</label>
+ <select id="w-sort" aria-label="Sort widgets">
+ <option value="updated" ${prefs.sort==='updated'?'selected':''}>Recently updated</option>
+ <option value="views" ${prefs.sort==='views' ?'selected':''}>Most viewed</option>
+ <option value="name" ${prefs.sort==='name' ?'selected':''}>Name (A–Z)</option>
+ </select>
+ <span id="w-count" class="muted" aria-live="polite"></span>
+ </div>
+ <div id="widget-list" class="cards" aria-busy="true"><div class="muted">Loading…</div></div>
+ `;
+
+ const list = root.querySelector('#widget-list');
+ const countEl = root.querySelector('#w-count');
+ let widgets = [];
+
+ try {
+ const data = await api.listWidgets();
+ widgets = data.widgets || [];
+ } catch (e) {
+ list.innerHTML = `<div class="err">${esc(e.message)}</div>`;
+ list.setAttribute('aria-busy', 'false');
+ return;
+ }
+
+ const observer = lazyIframeObserver();
+
+ function rerender() {
+ list.setAttribute('aria-busy', 'false');
+ if (!widgets.length) {
+ list.innerHTML = `
+ <div class="empty" style="grid-column:1/-1">
+ <p style="font-size:15px;color:#ccc;margin:0 0 8px">No widgets yet.</p>
+ <p style="margin:0 0 18px">Your widgets are embeddable 3D experiences — pick an avatar, a type, and we handle the rest.</p>
+ <a class="btn-primary" href="/studio">+ Create your first widget</a>
+ </div>
+ `;
+ countEl.textContent = '';
+ return;
+ }
+ const filtered = applyWidgetFilters(widgets, prefs);
+ countEl.textContent = filtered.length === widgets.length
+ ? `${widgets.length} widget${widgets.length===1?'':'s'}`
+ : `${filtered.length} of ${widgets.length}`;
+ list.innerHTML = '';
+ if (!filtered.length) {
+ list.innerHTML = `<div class="empty" style="grid-column:1/-1">No widgets match the current filters.</div>`;
+ return;
+ }
+ for (const w of filtered) {
+ const card = widgetCard(w, { reload: rerender, mutate: (next) => mutateLocal(widgets, w.id, next), remove: () => { widgets = widgets.filter((x) => x.id !== w.id); rerender(); } });
+ list.appendChild(card);
+ const ifr = card.querySelector('iframe[data-src]');
+ if (ifr) observer.observe(ifr);
+ }
+ }
+
+ root.querySelector('#w-search').addEventListener('input', (e) => { prefs.q = e.target.value; saveWidgetPrefs(prefs); rerender(); });
+ root.querySelector('#w-type').addEventListener('change', (e) => { prefs.type = e.target.value; saveWidgetPrefs(prefs); rerender(); });
+ root.querySelector('#w-sort').addEventListener('change', (e) => { prefs.sort = e.target.value; saveWidgetPrefs(prefs); rerender(); });
+
+ rerender();
+}
+
+function mutateLocal(arr, id, next) {
+ const i = arr.findIndex((x) => x.id === id);
+ if (i >= 0) arr[i] = { ...arr[i], ...next };
+}
+
+function applyWidgetFilters(widgets, prefs) {
+ let out = widgets;
+ if (prefs.type) out = out.filter((w) => w.type === prefs.type);
+ if (prefs.q) {
+ const q = prefs.q.trim().toLowerCase();
+ if (q) out = out.filter((w) => (w.name || '').toLowerCase().includes(q));
+ }
+ out = [...out];
+ if (prefs.sort === 'name') out.sort((a, b) => (a.name || '').localeCompare(b.name || ''));
+ if (prefs.sort === 'views') out.sort((a, b) => (b.view_count || 0) - (a.view_count || 0));
+ if (prefs.sort === 'updated' || !prefs.sort) {
+ out.sort((a, b) => new Date(b.updated_at) - new Date(a.updated_at));
+ }
+ return out;
+}
+
+function widgetCard(w, ctx) {
+ const meta = WIDGET_TYPE_META[w.type] || { label: w.type, color: '#888' };
+ const card = document.createElement('div');
+ card.className = 'widget-card card';
+ card.dataset.id = w.id;
+
+ const previewSrc = `/#widget=${encodeURIComponent(w.id)}&kiosk=true&preview=1`;
+ const previewHtml = w.avatar
+ ? `<iframe data-src="${attr(previewSrc)}" loading="lazy" tabindex="-1" title="Preview of ${attr(w.name || 'widget')}"></iframe>`
+ : `<div class="placeholder">Avatar unavailable.<br>Edit to pick a replacement.</div>`;
+
+ card.innerHTML = `
+ <div class="frame">${previewHtml}</div>
+ <div class="title">
+ <h3 title="Double-click to rename">${esc(w.name || 'Untitled')}</h3>
+ <span class="pill"><span class="dot" style="background:${attr(meta.color)}"></span>${esc(meta.label)}</span>
+ </div>
+ <div class="row" style="justify-content:space-between; gap:8px">
+ <span class="meta">${formatViewCount(w.view_count)} · updated ${timeAgo(w.updated_at)}</span>
+ <label class="toggle" title="${w.is_public ? 'Public — anyone with the URL can view' : 'Private — only you can view'}">
+ <input type="checkbox" data-public ${w.is_public?'checked':''}>
+ <span class="track"></span>
+ <span class="label">${w.is_public ? 'Public' : 'Private'}</span>
+ </label>
+ </div>
+ <div class="actions">
+ <a href="/studio?edit=${encodeURIComponent(w.id)}" data-edit>Edit</a>
+ <button data-share type="button">Share</button>
+ <button data-duplicate type="button">Duplicate</button>
+ <button data-details type="button">Details</button>
+ <button data-delete class="danger" type="button">Delete</button>
+ </div>
+ `;
+
+ // Inline rename — double-click on the title swaps in an input.
+ const titleEl = card.querySelector('.title h3');
+ titleEl.addEventListener('dblclick', () => beginRename(card, w, ctx));
+
+ // Public/private toggle — confirm before disabling so embeds aren't silently broken.
+ const toggleInput = card.querySelector('input[data-public]');
+ toggleInput.addEventListener('change', async () => {
+ const next = toggleInput.checked;
+ if (!next && !confirm('Making this widget private will break any existing embeds on other sites. Continue?')) {
+ toggleInput.checked = true;
+ return;
+ }
+ try {
+ await api.patchWidget(w.id, { is_public: next });
+ ctx.mutate({ is_public: next });
+ card.querySelector('.toggle .label').textContent = next ? 'Public' : 'Private';
+ toast(next ? 'Now public' : 'Now private');
+ } catch (err) {
+ toggleInput.checked = !next;
+ toast(err.message || 'Failed to update', true);
+ }
+ });
+
+ card.querySelector('[data-share]').addEventListener('click', () => openShareModal(w));
+ card.querySelector('[data-details]').addEventListener('click', () => openWidgetDrawer(w, ctx));
+ card.querySelector('[data-duplicate]').addEventListener('click', async () => {
+ try {
+ await api.duplicateWidget(w.id);
+ toast('Duplicated');
+ // Re-fetch via navigate so the new row's avatar join is populated.
+ navigate('widgets');
+ } catch (err) { toast(err.message || 'Duplicate failed', true); }
+ });
+ card.querySelector('[data-delete]').addEventListener('click', async () => {
+ if (!confirm(`Delete "${w.name || 'this widget'}"? This cannot be undone.`)) return;
+ try {
+ await api.deleteWidget(w.id);
+ card.style.transition = 'opacity .2s';
+ card.style.opacity = '0';
+ setTimeout(() => ctx.remove(), 220);
+ toast('Deleted');
+ } catch (err) { toast(err.message || 'Delete failed', true); }
+ });
+
+ return card;
+}
+
+function beginRename(card, w, ctx) {
+ const titleEl = card.querySelector('.title h3');
+ if (!titleEl) return;
+ const original = w.name || '';
+ const input = document.createElement('input');
+ input.type = 'text';
+ input.value = original;
+ input.maxLength = 120;
+ input.setAttribute('aria-label', 'Widget name');
+ titleEl.replaceWith(input);
+ input.focus();
+ input.select();
+
+ let settled = false;
+ const restore = (text) => {
+ if (settled) return; settled = true;
+ const h = document.createElement('h3');
+ h.textContent = text;
+ h.title = 'Double-click to rename';
+ input.replaceWith(h);
+ h.addEventListener('dblclick', () => beginRename(card, { ...w, name: text }, ctx));
+ };
+
+ input.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter') { e.preventDefault(); commit(); }
+ else if (e.key === 'Escape') { e.preventDefault(); restore(original); }
+ });
+ input.addEventListener('blur', commit);
+
+ async function commit() {
+ const next = input.value.trim();
+ if (!next || next === original) { restore(original); return; }
+ try {
+ await api.patchWidget(w.id, { name: next });
+ ctx.mutate({ name: next });
+ restore(next);
+ toast('Renamed');
+ } catch (err) {
+ restore(original);
+ toast(err.message || 'Rename failed', true);
+ }
+ }
+}
+
+function lazyIframeObserver() {
+ if (typeof IntersectionObserver === 'undefined') {
+ // Fallback — eagerly hydrate. Old browsers shouldn't pay this a/b cost.
+ return { observe(el) { hydrate(el); } };
+ }
+ const io = new IntersectionObserver((entries) => {
+ for (const entry of entries) {
+ if (entry.isIntersecting) {
+ hydrate(entry.target);
+ io.unobserve(entry.target);
+ }
+ }
+ }, { rootMargin: '120px' });
+ return io;
+ function hydrate(el) {
+ const src = el.getAttribute('data-src');
+ if (src && !el.src) el.src = src;
+ }
+}
+
+// ── Widget details drawer ───────────────────────────────────────────────────
+async function openWidgetDrawer(w, ctx) {
+ const overlay = document.createElement('div');
+ overlay.className = 'drawer-overlay';
+ const drawer = document.createElement('aside');
+ drawer.className = 'drawer';
+ drawer.setAttribute('role', 'dialog');
+ drawer.setAttribute('aria-label', `Widget details — ${w.name || 'untitled'}`);
+ drawer.tabIndex = -1;
+
+ const previewSrc = `/#widget=${encodeURIComponent(w.id)}&kiosk=true&preview=1`;
+ const pageUrl = `${location.origin}/w/${encodeURIComponent(w.id)}`;
+ const iframeSnippet = makeIframeSnippet(w, pageUrl, 600, 600);
+ const scriptSnippet = `<script async src="${location.origin}/embed.js" data-widget="${esc(w.id)}"></script>`;
+ const meta = WIDGET_TYPE_META[w.type] || { label: w.type, color: '#888' };
+
+ drawer.innerHTML = `
+ <header>
+ <h2>${esc(w.name || 'Untitled')}</h2>
+ <button class="btn sec" data-close type="button" aria-label="Close details">Close</button>
+ </header>
+ <div class="body">
+ <div class="frame-lg"><iframe src="${attr(previewSrc)}" title="Preview"></iframe></div>
+ <div>
+ <span class="pill"><span class="dot" style="background:${attr(meta.color)}"></span>${esc(meta.label)}</span>
+ <span class="muted" style="margin-left:8px">${esc(w.is_public ? 'Public' : 'Private')} · updated ${timeAgo(w.updated_at)}</span>
+ </div>
+ <div id="stats-region" aria-live="polite"><div class="muted">Loading stats…</div></div>
+ <details>
+ <summary>Embed code</summary>
+ <div style="display:flex; flex-direction:column; gap:10px; margin-top:8px">
+ <div>
+ <div class="row" style="justify-content:space-between; margin-bottom:4px"><strong style="font-size:12px">Iframe</strong><button class="btn sec" data-copy="iframe" type="button">Copy</button></div>
+ <pre id="snip-iframe" style="margin:0">${esc(iframeSnippet)}</pre>
+ </div>
+ <div>
+ <div class="row" style="justify-content:space-between; margin-bottom:4px"><strong style="font-size:12px">One-line script</strong><button class="btn sec" data-copy="script" type="button">Copy</button></div>
+ <pre id="snip-script" style="margin:0">${esc(scriptSnippet)}</pre>
+ </div>
+ <div>
+ <div class="row" style="justify-content:space-between; margin-bottom:4px"><strong style="font-size:12px">Direct URL</strong><button class="btn sec" data-copy="url" type="button">Copy</button></div>
+ <pre id="snip-url" style="margin:0">${esc(pageUrl)}</pre>
+ </div>
+ </div>
+ </details>
+ <details>
+ <summary>Configuration (read-only)</summary>
+ <pre style="margin:8px 0 0; max-height:220px">${esc(JSON.stringify(w.config || {}, null, 2))}</pre>
+ </details>
+ <div class="danger-zone">
+ <h3>Danger zone</h3>
+ <p class="muted" style="margin:0 0 10px; font-size:12px">Deleting removes the widget for everyone. Embeds will return 404.</p>
+ <button class="btn-primary btn-danger" data-drawer-delete type="button">Delete this widget</button>
+ </div>
+ </div>
+ `;
+
+ document.body.appendChild(overlay);
+ document.body.appendChild(drawer);
+ requestAnimationFrame(() => { overlay.classList.add('open'); drawer.classList.add('open'); });
+ drawer.focus();
+
+ const close = () => {
+ overlay.classList.remove('open');
+ drawer.classList.remove('open');
+ setTimeout(() => { overlay.remove(); drawer.remove(); document.removeEventListener('keydown', onKey); }, 220);
+ };
+ const onKey = (e) => { if (e.key === 'Escape') close(); };
+ document.addEventListener('keydown', onKey);
+ overlay.addEventListener('click', close);
+ drawer.querySelector('[data-close]').addEventListener('click', close);
+
+ for (const btn of drawer.querySelectorAll('[data-copy]')) {
+ btn.addEventListener('click', async () => {
+ const target = drawer.querySelector(`#snip-${btn.dataset.copy}`);
+ if (target) await copyToClipboard(target.textContent, btn);
+ });
+ }
+
+ drawer.querySelector('[data-drawer-delete]').addEventListener('click', async () => {
+ if (!confirm(`Delete "${w.name || 'this widget'}"? This cannot be undone.`)) return;
+ try {
+ await api.deleteWidget(w.id);
+ toast('Deleted');
+ close();
+ ctx?.remove?.();
+ } catch (err) { toast(err.message || 'Delete failed', true); }
+ });
+
+ // Stats — load async, render sparkline.
+ try {
+ const { stats } = await api.widgetStats(w.id);
+ drawer.querySelector('#stats-region').innerHTML = renderStatsPanel(w, stats);
+ } catch (err) {
+ drawer.querySelector('#stats-region').innerHTML = `<div class="err">${esc(err.message || 'Failed to load stats')}</div>`;
+ }
+}
+
+function renderStatsPanel(w, stats) {
+ const total7d = (stats.recent_views_7d || []).reduce((s, d) => s + (d.count || 0), 0);
+ const chatLine = stats.chat_count !== null && stats.chat_count !== undefined
+ ? `<div class="stat"><div class="n">${formatNum(stats.chat_count)}</div><div class="l">Chats (lifetime)</div></div>`
+ : '';
+ const lastSeen = stats.last_viewed_at
+ ? `<div class="muted" style="margin-top:4px; font-size:12px">Last viewed ${timeAgo(stats.last_viewed_at)}</div>`
+ : '';
+ const referers = (stats.top_referers || []).slice(0, 3);
+ const refList = referers.length
+ ? `<details><summary>Top referrers</summary><ul style="margin:6px 0 0; padding-left:18px; font-size:12px; color:#aaa">${referers.map((r) => `<li>${esc(r.host || '(direct)')} — ${formatNum(r.count)}</li>`).join('')}</ul></details>`
+ : '';
+ return `
+ <div class="stat-grid">
+ <div class="stat"><div class="n">${formatNum(stats.view_count)}</div><div class="l">Views (lifetime)</div></div>
+ <div class="stat"><div class="n">${formatNum(total7d)}</div><div class="l">Views (7 days)</div></div>
+ ${chatLine}
+ </div>
+ ${lastSeen}
+ <div style="margin-top:14px">
+ ${sparkline(stats.recent_views_7d || [])}
+ </div>
+ ${refList}
+ `;
+}
+
+function sparkline(days) {
+ if (!days.length) return '<div class="muted" style="font-size:12px">No views yet</div>';
+ const W = 480, H = 60, P = 4;
+ const max = Math.max(1, ...days.map((d) => d.count || 0));
+ const stepX = (W - 2 * P) / Math.max(1, days.length - 1);
+ const pts = days.map((d, i) => {
+ const x = P + i * stepX;
+ const y = H - P - ((d.count || 0) / max) * (H - 2 * P);
+ return [x, y];
+ });
+ const linePath = pts.map((p, i) => (i === 0 ? `M${p[0].toFixed(1)},${p[1].toFixed(1)}` : `L${p[0].toFixed(1)},${p[1].toFixed(1)}`)).join(' ');
+ const areaPath = `${linePath} L${pts[pts.length-1][0].toFixed(1)},${H-P} L${pts[0][0].toFixed(1)},${H-P} Z`;
+ const allZero = days.every((d) => !d.count);
+ const labels = `${esc(days[0].day)} → ${esc(days[days.length-1].day)}`;
+ return `
+ <svg class="spark" viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" role="img" aria-label="Views over the last 7 days, ${days.map((d) => `${d.day}: ${d.count}`).join(', ')}">
+ <line class="axis" x1="${P}" y1="${H-P}" x2="${W-P}" y2="${H-P}"></line>
+ ${allZero ? '' : `<path class="area" d="${areaPath}"></path><path class="line" d="${linePath}"></path>`}
+ </svg>
+ <div class="muted" style="font-size:11px; display:flex; justify-content:space-between; padding:0 4px">
+ <span>${labels}</span>
+ <span>${allZero ? 'No views yet' : `peak ${max}`}</span>
+ </div>
+ `;
+}
+
+// ── Share modal ─────────────────────────────────────────────────────────────
+function openShareModal(w) {
+ const SIZES = [
+ { label: 'Small', width: 320, height: 320 },
+ { label: 'Medium', width: 600, height: 600 },
+ { label: 'Banner', width: 1200, height: 400 },
+ { label: 'Custom', width: 0, height: 0 },
+ ];
+ let active = 1;
+ let dim = { ...SIZES[active] };
+ const pageUrl = `${location.origin}/w/${encodeURIComponent(w.id)}`;
+
+ const overlay = document.createElement('div');
+ overlay.className = 'modal-overlay';
+ overlay.innerHTML = `
+ <div class="modal" role="dialog" aria-label="Share widget">
+ <h2>Share "${esc(w.name || 'widget')}"</h2>
+ <p class="sub">Pick a size, copy the iframe, and you're done.</p>
+ <div class="size-presets" role="tablist">
+ ${SIZES.map((s, i) => `<button type="button" data-i="${i}" class="${i===active?'active':''}" role="tab" aria-selected="${i===active}">${esc(s.label)}${s.width?` (${s.width}×${s.height})`:''}</button>`).join('')}
+ </div>
+ <div class="size-inputs">
+ <label class="muted" style="font-size:12px">W <input id="m-w" type="number" min="120" max="2000" value="${dim.width||600}"></label>
+ <label class="muted" style="font-size:12px">H <input id="m-h" type="number" min="120" max="2000" value="${dim.height||600}"></label>
+ </div>
+ <div style="background:#0f0f17; border:1px solid var(--border); border-radius:10px; padding:12px; margin-bottom:12px">
+ <div class="muted" style="font-size:11px; margin-bottom:8px">Live preview (scaled to fit)</div>
+ <div id="m-preview" style="display:grid; place-items:center; min-height:200px; max-height:340px; overflow:hidden"></div>
+ </div>
+ <div>
+ <div class="row" style="justify-content:space-between; margin-bottom:4px"><strong style="font-size:12px">Iframe</strong><button class="btn sec" id="m-copy" type="button">Copy</button></div>
+ <pre id="m-snip" style="margin:0"></pre>
+ </div>
+ <div class="row" style="justify-content:space-between; margin-top:14px">
+ <a class="muted" style="font-size:12px" href="mailto:[email protected]?subject=Report+widget+${encodeURIComponent(w.id)}">Report this widget</a>
+ <button class="btn sec" id="m-close" type="button">Close</button>
+ </div>
+ </div>
+ `;
+ document.body.appendChild(overlay);
+ requestAnimationFrame(() => overlay.classList.add('open'));
+
+ const wInput = overlay.querySelector('#m-w');
+ const hInput = overlay.querySelector('#m-h');
+ const snipEl = overlay.querySelector('#m-snip');
+ const previewEl = overlay.querySelector('#m-preview');
+
+ function refresh() {
+ const snippet = makeIframeSnippet(w, pageUrl, dim.width, dim.height);
+ snipEl.textContent = snippet;
+ // Live preview at scaled size — fit within 320×320 while preserving ratio.
+ const maxW = 320, maxH = 320;
+ const scale = Math.min(maxW / dim.width, maxH / dim.height, 1);
+ previewEl.innerHTML = `<iframe src="/#widget=${encodeURIComponent(w.id)}&kiosk=true&preview=1" style="width:${dim.width}px; height:${dim.height}px; border:0; transform:scale(${scale}); transform-origin:center" title="Preview"></iframe>`;
+ previewEl.style.width = `${dim.width * scale}px`;
+ previewEl.style.height = `${dim.height * scale}px`;
+ }
+ function setPreset(i) {
+ active = i;
+ overlay.querySelectorAll('.size-presets button').forEach((b, j) => {
+ b.classList.toggle('active', i === j);
+ b.setAttribute('aria-selected', i === j ? 'true' : 'false');
+ });
+ if (SIZES[i].width) {
+ dim = { width: SIZES[i].width, height: SIZES[i].height };
+ wInput.value = dim.width; hInput.value = dim.height;
+ }
+ refresh();
+ }
+ overlay.querySelectorAll('.size-presets button').forEach((b) => {
+ b.addEventListener('click', () => setPreset(Number(b.dataset.i)));
+ });
+ const onDimChange = () => {
+ dim = { width: clampInt(wInput.value, 120, 2000, 600), height: clampInt(hInput.value, 120, 2000, 600) };
+ // Switch to "Custom" preset when typing.
+ setPresetSilent(SIZES.length - 1);
+ refresh();
+ };
+ function setPresetSilent(i) {
+ active = i;
+ overlay.querySelectorAll('.size-presets button').forEach((b, j) => {
+ b.classList.toggle('active', i === j);
+ b.setAttribute('aria-selected', i === j ? 'true' : 'false');
+ });
+ }
+ wInput.addEventListener('input', onDimChange);
+ hInput.addEventListener('input', onDimChange);
+
+ const close = () => {
+ overlay.classList.remove('open');
+ setTimeout(() => { overlay.remove(); document.removeEventListener('keydown', onKey); }, 200);
+ };
+ const onKey = (e) => { if (e.key === 'Escape') close(); };
+ document.addEventListener('keydown', onKey);
+ overlay.addEventListener('click', (e) => { if (e.target === overlay) close(); });
+ overlay.querySelector('#m-close').addEventListener('click', close);
+ overlay.querySelector('#m-copy').addEventListener('click', (e) => copyToClipboard(snipEl.textContent, e.currentTarget));
+
+ refresh();
+}
+
+function clampInt(v, lo, hi, fallback) {
+ const n = parseInt(v, 10);
+ if (Number.isNaN(n)) return fallback;
+ return Math.max(lo, Math.min(hi, n));
+}
+
+function makeIframeSnippet(w, pageUrl, width, height) {
+ const title = (w.name || 'Widget').replace(/"/g, '&quot;');
+ return `<iframe src="${pageUrl}" width="${width}" height="${height}" style="border:0;border-radius:12px;max-width:100%" allow="autoplay; xr-spatial-tracking; clipboard-write" title="${title}" loading="lazy"></iframe>`;
+}
+
+// ── shared widget UI helpers ────────────────────────────────────────────────
+async function copyToClipboard(text, btn) {
+ try {
+ await navigator.clipboard.writeText(text);
+ toast('Copied to clipboard');
+ if (btn) {
+ const orig = btn.textContent;
+ btn.textContent = 'Copied';
+ setTimeout(() => { btn.textContent = orig; }, 1100);
+ }
+ } catch {
+ toast('Copy failed — select and ⌘C manually', true);
+ }
+}
+
+let _toastTimer;
+function toast(message, isError = false) {
+ const existing = document.querySelector('.toast');
+ if (existing) existing.remove();
+ clearTimeout(_toastTimer);
+ const el = document.createElement('div');
+ el.className = 'toast';
+ if (isError) { el.style.color = '#ffb3b3'; el.style.borderColor = 'rgba(255,92,92,.4)'; }
+ el.setAttribute('role', isError ? 'alert' : 'status');
+ el.textContent = message;
+ document.body.appendChild(el);
+ _toastTimer = setTimeout(() => { el.style.opacity = '0'; el.style.transition = 'opacity .25s'; setTimeout(() => el.remove(), 260); }, 2200);
+}
+
+function timeAgo(ts) {
+ if (!ts) return 'never';
+ const then = new Date(ts).getTime();
+ const now = Date.now();
+ const sec = Math.max(1, Math.round((now - then) / 1000));
+ if (sec < 60) return `${sec}s ago`;
+ const min = Math.round(sec / 60);
+ if (min < 60) return `${min}m ago`;
+ const hr = Math.round(min / 60);
+ if (hr < 24) return `${hr}h ago`;
+ const day = Math.round(hr / 24);
+ if (day < 30) return `${day}d ago`;
+ const mo = Math.round(day / 30);
+ if (mo < 12) return `${mo}mo ago`;
+ return `${Math.round(mo / 12)}y ago`;
+}
+
+function formatNum(n) {
+ const v = Number(n || 0);
+ if (v < 1000) return String(v);
+ if (v < 10000) return (v / 1000).toFixed(1).replace(/\.0$/, '') + 'k';
+ if (v < 1_000_000) return Math.round(v / 1000) + 'k';
+ return (v / 1_000_000).toFixed(1).replace(/\.0$/, '') + 'M';
+}
+
+function formatViewCount(n) {
+ const v = Number(n || 0);
+ if (v === 0) return 'No views';
+ if (v === 1) return '1 view';
+ return `${formatNum(v)} views`;
+}
+
// ── utils ───────────────────────────────────────────────────────────────────
function fmtSize(b) { if (b < 1024) return b + ' B'; if (b < 1024*1024) return (b/1024).toFixed(1) + ' KB'; return (b/1024/1024).toFixed(1) + ' MB'; }
function esc(s) { return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;' }[c])); }
diff --git a/public/dashboard/index.html b/public/dashboard/index.html
index 1ff14ba21..29e51c799 100644
--- a/public/dashboard/index.html
+++ b/public/dashboard/index.html
@@ -42,6 +42,80 @@
.section { margin-top:34px; }
input, textarea, select { background:#0f0f17; border:1px solid var(--border); color:#eee; padding:9px 11px; border-radius:8px; font-size:14px; font-family:inherit; }
input:focus, textarea:focus, select:focus { outline:none; border-color:var(--accent); }
+
+ /* ── Widgets tab ─────────────────────────────────────────────────────── */
+ .btn-primary { display:inline-block; padding:9px 14px; border-radius:9px; border:0; font-size:13px; font-weight:600; cursor:pointer; background:var(--accent); color:#fff; text-decoration:none; }
+ .btn-primary:hover { filter:brightness(1.08); }
+ .btn-danger { background:#cc4040; }
+ .widgets-header { display:flex; justify-content:space-between; align-items:flex-start; gap:14px; margin-bottom:18px; flex-wrap:wrap; }
+ .widgets-header h1 { margin-bottom:6px; }
+ .widget-toolbar { display:flex; gap:10px; align-items:center; margin-bottom:18px; flex-wrap:wrap; }
+ .widget-toolbar input, .widget-toolbar select { padding:7px 10px; font-size:13px; }
+ .widget-toolbar input[type="search"] { min-width:200px; }
+ .widget-card { background:var(--panel); border:1px solid var(--border); border-radius:14px; padding:14px; display:flex; flex-direction:column; gap:10px; position:relative; transition:border-color .15s; }
+ .widget-card:hover { border-color:#2c2c40; }
+ .widget-card .frame { aspect-ratio:1/1; background:#0f0f17; border-radius:10px; overflow:hidden; position:relative; }
+ .widget-card .frame iframe { width:100%; height:100%; border:0; display:block; }
+ .widget-card .frame .placeholder { display:grid; place-items:center; height:100%; color:#555; font-size:12px; padding:10px; text-align:center; }
+ .widget-card .title { display:flex; align-items:baseline; gap:8px; min-height:22px; }
+ .widget-card .title h3 { margin:0; font-size:14px; cursor:text; flex:1; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
+ .widget-card .title input { flex:1; padding:3px 6px; font-size:14px; font-weight:600; }
+ .widget-card .pill { display:inline-flex; align-items:center; gap:6px; font-size:11px; padding:2px 8px; border-radius:99px; background:#20202c; color:#ccc; white-space:nowrap; }
+ .widget-card .pill .dot { width:7px; height:7px; border-radius:50%; }
+ .widget-card .meta { font-size:12px; color:#888; }
+ .widget-card .actions { display:flex; gap:6px; flex-wrap:wrap; margin-top:auto; }
+ .widget-card .actions button, .widget-card .actions a { padding:6px 10px; border-radius:7px; border:1px solid var(--border); background:#1a1a24; color:#ddd; font-size:12px; cursor:pointer; text-decoration:none; }
+ .widget-card .actions button:hover, .widget-card .actions a:hover { background:#22222e; }
+ .widget-card .actions .danger:hover { background:rgba(204,64,64,.18); border-color:rgba(204,64,64,.5); color:#ffb3b3; }
+ .toggle { position:relative; display:inline-flex; align-items:center; gap:6px; cursor:pointer; user-select:none; }
+ .toggle input { position:absolute; opacity:0; width:0; height:0; }
+ .toggle .track { width:30px; height:17px; background:#2a2a36; border-radius:99px; position:relative; transition:background .15s; }
+ .toggle .track::after { content:''; position:absolute; top:2px; left:2px; width:13px; height:13px; background:#aaa; border-radius:50%; transition:transform .15s, background .15s; }
+ .toggle input:checked + .track { background:rgba(106,92,255,.55); }
+ .toggle input:checked + .track::after { transform:translateX(13px); background:#fff; }
+ .toggle input:focus-visible + .track { outline:2px solid var(--accent); outline-offset:2px; }
+ .toggle .label { font-size:11px; color:#888; }
+
+ /* Drawer */
+ .drawer-overlay { position:fixed; inset:0; background:rgba(0,0,0,.55); z-index:50; opacity:0; pointer-events:none; transition:opacity .18s; }
+ .drawer-overlay.open { opacity:1; pointer-events:auto; }
+ .drawer { position:fixed; right:0; top:0; bottom:0; width:min(560px, 100vw); background:#0e0e16; border-left:1px solid var(--border); transform:translateX(100%); transition:transform .22s cubic-bezier(.2,.8,.2,1); z-index:51; overflow-y:auto; }
+ .drawer.open { transform:none; }
+ .drawer header { display:flex; align-items:center; justify-content:space-between; padding:16px 20px; border-bottom:1px solid var(--border); position:sticky; top:0; background:#0e0e16; z-index:1; }
+ .drawer header h2 { margin:0; font-size:16px; }
+ .drawer .body { padding:20px; display:flex; flex-direction:column; gap:18px; }
+ .drawer .frame-lg { aspect-ratio:1/1; background:#0f0f17; border-radius:10px; overflow:hidden; }
+ .drawer .frame-lg iframe { width:100%; height:100%; border:0; }
+ .drawer .stat-grid { display:grid; grid-template-columns:repeat(2, 1fr); gap:10px; }
+ .drawer .stat { background:#13131c; border:1px solid var(--border); border-radius:10px; padding:12px 14px; }
+ .drawer .stat .n { font-size:22px; font-weight:600; }
+ .drawer .stat .l { font-size:11px; color:#888; text-transform:uppercase; letter-spacing:.5px; }
+ .spark { width:100%; height:60px; }
+ .spark path.area { fill:rgba(106,92,255,.18); }
+ .spark path.line { fill:none; stroke:var(--accent); stroke-width:2; }
+ .spark .axis { stroke:#22222e; stroke-width:1; }
+ details summary { cursor:pointer; padding:6px 0; color:#aaa; font-size:13px; }
+ details[open] summary { color:#eee; }
+ .danger-zone { border:1px solid rgba(204,64,64,.4); border-radius:10px; padding:14px; background:rgba(204,64,64,.05); }
+ .danger-zone h3 { margin:0 0 6px; color:#ffb3b3; font-size:13px; }
+
+ /* Modal */
+ .modal-overlay { position:fixed; inset:0; background:rgba(0,0,0,.6); z-index:60; display:grid; place-items:center; opacity:0; pointer-events:none; transition:opacity .15s; }
+ .modal-overlay.open { opacity:1; pointer-events:auto; }
+ .modal { background:#0e0e16; border:1px solid var(--border); border-radius:14px; padding:22px; width:min(560px, calc(100vw - 32px)); max-height:calc(100vh - 32px); overflow-y:auto; }
+ .modal h2 { margin:0 0 4px; font-size:17px; }
+ .modal .sub { margin:0 0 18px; }
+ .size-presets { display:flex; gap:6px; flex-wrap:wrap; margin-bottom:14px; }
+ .size-presets button { padding:6px 12px; border-radius:99px; border:1px solid var(--border); background:#13131c; color:#ccc; font-size:12px; cursor:pointer; }
+ .size-presets button.active { border-color:var(--accent); color:#fff; background:rgba(106,92,255,.15); }
+ .size-inputs { display:flex; gap:8px; align-items:center; margin-bottom:14px; }
+ .size-inputs input { width:90px; }
+
+ .toast { position:fixed; bottom:24px; left:50%; transform:translateX(-50%); background:#1a1a24; border:1px solid var(--border); padding:10px 18px; border-radius:99px; font-size:13px; color:#ddd; z-index:70; box-shadow:0 4px 18px rgba(0,0,0,.4); animation:toast-in .2s; }
+ @keyframes toast-in { from { opacity:0; transform:translate(-50%, 8px); } to { opacity:1; transform:translateX(-50%); } }
+
+ /* visually-hidden utility for screen-reader-only labels */
+ .sr-only { position:absolute; width:1px; height:1px; padding:0; margin:-1px; overflow:hidden; clip:rect(0,0,0,0); border:0; }
</style>
<script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"></script>
</head>
@@ -58,6 +132,7 @@
<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="#widgets" data-tab="widgets">Widgets</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>
diff --git a/public/embed.js b/public/embed.js
new file mode 100644
index 000000000..8836141d9
--- /dev/null
+++ b/public/embed.js
@@ -0,0 +1,80 @@
+// 3D Agent — script-tag embed.
+// <script async src="https://3dagent.vercel.app/embed.js" data-widget="wdgt_..."></script>
+//
+// Injects a sandboxed iframe at the script tag's location, sized via data-*
+// attributes (or the type's default), then forwards widget:resize events from
+// the iframe to keep the host layout snug.
+//
+// Zero deps, plain DOM. Intentionally tiny — gets minified/cached at the edge.
+
+(function () {
+ 'use strict';
+
+ var TYPE_SIZES = {
+ 'turntable': [600, 600],
+ 'animation-gallery': [720, 720],
+ 'talking-agent': [420, 600],
+ 'passport': [480, 560],
+ 'hotspot-tour': [800, 600],
+ };
+
+ var ORIGIN = (function () {
+ try { return new URL(document.currentScript.src).origin; }
+ catch (e) { return 'https://3dagent.vercel.app'; }
+ })();
+
+ function attr(el, name, fallback) {
+ var v = el && el.getAttribute && el.getAttribute(name);
+ return v != null && v !== '' ? v : fallback;
+ }
+
+ function mount(scriptEl) {
+ var widgetId = attr(scriptEl, 'data-widget', null);
+ if (!widgetId) {
+ console.warn('[3d-agent embed] missing data-widget attribute');
+ return;
+ }
+ var type = attr(scriptEl, 'data-type', null);
+ var defaults = (type && TYPE_SIZES[type]) || [600, 600];
+ var width = attr(scriptEl, 'data-width', String(defaults[0]));
+ var height = attr(scriptEl, 'data-height', String(defaults[1]));
+ var radius = attr(scriptEl, 'data-radius', '12');
+ var border = attr(scriptEl, 'data-border', '0');
+
+ var src = ORIGIN + '/#widget=' + encodeURIComponent(widgetId) + '&kiosk=true';
+
+ var iframe = document.createElement('iframe');
+ iframe.src = src;
+ iframe.title = '3D Agent widget ' + widgetId;
+ iframe.loading = 'lazy';
+ iframe.allow = 'autoplay; xr-spatial-tracking; clipboard-write';
+ iframe.setAttribute('width', width);
+ iframe.setAttribute('height', height);
+ iframe.style.border = border + 'px solid transparent';
+ iframe.style.borderRadius = radius + 'px';
+ iframe.style.maxWidth = '100%';
+ iframe.style.display = 'block';
+
+ var anchor = scriptEl.parentNode;
+ if (!anchor) return;
+ anchor.insertBefore(iframe, scriptEl);
+
+ // Optional: auto-resize when the widget reports a preferred size.
+ window.addEventListener('message', function (e) {
+ if (e.origin !== ORIGIN) return;
+ if (!e.data || e.data.type !== 'widget:resize') return;
+ if (e.data.id && e.data.id !== widgetId) return;
+ if (e.data.width) iframe.setAttribute('width', String(e.data.width));
+ if (e.data.height) iframe.setAttribute('height', String(e.data.height));
+ });
+ }
+
+ // Mount every <script data-widget="..."> on the page (allows multiple embeds).
+ var current = document.currentScript;
+ if (current && current.getAttribute('data-widget')) {
+ mount(current);
+ return;
+ }
+ var scripts = document.querySelectorAll('script[data-widget][src*="embed.js"]');
+ for (var i = 0; i < scripts.length; i++) mount(scripts[i]);
+})();
diff --git a/public/login.html b/public/login.html
index f4546eed5..fd146a92d 100644
--- a/public/login.html
+++ b/public/login.html
@@ -5,6 +5,7 @@
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Sign in · 3D Agent</title>
<link rel="icon" href="/favicon.ico">
+<meta name="privy-app-id" content="">
<style>
:root { color-scheme: dark; --accent:#6a5cff; --accent2:#ff5ca8; }
* { box-sizing: border-box; }
@@ -39,9 +40,13 @@
<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="privy" type="button" class="wallet-btn" style="background:linear-gradient(135deg,var(--accent),var(--accent2)); border-color:transparent; color:#fff">
+ <svg class="wallet-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="8" r="4"/><path d="M20 21a8 8 0 0 0-16 0"/></svg>
+ Sign in with Privy
+ </button>
<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
+ Sign in with MetaMask
</button>
<div class="err" id="err"></div>
<p class="foot">No account? <a href="/register.html">Create one</a></p>
diff --git a/public/register.html b/public/register.html
index 53473318d..aa4ac5c98 100644
--- a/public/register.html
+++ b/public/register.html
@@ -5,6 +5,7 @@
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Create account · 3D Agent</title>
<link rel="icon" href="/favicon.ico">
+<meta name="privy-app-id" content="">
<style>
:root { color-scheme: dark; --accent:#6a5cff; --accent2:#ff5ca8; }
* { box-sizing: border-box; }
@@ -43,9 +44,13 @@
<div class="hint">At least 10 characters.</div>
<button id="submit" type="submit">Create account</button>
<div class="divider">or</div>
+ <button id="privy" type="button" class="wallet-btn" style="background:linear-gradient(135deg,var(--accent),var(--accent2)); border-color:transparent; color:#fff">
+ <svg class="wallet-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="8" r="4"/><path d="M20 21a8 8 0 0 0-16 0"/></svg>
+ Continue with Privy
+ </button>
<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
+ Continue with MetaMask
</button>
<div class="err" id="err"></div>
<p class="foot">Already have one? <a href="/login.html">Sign in</a></p>
diff --git a/public/studio/index.html b/public/studio/index.html
new file mode 100644
index 000000000..839368efd
--- /dev/null
+++ b/public/studio/index.html
@@ -0,0 +1,154 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta http-equiv="X-UA-Compatible" content="IE=edge">
+ <title>Widget Studio · 3D Agent</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
+ <meta name="description" content="Turn any avatar into an embeddable 3D widget. Five types, brand controls, one-line embed.">
+ <meta name="theme-color" content="#0a0a0a">
+ <meta name="robots" content="noindex">
+ <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="/studio/studio.css">
+</head>
+<body class="studio-body">
+ <header class="studio-header">
+ <h1><a href="/"><span class="wordmark-dot" aria-hidden="true"></span>3D Agent</a><span class="studio-tag">Studio</span></h1>
+ <nav>
+ <a href="/widgets">Gallery</a>
+ <a href="/docs/widgets">Docs</a>
+ <a href="/dashboard#widgets">My widgets</a>
+ <button class="btn-ghost" id="signout-btn" type="button">Sign out</button>
+ </nav>
+ </header>
+
+ <main class="studio-layout" id="studio-layout" hidden>
+ <section class="studio-col-left" aria-label="Pick avatar and widget type">
+ <div class="panel">
+ <h2>1. Pick avatar</h2>
+ <div class="avatar-list" id="avatar-list" aria-busy="true"></div>
+ </div>
+ <div class="panel">
+ <h2>2. Pick widget type</h2>
+ <div class="type-grid" id="type-grid"></div>
+ </div>
+ </section>
+
+ <section class="studio-col-mid" aria-label="Preview">
+ <div class="preview-shell">
+ <div class="preview-frame" id="preview-frame">
+ <iframe id="preview-iframe" title="Live widget preview" allow="autoplay; xr-spatial-tracking" loading="eager"></iframe>
+ </div>
+ <div class="preview-meta">
+ <span id="preview-status" class="muted">Pick an avatar to preview</span>
+ <button class="btn-ghost btn-sm" id="capture-camera-btn" type="button" disabled>Use current view</button>
+ </div>
+ </div>
+ </section>
+
+ <section class="studio-col-right" aria-label="Brand and config">
+ <div class="panel">
+ <h2>3. Brand</h2>
+ <form id="config-form" class="config-form" autocomplete="off" onsubmit="return false">
+ <label class="field">
+ <span>Name</span>
+ <input type="text" name="name" maxlength="120" required placeholder="My turntable widget">
+ </label>
+ <label class="field">
+ <span>Background</span>
+ <input type="color" name="background" value="#0a0a0a">
+ </label>
+ <label class="field">
+ <span>Accent</span>
+ <input type="color" name="accent" value="#8b5cf6">
+ </label>
+ <label class="field">
+ <span>Caption (optional)</span>
+ <input type="text" name="caption" maxlength="280" placeholder="Hello, world.">
+ </label>
+ <label class="field row">
+ <input type="checkbox" name="showControls" checked>
+ <span>Show controls</span>
+ </label>
+ <label class="field row">
+ <input type="checkbox" name="autoRotate" checked>
+ <span>Auto-rotate</span>
+ </label>
+ <label class="field">
+ <span>Environment</span>
+ <select name="envPreset">
+ <option value="none">None</option>
+ <option value="neutral" selected>Neutral</option>
+ <option value="venice-sunset">Venice sunset</option>
+ <option value="footprint-court">Footprint court</option>
+ </select>
+ </label>
+ <label class="field row">
+ <input type="checkbox" name="is_public" checked>
+ <span>Public widget (anyone with the URL can load it)</span>
+ </label>
+
+ <div id="type-fields" class="type-fields"></div>
+ </form>
+ </div>
+
+ <div class="action-row">
+ <button type="button" class="btn-ghost" id="save-draft-btn">Save draft</button>
+ <button type="button" class="btn-primary" id="generate-btn">Generate embed</button>
+ </div>
+ <p id="form-error" class="form-error" hidden></p>
+ </section>
+ </main>
+
+ <div class="auth-blocker" id="auth-blocker">
+ <div class="auth-blocker-card">
+ <p>Sign in to use the Studio.</p>
+ <a class="btn-primary" href="#" id="signin-link">Sign in →</a>
+ </div>
+ </div>
+
+ <div class="modal-overlay" id="embed-modal" hidden>
+ <div class="modal" role="dialog" aria-labelledby="embed-modal-title" aria-modal="true">
+ <button type="button" class="modal-close" id="embed-modal-close" aria-label="Close">×</button>
+ <h2 id="embed-modal-title">Your widget is live</h2>
+ <p class="muted">Share the URL or paste the snippet anywhere.</p>
+
+ <div class="embed-preview">
+ <iframe id="embed-preview-iframe" title="Embed preview" allow="autoplay; xr-spatial-tracking"></iframe>
+ </div>
+
+ <label class="field">
+ <span>Shareable URL</span>
+ <div class="copy-row">
+ <input type="text" id="embed-share-url" readonly>
+ <button type="button" class="btn-ghost btn-sm" data-copy="#embed-share-url">Copy</button>
+ </div>
+ </label>
+
+ <label class="field">
+ <span>iframe snippet</span>
+ <div class="copy-row">
+ <textarea id="embed-iframe-snippet" rows="3" readonly></textarea>
+ <button type="button" class="btn-ghost btn-sm" data-copy="#embed-iframe-snippet">Copy</button>
+ </div>
+ </label>
+
+ <details>
+ <summary>Script-tag embed</summary>
+ <div class="copy-row">
+ <textarea id="embed-script-snippet" rows="2" readonly></textarea>
+ <button type="button" class="btn-ghost btn-sm" data-copy="#embed-script-snippet">Copy</button>
+ </div>
+ </details>
+ </div>
+ </div>
+
+ <div class="toast" id="toast" hidden></div>
+
+ <script type="module" src="/studio/studio.js"></script>
+</body>
+</html>
diff --git a/public/studio/studio.css b/public/studio/studio.css
new file mode 100644
index 000000000..413d8d056
--- /dev/null
+++ b/public/studio/studio.css
@@ -0,0 +1,415 @@
+/* Widget Studio — dark, three-column. Reuses tokens from /style.css. */
+
+html, body.studio-body {
+ height: 100%;
+ overflow: hidden;
+}
+
+.studio-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: var(--space-sm) var(--space-lg);
+ border-bottom: 1px solid rgba(255, 255, 255, 0.06);
+ height: 56px;
+}
+.studio-header h1 {
+ margin: 0;
+ font-size: var(--text-lg);
+ font-weight: 600;
+ display: flex;
+ align-items: center;
+ gap: var(--space-sm);
+}
+.studio-header h1 a {
+ color: inherit;
+ text-decoration: none;
+ display: inline-flex;
+ align-items: center;
+ gap: var(--space-xs);
+}
+.studio-tag {
+ font-size: var(--text-sm);
+ font-weight: 500;
+ padding: 2px 10px;
+ border-radius: 999px;
+ background: rgba(139, 92, 246, 0.15);
+ color: #c4b5fd;
+ letter-spacing: 1px;
+ text-transform: uppercase;
+}
+.studio-header nav {
+ display: flex;
+ align-items: center;
+ gap: var(--space-md);
+ font-size: var(--text-sm);
+}
+.studio-header nav a {
+ color: rgba(229, 229, 229, 0.7);
+ text-decoration: none;
+}
+.studio-header nav a:hover { color: #fff; }
+
+.studio-layout {
+ display: grid;
+ grid-template-columns: 280px 1fr 320px;
+ gap: var(--space-md);
+ padding: var(--space-md);
+ height: calc(100vh - 56px);
+ overflow: hidden;
+}
+@media (max-width: 1024px) {
+ .studio-layout { grid-template-columns: 1fr; height: auto; overflow: auto; }
+ html, body.studio-body { overflow: auto; height: auto; }
+}
+
+.studio-col-left, .studio-col-right {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-md);
+ overflow-y: auto;
+ min-height: 0;
+}
+
+.studio-col-mid {
+ display: flex;
+ flex-direction: column;
+ min-height: 0;
+}
+
+.panel {
+ background: rgba(255, 255, 255, 0.025);
+ border: 1px solid rgba(255, 255, 255, 0.06);
+ border-radius: var(--radius-lg);
+ padding: var(--space-md);
+}
+.panel h2 {
+ font-family: var(--font-display);
+ font-weight: 500;
+ font-size: var(--text-base);
+ margin: 0 0 var(--space-sm);
+ color: rgba(229, 229, 229, 0.85);
+ letter-spacing: 0.3px;
+}
+
+.avatar-list {
+ display: grid;
+ grid-template-columns: repeat(2, 1fr);
+ gap: var(--space-xs);
+ max-height: 320px;
+ overflow-y: auto;
+}
+.avatar-card {
+ background: #0a0a0a;
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: var(--radius-md);
+ padding: var(--space-xs);
+ cursor: pointer;
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ font-size: var(--text-sm);
+ transition: border-color 0.15s, background 0.15s;
+ text-align: left;
+ color: inherit;
+ font-family: inherit;
+}
+.avatar-card:hover { border-color: rgba(139, 92, 246, 0.5); }
+.avatar-card.selected { border-color: var(--accent); background: rgba(139, 92, 246, 0.08); }
+.avatar-card:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+.avatar-card .thumb {
+ aspect-ratio: 1 / 1;
+ background: #050505;
+ border-radius: 4px;
+ display: grid;
+ place-items: center;
+ color: #444;
+ font-size: 22px;
+ overflow: hidden;
+}
+.avatar-card .thumb img { width: 100%; height: 100%; object-fit: cover; }
+.avatar-card .name { font-size: var(--text-sm); color: #ddd; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.avatar-card .meta { font-size: var(--text-xs); color: #777; }
+.avatar-list .empty { grid-column: 1 / -1; padding: var(--space-md); text-align: center; color: #777; font-size: var(--text-sm); }
+.avatar-list .empty a { color: var(--accent); }
+
+.type-grid {
+ display: grid;
+ grid-template-columns: repeat(2, 1fr);
+ gap: var(--space-xs);
+}
+.type-card {
+ background: #0a0a0a;
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: var(--radius-md);
+ padding: var(--space-sm);
+ cursor: pointer;
+ color: inherit;
+ font-family: inherit;
+ text-align: left;
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ transition: border-color 0.15s, background 0.15s;
+ position: relative;
+}
+.type-card:hover { border-color: rgba(139, 92, 246, 0.5); }
+.type-card.selected { border-color: var(--accent); background: rgba(139, 92, 246, 0.08); }
+.type-card:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+.type-card .icon { font-size: 18px; opacity: 0.8; }
+.type-card .label { font-size: var(--text-sm); color: #ddd; }
+.type-card .desc { font-size: var(--text-xs); color: #888; line-height: 1.4; }
+.type-card .pending {
+ font-size: 10px;
+ letter-spacing: 1px;
+ text-transform: uppercase;
+ color: #ffb94d;
+ background: rgba(255, 185, 77, 0.12);
+ padding: 1px 6px;
+ border-radius: 3px;
+ width: fit-content;
+}
+
+.preview-shell {
+ flex: 1;
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-xs);
+ background: rgba(255, 255, 255, 0.025);
+ border: 1px solid rgba(255, 255, 255, 0.06);
+ border-radius: var(--radius-lg);
+ padding: var(--space-sm);
+ min-height: 400px;
+}
+.preview-frame {
+ flex: 1;
+ background: #050505;
+ border-radius: var(--radius-md);
+ overflow: hidden;
+ position: relative;
+ min-height: 0;
+}
+.preview-frame iframe {
+ width: 100%;
+ height: 100%;
+ border: 0;
+ display: block;
+}
+.preview-meta {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ font-size: var(--text-sm);
+}
+.muted { color: rgba(229, 229, 229, 0.55); }
+
+.config-form {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-sm);
+}
+.field {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ font-size: var(--text-sm);
+ color: rgba(229, 229, 229, 0.75);
+}
+.field.row {
+ flex-direction: row;
+ align-items: center;
+ gap: var(--space-xs);
+ cursor: pointer;
+}
+.field input[type="text"], .field select, .field textarea, .field input[type="color"] {
+ background: #0a0a0a;
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ color: #e5e5e5;
+ padding: 6px 10px;
+ border-radius: var(--radius-md);
+ font-size: var(--text-sm);
+ font-family: inherit;
+}
+.field input[type="color"] { padding: 2px; height: 32px; cursor: pointer; }
+.field input:focus, .field select:focus, .field textarea:focus {
+ outline: none;
+ border-color: var(--accent);
+}
+.field input[type="checkbox"] { width: 16px; height: 16px; accent-color: var(--accent); }
+
+.type-fields {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-sm);
+ padding-top: var(--space-sm);
+ border-top: 1px solid rgba(255, 255, 255, 0.06);
+ margin-top: var(--space-xs);
+}
+.type-fields .pending-banner {
+ background: rgba(255, 185, 77, 0.08);
+ border: 1px solid rgba(255, 185, 77, 0.2);
+ padding: var(--space-sm);
+ border-radius: var(--radius-md);
+ font-size: var(--text-xs);
+ color: #ffd699;
+ line-height: 1.5;
+}
+
+.action-row {
+ display: flex;
+ gap: var(--space-xs);
+ margin-top: var(--space-sm);
+}
+.action-row button { flex: 1; }
+
+.btn-primary, .btn-ghost {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: var(--space-xs);
+ padding: var(--space-sm) var(--space-md);
+ border-radius: var(--radius-md);
+ font-family: inherit;
+ font-size: var(--text-sm);
+ font-weight: 500;
+ border: 1px solid transparent;
+ cursor: pointer;
+ text-decoration: none;
+ transition: background 0.15s, border-color 0.15s;
+}
+.btn-primary { background: var(--accent); color: #fff; }
+.btn-primary:hover { background: #7c3aed; }
+.btn-ghost {
+ background: transparent;
+ color: rgba(229, 229, 229, 0.85);
+ border-color: rgba(255, 255, 255, 0.15);
+}
+.btn-ghost:hover { background: rgba(255, 255, 255, 0.05); }
+.btn-ghost:disabled { opacity: 0.4; cursor: not-allowed; }
+.btn-sm { padding: 4px 10px; font-size: var(--text-xs); }
+
+.btn-primary:focus-visible, .btn-ghost:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+}
+
+.form-error {
+ margin: var(--space-xs) 0 0;
+ padding: var(--space-xs) var(--space-sm);
+ background: rgba(255, 80, 80, 0.08);
+ border: 1px solid rgba(255, 80, 80, 0.25);
+ border-radius: var(--radius-md);
+ color: #ffb3b3;
+ font-size: var(--text-xs);
+}
+
+.auth-blocker {
+ position: fixed;
+ inset: 0;
+ background: rgba(10, 10, 10, 0.92);
+ display: grid;
+ place-items: center;
+ z-index: 80;
+ visibility: hidden;
+ opacity: 0;
+ transition: opacity 0.15s;
+}
+.auth-blocker.visible { visibility: visible; opacity: 1; }
+.auth-blocker-card {
+ background: #14141c;
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ border-radius: var(--radius-lg);
+ padding: var(--space-xl);
+ text-align: center;
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-md);
+}
+
+.modal-overlay {
+ position: fixed;
+ inset: 0;
+ background: rgba(0, 0, 0, 0.6);
+ display: grid;
+ place-items: center;
+ z-index: 90;
+ padding: var(--space-md);
+}
+.modal-overlay[hidden] { display: none; }
+.modal {
+ background: #14141c;
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: var(--radius-lg);
+ padding: var(--space-lg);
+ width: min(560px, 100%);
+ max-height: calc(100vh - 32px);
+ overflow-y: auto;
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-md);
+ position: relative;
+}
+.modal h2 { margin: 0; font-family: var(--font-display); font-weight: 400; font-size: var(--text-lg); }
+.modal .muted { font-size: var(--text-sm); margin: 0; }
+.modal-close {
+ position: absolute;
+ top: 10px;
+ right: 14px;
+ background: none;
+ border: 0;
+ color: rgba(229, 229, 229, 0.5);
+ font-size: 24px;
+ cursor: pointer;
+ line-height: 1;
+ padding: 4px 8px;
+}
+.modal-close:hover { color: #fff; }
+
+.embed-preview {
+ aspect-ratio: 1 / 1;
+ background: #050505;
+ border-radius: var(--radius-md);
+ overflow: hidden;
+}
+.embed-preview iframe { width: 100%; height: 100%; border: 0; }
+
+.copy-row {
+ display: flex;
+ gap: var(--space-xs);
+ align-items: stretch;
+}
+.copy-row input, .copy-row textarea {
+ flex: 1;
+ background: #0a0a0a;
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ color: #e5e5e5;
+ padding: var(--space-xs) var(--space-sm);
+ border-radius: var(--radius-md);
+ font-family: var(--font-mono);
+ font-size: var(--text-xs);
+ resize: vertical;
+ min-height: 32px;
+}
+.copy-row button { flex-shrink: 0; }
+
+.toast {
+ position: fixed;
+ bottom: 24px;
+ left: 50%;
+ transform: translateX(-50%);
+ background: #14141c;
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ padding: var(--space-xs) var(--space-md);
+ border-radius: 999px;
+ font-size: var(--text-sm);
+ color: #ddd;
+ z-index: 100;
+ animation: toast-in 0.18s;
+}
+.toast[hidden] { display: none; }
+@keyframes toast-in { from { opacity: 0; transform: translate(-50%, 8px); } to { opacity: 1; transform: translateX(-50%); } }
+
+@media (prefers-reduced-motion: reduce) {
+ .toast { animation: none; }
+ .btn-primary, .btn-ghost { transition: none; }
+}
diff --git a/public/studio/studio.js b/public/studio/studio.js
new file mode 100644
index 000000000..e796c48da
--- /dev/null
+++ b/public/studio/studio.js
@@ -0,0 +1,438 @@
+// Widget Studio — three-column UI for creating + editing widgets.
+// Native DOM, no framework. Uses /api/widgets and /api/avatars.
+//
+// Type registry is inlined here (rather than imported from /src/) because
+// /public/* is served verbatim by Vercel — the build doesn't transform it.
+// Keep this list in sync with src/widget-types.js as new types light up.
+
+const WIDGET_TYPES = {
+ 'turntable': { label: 'Turntable Showcase', desc: 'Hero banner — auto-rotate, no UI, just the avatar.', status: 'ready', icon: '◎' },
+ 'animation-gallery': { label: 'Animation Gallery', desc: 'Click through every clip on a rigged avatar.', status: 'pending', icon: '▶' },
+ 'talking-agent': { label: 'Talking Agent', desc: 'Embodied chat — your agent on your site.', status: 'pending', icon: '◐' },
+ 'passport': { label: 'ERC-8004 Passport', desc: 'On-chain identity card for any agent.', status: 'ready', icon: '◊' },
+ 'hotspot-tour': { label: 'Hotspot Tour', desc: 'Annotated 3D scene with clickable POIs.', status: 'pending', icon: '⌖' },
+};
+
+const BRAND_DEFAULTS = Object.freeze({
+ background: '#0a0a0a', accent: '#8b5cf6', caption: '',
+ showControls: true, autoRotate: true, envPreset: 'neutral', cameraPosition: null,
+});
+
+const TYPE_DEFAULTS = {
+ 'turntable': { rotationSpeed: 0.5 },
+ 'animation-gallery': { defaultClip: '', loopAll: false, showClipPicker: true },
+ 'talking-agent': { greeting: 'Hi! What would you like to know?', brain: 'none', proxyURL: '' },
+ 'passport': { chain: 'base-sepolia', agentId: null, wallet: null, showReputation: true, showRecentFeedback: true, layout: 'portrait', rotationSpeed: 0.6 },
+ 'hotspot-tour': { hotspots: [] },
+};
+
+function defaultConfig(type) {
+ return { ...BRAND_DEFAULTS, ...(TYPE_DEFAULTS[type] || {}) };
+}
+
+const $ = (sel, root = document) => root.querySelector(sel);
+
+const layoutEl = $('#studio-layout');
+const blockerEl = $('#auth-blocker');
+const signinLink = $('#signin-link');
+const formEl = $('#config-form');
+const errEl = $('#form-error');
+const previewIfr = $('#preview-iframe');
+const previewSt = $('#preview-status');
+const captureBtn = $('#capture-camera-btn');
+const saveBtn = $('#save-draft-btn');
+const generateBtn= $('#generate-btn');
+const toastEl = $('#toast');
+
+const state = {
+ user: null,
+ avatars: [],
+ avatarId: null,
+ type: 'turntable',
+ editingId: null,
+ config: defaultConfig('turntable'),
+ name: '',
+ is_public: true,
+ preselectedModel: null,
+};
+
+const params = new URLSearchParams(location.search);
+const editId = params.get('edit');
+const tplId = params.get('template');
+const pickType = params.get('type');
+const preModel = params.get('model');
+
+if (pickType && WIDGET_TYPES[pickType]) state.type = pickType;
+if (preModel) state.preselectedModel = preModel;
+
+(async function boot() {
+ signinLink.href = `/login?next=${encodeURIComponent(location.pathname + location.search)}`;
+ const me = await fetchMe();
+ if (!me) {
+ blockerEl.classList.add('visible');
+ return;
+ }
+ state.user = me;
+ layoutEl.hidden = false;
+
+ renderTypeGrid();
+ renderTypeFields();
+ wireForm();
+ wireButtons();
+
+ await loadAvatars();
+
+ if (editId) await loadForEdit(editId);
+ else if (tplId) await cloneTemplate(tplId);
+ else if (state.preselectedModel) selectByModelUrl(state.preselectedModel);
+
+ updatePreview(true);
+})();
+
+// ── data ─────────────────────────────────────────────────────────────────────
+async function fetchMe() {
+ try {
+ const res = await fetch('/api/auth/me', { credentials: 'include' });
+ if (!res.ok) return null;
+ const { user } = await res.json();
+ return user || null;
+ } catch { return null; }
+}
+
+async function loadAvatars() {
+ const list = $('#avatar-list');
+ try {
+ const res = await fetch('/api/avatars?limit=100', { credentials: 'include' });
+ if (!res.ok) throw new Error(`avatars: ${res.status}`);
+ const { avatars = [] } = await res.json();
+ state.avatars = avatars;
+ list.removeAttribute('aria-busy');
+ renderAvatarList();
+ } catch (err) {
+ list.removeAttribute('aria-busy');
+ list.innerHTML = `<div class="empty">Couldn't load avatars: ${escapeHtml(err.message)}</div>`;
+ }
+}
+
+async function loadForEdit(id) {
+ try {
+ const res = await fetch(`/api/widgets/${encodeURIComponent(id)}`, { credentials: 'include' });
+ if (!res.ok) return;
+ const { widget } = await res.json();
+ state.editingId = widget.id;
+ state.type = widget.type;
+ state.avatarId = widget.avatar_id;
+ state.name = widget.name || '';
+ state.config = { ...defaultConfig(widget.type), ...(widget.config || {}) };
+ state.is_public = widget.is_public;
+ hydrateForm();
+ renderTypeGrid();
+ renderAvatarList();
+ renderTypeFields();
+ } catch (err) { console.warn('[studio] edit load failed', err); }
+}
+
+async function cloneTemplate(id) {
+ try {
+ const res = await fetch(`/api/widgets/${encodeURIComponent(id)}`);
+ if (!res.ok) return;
+ const { widget } = await res.json();
+ state.type = widget.type;
+ state.config = { ...defaultConfig(widget.type), ...(widget.config || {}) };
+ state.name = `Copy of ${widget.name}`;
+ // avatarId stays unset — user must pick their own
+ hydrateForm();
+ renderTypeGrid();
+ renderTypeFields();
+ } catch { /* ignore */ }
+}
+
+// ── rendering ────────────────────────────────────────────────────────────────
+function renderAvatarList() {
+ const list = $('#avatar-list');
+ if (!state.avatars.length) {
+ list.innerHTML = `<div class="empty">No avatars yet. <a href="/dashboard#upload">Upload one →</a></div>`;
+ return;
+ }
+ list.innerHTML = '';
+ for (const a of state.avatars) {
+ const card = document.createElement('button');
+ card.type = 'button';
+ card.className = 'avatar-card' + (a.id === state.avatarId ? ' selected' : '');
+ card.dataset.id = a.id;
+ card.setAttribute('aria-pressed', String(a.id === state.avatarId));
+ const thumb = a.thumbnail_url
+ ? `<div class="thumb"><img src="${attr(a.thumbnail_url)}" alt="" loading="lazy"></div>`
+ : `<div class="thumb">◎</div>`;
+ card.innerHTML = `${thumb}<span class="name">${escapeHtml(a.name || a.slug || a.id)}</span>`;
+ card.addEventListener('click', () => selectAvatar(a.id));
+ list.appendChild(card);
+ }
+}
+
+function renderTypeGrid() {
+ const grid = $('#type-grid');
+ grid.innerHTML = '';
+ for (const [key, t] of Object.entries(WIDGET_TYPES)) {
+ const card = document.createElement('button');
+ card.type = 'button';
+ card.className = 'type-card' + (key === state.type ? ' selected' : '');
+ card.setAttribute('aria-pressed', String(key === state.type));
+ card.innerHTML = `
+ <span class="icon" aria-hidden="true">${t.icon}</span>
+ <span class="label">${escapeHtml(t.label)}</span>
+ <span class="desc">${escapeHtml(t.desc)}</span>
+ ${t.status === 'pending' ? '<span class="pending">Coming soon</span>' : ''}
+ `;
+ card.addEventListener('click', () => selectType(key));
+ grid.appendChild(card);
+ }
+}
+
+function renderTypeFields() {
+ const wrap = $('#type-fields');
+ wrap.innerHTML = '';
+ const t = WIDGET_TYPES[state.type];
+ if (t.status === 'pending') {
+ const banner = document.createElement('div');
+ banner.className = 'pending-banner';
+ banner.textContent = `${t.label} runtime ships in a later prompt. You can still save the config; it'll light up when the runtime lands.`;
+ wrap.appendChild(banner);
+ return;
+ }
+ if (state.type === 'turntable') {
+ wrap.appendChild(numberField('rotationSpeed', 'Rotation speed', state.config.rotationSpeed ?? 0.5, { min: 0, max: 10, step: 0.1 }));
+ }
+}
+
+function numberField(name, label, value, { min, max, step }) {
+ const f = document.createElement('label');
+ f.className = 'field';
+ f.innerHTML = `<span>${escapeHtml(label)}</span>
+ <input type="number" name="${attr(name)}" value="${attr(String(value))}" min="${min}" max="${max}" step="${step}">`;
+ f.querySelector('input').addEventListener('input', (e) => {
+ const v = parseFloat(e.target.value);
+ if (!isNaN(v)) {
+ state.config[name] = v;
+ schedulePreview();
+ }
+ });
+ return f;
+}
+
+// ── interaction ──────────────────────────────────────────────────────────────
+function selectAvatar(id) {
+ state.avatarId = id;
+ renderAvatarList();
+ updatePreview(true);
+ captureBtn.disabled = false;
+}
+
+function selectByModelUrl(url) {
+ const found = state.avatars.find((a) => a.model_url === url);
+ if (found) selectAvatar(found.id);
+ else previewSt.textContent = 'Pick an avatar from your library';
+}
+
+function selectType(key) {
+ if (state.type === key) return;
+ state.type = key;
+ state.config = { ...defaultConfig(key), ...pickBrand(state.config) };
+ renderTypeGrid();
+ renderTypeFields();
+ updatePreview(true);
+}
+
+function pickBrand(cfg) {
+ const out = {};
+ for (const k of Object.keys(BRAND_DEFAULTS)) {
+ if (cfg[k] !== undefined) out[k] = cfg[k];
+ }
+ return out;
+}
+
+function wireForm() {
+ hydrateForm();
+ formEl.addEventListener('input', (e) => {
+ const t = e.target;
+ if (!t.name) return;
+ const val = t.type === 'checkbox' ? t.checked : t.value;
+ if (t.name === 'name') state.name = val;
+ else if (t.name === 'is_public') state.is_public = val;
+ else state.config[t.name] = val;
+ schedulePreview();
+ });
+}
+
+function hydrateForm() {
+ for (const el of formEl.elements) {
+ if (!el.name) continue;
+ if (el.name === 'name') el.value = state.name || '';
+ else if (el.name === 'is_public') el.checked = !!state.is_public;
+ else if (el.type === 'checkbox') el.checked = !!state.config[el.name];
+ else if (state.config[el.name] !== undefined) el.value = state.config[el.name];
+ }
+}
+
+function wireButtons() {
+ $('#signout-btn').addEventListener('click', async () => {
+ await fetch('/api/auth/logout', { method: 'POST', credentials: 'include' }).catch(() => {});
+ location.href = '/';
+ });
+
+ captureBtn.addEventListener('click', () => {
+ try {
+ const w = previewIfr.contentWindow;
+ const cam = w?.VIEWER?.viewer?.activeCamera;
+ if (!cam) return toast('Preview not ready');
+ state.config.cameraPosition = [cam.position.x, cam.position.y, cam.position.z];
+ toast('Camera captured');
+ updatePreview(true);
+ } catch { toast('Could not read camera'); }
+ });
+
+ saveBtn.addEventListener('click', () => save({ generate: false }));
+ generateBtn.addEventListener('click', () => save({ generate: true }));
+
+ $('#embed-modal-close').addEventListener('click', () => {
+ $('#embed-modal').hidden = true;
+ });
+
+ for (const btn of document.querySelectorAll('[data-copy]')) {
+ btn.addEventListener('click', () => copyFromSelector(btn.dataset.copy, btn));
+ }
+}
+
+// ── preview ──────────────────────────────────────────────────────────────────
+let previewTimer = null;
+let previewSrcKey = '';
+
+function schedulePreview() {
+ clearTimeout(previewTimer);
+ previewTimer = setTimeout(() => updatePreview(false), 200);
+}
+
+function updatePreview(forceReload) {
+ if (!state.avatarId) {
+ previewSt.textContent = 'Pick an avatar to preview';
+ return;
+ }
+ const avatar = state.avatars.find((a) => a.id === state.avatarId);
+ const modelUrl = avatar?.model_url || state.preselectedModel;
+ if (!modelUrl) {
+ previewSt.textContent = 'Avatar has no public URL — make it public/unlisted to preview';
+ return;
+ }
+ previewSt.textContent = 'Live preview';
+
+ const camStr = Array.isArray(state.config.cameraPosition)
+ ? `&cameraPosition=${state.config.cameraPosition.map((n) => n.toFixed(3)).join(',')}`
+ : '';
+ const presetStr = state.config.envPreset && state.config.envPreset !== 'none'
+ ? `&preset=${encodeURIComponent(state.config.envPreset)}` : '';
+ const src = `/?widget-preview=1#model=${encodeURIComponent(modelUrl)}&kiosk=true${camStr}${presetStr}`;
+ const key = src;
+ if (forceReload || key !== previewSrcKey) {
+ previewSrcKey = key;
+ previewIfr.src = src;
+ }
+ postConfigToPreview();
+}
+
+function postConfigToPreview() {
+ if (!previewIfr.contentWindow) return;
+ try {
+ previewIfr.contentWindow.postMessage(
+ { type: 'widget:config', config: { ...state.config } },
+ location.origin,
+ );
+ } catch { /* iframe may not be ready yet — full reload covers it */ }
+}
+
+// ── save / generate ──────────────────────────────────────────────────────────
+async function save({ generate }) {
+ errEl.hidden = true;
+
+ if (!state.name?.trim()) return showError('Name is required');
+ if (!state.avatarId) return showError('Pick an avatar first');
+ if (!WIDGET_TYPES[state.type]) return showError('Pick a widget type');
+
+ const body = {
+ type: state.type,
+ name: state.name.trim(),
+ avatar_id: state.avatarId,
+ is_public: state.is_public,
+ config: state.config,
+ };
+
+ const url = state.editingId ? `/api/widgets/${encodeURIComponent(state.editingId)}` : '/api/widgets';
+ const method = state.editingId ? 'PATCH' : 'POST';
+ const sendBody = state.editingId ? { name: body.name, avatar_id: body.avatar_id, is_public: body.is_public, config: body.config } : body;
+
+ saveBtn.disabled = true; generateBtn.disabled = true;
+ try {
+ const res = await fetch(url, {
+ method,
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify(sendBody),
+ });
+ if (!res.ok) {
+ const data = await res.json().catch(() => ({}));
+ throw new Error(data.error_description || `save failed: ${res.status}`);
+ }
+ const { widget } = await res.json();
+ state.editingId = widget.id;
+ const newUrl = new URL(location.href);
+ newUrl.searchParams.set('edit', widget.id);
+ newUrl.searchParams.delete('template');
+ newUrl.searchParams.delete('model');
+ history.replaceState(null, '', newUrl);
+
+ if (generate) openEmbedModal(widget);
+ else toast('Saved');
+ } catch (err) {
+ showError(err.message);
+ } finally {
+ saveBtn.disabled = false; generateBtn.disabled = false;
+ }
+}
+
+function openEmbedModal(widget) {
+ const origin = location.origin;
+ const shareUrl = `${origin}/w/${widget.id}`;
+ const embedUrl = `${origin}/#widget=${widget.id}&kiosk=true`;
+ $('#embed-share-url').value = shareUrl;
+ $('#embed-iframe-snippet').value = `<iframe src="${embedUrl}" width="600" height="600" style="border:0;border-radius:12px" allow="autoplay; xr-spatial-tracking" loading="lazy"></iframe>`;
+ $('#embed-script-snippet').value = `<script async src="${origin}/embed.js" data-widget="${widget.id}"></` + 'script>';
+ $('#embed-preview-iframe').src = embedUrl;
+ $('#embed-modal').hidden = false;
+}
+
+function copyFromSelector(sel, btn) {
+ const el = $(sel);
+ if (!el) return;
+ el.select?.();
+ navigator.clipboard.writeText(el.value).then(
+ () => { const o = btn.textContent; btn.textContent = 'Copied'; setTimeout(() => btn.textContent = o, 1200); },
+ () => toast('Copy failed'),
+ );
+}
+
+function showError(msg) {
+ errEl.textContent = msg;
+ errEl.hidden = false;
+}
+
+let toastTimer = null;
+function toast(msg) {
+ toastEl.textContent = msg;
+ toastEl.hidden = false;
+ clearTimeout(toastTimer);
+ toastTimer = setTimeout(() => toastEl.hidden = true, 1800);
+}
+
+function escapeHtml(s) {
+ return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;' }[c]));
+}
+function attr(s) { return escapeHtml(s); }
diff --git a/public/wallet-login.js b/public/wallet-login.js
index 283ac3c19..6afa64890 100644
--- a/public/wallet-login.js
+++ b/public/wallet-login.js
@@ -1,18 +1,66 @@
-// 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.
+// Client-side wallet authentication.
+// Used by /login and /register pages. Supports two paths:
+// 1. Privy — email/social/wallet login with auto-created embedded wallets
+// 2. Raw MetaMask/SIWE — direct Sign-In with Ethereum for existing wallets
+//
+// Loaded as a module from login.html — imports from CDN so it works outside Vite.
import { BrowserProvider } from 'https://esm.sh/[email protected]';
+const PRIVY_APP_ID = document.querySelector('meta[name="privy-app-id"]')?.content || '';
const params = new URLSearchParams(location.search);
const next = params.get('next') || '/dashboard/';
+// ── UI helpers ──────────────────────────────────────────────────────────────
+
+function ui() {
+ const walletBtn = document.getElementById('wallet');
+ const privyBtn = document.getElementById('privy');
+ const err = document.getElementById('err');
+ return {
+ walletBtn, privyBtn, err,
+ setErr: (m) => { if (err) { err.textContent = m; err.style.display = 'block'; } },
+ clearErr: () => { if (err) { err.style.display = 'none'; } },
+ };
+}
+
+// ── Privy login (primary path) ─────────────────────────────────────────────
+// Privy handles email + social + wallet login. On success it provides an
+// EIP-1193 provider (embedded or external) which we SIWE-verify against our
+// backend exactly like a raw MetaMask login.
+
+async function signInWithPrivy() {
+ const { privyBtn, setErr, clearErr } = ui();
+ if (!PRIVY_APP_ID) { setErr('Privy not configured.'); return; }
+
+ clearErr();
+ if (privyBtn) { privyBtn.disabled = true; privyBtn.textContent = 'Loading Privy…'; }
+
+ try {
+ const mod = await import('https://esm.sh/@privy-io/js-sdk-core@latest');
+ const PrivyClient = mod.PrivyClient || mod.default;
+ const privy = new PrivyClient({ appId: PRIVY_APP_ID });
+
+ if (privyBtn) privyBtn.textContent = 'Opening login…';
+ await privy.login({ loginMethods: ['wallet', 'email', 'google'] });
+
+ if (privyBtn) privyBtn.textContent = 'Connecting wallet…';
+ const eip1193 = await privy.getEthereumProvider();
+ if (!eip1193) throw new Error('No wallet provider returned by Privy.');
+
+ const provider = new BrowserProvider(eip1193);
+ await completeSignIn(provider, privyBtn);
+ } catch (e) {
+ const msg = e?.message || String(e);
+ setErr(msg === 'user rejected action' || msg.includes('cancelled') ? 'Login cancelled.' : msg);
+ if (privyBtn) { privyBtn.disabled = false; privyBtn.textContent = 'Sign in with Privy'; }
+ }
+}
+
+// ── Raw MetaMask / SIWE (fallback path) ────────────────────────────────────
+
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'; } };
+ const { walletBtn, setErr, clearErr } = ui();
if (!window.ethereum) {
setErr('No wallet detected. Install MetaMask or another Ethereum wallet.');
@@ -20,65 +68,73 @@ async function signInWithWallet() {
}
clearErr();
- btn.disabled = true;
- const original = btn.innerHTML;
- btn.textContent = 'Connecting…';
+ if (walletBtn) { walletBtn.disabled = true; walletBtn.textContent = 'Connecting…'; }
+ const original = walletBtn?.innerHTML;
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;
+ await provider.send('eth_requestAccounts', []);
+ await completeSignIn(provider, walletBtn);
} 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;
+ if (walletBtn) { walletBtn.disabled = false; walletBtn.innerHTML = original; }
}
}
-const btn = document.getElementById('wallet');
-if (btn) btn.addEventListener('click', signInWithWallet);
+// ── Shared SIWE flow ───────────────────────────────────────────────────────
+// Both Privy and raw wallet paths use this to complete the login.
+
+async function completeSignIn(provider, btn) {
+ const signer = await provider.getSigner();
+ const address = await signer.getAddress();
+ const network = await provider.getNetwork();
+ const chainId = Number(network.chainId);
+
+ if (btn) 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');
+
+ if (btn) btn.textContent = 'Check your wallet…';
+ const signature = await signer.signMessage(message);
+
+ if (btn) 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;
+}
+
+// ── Bind buttons ────────────────────────────────────────────────────────────
+
+const walletBtn = document.getElementById('wallet');
+const privyBtn = document.getElementById('privy');
+
+if (walletBtn) walletBtn.addEventListener('click', signInWithWallet);
+if (privyBtn) privyBtn.addEventListener('click', signInWithPrivy);
diff --git a/src/app.js b/src/app.js
index 02153b248..f2607150a 100644
--- a/src/app.js
+++ b/src/app.js
@@ -9,6 +9,7 @@ import { NichAgent } from './nich-agent.js';
import { AvatarCreator } from './avatar-creator.js';
import { resolveURI, isDecentralizedURI } from './ipfs.js';
import { saveRemoteGlbToAccount, getMe } from './account.js';
+import { getWidget } from './widgets.js';
import queryString from 'query-string';
// Agent system — the new primitive layer
@@ -48,6 +49,7 @@ class App {
brain: hash.brain || 'none',
proxyURL: hash.proxyURL || '',
agent: hash.agent || '',
+ widget: hash.widget || '',
};
this.el = el;
@@ -97,6 +99,14 @@ class App {
return;
}
+ // Load a saved widget by ID: /#widget=<wdgt_...>
+ if (options.widget) {
+ this._loadWidget(options.widget);
+ this._initAgentSystem();
+ this._initWidgetBridge();
+ return;
+ }
+
// Load specified model or default CZ avatar
const model = options.model || '/avatars/cz.glb';
const resolvedModel = isDecentralizedURI(model) ? resolveURI(model) : model;
@@ -104,6 +114,9 @@ class App {
// Boot the agent system once identity is ready
this._initAgentSystem();
+
+ // Studio preview iframes use postMessage to live-update brand config.
+ this._initWidgetBridge();
}
// ── Agent System Init ─────────────────────────────────────────────────────
@@ -236,6 +249,121 @@ class App {
this._initAgentSystem();
}
+ async _loadWidget(widgetId) {
+ let widget;
+ try {
+ widget = await getWidget(widgetId);
+ } catch (err) {
+ this._showWidgetError(`Widget not found: ${widgetId}`);
+ return;
+ }
+ window.VIEWER.widget = widget;
+
+ const cfg = widget.config || {};
+ const modelUrl = widget.avatar?.model_url || '/avatars/cz.glb';
+
+ // Apply config to options BEFORE creating the viewer so first frame is right.
+ if (Array.isArray(cfg.cameraPosition) && cfg.cameraPosition.length === 3) {
+ this.options.cameraPosition = cfg.cameraPosition;
+ }
+ if (cfg.envPreset && cfg.envPreset !== 'none') {
+ this.options.preset = cfg.envPreset;
+ }
+
+ // Kiosk + showControls drive the chrome.
+ if (cfg.showControls === false || this.options.kiosk) {
+ document.querySelector('header')?.style.setProperty('display', 'none');
+ }
+
+ const resolved = isDecentralizedURI(modelUrl) ? resolveURI(modelUrl) : modelUrl;
+ this.view(resolved, '', new Map());
+
+ // Apply post-create brand bits once viewer exists.
+ queueMicrotask(() => this._applyWidgetConfig(cfg));
+
+ // Caption overlay — render once, simple.
+ if (cfg.caption) this._renderWidgetCaption(cfg.caption);
+
+ // Notify parent (script embed / Studio) that we're up.
+ this._postToParent({ type: 'widget:ready', id: widget.id, widgetType: widget.type });
+ }
+
+ _applyWidgetConfig(cfg) {
+ if (!this.viewer) return;
+ try {
+ if (cfg.background) this.viewer.setBackgroundColor(cfg.background);
+ if (typeof cfg.autoRotate === 'boolean' && this.viewer.controls) {
+ this.viewer.controls.autoRotate = cfg.autoRotate;
+ if (typeof cfg.rotationSpeed === 'number') {
+ this.viewer.controls.autoRotateSpeed = cfg.rotationSpeed;
+ }
+ }
+ if (cfg.envPreset && this.viewer.setEnvironment) {
+ this.viewer.setEnvironment(cfg.envPreset);
+ }
+ } catch (e) {
+ console.warn('[widget] applyConfig failed', e?.message);
+ }
+ }
+
+ _renderWidgetCaption(text) {
+ let el = document.getElementById('widget-caption');
+ if (!el) {
+ el = document.createElement('div');
+ el.id = 'widget-caption';
+ el.style.cssText = 'position:fixed;left:50%;bottom:20px;transform:translateX(-50%);padding:8px 18px;background:rgba(0,0,0,0.55);color:#fff;font-family:Inter,system-ui,sans-serif;font-size:14px;border-radius:999px;backdrop-filter:blur(8px);z-index:5;pointer-events:none;max-width:90vw;text-align:center';
+ document.body.appendChild(el);
+ }
+ el.textContent = text;
+ }
+
+ _showWidgetError(message) {
+ const el = document.createElement('div');
+ el.style.cssText = 'position:fixed;inset:0;display:grid;place-items:center;background:#0a0a0a;color:#e0e0e0;font-family:Inter,system-ui,sans-serif;text-align:center;padding:2rem;z-index:9999';
+ el.innerHTML = `<div><h1 style="font-weight:300;margin:0 0 0.5rem">Widget unavailable</h1><p style="opacity:0.7;margin:0">${message.replace(/[<>&"]/g, '')}</p><p style="margin-top:1.5rem"><a href="/" style="color:#8b5cf6">Open viewer</a> · <a href="/widgets" style="color:#8b5cf6">Browse gallery</a></p></div>`;
+ document.body.appendChild(el);
+ }
+
+ _initWidgetBridge() {
+ // Studio sends live config updates without a full reload. Also handles
+ // runtime commands (play_clip, wave) for parent-driven embeds.
+ window.addEventListener('message', (event) => {
+ if (event.origin !== location.origin) return;
+ const data = event.data;
+ if (!data || typeof data !== 'object') return;
+
+ if (data.type === 'widget:config' && data.config) {
+ this._applyWidgetConfig(data.config);
+ if (typeof data.config.caption === 'string') {
+ this._renderWidgetCaption(data.config.caption);
+ }
+ return;
+ }
+
+ if (data.type === 'widget:command' && data.command) {
+ this._handleWidgetCommand(data.command, data.args || {});
+ }
+ });
+ }
+
+ _handleWidgetCommand(command, args) {
+ const sceneCtrl = this.sceneCtrl || window.VIEWER?.scene_ctrl;
+ if (!sceneCtrl) return;
+ try {
+ switch (command) {
+ case 'play_clip': sceneCtrl.playClipByName?.(args.name); break;
+ case 'lookAt': sceneCtrl.lookAt?.(args.target); break;
+ case 'setExpression':sceneCtrl.setExpression?.(args.name, args.weight); break;
+ }
+ } catch (e) { console.warn('[widget] command failed', command, e?.message); }
+ }
+
+ _postToParent(msg) {
+ if (window.parent && window.parent !== window) {
+ window.parent.postMessage(msg, '*');
+ }
+ }
+
_initNichAgent() {
const agent = new NichAgent(document.body, protocol, this.skills, this.identity, this.runtime);
window.VIEWER.agent = agent;
diff --git a/src/editor/texture-inspector.js b/src/editor/texture-inspector.js
index b618d2b99..09328ff08 100644
--- a/src/editor/texture-inspector.js
+++ b/src/editor/texture-inspector.js
@@ -1,8 +1,20 @@
/**
* TextureInspector — catalogs every texture referenced by the loaded model,
* shows a grid of thumbnails with metadata, and opens a lightbox with
- * per-channel extraction (R/G/B/A grayscale) for any texture.
+ * per-channel extraction (R/G/B/A grayscale), zoom/pan, and UV overlay
+ * for any texture.
*/
+import {
+ RepeatWrapping,
+ ClampToEdgeWrapping,
+ MirroredRepeatWrapping,
+ NearestFilter,
+ LinearFilter,
+ NearestMipmapNearestFilter,
+ LinearMipmapNearestFilter,
+ NearestMipmapLinearFilter,
+ LinearMipmapLinearFilter,
+} from 'three';
import { traverseMaterials } from '../viewer/internal.js';
const SLOT_LABELS = {
@@ -27,10 +39,48 @@ const SLOT_LABELS = {
lightMap: 'Light',
};
+const WRAP_LABELS = {
+ [RepeatWrapping]: 'repeat',
+ [ClampToEdgeWrapping]: 'clamp',
+ [MirroredRepeatWrapping]: 'mirror',
+};
+
+const FILTER_LABELS = {
+ [NearestFilter]: 'nearest',
+ [LinearFilter]: 'linear',
+ [NearestMipmapNearestFilter]: 'nearest-mip-nearest',
+ [LinearMipmapNearestFilter]: 'linear-mip-nearest',
+ [NearestMipmapLinearFilter]: 'nearest-mip-linear',
+ [LinearMipmapLinearFilter]: 'linear-mip-linear',
+};
+
+function detectFormat(tex) {
+ if (tex.isCompressedTexture) return 'KTX2/Basis';
+ const src = tex.image && tex.image.src;
+ if (typeof src === 'string') {
+ if (/\.ktx2(\?|$)/i.test(src)) return 'KTX2';
+ if (/\.(jpe?g)(\?|$)/i.test(src)) return 'JPEG';
+ if (/\.png(\?|$)/i.test(src)) return 'PNG';
+ if (/\.webp(\?|$)/i.test(src)) return 'WebP';
+ if (src.startsWith('data:image/png')) return 'PNG';
+ if (src.startsWith('data:image/jpeg')) return 'JPEG';
+ if (src.startsWith('data:image/webp')) return 'WebP';
+ }
+ if (tex.image && tex.image.tagName === 'VIDEO') return 'video';
+ return 'image';
+}
+
+function estimateMemoryMB(w, h, mipmap) {
+ const base = w * h * 4;
+ const total = mipmap ? base * 1.333 : base;
+ return (total / 1024 / 1024).toFixed(2);
+}
+
function drawSourceToCanvas(canvas, src) {
const ctx = canvas.getContext('2d');
ctx.imageSmoothingEnabled = true;
try {
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(src, 0, 0, canvas.width, canvas.height);
return true;
} catch (e) {
@@ -50,12 +100,16 @@ export class TextureInspector {
this.gui = viewer.gui;
this.folder = null;
this.panel = null;
+ this._lastTextures = null;
+ this._keyHandler = (e) => this._onKey(e);
+ window.addEventListener('keydown', this._keyHandler);
}
rebuild() {
this._clear();
if (!this.viewer.content || !this.gui) return;
const textures = this._collectTextures();
+ this._lastTextures = textures;
if (textures.length === 0) return;
this.folder = this.gui.addFolder('Textures');
@@ -66,7 +120,21 @@ export class TextureInspector {
},
'open',
)
- .name(`inspect (${textures.length})`);
+ .name(`inspect (${textures.length}) [X]`);
+ }
+
+ _onKey(e) {
+ if (e.key !== 'x' && e.key !== 'X') return;
+ const t = e.target;
+ if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable)) return;
+ if (this.panel) {
+ this.panel.remove();
+ this.panel = null;
+ return;
+ }
+ if (this._lastTextures && this._lastTextures.length) {
+ this._openPanel(this._lastTextures);
+ }
}
_collectTextures() {
@@ -77,13 +145,28 @@ export class TextureInspector {
if (!tex || !tex.image) continue;
const key = tex.uuid;
if (!byUuid.has(key)) {
- byUuid.set(key, { tex, slots: new Set(), materials: new Set() });
+ byUuid.set(key, { tex, slots: new Set(), materials: new Set(), meshes: [] });
}
const entry = byUuid.get(key);
entry.slots.add(SLOT_LABELS[slot]);
entry.materials.add(mat.name || mat.type);
}
});
+
+ // Second pass: gather meshes per texture for UV overlay
+ this.viewer.content.traverse((node) => {
+ if (!node.geometry || !node.material) return;
+ const mats = Array.isArray(node.material) ? node.material : [node.material];
+ mats.forEach((mat) => {
+ for (const slot in SLOT_LABELS) {
+ const tex = mat[slot];
+ if (!tex || !byUuid.has(tex.uuid)) continue;
+ const entry = byUuid.get(tex.uuid);
+ if (!entry.meshes.includes(node)) entry.meshes.push(node);
+ }
+ });
+ });
+
return [...byUuid.values()];
}
@@ -95,7 +178,7 @@ export class TextureInspector {
panel.innerHTML = `
<div class="texture-inspector__header">
<span class="texture-inspector__title">Texture Inspector · ${textures.length}</span>
- <button class="texture-inspector__close" title="Close">×</button>
+ <button class="texture-inspector__close" title="Close [X]">×</button>
</div>
<div class="texture-inspector__grid"></div>
`;
@@ -111,11 +194,15 @@ export class TextureInspector {
textures.forEach((entry) => grid.appendChild(this._buildCard(entry)));
}
- _buildCard({ tex, slots, materials }) {
+ _buildCard(entry) {
+ const { tex, slots, materials } = entry;
const img = tex.image;
const w = img.width || img.videoWidth || 0;
const h = img.height || img.videoHeight || 0;
- const memMB = ((w * h * 4 * 1.33) / 1024 / 1024).toFixed(2);
+ const memMB = estimateMemoryMB(w, h, tex.generateMipmaps !== false);
+ const format = detectFormat(tex);
+ const wrap = `${WRAP_LABELS[tex.wrapS] || '?'}/${WRAP_LABELS[tex.wrapT] || '?'}`;
+ const uvChannel = tex.channel ?? 0;
const card = document.createElement('div');
card.className = 'texture-card';
@@ -130,25 +217,34 @@ export class TextureInspector {
info.className = 'texture-card__info';
info.innerHTML = `
<div class="texture-card__name">${[...slots].join(' · ')}</div>
- <div class="texture-card__meta">${w}×${h} · ~${memMB} MB</div>
+ <div class="texture-card__meta">${w}×${h} · ${format} · ~${memMB} MB</div>
+ <div class="texture-card__meta">UV${uvChannel} · ${wrap}</div>
<div class="texture-card__mats">${[...materials].slice(0, 3).join(', ')}${
materials.size > 3 ? '…' : ''
}</div>
`;
card.appendChild(info);
- thumb.addEventListener('click', () => this._openLightbox(tex, slots, materials));
+ const open = () => this._openLightbox(entry);
+ thumb.addEventListener('click', open);
card.addEventListener('click', (e) => {
if (e.target === thumb) return;
- this._openLightbox(tex, slots, materials);
+ open();
});
return card;
}
- _openLightbox(tex, slots, materials) {
+ _openLightbox(entry) {
+ const { tex, slots, materials, meshes } = entry;
const img = tex.image;
const w = img.width || 256;
const h = img.height || 256;
+ const format = detectFormat(tex);
+ const memMB = estimateMemoryMB(w, h, tex.generateMipmaps !== false);
+ const wrap = `${WRAP_LABELS[tex.wrapS] || '?'}/${WRAP_LABELS[tex.wrapT] || '?'}`;
+ const magFilter = FILTER_LABELS[tex.magFilter] || '?';
+ const minFilter = FILTER_LABELS[tex.minFilter] || '?';
+ const uvChannel = tex.channel ?? 0;
const lb = document.createElement('div');
lb.className = 'texture-lightbox';
@@ -156,7 +252,7 @@ export class TextureInspector {
<div class="texture-lightbox__bar">
<div class="texture-lightbox__meta">
<span class="texture-lightbox__title">${[...slots].join(' · ')}</span>
- <span class="texture-lightbox__dim">${w}×${h}</span>
+ <span class="texture-lightbox__dim">${w}×${h} · ${format} · ~${memMB} MB · UV${uvChannel} · wrap ${wrap} · mag ${magFilter} · min ${minFilter}</span>
</div>
<div class="texture-lightbox__channels">
<button data-ch="rgb" class="active">RGB</button>
@@ -165,17 +261,24 @@ export class TextureInspector {
<button data-ch="b">B</button>
<button data-ch="a">A</button>
<button data-ch="checker" title="Alpha over checkerboard">⌗</button>
+ <button data-act="uv" title="Toggle UV wireframe">UV</button>
+ <button data-act="fit" title="Reset zoom">⤢</button>
</div>
<button class="texture-lightbox__close" title="Close">×</button>
</div>
<div class="texture-lightbox__stage">
- <canvas class="texture-lightbox__canvas" width="${w}" height="${h}"></canvas>
+ <div class="texture-lightbox__viewport">
+ <canvas class="texture-lightbox__canvas" width="${w}" height="${h}"></canvas>
+ <canvas class="texture-lightbox__uv" width="${w}" height="${h}"></canvas>
+ </div>
</div>
- <div class="texture-lightbox__footer">Used by: ${[...materials].join(', ')}</div>
+ <div class="texture-lightbox__footer">Used by: ${[...materials].join(', ')} · ${meshes.length} mesh${meshes.length === 1 ? '' : 'es'}</div>
`;
document.body.appendChild(lb);
const canvas = lb.querySelector('.texture-lightbox__canvas');
+ const uvCanvas = lb.querySelector('.texture-lightbox__uv');
+ const viewport = lb.querySelector('.texture-lightbox__viewport');
const ctx = canvas.getContext('2d');
drawSourceToCanvas(canvas, img);
@@ -186,6 +289,9 @@ export class TextureInspector {
imgData = null;
}
+ let currentChannel = 'rgb';
+ let uvVisible = false;
+
const drawChecker = () => {
const tile = 16;
ctx.fillStyle = '#ccc';
@@ -199,6 +305,7 @@ export class TextureInspector {
};
const drawChannel = (ch) => {
+ currentChannel = ch;
ctx.clearRect(0, 0, w, h);
if (ch === 'rgb') {
drawSourceToCanvas(canvas, img);
@@ -231,9 +338,107 @@ export class TextureInspector {
ctx.putImageData(out, 0, 0);
};
+ const drawUV = () => {
+ const uctx = uvCanvas.getContext('2d');
+ uctx.clearRect(0, 0, w, h);
+ if (!uvVisible) return;
+ uctx.strokeStyle = 'rgba(0, 255, 180, 0.75)';
+ uctx.lineWidth = Math.max(1, w / 800);
+ const attrName = uvChannel === 1 ? 'uv1' : 'uv';
+ meshes.forEach((mesh) => {
+ const geo = mesh.geometry;
+ const uvAttr = geo.attributes[attrName] || geo.attributes.uv;
+ if (!uvAttr) return;
+ const index = geo.index;
+ uctx.beginPath();
+ const drawTri = (a, b, c) => {
+ const ax = uvAttr.getX(a) * w;
+ const ay = (1 - uvAttr.getY(a)) * h;
+ const bx = uvAttr.getX(b) * w;
+ const by = (1 - uvAttr.getY(b)) * h;
+ const cx = uvAttr.getX(c) * w;
+ const cy = (1 - uvAttr.getY(c)) * h;
+ uctx.moveTo(ax, ay); uctx.lineTo(bx, by);
+ uctx.moveTo(bx, by); uctx.lineTo(cx, cy);
+ uctx.moveTo(cx, cy); uctx.lineTo(ax, ay);
+ };
+ if (index) {
+ const arr = index.array;
+ for (let i = 0; i < arr.length; i += 3) drawTri(arr[i], arr[i + 1], arr[i + 2]);
+ } else {
+ for (let i = 0; i < uvAttr.count; i += 3) drawTri(i, i + 1, i + 2);
+ }
+ uctx.stroke();
+ });
+ };
+
+ // Zoom / pan
+ let zoom = 1;
+ let tx = 0;
+ let ty = 0;
+ let dragging = false;
+ let lastX = 0;
+ let lastY = 0;
+
+ const applyTransform = () => {
+ const t = `translate(${tx}px, ${ty}px) scale(${zoom})`;
+ canvas.style.transform = t;
+ uvCanvas.style.transform = t;
+ };
+ applyTransform();
+
+ viewport.addEventListener('wheel', (e) => {
+ e.preventDefault();
+ const factor = e.deltaY < 0 ? 1.15 : 1 / 1.15;
+ const next = Math.max(0.1, Math.min(12, zoom * factor));
+ // zoom toward cursor
+ const rect = viewport.getBoundingClientRect();
+ const cx = e.clientX - rect.left - rect.width / 2;
+ const cy = e.clientY - rect.top - rect.height / 2;
+ tx = cx - (cx - tx) * (next / zoom);
+ ty = cy - (cy - ty) * (next / zoom);
+ zoom = next;
+ applyTransform();
+ }, { passive: false });
+
+ viewport.addEventListener('mousedown', (e) => {
+ dragging = true;
+ lastX = e.clientX;
+ lastY = e.clientY;
+ viewport.style.cursor = 'grabbing';
+ });
+ window.addEventListener('mousemove', (e) => {
+ if (!dragging) return;
+ tx += e.clientX - lastX;
+ ty += e.clientY - lastY;
+ lastX = e.clientX;
+ lastY = e.clientY;
+ applyTransform();
+ });
+ window.addEventListener('mouseup', () => {
+ dragging = false;
+ viewport.style.cursor = '';
+ });
+
+ const fit = () => {
+ zoom = 1; tx = 0; ty = 0;
+ applyTransform();
+ };
+
lb.querySelectorAll('.texture-lightbox__channels button').forEach((btn) => {
btn.addEventListener('click', () => {
- lb.querySelectorAll('.texture-lightbox__channels button').forEach((b) =>
+ const act = btn.dataset.act;
+ if (act === 'uv') {
+ uvVisible = !uvVisible;
+ btn.classList.toggle('active', uvVisible);
+ drawUV();
+ return;
+ }
+ if (act === 'fit') {
+ fit();
+ return;
+ }
+ lb.querySelectorAll('.texture-lightbox__channels button[data-ch]').forEach((b) =>
b.classList.remove('active'),
);
btn.classList.add('active');
@@ -262,5 +467,6 @@ export class TextureInspector {
dispose() {
this._clear();
+ window.removeEventListener('keydown', this._keyHandler);
}
}
diff --git a/src/features/hero-dragon.js b/src/features/hero-dragon.js
new file mode 100644
index 000000000..80b229c83
--- /dev/null
+++ b/src/features/hero-dragon.js
@@ -0,0 +1,261 @@
+// Dragon mode — the hero avatar chases the cursor while the subtitle reflows
+// around its silhouette every frame. Inspired by the chenglou/pretext dragon
+// demo. Opt-in via ?pretext=4 only; gimmick risk is real.
+//
+// Layering:
+// - Avatar is translated via transform (.hero-avatar). .hero--dragon absolutely
+// positions it within .hero; a home transform returns it to grid baseline.
+// - Text reflows via PretextHero.paintCircle(cx, cy, r), called once per frame.
+// - One rAF drives both the spring integrator and the reflow.
+//
+// Auto-downgrade: if mean reflow cost over a 30-frame window exceeds
+// COST_BUDGET_MS, disable per-frame relayout and keep the chase running.
+
+const STIFFNESS = 120;
+const DAMPING = 20;
+const MASS = 1;
+const RETURN_EPS_POS = 0.5; // px
+const RETURN_EPS_VEL = 5; // px/s
+const COST_BUDGET_MS = 8;
+const COST_WINDOW = 30;
+const HERO_INSET = 16; // px — keep avatar fully inside hero
+
+function prefersReducedMotion() {
+ return typeof window !== 'undefined'
+ && window.matchMedia
+ && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
+}
+
+function hasHover() {
+ return typeof window !== 'undefined'
+ && window.matchMedia
+ && window.matchMedia('(hover: hover)').matches;
+}
+
+export class HeroDragon {
+ constructor(hero) {
+ this.hero = hero;
+ this.root = hero.root;
+ this.avatar = hero.avatar;
+ this.modelViewer = hero.modelViewer;
+
+ this._targetX = 0;
+ this._targetY = 0;
+ this._x = 0;
+ this._y = 0;
+ this._vx = 0;
+ this._vy = 0;
+
+ this._homeRect = null;
+ this._heroRect = null;
+ this._lastTs = 0;
+ this._rafId = null;
+ this._attached = false;
+ this._returning = false;
+
+ this._costSamples = [];
+ this._downgraded = false;
+
+ this._onPointerMove = this._onPointerMove.bind(this);
+ this._onPointerLeave = this._onPointerLeave.bind(this);
+ this._onResize = this._onResize.bind(this);
+ this._onVisibility = this._onVisibility.bind(this);
+ this._tick = this._tick.bind(this);
+ }
+
+ attach() {
+ if (this._attached) return;
+ if (!this.avatar || !this.root || !this.hero?.pretext) return;
+ if (prefersReducedMotion()) return;
+ if (!hasHover()) return;
+
+ this._attached = true;
+
+ this.root.classList.add('hero--dragon');
+ this._setAutoRotate(false);
+
+ // Wait a frame for the CSS to resettle (grid column changes), then
+ // measure rects and recompute pretext layout context.
+ requestAnimationFrame(() => {
+ if (!this._attached) return;
+ this._measureRects();
+ this.hero.recomputeContext?.();
+ this._paint();
+
+ this.root.addEventListener('pointermove', this._onPointerMove, { passive: true });
+ this.root.addEventListener('pointerleave', this._onPointerLeave);
+ window.addEventListener('resize', this._onResize, { passive: true });
+ window.addEventListener('scroll', this._onResize, { passive: true });
+ document.addEventListener('visibilitychange', this._onVisibility);
+
+ this._lastTs = performance.now();
+ this._rafId = requestAnimationFrame(this._tick);
+ });
+ }
+
+ detach() {
+ if (!this._attached) return;
+ this._attached = false;
+
+ this.root.removeEventListener('pointermove', this._onPointerMove);
+ this.root.removeEventListener('pointerleave', this._onPointerLeave);
+ window.removeEventListener('resize', this._onResize);
+ window.removeEventListener('scroll', this._onResize);
+ document.removeEventListener('visibilitychange', this._onVisibility);
+
+ if (this._rafId != null) cancelAnimationFrame(this._rafId);
+ this._rafId = null;
+
+ this.root.classList.remove('hero--dragon');
+ if (this.avatar) {
+ this.avatar.style.transform = '';
+ this.avatar.style.willChange = '';
+ }
+ this._setAutoRotate(true);
+
+ // Static wrap resumes once the class is gone — bounce through pretext's
+ // own repaint path so the overlay matches the non-dragon layout.
+ this.hero.recomputeContext?.();
+ const c = this._homeCircle();
+ if (c) this.hero.paintCircle?.(c.x, c.y, c.r);
+ }
+
+ _measureRects() {
+ this._heroRect = this.root.getBoundingClientRect();
+ this._homeRect = this.avatar.getBoundingClientRect();
+ this.avatar.style.willChange = 'transform';
+ }
+
+ _homeCircle() {
+ const ctx = this.hero._ctx;
+ if (!ctx) return null;
+ // Home center in overlay-local coords, mirroring _avatarCircle()
+ // but using the avatar's home rect.
+ const r = this._homeRect ?? ctx.avatarRect;
+ return {
+ x: (r.left + r.width / 2) - ctx.subtitleLeftPage,
+ y: (r.top + r.height / 2) - ctx.subtitleTopPage,
+ r: ctx.circleBaseR,
+ };
+ }
+
+ _onResize() {
+ if (this._resizePending) return;
+ this._resizePending = true;
+ requestAnimationFrame(() => {
+ this._resizePending = false;
+ this._measureRects();
+ this.hero.recomputeContext?.();
+ });
+ }
+
+ _onVisibility() {
+ if (document.hidden) {
+ if (this._rafId != null) cancelAnimationFrame(this._rafId);
+ this._rafId = null;
+ } else if (this._attached && this._rafId == null) {
+ this._lastTs = performance.now();
+ this._rafId = requestAnimationFrame(this._tick);
+ }
+ }
+
+ _onPointerMove(e) {
+ const home = this._homeRect;
+ const hero = this._heroRect;
+ if (!home || !hero) return;
+
+ const homeCx = home.left + home.width / 2;
+ const homeCy = home.top + home.height / 2;
+
+ // Clamp so the avatar rect stays within the hero rect (minus inset).
+ const halfW = home.width / 2;
+ const halfH = home.height / 2;
+ const minCx = hero.left + halfW + HERO_INSET;
+ const maxCx = hero.right - halfW - HERO_INSET;
+ const minCy = hero.top + halfH + HERO_INSET;
+ const maxCy = hero.bottom - halfH - HERO_INSET;
+
+ const cx = Math.min(maxCx, Math.max(minCx, e.clientX));
+ const cy = Math.min(maxCy, Math.max(minCy, e.clientY));
+
+ this._targetX = cx - homeCx;
+ this._targetY = cy - homeCy;
+ this._returning = false;
+ }
+
+ _onPointerLeave() {
+ this._targetX = 0;
+ this._targetY = 0;
+ this._returning = true;
+ }
+
+ _tick(ts) {
+ if (!this._attached) return;
+
+ const dtRaw = (ts - this._lastTs) / 1000;
+ this._lastTs = ts;
+ // Cap dt to avoid spring explosions after a tab-switch pause.
+ const dt = Math.min(dtRaw, 1 / 30);
+
+ // Semi-implicit Euler spring integrator.
+ const ax = (STIFFNESS * (this._targetX - this._x) - DAMPING * this._vx) / MASS;
+ const ay = (STIFFNESS * (this._targetY - this._y) - DAMPING * this._vy) / MASS;
+ this._vx += ax * dt;
+ this._vy += ay * dt;
+ this._x += this._vx * dt;
+ this._y += this._vy * dt;
+
+ this.avatar.style.transform = `translate3d(${this._x.toFixed(2)}px, ${this._y.toFixed(2)}px, 0)`;
+
+ this._paint();
+
+ // Once fully settled at home after a pointerleave, detach cleanly so
+ // the static wrap and auto-rotate resume.
+ if (this._returning) {
+ const settled =
+ Math.abs(this._x) < RETURN_EPS_POS &&
+ Math.abs(this._y) < RETURN_EPS_POS &&
+ Math.abs(this._vx) < RETURN_EPS_VEL &&
+ Math.abs(this._vy) < RETURN_EPS_VEL;
+ if (settled) {
+ this.detach();
+ return;
+ }
+ }
+
+ this._rafId = requestAnimationFrame(this._tick);
+ }
+
+ _paint() {
+ if (this._downgraded) return;
+ const ctx = this.hero._ctx;
+ if (!ctx) return;
+
+ const home = this._homeRect;
+ if (!home) return;
+
+ const homeCxPage = home.left + home.width / 2;
+ const homeCyPage = home.top + home.height / 2;
+ const cx = (homeCxPage + this._x) - ctx.subtitleLeftPage;
+ const cy = (homeCyPage + this._y) - ctx.subtitleTopPage;
+
+ const cost = this.hero.paintCircle?.(cx, cy, ctx.circleBaseR) ?? 0;
+
+ this._costSamples.push(cost);
+ if (this._costSamples.length > COST_WINDOW) this._costSamples.shift();
+ if (this._costSamples.length === COST_WINDOW) {
+ let sum = 0;
+ for (const c of this._costSamples) sum += c;
+ if (sum / COST_WINDOW > COST_BUDGET_MS) {
+ this._downgraded = true;
+ console.warn('[pretext-hero] dragon downgraded — reflow cost exceeded budget');
+ }
+ }
+ }
+
+ _setAutoRotate(on) {
+ if (!this.modelViewer) return;
+ if (on) this.modelViewer.setAttribute('auto-rotate', '');
+ else this.modelViewer.removeAttribute('auto-rotate');
+ }
+}
diff --git a/src/features/hero-gaze.js b/src/features/hero-gaze.js
index 4497f3f7e..61a1efa4e 100644
--- a/src/features/hero-gaze.js
+++ b/src/features/hero-gaze.js
@@ -154,14 +154,17 @@ export class HeroGaze {
}
const now = performance.now();
- const idleFor = this._lastMoveAt > 0 ? now - this._lastMoveAt : Infinity;
+ const idleFor = this._lastMoveAt > 0 ? now - this._lastMoveAt : 0;
const settled =
Math.abs(this._currentTheta - BASE_THETA_DEG) < SETTLE_EPSILON &&
Math.abs(this._currentPhi - BASE_PHI_DEG) < SETTLE_EPSILON;
// Resume auto-rotate either after a quiet window (cursor still over the
// hero but idle) or after pointerleave once the avatar has eased home.
- if (this._tracking && (idleFor > IDLE_MS || (this._lastMoveAt === 0 && settled))) {
+ const shouldResume = this._lastMoveAt === 0
+ ? settled // pointerleave: wait for ease-back to complete
+ : idleFor > IDLE_MS; // idle: cursor still in hero but stopped
+ if (this._tracking && shouldResume) {
this._tracking = false;
if (this._lastMoveAt === 0 && settled) {
// Snap to the canonical orbit so auto-rotate picks up cleanly.
diff --git a/src/features/hero-pretext.js b/src/features/hero-pretext.js
index e707a9f8b..2dd5f721d 100644
--- a/src/features/hero-pretext.js
+++ b/src/features/hero-pretext.js
@@ -20,10 +20,12 @@ export default class PretextHero {
this.pretext = null;
this._gaze = null;
+ this._dragon = null;
this._overlay = null;
this._onResize = null;
this._resizeT = null;
this._rafToken = 0;
+ this._ctx = null;
}
async init() {
@@ -41,8 +43,9 @@ export default class PretextHero {
}
}
- // Flag-gated submodules. 2 and 4 are reserved for text-wrap + dragon mode.
- if (this.flag === '3' || this.flag === '4') {
+ // Gaze follows the cursor with subtle head rotation. Dragon mode moves
+ // the avatar itself, so the two don't compose — flag 4 opts out of gaze.
+ if (this.flag === '3') {
try {
const { HeroGaze } = await import('./hero-gaze.js');
this._gaze = new HeroGaze(this);
@@ -52,12 +55,26 @@ export default class PretextHero {
}
}
+ if (this.flag === '4') {
+ try {
+ const { HeroDragon } = await import('./hero-dragon.js');
+ this._dragon = new HeroDragon(this);
+ this._dragon.attach();
+ } catch (err) {
+ console.warn('[pretext-hero] dragon unavailable:', err);
+ }
+ }
+
return this;
}
enableStaticWrap() {
if (!this.content || !this.subtitle || !this.avatar || !this.pretext) return;
+ // Keep the original subtitle accessible to screen readers even when
+ // visually hidden via .pretext-active; the overlay is aria-hidden.
+ this.subtitle.setAttribute('aria-hidden', 'false');
+
this._overlay = document.createElement('div');
this._overlay.className = 'hero-subtitle-pretext';
this._overlay.setAttribute('aria-hidden', 'true');
@@ -87,23 +104,38 @@ export default class PretextHero {
_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';
+ this._ctx = null;
return;
}
this._overlay.style.display = '';
- // ── Read phase ───────────────────────────────────────────────────────
+ const ctx = this._computeLayoutContext();
+ if (!ctx) return;
+ this._ctx = ctx;
+
+ const { circleX, circleY, circleR } = this._avatarCircle(ctx);
+ const { lines, contentHeight } = this._layoutLinesAroundCircle(ctx, circleX, circleY, circleR);
+
+ const token = ++this._rafToken;
+ requestAnimationFrame(() => {
+ if (token !== this._rafToken || !this._overlay) return;
+ this._paintLines(ctx, lines, contentHeight);
+ this.root.classList.add('pretext-active');
+ });
+ }
+
+ // Reads rects + style once. Returned context is the input to
+ // _layoutLinesAroundCircle, which is pure math and reusable per-frame
+ // by dragon mode.
+ _computeLayoutContext() {
+ if (!this.content || !this.subtitle || !this.avatar || !this.pretext) return null;
+
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);
@@ -112,38 +144,47 @@ export default class PretextHero {
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 ?? '';
+ // Dragon mode stretches .hero-content to full hero width, so use the
+ // content box as the outer bound and let the subtitle flow wider.
+ const heroRect = this.root.getBoundingClientRect();
+ const rightmostPage = this.root.classList.contains('hero--dragon')
+ ? heroRect.right - 32
+ : Math.max(avatarRect.right - 24, subtitleRect.right);
+ const overlayWidth = Math.max(subtitleRect.width, rightmostPage - subtitleRect.left);
+
+ const text = this.subtitle.textContent ?? '';
const prepared = this.pretext.prepareWithSegments(text, font);
+ const circleBaseR = (Math.min(avatarRect.width, avatarRect.height) / 2) * 0.92;
+
+ return {
+ font, lineHeight, prepared, text,
+ overlayLeft, overlayTop, overlayWidth,
+ subtitleRect, avatarRect, subtitleLeftPage: subtitleRect.left, subtitleTopPage: subtitleRect.top,
+ circleBaseR,
+ hPad: 14, maxLines: 32,
+ };
+ }
+
+ _avatarCircle(ctx) {
+ const r = ctx.avatarRect;
+ return {
+ circleX: (r.left + r.width / 2) - ctx.subtitleLeftPage,
+ circleY: (r.top + r.height / 2) - ctx.subtitleTopPage,
+ circleR: ctx.circleBaseR,
+ };
+ }
+
+ _layoutLinesAroundCircle(ctx, circleX, circleY, circleR) {
+ const { overlayWidth, lineHeight, hPad, prepared, maxLines } = ctx;
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;
@@ -152,16 +193,10 @@ export default class PretextHero {
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;
}
@@ -172,34 +207,47 @@ export default class PretextHero {
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;
+ return { lines, contentHeight: lineTop };
+ }
- 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);
+ _paintLines(ctx, lines, contentHeight) {
+ if (!this._overlay) return;
+ const overlay = this._overlay;
+ overlay.style.left = `${ctx.overlayLeft}px`;
+ overlay.style.top = `${ctx.overlayTop}px`;
+ overlay.style.width = `${ctx.overlayWidth}px`;
+ overlay.style.height = `${Math.max(contentHeight, ctx.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');
- });
+ // Public for dragon mode — recompute rects after toggling .hero--dragon.
+ recomputeContext() {
+ this._ctx = this._computeLayoutContext();
+ return this._ctx;
+ }
+
+ // Public for dragon mode — reflow using the current cached context and
+ // the caller-supplied avatar circle (in overlay-local coordinates).
+ // Returns the measured layout cost in ms for the auto-downgrade budget.
+ paintCircle(circleX, circleY, circleR) {
+ if (!this._ctx || !this._overlay) return 0;
+ const t0 = performance.now();
+ const { lines, contentHeight } = this._layoutLinesAroundCircle(this._ctx, circleX, circleY, circleR);
+ this._paintLines(this._ctx, lines, contentHeight);
+ return performance.now() - t0;
}
dispose() {
@@ -215,11 +263,17 @@ export default class PretextHero {
this._overlay.remove();
this._overlay = null;
}
+ this.subtitle?.removeAttribute('aria-hidden');
this.root?.classList.remove('pretext-active');
if (this._gaze) {
this._gaze.detach();
this._gaze = null;
}
+ if (this._dragon) {
+ this._dragon.detach();
+ this._dragon = null;
+ }
+ this._ctx = null;
}
}
diff --git a/src/viewer.js b/src/viewer.js
index 912325249..525e3c4ae 100644
--- a/src/viewer.js
+++ b/src/viewer.js
@@ -541,6 +541,17 @@ export class Viewer {
this.invalidate();
}
+ /**
+ * Public setter for the scene background color. Used by the widget runtime
+ * + Studio postMessage bridge to apply brand config without touching dat.gui.
+ * @param {string|number} color CSS color string or hex int.
+ */
+ setBackgroundColor(color) {
+ this.state.bgColor = typeof color === 'string' ? color : '#' + color.toString(16).padStart(6, '0');
+ this.state.transparentBg = false;
+ this.updateBackground();
+ }
+
/**
* Adds AxesHelper.
*
diff --git a/src/widget-types.js b/src/widget-types.js
new file mode 100644
index 000000000..330631153
--- /dev/null
+++ b/src/widget-types.js
@@ -0,0 +1,216 @@
+// Widget type registry + brand defaults + per-type config validators.
+// Both the Studio UI and the public widget runtime import from here.
+//
+// `status: 'ready'` widgets have a working runtime. `status: 'pending'`
+// widgets save their config but the runtime renders a "coming soon" banner
+// — Prompts 01-05 flip these to 'ready' as their runtimes ship.
+
+import { z } from 'zod';
+
+export const WIDGET_TYPES = {
+ 'turntable': {
+ label: 'Turntable Showcase',
+ desc: 'Hero banner — auto-rotate, no UI, just the avatar.',
+ status: 'ready',
+ icon: '◎',
+ },
+ 'animation-gallery': {
+ label: 'Animation Gallery',
+ desc: 'Click through every clip on a rigged avatar.',
+ status: 'pending',
+ icon: '▶',
+ },
+ 'talking-agent': {
+ label: 'Talking Agent',
+ desc: 'Embodied chat — your agent on your site.',
+ status: 'pending',
+ icon: '◐',
+ },
+ 'passport': {
+ label: 'ERC-8004 Passport',
+ desc: 'On-chain identity card for any agent.',
+ status: 'ready',
+ icon: '◊',
+ },
+ 'hotspot-tour': {
+ label: 'Hotspot Tour',
+ desc: 'Annotated 3D scene with clickable points of interest.',
+ status: 'pending',
+ icon: '⌖',
+ },
+};
+
+export const WIDGET_TYPE_KEYS = Object.keys(WIDGET_TYPES);
+
+export const BRAND_DEFAULTS = Object.freeze({
+ background: '#0a0a0a',
+ accent: '#8b5cf6',
+ caption: '',
+ showControls: true,
+ autoRotate: true,
+ envPreset: 'neutral',
+ cameraPosition: null,
+});
+
+const TYPE_DEFAULTS = {
+ 'turntable': { rotationSpeed: 0.5 },
+ 'animation-gallery': { defaultClip: '', loopAll: false, showClipPicker: true },
+ 'talking-agent': { greeting: 'Hi! What would you like to know?', brain: 'none', proxyURL: '' },
+ 'passport': {
+ chain: 'base-sepolia',
+ agentId: null,
+ wallet: null,
+ showReputation: true,
+ showRecentFeedback: true,
+ showValidation: false,
+ showRegistrationJSON: true,
+ layout: 'portrait',
+ badgeSize: 'medium',
+ rotationSpeed: 0.6,
+ rpcURL: '',
+ refreshIntervalSec: 60,
+ showPoweredBy: true,
+ },
+ 'hotspot-tour': { hotspots: [] },
+};
+
+const hexColor = z.string().regex(/^#[0-9a-fA-F]{3,8}$/, 'must be a hex color');
+const cameraVec = z.tuple([z.number(), z.number(), z.number()]).nullable();
+const envPreset = z.enum(['none', 'neutral', 'venice-sunset', 'footprint-court']);
+
+const brandSchema = z.object({
+ background: hexColor.default(BRAND_DEFAULTS.background),
+ accent: hexColor.default(BRAND_DEFAULTS.accent),
+ caption: z.string().max(280).default(BRAND_DEFAULTS.caption),
+ showControls: z.boolean().default(BRAND_DEFAULTS.showControls),
+ autoRotate: z.boolean().default(BRAND_DEFAULTS.autoRotate),
+ envPreset: envPreset.default(BRAND_DEFAULTS.envPreset),
+ cameraPosition: cameraVec.default(BRAND_DEFAULTS.cameraPosition),
+});
+
+const TYPE_SCHEMAS = {
+ 'turntable': brandSchema.extend({
+ rotationSpeed: z.number().min(0).max(10).default(0.5),
+ }),
+ 'animation-gallery': brandSchema.extend({
+ defaultClip: z.string().max(120).default(''),
+ loopAll: z.boolean().default(false),
+ showClipPicker: z.boolean().default(true),
+ }),
+ 'talking-agent': brandSchema.extend({
+ greeting: z.string().max(280).default('Hi! What would you like to know?'),
+ brain: z.enum(['none', 'anthropic']).default('none'),
+ proxyURL: z.string().url().or(z.literal('')).default(''),
+ }),
+ 'passport': brandSchema.extend({
+ chain: z.string().min(1).default('base-sepolia'),
+ agentId: z.string().regex(/^\d+$/, 'agentId must be a uint256 string').nullable().default(null),
+ wallet: z.string().regex(/^0x[0-9a-fA-F]{40}$/).nullable().default(null),
+ showReputation: z.boolean().default(true),
+ showRecentFeedback: z.boolean().default(true),
+ showValidation: z.boolean().default(false),
+ showRegistrationJSON: z.boolean().default(true),
+ layout: z.enum(['portrait', 'landscape', 'badge']).default('portrait'),
+ badgeSize: z.enum(['small', 'medium', 'large']).default('medium'),
+ rotationSpeed: z.number().min(0).max(10).default(0.6),
+ rpcURL: z.string().url().startsWith('https://').or(z.literal('')).default(''),
+ refreshIntervalSec: z.number().int().min(0).max(3600).default(60),
+ showPoweredBy: z.boolean().default(true),
+ }),
+ 'hotspot-tour': brandSchema.extend({
+ hotspots: z.array(z.object({
+ id: z.string().min(1).max(40),
+ label: z.string().min(1).max(120),
+ position: z.tuple([z.number(), z.number(), z.number()]),
+ body: z.string().max(2000).optional(),
+ })).max(40).default([]),
+ }),
+};
+
+export function defaultConfig(type) {
+ if (!WIDGET_TYPES[type]) throw new Error(`unknown widget type: ${type}`);
+ return { ...BRAND_DEFAULTS, ...(TYPE_DEFAULTS[type] || {}) };
+}
+
+export function validateConfig(type, config) {
+ const schema = TYPE_SCHEMAS[type];
+ if (!schema) throw new Error(`unknown widget type: ${type}`);
+ const res = schema.safeParse(config || {});
+ if (!res.success) {
+ const err = new Error(res.error.issues.map((i) => `${i.path.join('.') || 'config'}: ${i.message}`).join('; '));
+ err.code = 'validation_error';
+ throw err;
+ }
+ return res.data;
+}
+
+export function isReady(type) {
+ return WIDGET_TYPES[type]?.status === 'ready';
+}
+
+// Server-side counterpart — the API can validate the same way.
+export const widgetTypeEnum = z.enum(WIDGET_TYPE_KEYS);
+export const widgetConfigSchemas = TYPE_SCHEMAS;
+
+// ---------------------------------------------------------------------------
+// Chain registry — used by the passport widget to resolve slugs to chainIds,
+// pick a public RPC, and build explorer links.
+// ---------------------------------------------------------------------------
+
+export const CHAIN_SLUGS = {
+ 'ethereum': 1,
+ 'optimism': 10,
+ 'bsc': 56,
+ 'polygon': 137,
+ 'base': 8453,
+ 'arbitrum': 42161,
+ 'sepolia': 11155111,
+ 'base-sepolia': 84532,
+ 'optimism-sepolia': 11155420,
+ 'arbitrum-sepolia': 421614,
+ 'polygon-amoy': 80002,
+};
+
+export const PUBLIC_RPCS = {
+ 1: 'https://eth.llamarpc.com',
+ 10: 'https://mainnet.optimism.io',
+ 56: 'https://bsc-dataseed.binance.org',
+ 137: 'https://polygon-rpc.com',
+ 8453: 'https://mainnet.base.org',
+ 42161: 'https://arb1.arbitrum.io/rpc',
+ 11155111: 'https://ethereum-sepolia-rpc.publicnode.com',
+ 84532: 'https://sepolia.base.org',
+ 11155420: 'https://sepolia.optimism.io',
+ 421614: 'https://sepolia-rollup.arbitrum.io/rpc',
+ 80002: 'https://rpc-amoy.polygon.technology',
+};
+
+export const EXPLORERS = {
+ 1: 'https://etherscan.io',
+ 10: 'https://optimistic.etherscan.io',
+ 56: 'https://bscscan.com',
+ 137: 'https://polygonscan.com',
+ 8453: 'https://basescan.org',
+ 42161: 'https://arbiscan.io',
+ 11155111: 'https://sepolia.etherscan.io',
+ 84532: 'https://sepolia.basescan.org',
+ 11155420: 'https://sepolia-optimism.etherscan.io',
+ 421614: 'https://sepolia.arbiscan.io',
+ 80002: 'https://amoy.polygonscan.com',
+};
+
+/** Resolve a chain reference (slug or numeric id or numeric string) to chainId. */
+export function resolveChainId(ref) {
+ if (typeof ref === 'number') return ref;
+ if (typeof ref !== 'string') return null;
+ const slug = ref.toLowerCase();
+ if (CHAIN_SLUGS[slug]) return CHAIN_SLUGS[slug];
+ const n = Number(slug);
+ return Number.isFinite(n) ? n : null;
+}
+
+/** Pretty display name for a chainId. */
+export function chainLabel(chainId) {
+ const entry = Object.entries(CHAIN_SLUGS).find(([, v]) => v === chainId);
+ return entry ? entry[0] : `chain-${chainId}`;
+}
diff --git a/src/widgets.js b/src/widgets.js
new file mode 100644
index 000000000..5d4fe8488
--- /dev/null
+++ b/src/widgets.js
@@ -0,0 +1,89 @@
+// Client helpers for /api/widgets. Mirrors src/account.js.
+// All write calls send credentials so the session cookie travels with them.
+// getWidget() is public — no credentials, so cached CDN responses can be
+// shared between visitors loading the same embed URL.
+
+const API = '';
+
+export async function listWidgets({ limit, cursor } = {}) {
+ const url = new URL(`${API}/api/widgets`, location.origin);
+ if (limit) url.searchParams.set('limit', String(limit));
+ if (cursor) url.searchParams.set('cursor', cursor);
+ const res = await fetch(url.pathname + url.search, { credentials: 'include' });
+ if (res.status === 401) throw err401();
+ if (!res.ok) throw await asError(res);
+ return res.json();
+}
+
+export async function getWidget(id) {
+ if (!id) throw new Error('widget id required');
+ const res = await fetch(`${API}/api/widgets/${encodeURIComponent(id)}`);
+ if (res.status === 404) {
+ const e = new Error('widget not found');
+ e.code = 'not_found';
+ e.status = 404;
+ throw e;
+ }
+ if (!res.ok) throw await asError(res);
+ const { widget } = await res.json();
+ return widget;
+}
+
+export async function createWidget({ type, name, avatar_id, config, is_public }) {
+ const data = await postJson('/api/widgets', { type, name, avatar_id, config, is_public });
+ return data.widget;
+}
+
+export async function updateWidget(id, patch) {
+ if (!id) throw new Error('widget id required');
+ const res = await fetch(`${API}/api/widgets/${encodeURIComponent(id)}`, {
+ method: 'PATCH',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify(patch),
+ });
+ if (res.status === 401) throw err401();
+ if (!res.ok) throw await asError(res);
+ const { widget } = await res.json();
+ return widget;
+}
+
+export async function deleteWidget(id) {
+ if (!id) throw new Error('widget id required');
+ const res = await fetch(`${API}/api/widgets/${encodeURIComponent(id)}`, {
+ method: 'DELETE',
+ credentials: 'include',
+ });
+ if (res.status === 401) throw err401();
+ if (!res.ok) throw await asError(res);
+ return true;
+}
+
+async function postJson(path, body) {
+ const res = await fetch(`${API}${path}`, {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify(body),
+ });
+ if (res.status === 401) throw err401();
+ if (!res.ok) throw await asError(res);
+ return res.json();
+}
+
+async function asError(res) {
+ let data = null;
+ try { data = await res.json(); } catch {}
+ const e = new Error(data?.error_description || res.statusText || 'request failed');
+ e.status = res.status;
+ e.code = data?.error || 'request_failed';
+ e.data = data;
+ return e;
+}
+
+function err401() {
+ const e = new Error('not_signed_in');
+ e.status = 401;
+ e.code = 'not_signed_in';
+ return e;
+}
diff --git a/src/widgets/passport.js b/src/widgets/passport.js
new file mode 100644
index 000000000..1fe22ebd2
--- /dev/null
+++ b/src/widgets/passport.js
@@ -0,0 +1,507 @@
+/**
+ * ERC-8004 Passport Widget — public, read-only on-chain identity card
+ * rendered alongside the 3D avatar canvas.
+ *
+ * Contract reads run in parallel:
+ * IdentityRegistry.ownerOf(agentId) → wallet
+ * IdentityRegistry.tokenURI(agentId) → registration JSON URL
+ * IdentityRegistry.name()/symbol() → collection label
+ * ReputationRegistry.getReputation(id) → (total, count) → average
+ * ReputationRegistry event log → recent feedback (if enabled)
+ * ValidationRegistry.getLatestValidation → optional proof row
+ *
+ * No wallet connection, no writes, no feedback submission. That's a v2 task.
+ */
+
+import { Contract, JsonRpcProvider } from 'ethers';
+import {
+ IDENTITY_REGISTRY_ABI,
+ REPUTATION_REGISTRY_ABI,
+ REGISTRY_DEPLOYMENTS,
+} from '../erc8004/index.js';
+import {
+ CHAIN_SLUGS, PUBLIC_RPCS, EXPLORERS,
+ resolveChainId, chainLabel,
+} from '../widget-types.js';
+import { resolveURI, isDecentralizedURI } from '../ipfs.js';
+
+const CACHE_PREFIX = 'erc8004-passport:';
+const STALE_TTL_MS = 1000 * 60 * 60 * 24; // 24h hard ceiling on stale cache
+
+/**
+ * Mount the passport widget.
+ *
+ * @param {import('../viewer.js').Viewer} viewer The three.js viewer instance.
+ * @param {object} config Passport config (see widget-types.js passport schema).
+ * @param {HTMLElement} container Root container. The widget takes this over.
+ * @param {string} [widgetId] Optional cache-busting key.
+ * @returns {Promise<{ destroy: () => void }>}
+ */
+export async function mountPassport(viewer, config, container, widgetId) {
+ const state = {
+ config,
+ widgetId: widgetId || `${config.chain}:${config.agentId}`,
+ cacheKey: `${CACHE_PREFIX}${config.chain}:${config.agentId}`,
+ chainId: resolveChainId(config.chain),
+ data: null,
+ lastVerifiedAt: null,
+ destroyed: false,
+ pollTimer: null,
+ visibilityHandler: null,
+ };
+
+ _applyTurntable(viewer, config);
+ _kioskifyCanvas(viewer, container);
+
+ const panel = document.createElement('div');
+ panel.className = `passport-panel passport-layout--${config.layout} passport-badge-size--${config.badgeSize}`;
+ container.appendChild(panel);
+
+ const root = container;
+ root.classList.add('passport-widget', `passport-root--${config.layout}`);
+
+ _renderLoading(panel, config);
+
+ // Hydrate from cache immediately so the panel has content before RPC responds.
+ const cached = _readCache(state.cacheKey);
+ if (cached && cached.data) {
+ state.data = cached.data;
+ state.lastVerifiedAt = cached.savedAt;
+ _render(panel, state);
+ }
+
+ await _refresh(state, panel);
+
+ if (config.refreshIntervalSec > 0) {
+ const tick = () => {
+ if (state.destroyed) return;
+ if (document.hidden) return;
+ _refresh(state, panel).catch(() => { /* keep stale */ });
+ };
+ state.pollTimer = setInterval(tick, config.refreshIntervalSec * 1000);
+
+ state.visibilityHandler = () => {
+ if (!document.hidden) tick();
+ };
+ document.addEventListener('visibilitychange', state.visibilityHandler);
+ }
+
+ return {
+ destroy() {
+ state.destroyed = true;
+ if (state.pollTimer) clearInterval(state.pollTimer);
+ if (state.visibilityHandler) {
+ document.removeEventListener('visibilitychange', state.visibilityHandler);
+ }
+ panel.remove();
+ root.classList.remove('passport-widget', `passport-root--${config.layout}`);
+ },
+ };
+}
+
+// ---------------------------------------------------------------------------
+// RPC + contract reads
+// ---------------------------------------------------------------------------
+
+function _pickRpc(config, chainId) {
+ if (config.rpcURL) {
+ // Require HTTPS per the security spec.
+ if (!/^https:\/\//i.test(config.rpcURL)) {
+ console.warn('[passport] ignoring non-HTTPS rpcURL');
+ } else {
+ return config.rpcURL;
+ }
+ }
+ return PUBLIC_RPCS[chainId] || null;
+}
+
+async function _refresh(state, panel) {
+ const { config, chainId } = state;
+
+ if (!chainId) {
+ _renderError(panel, `Unknown chain "${config.chain}".`, state);
+ return;
+ }
+ const deployment = REGISTRY_DEPLOYMENTS[chainId];
+ if (!deployment || !deployment.identityRegistry) {
+ _renderError(panel, `No ERC-8004 registry deployed on ${chainLabel(chainId)}.`, state);
+ return;
+ }
+ if (!config.agentId) {
+ _renderError(panel, 'No agent id configured.', state);
+ return;
+ }
+ if (!/^\d+$/.test(String(config.agentId))) {
+ _renderError(panel, 'Invalid agent id.', state);
+ return;
+ }
+
+ const rpcURL = _pickRpc(config, chainId);
+ if (!rpcURL) {
+ _renderError(panel, `No RPC available for ${chainLabel(chainId)}.`, state);
+ return;
+ }
+
+ try {
+ const provider = new JsonRpcProvider(rpcURL, chainId, { staticNetwork: true });
+ const identity = new Contract(deployment.identityRegistry, IDENTITY_REGISTRY_ABI, provider);
+ const reputation = deployment.reputationRegistry
+ ? new Contract(deployment.reputationRegistry, REPUTATION_REGISTRY_ABI, provider)
+ : null;
+
+ const agentId = BigInt(config.agentId);
+
+ // ownerOf will revert for non-existent tokens; catch that specifically.
+ const [ownerRes, tokenURIRes, nameRes, symbolRes, repRes] = await Promise.allSettled([
+ identity.ownerOf(agentId),
+ identity.tokenURI(agentId),
+ identity.name(),
+ identity.symbol(),
+ reputation && config.showReputation
+ ? reputation.getReputation(agentId)
+ : Promise.resolve(null),
+ ]);
+
+ if (ownerRes.status === 'rejected') {
+ _renderError(panel, 'Agent not found on this chain.', state);
+ return;
+ }
+
+ const wallet = ownerRes.value;
+ const tokenURI = tokenURIRes.status === 'fulfilled' ? tokenURIRes.value : '';
+ const name = nameRes.status === 'fulfilled' ? nameRes.value : '';
+ const symbol = symbolRes.status === 'fulfilled' ? symbolRes.value : '';
+ let reputationData = null;
+ if (repRes.status === 'fulfilled' && repRes.value) {
+ const [total, count] = repRes.value;
+ const n = Number(count);
+ const t = Number(total);
+ reputationData = { total: t, count: n, average: n === 0 ? 0 : t / n };
+ }
+
+ let feedback = [];
+ if (reputation && config.showRecentFeedback) {
+ feedback = await _fetchRecentFeedback(reputation, agentId, provider).catch(() => []);
+ }
+
+ let manifest = null;
+ if (tokenURI) {
+ manifest = await _fetchManifest(tokenURI).catch(() => null);
+ }
+
+ state.data = { wallet, tokenURI, name, symbol, reputation: reputationData, feedback, manifest };
+ state.lastVerifiedAt = Date.now();
+
+ _writeCache(state.cacheKey, { data: state.data, savedAt: state.lastVerifiedAt });
+ _render(panel, state);
+ } catch (err) {
+ console.warn('[passport] refresh failed:', err.message || err);
+ // Leave whatever stale data we had; update the status label.
+ _render(panel, state, { staleReason: 'RPC error' });
+ }
+}
+
+/**
+ * Query the last N ReputationSubmitted events for this agent.
+ * Scoped to the recent history to avoid full-log scans.
+ */
+async function _fetchRecentFeedback(contract, agentId, provider) {
+ const latest = await provider.getBlockNumber();
+ const LOOKBACK = 200_000;
+ const fromBlock = Math.max(0, latest - LOOKBACK);
+ const filter = contract.filters.ReputationSubmitted(agentId);
+ const events = await contract.queryFilter(filter, fromBlock, latest);
+ return events
+ .slice(-5)
+ .reverse()
+ .map((ev) => ({
+ from: ev.args.submitter,
+ score: Number(ev.args.score),
+ comment: _sanitizeText(ev.args.comment || ''),
+ txHash: ev.transactionHash,
+ }));
+}
+
+async function _fetchManifest(tokenURI) {
+ const resolved = isDecentralizedURI(tokenURI) ? resolveURI(tokenURI) : tokenURI;
+ if (!/^https?:\/\//i.test(resolved)) return null;
+ const res = await fetch(resolved, { mode: 'cors' });
+ if (!res.ok) throw new Error(`manifest fetch ${res.status}`);
+ const ct = res.headers.get('content-type') || '';
+ if (!ct.includes('json') && !resolved.endsWith('.json')) {
+ // Only fetch JSON — never render tokenURI HTML.
+ return null;
+ }
+ const json = await res.json();
+ return _pickManifestFields(json);
+}
+
+/** Allow-list the fields we render. Drop everything else. */
+function _pickManifestFields(raw) {
+ if (!raw || typeof raw !== 'object') return null;
+ return {
+ name: typeof raw.name === 'string' ? raw.name.slice(0, 120) : '',
+ description: typeof raw.description === 'string' ? raw.description.slice(0, 500) : '',
+ image: typeof raw.image === 'string' ? raw.image : '',
+ agentRegistry: typeof raw.agentRegistry === 'string' ? raw.agentRegistry.slice(0, 200) : '',
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Rendering
+// ---------------------------------------------------------------------------
+
+function _renderLoading(panel, config) {
+ panel.innerHTML = `
+ <div class="passport-card" role="status">
+ <div class="passport-skeleton">
+ <div class="passport-skeleton-row"></div>
+ <div class="passport-skeleton-row short"></div>
+ <div class="passport-skeleton-row"></div>
+ </div>
+ <span class="passport-loading-label">Loading on-chain identity…</span>
+ </div>
+ ${config.showPoweredBy ? _poweredByHTML(config) : ''}
+ `;
+}
+
+function _renderError(panel, message, state) {
+ const { config } = state;
+ panel.innerHTML = `
+ <div class="passport-card passport-card--error" role="alert">
+ <div class="passport-error-icon" aria-hidden="true">!</div>
+ <div class="passport-error-msg">${_escapeHTML(message)}</div>
+ </div>
+ ${config.showPoweredBy ? _poweredByHTML(config) : ''}
+ `;
+}
+
+function _render(panel, state, opts = {}) {
+ const { config, chainId, data, lastVerifiedAt } = state;
+ if (!data) {
+ // No data and no error path yet — leave whatever's up.
+ return;
+ }
+
+ const explorer = EXPLORERS[chainId] || '';
+ const walletShort = _shortAddr(data.wallet);
+ const agentName = data.manifest?.name || data.name || `Agent #${config.agentId}`;
+ const verifiedISO = lastVerifiedAt ? new Date(lastVerifiedAt).toISOString() : '';
+ const verifiedRel = lastVerifiedAt ? _relativeTime(lastVerifiedAt) : '';
+ const stale = Boolean(opts.staleReason);
+
+ const repBlock = (config.showReputation && data.reputation) ? `
+ <div class="passport-row passport-row--reputation">
+ <span class="passport-star" aria-hidden="true">★</span>
+ <span class="passport-rep-avg">${data.reputation.count === 0 ? '—' : data.reputation.average.toFixed(2)}</span>
+ <span class="passport-rep-count">(${data.reputation.count} ${data.reputation.count === 1 ? 'review' : 'reviews'})</span>
+ </div>
+ ` : '';
+
+ const feedbackBlock = (config.showRecentFeedback && data.feedback && data.feedback.length) ? `
+ <div class="passport-section passport-section--feedback">
+ <div class="passport-section-title">Recent feedback</div>
+ <ul class="passport-feedback-list">
+ ${data.feedback.map((f) => `
+ <li class="passport-feedback-item">
+ <span class="passport-feedback-comment">${_escapeHTML(f.comment || '—')}</span>
+ <span class="passport-feedback-meta">${_shortAddr(f.from)} · ${f.score}★</span>
+ </li>
+ `).join('')}
+ </ul>
+ </div>
+ ` : '';
+
+ const jsonBlock = (config.showRegistrationJSON && data.tokenURI) ? `
+ <div class="passport-section passport-section--json">
+ <a class="passport-json-link" href="${_escapeAttr(_resolveForLink(data.tokenURI))}" target="_blank" rel="noopener noreferrer">
+ View passport JSON ↗
+ </a>
+ </div>
+ ` : '';
+
+ const explorerLink = explorer ? `
+ <a class="passport-explorer-link" href="${_escapeAttr(`${explorer}/address/${data.wallet}`)}" target="_blank" rel="noopener noreferrer" title="View on explorer">↗</a>
+ ` : '';
+
+ const chainSlug = chainLabel(chainId);
+
+ const staleBanner = stale ? `
+ <div class="passport-stale">Offline · last verified ${_escapeHTML(verifiedRel)}</div>
+ ` : '';
+
+ if (config.layout === 'badge') {
+ panel.innerHTML = `
+ <div class="passport-badge" role="group" aria-label="ERC-8004 Passport">
+ <div class="passport-badge-name" title="${_escapeAttr(agentName)}">${_escapeHTML(agentName)}</div>
+ <div class="passport-badge-line">
+ <span class="passport-badge-id">#${_escapeHTML(String(config.agentId))}</span>
+ <span class="passport-badge-sep">·</span>
+ <span class="passport-badge-chain">${_escapeHTML(chainSlug)}</span>
+ <span class="passport-badge-check" aria-label="Registered on-chain">✓</span>
+ </div>
+ ${config.showReputation && data.reputation ? `
+ <div class="passport-badge-rep">
+ <span class="passport-star" aria-hidden="true">★</span>
+ ${data.reputation.count === 0 ? '—' : data.reputation.average.toFixed(2)}
+ </div>
+ ` : ''}
+ ${staleBanner}
+ </div>
+ ${config.showPoweredBy ? _poweredByHTML(config) : ''}
+ `;
+ return;
+ }
+
+ panel.innerHTML = `
+ <div class="passport-card">
+ <div class="passport-header">
+ <div class="passport-name">${_escapeHTML(agentName)}</div>
+ <div class="passport-check" aria-label="Registered on-chain" title="Registered on-chain">✓</div>
+ </div>
+ <div class="passport-subhead">
+ <span class="passport-id">Agent #${_escapeHTML(String(config.agentId))}</span>
+ <span class="passport-sep">·</span>
+ <span class="passport-chain">${_escapeHTML(chainSlug)}</span>
+ </div>
+ <div class="passport-wallet-row">
+ <button type="button" class="passport-wallet" data-copy="${_escapeAttr(data.wallet)}" title="Copy ${_escapeAttr(data.wallet)}">
+ ${_escapeHTML(walletShort)}
+ </button>
+ ${explorerLink}
+ </div>
+ ${repBlock}
+ ${feedbackBlock}
+ ${jsonBlock}
+ ${lastVerifiedAt ? `
+ <div class="passport-verified" title="${_escapeAttr(verifiedISO)}">
+ ${stale ? 'Last verified' : 'Verified'} ${_escapeHTML(verifiedRel)}
+ </div>
+ ` : ''}
+ </div>
+ ${config.showPoweredBy ? _poweredByHTML(config) : ''}
+ `;
+
+ const copyBtn = panel.querySelector('.passport-wallet[data-copy]');
+ if (copyBtn) {
+ copyBtn.addEventListener('click', () => {
+ const addr = copyBtn.dataset.copy;
+ if (!addr) return;
+ navigator.clipboard?.writeText(addr).then(() => {
+ copyBtn.classList.add('passport-wallet--copied');
+ setTimeout(() => copyBtn.classList.remove('passport-wallet--copied'), 1200);
+ }).catch(() => { /* ignore */ });
+ });
+ }
+}
+
+function _poweredByHTML(_config) {
+ return `
+ <a class="passport-powered-by" href="https://3dagent.vercel.app" target="_blank" rel="noopener noreferrer">
+ 3dagent
+ </a>
+ `;
+}
+
+// ---------------------------------------------------------------------------
+// Viewer setup
+// ---------------------------------------------------------------------------
+
+function _applyTurntable(viewer, config) {
+ if (!viewer || !viewer.controls) return;
+ if (config.autoRotate === false) return;
+ viewer.state.autoRotate = true;
+ viewer.controls.autoRotate = true;
+ viewer.controls.autoRotateSpeed = (config.rotationSpeed ?? 0.6) * 4;
+ viewer.invalidate?.();
+}
+
+function _kioskifyCanvas(_viewer, container) {
+ // Reduce viewer chrome for embed contexts.
+ const validator = document.querySelector('.validator-toggle');
+ if (validator) validator.style.display = 'none';
+ const header = document.querySelector('header');
+ if (header) header.style.display = 'none';
+ container.classList.add('passport-canvas-host');
+}
+
+// ---------------------------------------------------------------------------
+// Cache
+// ---------------------------------------------------------------------------
+
+function _readCache(key) {
+ try {
+ const raw = localStorage.getItem(key);
+ if (!raw) return null;
+ const parsed = JSON.parse(raw);
+ if (!parsed?.savedAt) return null;
+ if (Date.now() - parsed.savedAt > STALE_TTL_MS) return null;
+ return parsed;
+ } catch { return null; }
+}
+
+function _writeCache(key, payload) {
+ try {
+ // Wallet & tokenURI are strings. Only persist serialisable fields.
+ const safe = {
+ savedAt: payload.savedAt,
+ data: {
+ wallet: payload.data.wallet,
+ tokenURI: payload.data.tokenURI,
+ name: payload.data.name,
+ symbol: payload.data.symbol,
+ reputation: payload.data.reputation,
+ feedback: payload.data.feedback,
+ manifest: payload.data.manifest,
+ },
+ };
+ localStorage.setItem(key, JSON.stringify(safe));
+ } catch { /* quota / privacy mode — ignore */ }
+}
+
+// ---------------------------------------------------------------------------
+// Utilities
+// ---------------------------------------------------------------------------
+
+function _shortAddr(addr) {
+ if (!addr || typeof addr !== 'string') return '';
+ if (addr.length < 12) return addr;
+ return `${addr.slice(0, 6)}…${addr.slice(-4)}`;
+}
+
+function _escapeHTML(s) {
+ return String(s ?? '')
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;')
+ .replace(/'/g, '&#39;');
+}
+
+function _escapeAttr(s) {
+ return _escapeHTML(s);
+}
+
+function _sanitizeText(s) {
+ // Strip anything that looks like a tag. Feedback is plain text.
+ return String(s ?? '').replace(/<[^>]*>/g, '').slice(0, 500);
+}
+
+function _relativeTime(ts) {
+ const diff = Date.now() - ts;
+ const sec = Math.floor(diff / 1000);
+ if (sec < 60) return 'just now';
+ const min = Math.floor(sec / 60);
+ if (min < 60) return `${min}m ago`;
+ const hr = Math.floor(min / 60);
+ if (hr < 24) return `${hr}h ago`;
+ const day = Math.floor(hr / 24);
+ return `${day}d ago`;
+}
+
+function _resolveForLink(uri) {
+ return isDecentralizedURI(uri) ? resolveURI(uri) : uri;
+}
+
+// Re-export for Studio later.
+export { CHAIN_SLUGS };
diff --git a/style.css b/style.css
index 4a0531ecb..bf4505a3b 100644
--- a/style.css
+++ b/style.css
@@ -2501,7 +2501,7 @@ footer .separator {
display: flex;
align-items: center;
justify-content: center;
- overflow: auto;
+ overflow: hidden;
padding: var(--space-md);
background:
linear-gradient(45deg, #1a1a22 25%, transparent 25%),
@@ -2510,14 +2510,34 @@ footer .separator {
linear-gradient(-45deg, transparent 75%, #1a1a22 75%);
background-size: 20px 20px;
background-position: 0 0, 0 10px, 10px -10px, 10px 0;
+ cursor: grab;
}
-.texture-lightbox__canvas {
+.texture-lightbox__viewport {
+ position: relative;
max-width: 100%;
max-height: 100%;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+}
+.texture-lightbox__canvas {
+ max-width: min(90vw, 1200px);
+ max-height: calc(100vh - 160px);
object-fit: contain;
image-rendering: pixelated;
border: 1px solid #2a2a36;
background: #000;
+ transform-origin: center center;
+ transition: none;
+}
+.texture-lightbox__uv {
+ position: absolute;
+ inset: 0;
+ max-width: min(90vw, 1200px);
+ max-height: calc(100vh - 160px);
+ object-fit: contain;
+ pointer-events: none;
+ transform-origin: center center;
}
.texture-lightbox__footer {
padding: var(--space-xs) var(--space-md);
diff --git a/vercel.json b/vercel.json
index d417e7c73..e813219e0 100644
--- a/vercel.json
+++ b/vercel.json
@@ -17,10 +17,14 @@
{ "src": "/dashboard", "dest": "/public/dashboard/index.html" },
{ "src": "/dashboard/", "dest": "/public/dashboard/index.html" },
{ "src": "/dashboard/(.*)", "dest": "/public/dashboard/$1" },
+ { "src": "/studio", "dest": "/public/studio/index.html" },
+ { "src": "/studio/", "dest": "/public/studio/index.html" },
+ { "src": "/studio/(.*)", "dest": "/public/studio/$1" },
{ "src": "/api/agents/me", "dest": "/api/agents" },
{ "src": "/api/agents/([^/]+)/wallet", "dest": "/api/agents/[id]" },
{ "src": "/api/agents/([^/]+)/embed-policy", "dest": "/api/agents/[id]/embed-policy?id=$1" },
+ { "src": "/api/agents/([^/]+)/sign", "dest": "/api/agents/[id]/sign?id=$1" },
{ "src": "/api/agents/([^/]+)", "dest": "/api/agents/[id]" },
{ "src": "/api/agents", "dest": "/api/agents" },
{ "src": "/api/agent-actions", "dest": "/api/agent-actions" },
@@ -36,6 +40,10 @@
{ "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": "/api/widgets/([A-Za-z0-9_-]+)/duplicate","dest": "/api/widgets/[id]/duplicate?id=$1" },
+ { "src": "/api/widgets/([A-Za-z0-9_-]+)/stats", "dest": "/api/widgets/[id]/stats?id=$1" },
+ { "src": "/api/widgets", "dest": "/api/widgets" },
+ { "src": "/api/widgets/([A-Za-z0-9_-]+)", "dest": "/api/widgets/[id]?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" },